@mastra/ai-sdk 0.0.0-cloud-storage-adapter-20251106204059 → 0.0.0-cloud-604-map-nested-flow-details-to-side-panel-20251212192149

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
@@ -1,6 +1,9 @@
1
1
  import { registerApiRoute } from '@mastra/core/server';
2
- import { createUIMessageStream, createUIMessageStreamResponse } from 'ai';
3
- import { DefaultGeneratedFile, DefaultGeneratedFileWithType } from '@mastra/core/stream';
2
+ import { createUIMessageStream, createUIMessageStreamResponse, wrapLanguageModel } from 'ai';
3
+ import { convertFullStreamChunkToMastra, DefaultGeneratedFile, DefaultGeneratedFileWithType } from '@mastra/core/stream';
4
+ import { TripWire, MessageList } from '@mastra/core/agent';
5
+ import { RequestContext } from '@mastra/core/di';
6
+ import { WorkingMemory, MessageHistory, SemanticRecall } from '@mastra/core/processors';
4
7
 
5
8
  // src/chat-route.ts
6
9
 
@@ -8,6 +11,35 @@ import { DefaultGeneratedFile, DefaultGeneratedFileWithType } from '@mastra/core
8
11
  var isDataChunkType = (chunk) => {
9
12
  return chunk && typeof chunk === "object" && "type" in chunk && chunk.type?.startsWith("data-");
10
13
  };
14
+ var isMastraTextStreamChunk = (chunk) => {
15
+ return chunk && typeof chunk === "object" && "type" in chunk && typeof chunk.type === "string" && [
16
+ "text-start",
17
+ "text-delta",
18
+ "text-end",
19
+ "reasoning-start",
20
+ "reasoning-delta",
21
+ "reasoning-end",
22
+ "file",
23
+ "source",
24
+ "tool-input-start",
25
+ "tool-input-delta",
26
+ "tool-call-approval",
27
+ "tool-call-suspended",
28
+ "tool-call",
29
+ "tool-result",
30
+ "tool-error",
31
+ "error",
32
+ "start-step",
33
+ "finish-step",
34
+ "start",
35
+ "finish",
36
+ "abort",
37
+ "tool-input-end",
38
+ "object",
39
+ "tripwire",
40
+ "raw"
41
+ ].includes(chunk.type);
42
+ };
11
43
  function safeParseErrorObject(obj) {
12
44
  if (typeof obj !== "object" || obj === null) {
13
45
  return String(obj);
@@ -30,6 +62,12 @@ var isWorkflowExecutionDataChunkType = (chunk) => {
30
62
  };
31
63
 
32
64
  // src/helpers.ts
65
+ function toAISDKFinishReason(reason) {
66
+ if (reason === "tripwire" || reason === "retry") {
67
+ return "other";
68
+ }
69
+ return reason;
70
+ }
33
71
  function convertMastraChunkToAISDKv5({
34
72
  chunk,
35
73
  mode = "stream"
@@ -54,7 +92,7 @@ function convertMastraChunkToAISDKv5({
54
92
  case "finish": {
55
93
  return {
56
94
  type: "finish",
57
- finishReason: chunk.payload.stepResult.reason,
95
+ finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
58
96
  totalUsage: chunk.payload.output.usage
59
97
  };
60
98
  }
@@ -138,6 +176,28 @@ function convertMastraChunkToAISDKv5({
138
176
  toolName: chunk.payload.toolName,
139
177
  input: chunk.payload.args
140
178
  };
179
+ case "tool-call-approval":
180
+ return {
181
+ type: "data-tool-call-approval",
182
+ id: chunk.payload.toolCallId,
183
+ data: {
184
+ runId: chunk.runId,
185
+ toolCallId: chunk.payload.toolCallId,
186
+ toolName: chunk.payload.toolName,
187
+ args: chunk.payload.args
188
+ }
189
+ };
190
+ case "tool-call-suspended":
191
+ return {
192
+ type: "data-tool-call-suspended",
193
+ id: chunk.payload.toolCallId,
194
+ data: {
195
+ runId: chunk.runId,
196
+ toolCallId: chunk.payload.toolCallId,
197
+ toolName: chunk.payload.toolName,
198
+ suspendPayload: chunk.payload.suspendPayload
199
+ }
200
+ };
141
201
  case "tool-call-input-streaming-start":
142
202
  return {
143
203
  type: "tool-input-start",
@@ -171,7 +231,7 @@ function convertMastraChunkToAISDKv5({
171
231
  ...rest2
172
232
  },
173
233
  usage: chunk.payload.output.usage,
174
- finishReason: chunk.payload.stepResult.reason,
234
+ finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
175
235
  providerMetadata
176
236
  };
177
237
  }
@@ -228,6 +288,16 @@ function convertMastraChunkToAISDKv5({
228
288
  type: "object",
229
289
  object: chunk.object
230
290
  };
291
+ case "tripwire":
292
+ return {
293
+ type: "data-tripwire",
294
+ data: {
295
+ reason: chunk.payload.reason,
296
+ retry: chunk.payload.retry,
297
+ metadata: chunk.payload.metadata,
298
+ processorId: chunk.payload.processorId
299
+ }
300
+ };
231
301
  default:
232
302
  if (chunk.type && "payload" in chunk && chunk.payload) {
233
303
  return {
@@ -283,6 +353,14 @@ function convertFullStreamChunkToUIMessageStream({
283
353
  };
284
354
  }
285
355
  case "reasoning-delta": {
356
+ if (sendReasoning) {
357
+ return {
358
+ type: "reasoning-delta",
359
+ id: part.id,
360
+ delta: part.text,
361
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
362
+ };
363
+ }
286
364
  return;
287
365
  }
288
366
  case "reasoning-end": {
@@ -300,6 +378,25 @@ function convertFullStreamChunkToUIMessageStream({
300
378
  };
301
379
  }
302
380
  case "source": {
381
+ if (sendSources && part.sourceType === "url") {
382
+ return {
383
+ type: "source-url",
384
+ sourceId: part.id,
385
+ url: part.url,
386
+ title: part.title,
387
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
388
+ };
389
+ }
390
+ if (sendSources && part.sourceType === "document") {
391
+ return {
392
+ type: "source-document",
393
+ sourceId: part.id,
394
+ mediaType: part.mediaType,
395
+ title: part.title,
396
+ filename: part.filename,
397
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
398
+ };
399
+ }
303
400
  return;
304
401
  }
305
402
  case "tool-input-start": {
@@ -357,6 +454,14 @@ function convertFullStreamChunkToUIMessageStream({
357
454
  toolCallId: part.toolCallId,
358
455
  payload: part.output
359
456
  };
457
+ } else if (isDataChunkType(part.output)) {
458
+ if (!("data" in part.output)) {
459
+ throw new Error(
460
+ `UI Messages require a data property when using data- prefixed chunks
461
+ ${JSON.stringify(part)}`
462
+ );
463
+ }
464
+ return part.output;
360
465
  }
361
466
  return;
362
467
  }
@@ -382,21 +487,23 @@ function convertFullStreamChunkToUIMessageStream({
382
487
  return { type: "finish-step" };
383
488
  }
384
489
  case "start": {
385
- {
490
+ if (sendStart) {
386
491
  return {
387
492
  type: "start",
388
493
  ...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},
389
494
  ...responseMessageId != null ? { messageId: responseMessageId } : {}
390
495
  };
391
496
  }
497
+ return;
392
498
  }
393
499
  case "finish": {
394
- {
500
+ if (sendFinish) {
395
501
  return {
396
502
  type: "finish",
397
503
  ...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}
398
504
  };
399
505
  }
506
+ return;
400
507
  }
401
508
  case "abort": {
402
509
  return part;
@@ -423,7 +530,10 @@ function convertFullStreamChunkToUIMessageStream({
423
530
  }
424
531
 
425
532
  // src/transformers.ts
426
- function WorkflowStreamToAISDKTransformer() {
533
+ var PRIMITIVE_CACHE_SYMBOL = Symbol("primitive-cache");
534
+ function WorkflowStreamToAISDKTransformer({
535
+ includeTextStreamParts
536
+ } = {}) {
427
537
  const bufferedWorkflows = /* @__PURE__ */ new Map();
428
538
  return new TransformStream({
429
539
  start(controller) {
@@ -437,7 +547,7 @@ function WorkflowStreamToAISDKTransformer() {
437
547
  });
438
548
  },
439
549
  transform(chunk, controller) {
440
- const transformed = transformWorkflow(chunk, bufferedWorkflows);
550
+ const transformed = transformWorkflow(chunk, bufferedWorkflows, false, includeTextStreamParts);
441
551
  if (transformed) controller.enqueue(transformed);
442
552
  }
443
553
  });
@@ -461,20 +571,37 @@ function AgentNetworkToAISDKTransformer() {
461
571
  }
462
572
  });
463
573
  }
464
- function AgentStreamToAISDKTransformer(lastMessageId) {
574
+ function AgentStreamToAISDKTransformer({
575
+ lastMessageId,
576
+ sendStart,
577
+ sendFinish,
578
+ sendReasoning,
579
+ sendSources,
580
+ messageMetadata,
581
+ onError
582
+ }) {
465
583
  let bufferedSteps = /* @__PURE__ */ new Map();
584
+ let tripwireOccurred = false;
585
+ let finishEventSent = false;
466
586
  return new TransformStream({
467
587
  transform(chunk, controller) {
588
+ if (chunk.type === "tripwire") {
589
+ tripwireOccurred = true;
590
+ }
591
+ if (chunk.type === "finish") {
592
+ finishEventSent = true;
593
+ }
468
594
  const part = convertMastraChunkToAISDKv5({ chunk, mode: "stream" });
469
595
  const transformedChunk = convertFullStreamChunkToUIMessageStream({
470
596
  part,
471
- sendReasoning: false,
472
- sendSources: false,
473
- sendStart: true,
474
- sendFinish: true,
597
+ sendReasoning,
598
+ sendSources,
599
+ messageMetadataValue: messageMetadata?.({ part }),
600
+ sendStart,
601
+ sendFinish,
475
602
  responseMessageId: lastMessageId,
476
603
  onError(error) {
477
- return safeParseErrorObject(error);
604
+ return onError ? onError(error) : safeParseErrorObject(error);
478
605
  }
479
606
  });
480
607
  if (transformedChunk) {
@@ -494,6 +621,14 @@ function AgentStreamToAISDKTransformer(lastMessageId) {
494
621
  controller.enqueue(transformedChunk);
495
622
  }
496
623
  }
624
+ },
625
+ flush(controller) {
626
+ if (tripwireOccurred && !finishEventSent && sendFinish) {
627
+ controller.enqueue({
628
+ type: "finish",
629
+ finishReason: "other"
630
+ });
631
+ }
497
632
  }
498
633
  });
499
634
  }
@@ -633,7 +768,7 @@ function transformAgent(payload, bufferedSteps) {
633
768
  }
634
769
  return null;
635
770
  }
636
- function transformWorkflow(payload, bufferedWorkflows, isNested) {
771
+ function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStreamParts) {
637
772
  switch (payload.type) {
638
773
  case "workflow-start":
639
774
  bufferedWorkflows.set(payload.runId, {
@@ -726,6 +861,29 @@ function transformWorkflow(payload, bufferedWorkflows, isNested) {
726
861
  }
727
862
  };
728
863
  }
864
+ case "workflow-step-output": {
865
+ const output = payload.payload.output;
866
+ if (includeTextStreamParts && output && isMastraTextStreamChunk(output)) {
867
+ const part = convertMastraChunkToAISDKv5({ chunk: output, mode: "stream" });
868
+ const transformedChunk = convertFullStreamChunkToUIMessageStream({
869
+ part,
870
+ onError(error) {
871
+ return safeParseErrorObject(error);
872
+ }
873
+ });
874
+ return transformedChunk;
875
+ }
876
+ if (output && isDataChunkType(output)) {
877
+ if (!("data" in output)) {
878
+ throw new Error(
879
+ `UI Messages require a data property when using data- prefixed chunks
880
+ ${JSON.stringify(output)}`
881
+ );
882
+ }
883
+ return output;
884
+ }
885
+ return null;
886
+ }
729
887
  default: {
730
888
  if (isDataChunkType(payload)) {
731
889
  if (!("data" in payload)) {
@@ -745,12 +903,29 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
745
903
  case "routing-agent-start": {
746
904
  if (!bufferedNetworks.has(payload.runId)) {
747
905
  bufferedNetworks.set(payload.runId, {
748
- name: payload.payload.agentId,
906
+ name: payload.payload.networkId,
749
907
  steps: [],
750
908
  usage: null,
751
909
  output: null
752
910
  });
753
911
  }
912
+ const current = bufferedNetworks.get(payload.runId);
913
+ current.steps.push({
914
+ id: payload.payload.runId,
915
+ name: payload.payload.agentId,
916
+ status: "running",
917
+ iteration: payload.payload.inputData.iteration,
918
+ input: {
919
+ task: payload.payload.inputData.task,
920
+ threadId: payload.payload.inputData.threadId,
921
+ threadResourceId: payload.payload.inputData.threadResourceId
922
+ },
923
+ output: "",
924
+ task: null,
925
+ suspendPayload: null,
926
+ resumePayload: null,
927
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
928
+ });
754
929
  return {
755
930
  type: isNested ? "data-tool-network" : "data-network",
756
931
  id: payload.runId,
@@ -781,14 +956,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
781
956
  };
782
957
  }
783
958
  case "agent-execution-start": {
784
- const current = bufferedNetworks.get(payload.runId) || { name: "", steps: [], usage: null, output: null };
959
+ const current = bufferedNetworks.get(payload.runId);
960
+ if (!current) return null;
785
961
  current.steps.push({
962
+ id: payload.payload.runId,
786
963
  name: payload.payload.agentId,
787
964
  status: "running",
788
- input: payload.payload.args || null,
965
+ iteration: payload.payload.args?.iteration ?? 0,
966
+ input: { prompt: payload.payload.args?.prompt ?? "" },
789
967
  output: null,
968
+ task: null,
790
969
  suspendPayload: null,
791
- resumePayload: null
970
+ resumePayload: null,
971
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
792
972
  });
793
973
  bufferedNetworks.set(payload.runId, current);
794
974
  return {
@@ -801,14 +981,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
801
981
  };
802
982
  }
803
983
  case "workflow-execution-start": {
804
- const current = bufferedNetworks.get(payload.runId) || { name: "", steps: [], usage: null, output: null };
984
+ const current = bufferedNetworks.get(payload.runId);
985
+ if (!current) return null;
805
986
  current.steps.push({
806
- name: payload.payload.name,
987
+ id: payload.payload.runId,
988
+ name: payload.payload.workflowId,
807
989
  status: "running",
808
- input: payload.payload.args || null,
990
+ iteration: payload.payload.args?.iteration ?? 0,
991
+ input: { prompt: payload.payload.args?.prompt ?? "" },
809
992
  output: null,
993
+ task: null,
810
994
  suspendPayload: null,
811
- resumePayload: null
995
+ resumePayload: null,
996
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
812
997
  });
813
998
  bufferedNetworks.set(payload.runId, current);
814
999
  return {
@@ -821,14 +1006,21 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
821
1006
  };
822
1007
  }
823
1008
  case "tool-execution-start": {
824
- const current = bufferedNetworks.get(payload.runId) || { name: "", steps: [], usage: null, output: null };
1009
+ const current = bufferedNetworks.get(payload.runId);
1010
+ if (!current) return null;
825
1011
  current.steps.push({
1012
+ id: payload.payload.args.toolCallId,
826
1013
  name: payload.payload.args?.toolName,
827
1014
  status: "running",
1015
+ iteration: payload.payload.args?.iteration ? Number(payload.payload.args.iteration) : 0,
1016
+ task: {
1017
+ id: payload.payload.args?.toolName
1018
+ },
828
1019
  input: payload.payload.args?.args || null,
829
1020
  output: null,
830
1021
  suspendPayload: null,
831
- resumePayload: null
1022
+ resumePayload: null,
1023
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
832
1024
  });
833
1025
  bufferedNetworks.set(payload.runId, current);
834
1026
  return {
@@ -843,14 +1035,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
843
1035
  case "agent-execution-end": {
844
1036
  const current = bufferedNetworks.get(payload.runId);
845
1037
  if (!current) return null;
846
- current.steps.push({
847
- name: payload.payload.agentId,
848
- status: "success",
849
- input: null,
850
- output: payload.payload.result,
851
- suspendPayload: null,
852
- resumePayload: null
853
- });
1038
+ const stepId = payload.payload.runId;
1039
+ const step = current.steps.find((step2) => step2.id === stepId);
1040
+ if (!step) {
1041
+ return null;
1042
+ }
1043
+ step.status = "success";
1044
+ step.output = payload.payload.result;
854
1045
  return {
855
1046
  type: isNested ? "data-tool-network" : "data-network",
856
1047
  id: payload.runId,
@@ -865,14 +1056,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
865
1056
  case "tool-execution-end": {
866
1057
  const current = bufferedNetworks.get(payload.runId);
867
1058
  if (!current) return null;
868
- current.steps.push({
869
- name: payload.payload.toolName,
870
- status: "success",
871
- input: null,
872
- output: payload.payload.result,
873
- suspendPayload: null,
874
- resumePayload: null
875
- });
1059
+ const stepId = payload.payload.toolCallId;
1060
+ const step = current.steps.find((step2) => step2.id === stepId);
1061
+ if (!step) {
1062
+ return null;
1063
+ }
1064
+ step.status = "success";
1065
+ step.output = payload.payload.result;
876
1066
  return {
877
1067
  type: isNested ? "data-tool-network" : "data-network",
878
1068
  id: payload.runId,
@@ -886,14 +1076,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
886
1076
  case "workflow-execution-end": {
887
1077
  const current = bufferedNetworks.get(payload.runId);
888
1078
  if (!current) return null;
889
- current.steps.push({
890
- name: payload.payload.name,
891
- status: "success",
892
- input: null,
893
- output: payload.payload.result,
894
- suspendPayload: null,
895
- resumePayload: null
896
- });
1079
+ const stepId = payload.payload.runId;
1080
+ const step = current.steps.find((step2) => step2.id === stepId);
1081
+ if (!step) {
1082
+ return null;
1083
+ }
1084
+ step.status = "success";
1085
+ step.output = payload.payload.result;
897
1086
  return {
898
1087
  type: isNested ? "data-tool-network" : "data-network",
899
1088
  id: payload.runId,
@@ -908,12 +1097,24 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
908
1097
  case "routing-agent-end": {
909
1098
  const current = bufferedNetworks.get(payload.runId);
910
1099
  if (!current) return null;
1100
+ const stepId = payload.payload.runId;
1101
+ const step = current.steps.find((step2) => step2.id === stepId);
1102
+ if (!step) {
1103
+ return null;
1104
+ }
1105
+ step.status = "success";
1106
+ step.task = {
1107
+ id: payload.payload.primitiveId,
1108
+ type: payload.payload.primitiveType,
1109
+ name: payload.payload.task,
1110
+ reason: payload.payload.selectionReason
1111
+ };
1112
+ step.output = payload.payload.result;
911
1113
  return {
912
1114
  type: isNested ? "data-tool-network" : "data-network",
913
1115
  id: payload.runId,
914
1116
  data: {
915
1117
  ...current,
916
- status: "finished",
917
1118
  usage: payload.payload?.usage ?? current.usage,
918
1119
  output: payload.payload?.result ?? current.output
919
1120
  }
@@ -947,32 +1148,86 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
947
1148
  };
948
1149
  }
949
1150
  default: {
950
- if (isDataChunkType(payload)) {
951
- if (!("data" in payload)) {
1151
+ if (isAgentExecutionDataChunkType(payload)) {
1152
+ if (!("data" in payload.payload)) {
952
1153
  throw new Error(
953
1154
  `UI Messages require a data property when using data- prefixed chunks
954
1155
  ${JSON.stringify(payload)}`
955
1156
  );
956
1157
  }
957
- return payload;
1158
+ const { type, data } = payload.payload;
1159
+ return { type, data };
958
1160
  }
959
- if (isAgentExecutionDataChunkType(payload)) {
1161
+ if (isWorkflowExecutionDataChunkType(payload)) {
960
1162
  if (!("data" in payload.payload)) {
961
1163
  throw new Error(
962
1164
  `UI Messages require a data property when using data- prefixed chunks
963
1165
  ${JSON.stringify(payload)}`
964
1166
  );
965
1167
  }
966
- return payload.payload;
1168
+ const { type, data } = payload.payload;
1169
+ return { type, data };
967
1170
  }
968
- if (isWorkflowExecutionDataChunkType(payload)) {
969
- if (!("data" in payload.payload)) {
1171
+ if (payload.type.startsWith("agent-execution-event-")) {
1172
+ const stepId = payload.payload.runId;
1173
+ const current = bufferedNetworks.get(payload.runId);
1174
+ if (!current) return null;
1175
+ const step = current.steps.find((step2) => step2.id === stepId);
1176
+ if (!step) {
1177
+ return null;
1178
+ }
1179
+ step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
1180
+ const result = transformAgent(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
1181
+ if (result) {
1182
+ const { request, response, ...data } = result.data;
1183
+ step.task = data;
1184
+ }
1185
+ bufferedNetworks.set(payload.runId, current);
1186
+ return {
1187
+ type: isNested ? "data-tool-network" : "data-network",
1188
+ id: payload.runId,
1189
+ data: {
1190
+ ...current,
1191
+ status: "running"
1192
+ }
1193
+ };
1194
+ }
1195
+ if (payload.type.startsWith("workflow-execution-event-")) {
1196
+ const stepId = payload.payload.runId;
1197
+ const current = bufferedNetworks.get(payload.runId);
1198
+ if (!current) return null;
1199
+ const step = current.steps.find((step2) => step2.id === stepId);
1200
+ if (!step) {
1201
+ return null;
1202
+ }
1203
+ step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
1204
+ const result = transformWorkflow(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
1205
+ if (result && "data" in result) {
1206
+ const data = result.data;
1207
+ step.task = data;
1208
+ if (data.name && step.task) {
1209
+ step.task.id = data.name;
1210
+ }
1211
+ }
1212
+ bufferedNetworks.set(payload.runId, current);
1213
+ return {
1214
+ type: isNested ? "data-tool-network" : "data-network",
1215
+ id: payload.runId,
1216
+ data: {
1217
+ ...current,
1218
+ status: "running"
1219
+ }
1220
+ };
1221
+ }
1222
+ if (isDataChunkType(payload)) {
1223
+ if (!("data" in payload)) {
970
1224
  throw new Error(
971
1225
  `UI Messages require a data property when using data- prefixed chunks
972
1226
  ${JSON.stringify(payload)}`
973
1227
  );
974
1228
  }
975
- return payload.payload;
1229
+ const { type, data } = payload;
1230
+ return { type, data };
976
1231
  }
977
1232
  return null;
978
1233
  }
@@ -980,23 +1235,95 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
980
1235
  }
981
1236
 
982
1237
  // src/convert-streams.ts
983
- function toAISdkV5Stream(stream, options = { from: "agent" }) {
1238
+ function toAISdkV5Stream(stream, options = {
1239
+ from: "agent",
1240
+ sendStart: true,
1241
+ sendFinish: true
1242
+ }) {
984
1243
  const from = options?.from;
985
1244
  if (from === "workflow") {
986
- return stream.pipeThrough(WorkflowStreamToAISDKTransformer());
1245
+ const includeTextStreamParts = options?.includeTextStreamParts ?? true;
1246
+ return stream.pipeThrough(
1247
+ WorkflowStreamToAISDKTransformer({ includeTextStreamParts })
1248
+ );
987
1249
  }
988
1250
  if (from === "network") {
989
1251
  return stream.pipeThrough(AgentNetworkToAISDKTransformer());
990
1252
  }
991
1253
  const agentReadable = "fullStream" in stream ? stream.fullStream : stream;
992
- return agentReadable.pipeThrough(AgentStreamToAISDKTransformer(options?.lastMessageId));
1254
+ return agentReadable.pipeThrough(
1255
+ AgentStreamToAISDKTransformer({
1256
+ lastMessageId: options?.lastMessageId,
1257
+ sendStart: options?.sendStart,
1258
+ sendFinish: options?.sendFinish,
1259
+ sendReasoning: options?.sendReasoning,
1260
+ sendSources: options?.sendSources,
1261
+ messageMetadata: options?.messageMetadata,
1262
+ onError: options?.onError
1263
+ })
1264
+ );
993
1265
  }
994
1266
 
995
1267
  // src/chat-route.ts
1268
+ async function handleChatStream({
1269
+ mastra,
1270
+ agentId,
1271
+ params,
1272
+ defaultOptions,
1273
+ sendStart = true,
1274
+ sendFinish = true,
1275
+ sendReasoning = false,
1276
+ sendSources = false
1277
+ }) {
1278
+ const { messages, resumeData, runId, requestContext, ...rest } = params;
1279
+ if (resumeData && !runId) {
1280
+ throw new Error("runId is required when resumeData is provided");
1281
+ }
1282
+ const agentObj = mastra.getAgentById(agentId);
1283
+ if (!agentObj) {
1284
+ throw new Error(`Agent ${agentId} not found`);
1285
+ }
1286
+ if (!Array.isArray(messages)) {
1287
+ throw new Error("Messages must be an array of UIMessage objects");
1288
+ }
1289
+ const mergedOptions = {
1290
+ ...defaultOptions,
1291
+ ...rest,
1292
+ ...runId && { runId },
1293
+ requestContext: requestContext || defaultOptions?.requestContext
1294
+ };
1295
+ const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messages, mergedOptions);
1296
+ let lastMessageId;
1297
+ if (messages.length) {
1298
+ const lastMessage = messages[messages.length - 1];
1299
+ if (lastMessage?.role === "assistant") {
1300
+ lastMessageId = lastMessage.id;
1301
+ }
1302
+ }
1303
+ return createUIMessageStream({
1304
+ originalMessages: messages,
1305
+ execute: async ({ writer }) => {
1306
+ for await (const part of toAISdkV5Stream(result, {
1307
+ from: "agent",
1308
+ lastMessageId,
1309
+ sendStart,
1310
+ sendFinish,
1311
+ sendReasoning,
1312
+ sendSources
1313
+ })) {
1314
+ writer.write(part);
1315
+ }
1316
+ }
1317
+ });
1318
+ }
996
1319
  function chatRoute({
997
1320
  path = "/chat/:agentId",
998
1321
  agent,
999
- defaultOptions
1322
+ defaultOptions,
1323
+ sendStart = true,
1324
+ sendFinish = true,
1325
+ sendReasoning = false,
1326
+ sendSources = false
1000
1327
  }) {
1001
1328
  if (!agent && !path.includes("/:agentId")) {
1002
1329
  throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
@@ -1025,6 +1352,14 @@ function chatRoute({
1025
1352
  schema: {
1026
1353
  type: "object",
1027
1354
  properties: {
1355
+ resumeData: {
1356
+ type: "object",
1357
+ description: "Resume data for the agent"
1358
+ },
1359
+ runId: {
1360
+ type: "string",
1361
+ description: "The run ID required when resuming an agent execution"
1362
+ },
1028
1363
  messages: {
1029
1364
  type: "array",
1030
1365
  description: "Array of messages in the conversation",
@@ -1095,9 +1430,9 @@ function chatRoute({
1095
1430
  }
1096
1431
  },
1097
1432
  handler: async (c) => {
1098
- const { messages, ...rest } = await c.req.json();
1433
+ const params = await c.req.json();
1099
1434
  const mastra = c.get("mastra");
1100
- const requestContext = c.get("requestContext");
1435
+ const contextRequestContext = c.get("requestContext");
1101
1436
  let agentToUse = agent;
1102
1437
  if (!agent) {
1103
1438
  const agentId = c.req.param("agentId");
@@ -1108,32 +1443,24 @@ function chatRoute({
1108
1443
  `Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
1109
1444
  );
1110
1445
  }
1111
- if (requestContext && defaultOptions?.requestContext) {
1446
+ if (contextRequestContext && defaultOptions?.requestContext) {
1112
1447
  mastra.getLogger()?.warn(`"requestContext" set in the route options will be overridden by the request's "requestContext".`);
1113
1448
  }
1114
1449
  if (!agentToUse) {
1115
1450
  throw new Error("Agent ID is required");
1116
1451
  }
1117
- const agentObj = mastra.getAgent(agentToUse);
1118
- if (!agentObj) {
1119
- throw new Error(`Agent ${agentToUse} not found`);
1120
- }
1121
- const result = await agentObj.stream(messages, {
1122
- ...defaultOptions,
1123
- ...rest,
1124
- requestContext: requestContext || defaultOptions?.requestContext
1125
- });
1126
- let lastMessageId;
1127
- if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1128
- lastMessageId = messages[messages.length - 1].id;
1129
- }
1130
- const uiMessageStream = createUIMessageStream({
1131
- originalMessages: messages,
1132
- execute: async ({ writer }) => {
1133
- for await (const part of toAISdkV5Stream(result, { from: "agent", lastMessageId })) {
1134
- writer.write(part);
1135
- }
1136
- }
1452
+ const uiMessageStream = await handleChatStream({
1453
+ mastra,
1454
+ agentId: agentToUse,
1455
+ params: {
1456
+ ...params,
1457
+ requestContext: contextRequestContext || params.requestContext
1458
+ },
1459
+ defaultOptions,
1460
+ sendStart,
1461
+ sendFinish,
1462
+ sendReasoning,
1463
+ sendSources
1137
1464
  });
1138
1465
  return createUIMessageStreamResponse({
1139
1466
  stream: uiMessageStream
@@ -1141,9 +1468,31 @@ function chatRoute({
1141
1468
  }
1142
1469
  });
1143
1470
  }
1471
+ async function handleWorkflowStream({
1472
+ mastra,
1473
+ workflowId,
1474
+ params,
1475
+ includeTextStreamParts = true
1476
+ }) {
1477
+ const { runId, resourceId, inputData, resumeData, requestContext, ...rest } = params;
1478
+ const workflowObj = mastra.getWorkflowById(workflowId);
1479
+ if (!workflowObj) {
1480
+ throw new Error(`Workflow ${workflowId} not found`);
1481
+ }
1482
+ const run = await workflowObj.createRun({ runId, resourceId, ...rest });
1483
+ const stream = resumeData ? run.resumeStream({ resumeData, ...rest, requestContext }) : run.stream({ inputData, ...rest, requestContext });
1484
+ return createUIMessageStream({
1485
+ execute: async ({ writer }) => {
1486
+ for await (const part of toAISdkV5Stream(stream, { from: "workflow", includeTextStreamParts })) {
1487
+ writer.write(part);
1488
+ }
1489
+ }
1490
+ });
1491
+ }
1144
1492
  function workflowRoute({
1145
1493
  path = "/api/workflows/:workflowId/stream",
1146
- workflow
1494
+ workflow,
1495
+ includeTextStreamParts = true
1147
1496
  }) {
1148
1497
  if (!workflow && !path.includes("/:workflowId")) {
1149
1498
  throw new Error("Path must include :workflowId to route to the correct workflow or pass the workflow explicitly");
@@ -1170,9 +1519,13 @@ function workflowRoute({
1170
1519
  schema: {
1171
1520
  type: "object",
1172
1521
  properties: {
1522
+ runId: { type: "string" },
1523
+ resourceId: { type: "string" },
1173
1524
  inputData: { type: "object", additionalProperties: true },
1525
+ resumeData: { type: "object", additionalProperties: true },
1174
1526
  requestContext: { type: "object", additionalProperties: true },
1175
- tracingOptions: { type: "object", additionalProperties: true }
1527
+ tracingOptions: { type: "object", additionalProperties: true },
1528
+ step: { type: "string" }
1176
1529
  }
1177
1530
  }
1178
1531
  }
@@ -1190,8 +1543,9 @@ function workflowRoute({
1190
1543
  }
1191
1544
  },
1192
1545
  handler: async (c) => {
1193
- const { inputData, resumeData, ...rest } = await c.req.json();
1546
+ const params = await c.req.json();
1194
1547
  const mastra = c.get("mastra");
1548
+ const contextRequestContext = c.get("requestContext");
1195
1549
  let workflowToUse = workflow;
1196
1550
  if (!workflow) {
1197
1551
  const workflowId = c.req.param("workflowId");
@@ -1205,23 +1559,47 @@ function workflowRoute({
1205
1559
  if (!workflowToUse) {
1206
1560
  throw new Error("Workflow ID is required");
1207
1561
  }
1208
- const workflowObj = mastra.getWorkflow(workflowToUse);
1209
- if (!workflowObj) {
1210
- throw new Error(`Workflow ${workflowToUse} not found`);
1562
+ if (contextRequestContext && params.requestContext) {
1563
+ mastra.getLogger()?.warn(
1564
+ `"requestContext" from the request body will be ignored because "requestContext" is already set in the route options.`
1565
+ );
1211
1566
  }
1212
- const run = await workflowObj.createRun();
1213
- const stream = resumeData ? run.resumeStream({ resumeData, ...rest }) : run.stream({ inputData, ...rest });
1214
- const uiMessageStream = createUIMessageStream({
1215
- execute: async ({ writer }) => {
1216
- for await (const part of toAISdkV5Stream(stream, { from: "workflow" })) {
1217
- writer.write(part);
1218
- }
1219
- }
1567
+ const uiMessageStream = await handleWorkflowStream({
1568
+ mastra,
1569
+ workflowId: workflowToUse,
1570
+ params: {
1571
+ ...params,
1572
+ requestContext: contextRequestContext || params.requestContext
1573
+ },
1574
+ includeTextStreamParts
1220
1575
  });
1221
1576
  return createUIMessageStreamResponse({ stream: uiMessageStream });
1222
1577
  }
1223
1578
  });
1224
1579
  }
1580
+ async function handleNetworkStream({
1581
+ mastra,
1582
+ agentId,
1583
+ params,
1584
+ defaultOptions
1585
+ }) {
1586
+ const { messages, ...rest } = params;
1587
+ const agentObj = mastra.getAgentById(agentId);
1588
+ if (!agentObj) {
1589
+ throw new Error(`Agent ${agentId} not found`);
1590
+ }
1591
+ const result = await agentObj.network(messages, {
1592
+ ...defaultOptions,
1593
+ ...rest
1594
+ });
1595
+ return createUIMessageStream({
1596
+ execute: async ({ writer }) => {
1597
+ for await (const part of toAISdkV5Stream(result, { from: "network" })) {
1598
+ writer.write(part);
1599
+ }
1600
+ }
1601
+ });
1602
+ }
1225
1603
  function networkRoute({
1226
1604
  path = "/network/:agentId",
1227
1605
  agent,
@@ -1282,7 +1660,7 @@ function networkRoute({
1282
1660
  }
1283
1661
  },
1284
1662
  handler: async (c) => {
1285
- const { messages, ...rest } = await c.req.json();
1663
+ const params = await c.req.json();
1286
1664
  const mastra = c.get("mastra");
1287
1665
  let agentToUse = agent;
1288
1666
  if (!agent) {
@@ -1297,25 +1675,465 @@ function networkRoute({
1297
1675
  if (!agentToUse) {
1298
1676
  throw new Error("Agent ID is required");
1299
1677
  }
1300
- const agentObj = mastra.getAgent(agentToUse);
1301
- if (!agentObj) {
1302
- throw new Error(`Agent ${agentToUse} not found`);
1678
+ const uiMessageStream = await handleNetworkStream({
1679
+ mastra,
1680
+ agentId: agentToUse,
1681
+ params,
1682
+ defaultOptions
1683
+ });
1684
+ return createUIMessageStreamResponse({ stream: uiMessageStream });
1685
+ }
1686
+ });
1687
+ }
1688
+ function withMastra(model, options = {}) {
1689
+ const { memory, inputProcessors = [], outputProcessors = [] } = options;
1690
+ const allInputProcessors = [...inputProcessors];
1691
+ const allOutputProcessors = [...outputProcessors];
1692
+ if (memory) {
1693
+ const { storage, lastMessages, semanticRecall, workingMemory } = memory;
1694
+ const isWorkingMemoryEnabled = typeof workingMemory === "object" && workingMemory.enabled !== false;
1695
+ if (isWorkingMemoryEnabled && typeof workingMemory === "object") {
1696
+ let template;
1697
+ if (workingMemory.template) {
1698
+ template = {
1699
+ format: "markdown",
1700
+ content: workingMemory.template
1701
+ };
1702
+ }
1703
+ const workingMemoryProcessor = new WorkingMemory({
1704
+ storage,
1705
+ template,
1706
+ scope: workingMemory.scope,
1707
+ useVNext: "version" in workingMemory && workingMemory.version === "vnext"
1708
+ });
1709
+ allInputProcessors.push(workingMemoryProcessor);
1710
+ }
1711
+ if (lastMessages !== false && lastMessages !== void 0) {
1712
+ const messageHistory = new MessageHistory({
1713
+ storage,
1714
+ lastMessages: typeof lastMessages === "number" ? lastMessages : void 0
1715
+ });
1716
+ allInputProcessors.push(messageHistory);
1717
+ allOutputProcessors.push(messageHistory);
1718
+ }
1719
+ if (semanticRecall) {
1720
+ const { vector, embedder, indexName, ...semanticConfig } = semanticRecall;
1721
+ const semanticRecallProcessor = new SemanticRecall({
1722
+ storage,
1723
+ vector,
1724
+ embedder,
1725
+ indexName: indexName || "memory_messages",
1726
+ ...semanticConfig
1727
+ });
1728
+ allInputProcessors.push(semanticRecallProcessor);
1729
+ allOutputProcessors.push(semanticRecallProcessor);
1730
+ }
1731
+ }
1732
+ return wrapLanguageModel({
1733
+ model,
1734
+ middleware: createProcessorMiddleware({
1735
+ inputProcessors: allInputProcessors,
1736
+ outputProcessors: allOutputProcessors,
1737
+ memory: memory ? {
1738
+ threadId: memory.threadId,
1739
+ resourceId: memory.resourceId
1740
+ } : void 0
1741
+ })
1742
+ });
1743
+ }
1744
+ function createProcessorMiddleware(options) {
1745
+ const { inputProcessors = [], outputProcessors = [], memory } = options;
1746
+ const requestContext = new RequestContext();
1747
+ if (memory) {
1748
+ requestContext.set("MastraMemory", {
1749
+ thread: memory.threadId ? { id: memory.threadId } : void 0,
1750
+ resourceId: memory.resourceId,
1751
+ memoryConfig: memory.config
1752
+ });
1753
+ }
1754
+ return {
1755
+ middlewareVersion: "v2",
1756
+ /**
1757
+ * Transform params runs input processors (processInput)
1758
+ */
1759
+ async transformParams({ params }) {
1760
+ const messageList = new MessageList({
1761
+ threadId: memory?.threadId,
1762
+ resourceId: memory?.resourceId
1763
+ });
1764
+ for (const msg of params.prompt) {
1765
+ if (msg.role === "system") {
1766
+ messageList.addSystem(msg.content);
1767
+ } else {
1768
+ messageList.add(msg, "input");
1769
+ }
1770
+ }
1771
+ for (const processor of inputProcessors) {
1772
+ if (processor.processInput) {
1773
+ try {
1774
+ await processor.processInput({
1775
+ messages: messageList.get.input.db(),
1776
+ systemMessages: messageList.getAllSystemMessages(),
1777
+ messageList,
1778
+ requestContext,
1779
+ abort: (reason) => {
1780
+ throw new TripWire(reason || "Aborted by processor");
1781
+ }
1782
+ });
1783
+ } catch (error) {
1784
+ if (error instanceof TripWire) {
1785
+ return {
1786
+ ...params,
1787
+ providerOptions: {
1788
+ ...params.providerOptions,
1789
+ mastraProcessors: {
1790
+ tripwire: true,
1791
+ reason: error.message
1792
+ }
1793
+ }
1794
+ };
1795
+ }
1796
+ throw error;
1797
+ }
1798
+ }
1799
+ }
1800
+ const newPrompt = messageList.get.all.aiV5.prompt().map(MessageList.aiV5ModelMessageToV2PromptMessage);
1801
+ return {
1802
+ ...params,
1803
+ prompt: newPrompt
1804
+ };
1805
+ },
1806
+ /**
1807
+ * Wrap generate for non-streaming output processing
1808
+ */
1809
+ async wrapGenerate({ doGenerate, params }) {
1810
+ const processorState = params.providerOptions?.mastraProcessors;
1811
+ if (processorState?.tripwire) {
1812
+ const reason = processorState.reason || "Blocked by processor";
1813
+ return {
1814
+ content: [{ type: "text", text: reason }],
1815
+ finishReason: "stop",
1816
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
1817
+ warnings: [{ type: "other", message: `Tripwire: ${reason}` }]
1818
+ };
1303
1819
  }
1304
- const result = await agentObj.network(messages, {
1305
- ...defaultOptions,
1306
- ...rest
1820
+ const result = await doGenerate();
1821
+ if (!outputProcessors.length) return result;
1822
+ const messageList = new MessageList({
1823
+ threadId: memory?.threadId,
1824
+ resourceId: memory?.resourceId
1307
1825
  });
1308
- const uiMessageStream = createUIMessageStream({
1309
- execute: async ({ writer }) => {
1310
- for await (const part of toAISdkV5Stream(result, { from: "network" })) {
1311
- writer.write(part);
1826
+ for (const msg of params.prompt) {
1827
+ if (msg.role === "system") {
1828
+ messageList.addSystem(msg.content);
1829
+ } else {
1830
+ messageList.add(msg, "input");
1831
+ }
1832
+ }
1833
+ const textContent = result.content.filter((c) => c.type === "text").map((c) => c.text).join("");
1834
+ const responseMessage = {
1835
+ id: crypto.randomUUID(),
1836
+ role: "assistant",
1837
+ content: {
1838
+ format: 2,
1839
+ parts: [{ type: "text", text: textContent }]
1840
+ },
1841
+ createdAt: /* @__PURE__ */ new Date(),
1842
+ ...memory?.threadId && { threadId: memory.threadId },
1843
+ ...memory?.resourceId && { resourceId: memory.resourceId }
1844
+ };
1845
+ messageList.add(responseMessage, "response");
1846
+ for (const processor of outputProcessors) {
1847
+ if (processor.processOutputResult) {
1848
+ try {
1849
+ await processor.processOutputResult({
1850
+ messages: messageList.get.all.db(),
1851
+ messageList,
1852
+ requestContext,
1853
+ abort: (reason) => {
1854
+ throw new TripWire(reason || "Aborted by processor");
1855
+ }
1856
+ });
1857
+ } catch (error) {
1858
+ if (error instanceof TripWire) {
1859
+ return {
1860
+ content: [{ type: "text", text: error.message }],
1861
+ finishReason: "stop",
1862
+ usage: result.usage,
1863
+ warnings: [{ type: "other", message: `Output blocked: ${error.message}` }]
1864
+ };
1865
+ }
1866
+ throw error;
1312
1867
  }
1313
1868
  }
1869
+ }
1870
+ const processedText = messageList.get.response.db().map((m) => extractTextFromMastraMessage(m)).join("");
1871
+ return {
1872
+ ...result,
1873
+ content: [{ type: "text", text: processedText }]
1874
+ };
1875
+ },
1876
+ /**
1877
+ * Wrap stream for streaming output processing
1878
+ */
1879
+ async wrapStream({ doStream, params }) {
1880
+ const processorState = params.providerOptions?.mastraProcessors;
1881
+ if (processorState?.tripwire) {
1882
+ const reason = processorState.reason || "Blocked by processor";
1883
+ return {
1884
+ stream: createBlockedStream(reason)
1885
+ };
1886
+ }
1887
+ const { stream, ...rest } = await doStream();
1888
+ if (!outputProcessors.length) return { stream, ...rest };
1889
+ const processorStates = /* @__PURE__ */ new Map();
1890
+ const runId = crypto.randomUUID();
1891
+ const transformedStream = stream.pipeThrough(
1892
+ new TransformStream({
1893
+ async transform(chunk, controller) {
1894
+ let mastraChunk = convertFullStreamChunkToMastra(
1895
+ chunk,
1896
+ { runId }
1897
+ );
1898
+ if (!mastraChunk) {
1899
+ controller.enqueue(chunk);
1900
+ return;
1901
+ }
1902
+ for (const processor of outputProcessors) {
1903
+ if (processor.processOutputStream && mastraChunk) {
1904
+ let state = processorStates.get(processor.id);
1905
+ if (!state) {
1906
+ state = { streamParts: [], customState: {} };
1907
+ processorStates.set(processor.id, state);
1908
+ }
1909
+ state.streamParts.push(mastraChunk);
1910
+ try {
1911
+ const result = await processor.processOutputStream({
1912
+ part: mastraChunk,
1913
+ streamParts: state.streamParts,
1914
+ state: state.customState,
1915
+ requestContext,
1916
+ abort: (reason) => {
1917
+ throw new TripWire(reason || "Aborted by processor");
1918
+ }
1919
+ });
1920
+ if (result === null || result === void 0) {
1921
+ mastraChunk = void 0;
1922
+ } else {
1923
+ mastraChunk = result;
1924
+ }
1925
+ } catch (error) {
1926
+ if (error instanceof TripWire) {
1927
+ controller.enqueue({
1928
+ type: "error",
1929
+ error: new Error(error.message)
1930
+ });
1931
+ controller.terminate();
1932
+ return;
1933
+ }
1934
+ throw error;
1935
+ }
1936
+ }
1937
+ }
1938
+ if (mastraChunk) {
1939
+ const aiChunk = convertMastraChunkToAISDKStreamPart(mastraChunk);
1940
+ if (aiChunk) {
1941
+ controller.enqueue(aiChunk);
1942
+ }
1943
+ }
1944
+ }
1945
+ })
1946
+ );
1947
+ return { stream: transformedStream, ...rest };
1948
+ }
1949
+ };
1950
+ }
1951
+ function createBlockedStream(reason) {
1952
+ return new ReadableStream({
1953
+ start(controller) {
1954
+ const id = crypto.randomUUID();
1955
+ controller.enqueue({
1956
+ type: "text-start",
1957
+ id
1314
1958
  });
1315
- return createUIMessageStreamResponse({ stream: uiMessageStream });
1959
+ controller.enqueue({
1960
+ type: "text-delta",
1961
+ id,
1962
+ delta: reason
1963
+ });
1964
+ controller.enqueue({
1965
+ type: "text-end",
1966
+ id
1967
+ });
1968
+ controller.enqueue({
1969
+ type: "finish",
1970
+ finishReason: "stop",
1971
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
1972
+ });
1973
+ controller.close();
1316
1974
  }
1317
1975
  });
1318
1976
  }
1977
+ function extractTextFromMastraMessage(msg) {
1978
+ const content = msg.content;
1979
+ if (typeof content === "string") {
1980
+ return content;
1981
+ }
1982
+ if (content?.parts) {
1983
+ return content.parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join("");
1984
+ }
1985
+ return "";
1986
+ }
1987
+ function convertMastraChunkToAISDKStreamPart(chunk) {
1988
+ switch (chunk.type) {
1989
+ // Text streaming
1990
+ case "text-start":
1991
+ return {
1992
+ type: "text-start",
1993
+ id: chunk.payload.id || crypto.randomUUID(),
1994
+ providerMetadata: chunk.payload.providerMetadata
1995
+ };
1996
+ case "text-delta":
1997
+ return {
1998
+ type: "text-delta",
1999
+ id: chunk.payload.id || crypto.randomUUID(),
2000
+ delta: chunk.payload.text,
2001
+ providerMetadata: chunk.payload.providerMetadata
2002
+ };
2003
+ case "text-end":
2004
+ return {
2005
+ type: "text-end",
2006
+ id: chunk.payload.id || crypto.randomUUID(),
2007
+ providerMetadata: chunk.payload.providerMetadata
2008
+ };
2009
+ // Reasoning streaming
2010
+ case "reasoning-start":
2011
+ return {
2012
+ type: "reasoning-start",
2013
+ id: chunk.payload.id || crypto.randomUUID(),
2014
+ providerMetadata: chunk.payload.providerMetadata
2015
+ };
2016
+ case "reasoning-delta":
2017
+ return {
2018
+ type: "reasoning-delta",
2019
+ id: chunk.payload.id || crypto.randomUUID(),
2020
+ delta: chunk.payload.text,
2021
+ providerMetadata: chunk.payload.providerMetadata
2022
+ };
2023
+ case "reasoning-end":
2024
+ return {
2025
+ type: "reasoning-end",
2026
+ id: chunk.payload.id || crypto.randomUUID(),
2027
+ providerMetadata: chunk.payload.providerMetadata
2028
+ };
2029
+ // Tool call (complete)
2030
+ case "tool-call":
2031
+ return {
2032
+ type: "tool-call",
2033
+ toolCallId: chunk.payload.toolCallId,
2034
+ toolName: chunk.payload.toolName,
2035
+ input: JSON.stringify(chunk.payload.args),
2036
+ providerExecuted: chunk.payload.providerExecuted,
2037
+ providerMetadata: chunk.payload.providerMetadata
2038
+ };
2039
+ // Tool call input streaming
2040
+ case "tool-call-input-streaming-start":
2041
+ return {
2042
+ type: "tool-input-start",
2043
+ id: chunk.payload.toolCallId,
2044
+ toolName: chunk.payload.toolName,
2045
+ providerExecuted: chunk.payload.providerExecuted,
2046
+ providerMetadata: chunk.payload.providerMetadata
2047
+ };
2048
+ case "tool-call-delta":
2049
+ return {
2050
+ type: "tool-input-delta",
2051
+ id: chunk.payload.toolCallId,
2052
+ delta: chunk.payload.argsTextDelta,
2053
+ providerMetadata: chunk.payload.providerMetadata
2054
+ };
2055
+ case "tool-call-input-streaming-end":
2056
+ return {
2057
+ type: "tool-input-end",
2058
+ id: chunk.payload.toolCallId,
2059
+ providerMetadata: chunk.payload.providerMetadata
2060
+ };
2061
+ // Tool result
2062
+ case "tool-result":
2063
+ return {
2064
+ type: "tool-result",
2065
+ toolCallId: chunk.payload.toolCallId,
2066
+ toolName: chunk.payload.toolName,
2067
+ result: { type: "json", value: chunk.payload.result },
2068
+ isError: chunk.payload.isError,
2069
+ providerExecuted: chunk.payload.providerExecuted,
2070
+ providerMetadata: chunk.payload.providerMetadata
2071
+ };
2072
+ // Source (citations)
2073
+ case "source":
2074
+ if (chunk.payload.sourceType === "url") {
2075
+ return {
2076
+ type: "source",
2077
+ sourceType: "url",
2078
+ id: chunk.payload.id,
2079
+ url: chunk.payload.url,
2080
+ title: chunk.payload.title,
2081
+ providerMetadata: chunk.payload.providerMetadata
2082
+ };
2083
+ } else {
2084
+ return {
2085
+ type: "source",
2086
+ sourceType: "document",
2087
+ id: chunk.payload.id,
2088
+ mediaType: chunk.payload.mimeType,
2089
+ title: chunk.payload.title,
2090
+ filename: chunk.payload.filename,
2091
+ providerMetadata: chunk.payload.providerMetadata
2092
+ };
2093
+ }
2094
+ // File output
2095
+ case "file":
2096
+ return {
2097
+ type: "file",
2098
+ data: chunk.payload.data || chunk.payload.base64,
2099
+ mediaType: chunk.payload.mimeType
2100
+ };
2101
+ // Response metadata
2102
+ case "response-metadata":
2103
+ return {
2104
+ type: "response-metadata",
2105
+ ...chunk.payload
2106
+ };
2107
+ // Raw provider data
2108
+ case "raw":
2109
+ return {
2110
+ type: "raw",
2111
+ rawValue: chunk.payload
2112
+ };
2113
+ // Finish
2114
+ case "finish": {
2115
+ const usage = chunk.payload.output?.usage;
2116
+ return {
2117
+ type: "finish",
2118
+ finishReason: toAISDKFinishReason(chunk.payload.stepResult?.reason || "stop"),
2119
+ usage: usage ? {
2120
+ inputTokens: usage.inputTokens || 0,
2121
+ outputTokens: usage.outputTokens || 0,
2122
+ totalTokens: usage.totalTokens || 0
2123
+ } : { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
2124
+ providerMetadata: chunk.payload.metadata?.providerMetadata
2125
+ };
2126
+ }
2127
+ // Error
2128
+ case "error":
2129
+ return {
2130
+ type: "error",
2131
+ error: chunk.payload.error || chunk.payload
2132
+ };
2133
+ default:
2134
+ return null;
2135
+ }
2136
+ }
1319
2137
 
1320
2138
  // src/to-ai-sdk-format.ts
1321
2139
  function toAISdkFormat() {
@@ -1324,6 +2142,6 @@ function toAISdkFormat() {
1324
2142
  );
1325
2143
  }
1326
2144
 
1327
- export { chatRoute, networkRoute, toAISdkFormat, toAISdkV5Stream as toAISdkStream, workflowRoute };
2145
+ export { chatRoute, handleChatStream, handleNetworkStream, handleWorkflowStream, networkRoute, toAISdkFormat, toAISdkV5Stream as toAISdkStream, withMastra, workflowRoute };
1328
2146
  //# sourceMappingURL=index.js.map
1329
2147
  //# sourceMappingURL=index.js.map