@mastra/core 0.20.2 → 0.21.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/dist/agent/agent.d.ts +4 -9
  3. package/dist/agent/agent.d.ts.map +1 -1
  4. package/dist/agent/agent.types.d.ts +8 -13
  5. package/dist/agent/agent.types.d.ts.map +1 -1
  6. package/dist/agent/index.cjs +19 -11
  7. package/dist/agent/index.d.ts +2 -1
  8. package/dist/agent/index.d.ts.map +1 -1
  9. package/dist/agent/index.js +2 -2
  10. package/dist/agent/input-processor/index.cjs +6 -6
  11. package/dist/agent/input-processor/index.js +1 -1
  12. package/dist/agent/message-list/index.d.ts +4 -4
  13. package/dist/agent/message-list/index.d.ts.map +1 -1
  14. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts +1 -1
  15. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts.map +1 -1
  16. package/dist/agent/message-list/prompt/convert-file.d.ts +2 -2
  17. package/dist/agent/message-list/prompt/convert-file.d.ts.map +1 -1
  18. package/dist/agent/message-list/types.d.ts +2 -2
  19. package/dist/agent/message-list/types.d.ts.map +1 -1
  20. package/dist/agent/message-list/utils/convert-messages.d.ts +2 -2
  21. package/dist/agent/types.d.ts +13 -5
  22. package/dist/agent/types.d.ts.map +1 -1
  23. package/dist/agent/utils.d.ts +110 -0
  24. package/dist/agent/utils.d.ts.map +1 -0
  25. package/dist/agent/workflows/prepare-stream/index.d.ts +2 -2
  26. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  27. package/dist/agent/workflows/prepare-stream/map-results-step.d.ts.map +1 -1
  28. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts +2 -2
  29. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts +1 -2
  30. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  31. package/dist/agent/workflows/prepare-stream/schema.d.ts +2 -2
  32. package/dist/ai-tracing/index.cjs +32 -32
  33. package/dist/ai-tracing/index.js +1 -1
  34. package/dist/ai-tracing/types.d.ts +8 -0
  35. package/dist/ai-tracing/types.d.ts.map +1 -1
  36. package/dist/{chunk-KK5LUATU.js → chunk-2VSJYKJF.js} +4 -4
  37. package/dist/{chunk-KK5LUATU.js.map → chunk-2VSJYKJF.js.map} +1 -1
  38. package/dist/{chunk-2QV245Q5.cjs → chunk-37ZKH5YV.cjs} +25 -18
  39. package/dist/chunk-37ZKH5YV.cjs.map +1 -0
  40. package/dist/{chunk-JZ5MQXUL.cjs → chunk-46URAIGN.cjs} +4 -4
  41. package/dist/{chunk-JZ5MQXUL.cjs.map → chunk-46URAIGN.cjs.map} +1 -1
  42. package/dist/{chunk-X5SB7NR3.cjs → chunk-5SQ4LGZX.cjs} +9 -10
  43. package/dist/chunk-5SQ4LGZX.cjs.map +1 -0
  44. package/dist/{chunk-T5SM2HLV.cjs → chunk-6E3YXNS2.cjs} +4 -4
  45. package/dist/chunk-6E3YXNS2.cjs.map +1 -0
  46. package/dist/{chunk-HTX7EHW5.js → chunk-7G7VIPVE.js} +3 -3
  47. package/dist/{chunk-HTX7EHW5.js.map → chunk-7G7VIPVE.js.map} +1 -1
  48. package/dist/{chunk-YBC4V5GE.js → chunk-ACQCDLM5.js} +4 -4
  49. package/dist/{chunk-YBC4V5GE.js.map → chunk-ACQCDLM5.js.map} +1 -1
  50. package/dist/{chunk-7ZXDZXGD.cjs → chunk-CHGLK2EE.cjs} +2 -2
  51. package/dist/chunk-CHGLK2EE.cjs.map +1 -0
  52. package/dist/chunk-CMEDBCQI.cjs +13738 -0
  53. package/dist/chunk-CMEDBCQI.cjs.map +1 -0
  54. package/dist/chunk-CN3DPBSR.js +13713 -0
  55. package/dist/chunk-CN3DPBSR.js.map +1 -0
  56. package/dist/{chunk-BWC4WQTS.js → chunk-HY7VW2VD.js} +21 -14
  57. package/dist/chunk-HY7VW2VD.js.map +1 -0
  58. package/dist/{chunk-PPCSJI73.cjs → chunk-IWYVLIYC.cjs} +33 -14
  59. package/dist/chunk-IWYVLIYC.cjs.map +1 -0
  60. package/dist/{chunk-4PRV2Y55.cjs → chunk-LOUJSR3F.cjs} +5 -5
  61. package/dist/{chunk-4PRV2Y55.cjs.map → chunk-LOUJSR3F.cjs.map} +1 -1
  62. package/dist/{chunk-YICS4NNU.cjs → chunk-LPXWG36P.cjs} +12 -12
  63. package/dist/{chunk-YICS4NNU.cjs.map → chunk-LPXWG36P.cjs.map} +1 -1
  64. package/dist/{chunk-VSTMNPZJ.js → chunk-O2WF4GIK.js} +7 -8
  65. package/dist/chunk-O2WF4GIK.js.map +1 -0
  66. package/dist/{chunk-7H72OAZ3.js → chunk-PVVDB5IT.js} +3 -3
  67. package/dist/{chunk-7H72OAZ3.js.map → chunk-PVVDB5IT.js.map} +1 -1
  68. package/dist/{chunk-SWNIMD7I.js → chunk-RLLLUDY3.js} +3 -3
  69. package/dist/chunk-RLLLUDY3.js.map +1 -0
  70. package/dist/{chunk-DBYLVMIV.js → chunk-TUEJ2F25.js} +25 -7
  71. package/dist/chunk-TUEJ2F25.js.map +1 -0
  72. package/dist/{chunk-RE7SRMBE.cjs → chunk-U27VX7MI.cjs} +16 -16
  73. package/dist/chunk-U27VX7MI.cjs.map +1 -0
  74. package/dist/{chunk-6ZSVXXMJ.js → chunk-UAU56I6S.js} +2 -2
  75. package/dist/chunk-UAU56I6S.js.map +1 -0
  76. package/dist/{chunk-M2MHQQGJ.js → chunk-UJXD5L66.js} +4 -4
  77. package/dist/chunk-UJXD5L66.js.map +1 -0
  78. package/dist/{chunk-OC7MSESV.cjs → chunk-W5SR3JVW.cjs} +6 -6
  79. package/dist/{chunk-OC7MSESV.cjs.map → chunk-W5SR3JVW.cjs.map} +1 -1
  80. package/dist/{chunk-ECMIW6W2.cjs → chunk-W6OYSIHF.cjs} +99 -94
  81. package/dist/chunk-W6OYSIHF.cjs.map +1 -0
  82. package/dist/{chunk-EB2KTBHB.js → chunk-WYJFP2MU.js} +65 -62
  83. package/dist/chunk-WYJFP2MU.js.map +1 -0
  84. package/dist/index.cjs +53 -49
  85. package/dist/index.js +10 -10
  86. package/dist/llm/index.cjs +9 -5
  87. package/dist/llm/index.d.ts +3 -2
  88. package/dist/llm/index.d.ts.map +1 -1
  89. package/dist/llm/index.js +1 -1
  90. package/dist/llm/model/base.types.d.ts +2 -2
  91. package/dist/llm/model/base.types.d.ts.map +1 -1
  92. package/dist/llm/model/gateways/base.d.ts +1 -1
  93. package/dist/llm/model/gateways/base.d.ts.map +1 -1
  94. package/dist/llm/model/gateways/models-dev.d.ts +1 -1
  95. package/dist/llm/model/gateways/models-dev.d.ts.map +1 -1
  96. package/dist/llm/model/gateways/netlify.d.ts +1 -1
  97. package/dist/llm/model/gateways/netlify.d.ts.map +1 -1
  98. package/dist/llm/model/index.d.ts +1 -0
  99. package/dist/llm/model/index.d.ts.map +1 -1
  100. package/dist/llm/model/model.d.ts +2 -2
  101. package/dist/llm/model/model.d.ts.map +1 -1
  102. package/dist/llm/model/model.loop.d.ts +3 -3
  103. package/dist/llm/model/model.loop.d.ts.map +1 -1
  104. package/dist/llm/model/model.loop.types.d.ts +2 -3
  105. package/dist/llm/model/model.loop.types.d.ts.map +1 -1
  106. package/dist/llm/model/resolve-model.d.ts +46 -0
  107. package/dist/llm/model/resolve-model.d.ts.map +1 -0
  108. package/dist/llm/model/router.d.ts +1 -1
  109. package/dist/llm/model/router.d.ts.map +1 -1
  110. package/dist/llm/model/shared.types.d.ts +9 -3
  111. package/dist/llm/model/shared.types.d.ts.map +1 -1
  112. package/dist/loop/index.cjs +2 -2
  113. package/dist/loop/index.js +1 -1
  114. package/dist/loop/loop.d.ts +1 -1
  115. package/dist/loop/loop.d.ts.map +1 -1
  116. package/dist/loop/network/index.d.ts.map +1 -1
  117. package/dist/loop/telemetry/index.d.ts +1 -1
  118. package/dist/loop/telemetry/index.d.ts.map +1 -1
  119. package/dist/loop/test-utils/streamObject.d.ts +1 -1
  120. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  121. package/dist/loop/test-utils/utils.d.ts +2 -2
  122. package/dist/loop/test-utils/utils.d.ts.map +1 -1
  123. package/dist/loop/types.d.ts +4 -3
  124. package/dist/loop/types.d.ts.map +1 -1
  125. package/dist/loop/workflows/agentic-execution/index.d.ts +73 -73
  126. package/dist/loop/workflows/agentic-execution/index.d.ts.map +1 -1
  127. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +50 -50
  128. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  129. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +25 -25
  130. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts.map +1 -1
  131. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +1 -1
  132. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts.map +1 -1
  133. package/dist/loop/workflows/agentic-loop/index.d.ts +73 -73
  134. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  135. package/dist/loop/workflows/run-state.d.ts +1 -1
  136. package/dist/loop/workflows/run-state.d.ts.map +1 -1
  137. package/dist/loop/workflows/schema.d.ts +33 -33
  138. package/dist/loop/workflows/schema.d.ts.map +1 -1
  139. package/dist/loop/workflows/stream.d.ts +1 -1
  140. package/dist/loop/workflows/stream.d.ts.map +1 -1
  141. package/dist/mastra/hooks.d.ts.map +1 -1
  142. package/dist/mastra/index.cjs +2 -2
  143. package/dist/mastra/index.js +1 -1
  144. package/dist/memory/index.cjs +4 -4
  145. package/dist/memory/index.js +1 -1
  146. package/dist/memory/memory.d.ts +2 -2
  147. package/dist/memory/memory.d.ts.map +1 -1
  148. package/dist/memory/types.d.ts +3 -3
  149. package/dist/memory/types.d.ts.map +1 -1
  150. package/dist/processors/index.cjs +11 -11
  151. package/dist/processors/index.js +1 -1
  152. package/dist/processors/processors/language-detector.d.ts.map +1 -1
  153. package/dist/processors/processors/moderation.d.ts +6 -3
  154. package/dist/processors/processors/moderation.d.ts.map +1 -1
  155. package/dist/processors/processors/pii-detector.d.ts +6 -3
  156. package/dist/processors/processors/pii-detector.d.ts.map +1 -1
  157. package/dist/processors/processors/prompt-injection-detector.d.ts.map +1 -1
  158. package/dist/processors/processors/structured-output.d.ts +2 -2
  159. package/dist/processors/processors/structured-output.d.ts.map +1 -1
  160. package/dist/processors/processors/system-prompt-scrubber.d.ts.map +1 -1
  161. package/dist/relevance/index.cjs +4 -4
  162. package/dist/relevance/index.js +1 -1
  163. package/dist/relevance/mastra-agent/index.d.ts +2 -2
  164. package/dist/relevance/mastra-agent/index.d.ts.map +1 -1
  165. package/dist/scores/base.d.ts +6 -6
  166. package/dist/scores/base.d.ts.map +1 -1
  167. package/dist/scores/index.cjs +9 -9
  168. package/dist/scores/index.js +2 -2
  169. package/dist/scores/run-experiment/index.d.ts +1 -1
  170. package/dist/scores/run-experiment/index.d.ts.map +1 -1
  171. package/dist/scores/scoreTraces/index.cjs +8 -8
  172. package/dist/scores/scoreTraces/index.cjs.map +1 -1
  173. package/dist/scores/scoreTraces/index.js +3 -3
  174. package/dist/scores/scoreTraces/index.js.map +1 -1
  175. package/dist/scores/types.d.ts +1 -1
  176. package/dist/scores/types.d.ts.map +1 -1
  177. package/dist/storage/index.cjs +3 -3
  178. package/dist/storage/index.js +1 -1
  179. package/dist/stream/aisdk/v4/input.d.ts +1 -1
  180. package/dist/stream/aisdk/v4/input.d.ts.map +1 -1
  181. package/dist/stream/aisdk/v5/compat/content.d.ts +2 -2
  182. package/dist/stream/aisdk/v5/compat/content.d.ts.map +1 -1
  183. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts +2 -2
  184. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts.map +1 -1
  185. package/dist/stream/aisdk/v5/compat/ui-message.d.ts +1 -1
  186. package/dist/stream/aisdk/v5/compat/ui-message.d.ts.map +1 -1
  187. package/dist/stream/aisdk/v5/compat/validation.d.ts +1 -1
  188. package/dist/stream/aisdk/v5/compat/validation.d.ts.map +1 -1
  189. package/dist/stream/aisdk/v5/execute.d.ts +5 -4
  190. package/dist/stream/aisdk/v5/execute.d.ts.map +1 -1
  191. package/dist/stream/aisdk/v5/input.d.ts +1 -1
  192. package/dist/stream/aisdk/v5/input.d.ts.map +1 -1
  193. package/dist/stream/aisdk/v5/output-helpers.d.ts +9 -9
  194. package/dist/stream/aisdk/v5/output-helpers.d.ts.map +1 -1
  195. package/dist/stream/aisdk/v5/output.d.ts +40 -39
  196. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  197. package/dist/stream/aisdk/v5/test-utils.d.ts +1 -1
  198. package/dist/stream/aisdk/v5/test-utils.d.ts.map +1 -1
  199. package/dist/stream/aisdk/v5/transform.d.ts +2 -2
  200. package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
  201. package/dist/stream/base/input.d.ts +1 -1
  202. package/dist/stream/base/input.d.ts.map +1 -1
  203. package/dist/stream/base/output-format-handlers.d.ts +3 -2
  204. package/dist/stream/base/output-format-handlers.d.ts.map +1 -1
  205. package/dist/stream/base/output.d.ts +31 -25
  206. package/dist/stream/base/output.d.ts.map +1 -1
  207. package/dist/stream/base/schema.d.ts +1 -1
  208. package/dist/stream/base/schema.d.ts.map +1 -1
  209. package/dist/stream/index.cjs +9 -9
  210. package/dist/stream/index.js +2 -2
  211. package/dist/stream/types.d.ts +12 -6
  212. package/dist/stream/types.d.ts.map +1 -1
  213. package/dist/test-utils/llm-mock.cjs +6 -6
  214. package/dist/test-utils/llm-mock.cjs.map +1 -1
  215. package/dist/test-utils/llm-mock.d.ts +1 -1
  216. package/dist/test-utils/llm-mock.d.ts.map +1 -1
  217. package/dist/test-utils/llm-mock.js +3 -3
  218. package/dist/test-utils/llm-mock.js.map +1 -1
  219. package/dist/tools/types.d.ts +2 -2
  220. package/dist/tools/types.d.ts.map +1 -1
  221. package/dist/utils.cjs +17 -17
  222. package/dist/utils.d.ts +3 -2
  223. package/dist/utils.d.ts.map +1 -1
  224. package/dist/utils.js +1 -1
  225. package/dist/vector/embed.d.ts +2 -2
  226. package/dist/vector/embed.d.ts.map +1 -1
  227. package/dist/vector/index.cjs +4 -4
  228. package/dist/vector/index.js +1 -1
  229. package/dist/vector/vector.d.ts +2 -2
  230. package/dist/vector/vector.d.ts.map +1 -1
  231. package/dist/workflows/default.d.ts +2 -2
  232. package/dist/workflows/default.d.ts.map +1 -1
  233. package/dist/workflows/evented/execution-engine.d.ts +1 -1
  234. package/dist/workflows/evented/execution-engine.d.ts.map +1 -1
  235. package/dist/workflows/evented/index.cjs +10 -10
  236. package/dist/workflows/evented/index.js +1 -1
  237. package/dist/workflows/execution-engine.d.ts +1 -1
  238. package/dist/workflows/execution-engine.d.ts.map +1 -1
  239. package/dist/workflows/index.cjs +12 -12
  240. package/dist/workflows/index.js +1 -1
  241. package/dist/workflows/legacy/index.cjs +22 -22
  242. package/dist/workflows/legacy/index.js +1 -1
  243. package/dist/workflows/legacy/machine.d.ts +1 -1
  244. package/dist/workflows/legacy/workflow.d.ts +1 -1
  245. package/dist/workflows/step.d.ts +1 -1
  246. package/dist/workflows/step.d.ts.map +1 -1
  247. package/dist/workflows/types.d.ts +1 -1
  248. package/dist/workflows/types.d.ts.map +1 -1
  249. package/dist/workflows/workflow.d.ts +5 -7
  250. package/dist/workflows/workflow.d.ts.map +1 -1
  251. package/package.json +22 -19
  252. package/dist/chunk-2QV245Q5.cjs.map +0 -1
  253. package/dist/chunk-6ZSVXXMJ.js.map +0 -1
  254. package/dist/chunk-7ZXDZXGD.cjs.map +0 -1
  255. package/dist/chunk-BWC4WQTS.js.map +0 -1
  256. package/dist/chunk-BZ6BIHLE.js +0 -1418
  257. package/dist/chunk-BZ6BIHLE.js.map +0 -1
  258. package/dist/chunk-DBYLVMIV.js.map +0 -1
  259. package/dist/chunk-EB2KTBHB.js.map +0 -1
  260. package/dist/chunk-ECMIW6W2.cjs.map +0 -1
  261. package/dist/chunk-M2MHQQGJ.js.map +0 -1
  262. package/dist/chunk-PPCSJI73.cjs.map +0 -1
  263. package/dist/chunk-RE7SRMBE.cjs.map +0 -1
  264. package/dist/chunk-REVAU76X.cjs +0 -1423
  265. package/dist/chunk-REVAU76X.cjs.map +0 -1
  266. package/dist/chunk-SWNIMD7I.js.map +0 -1
  267. package/dist/chunk-T5SM2HLV.cjs.map +0 -1
  268. package/dist/chunk-VSTMNPZJ.js.map +0 -1
  269. package/dist/chunk-X5SB7NR3.cjs.map +0 -1
  270. package/dist/stream/aisdk/v5/model-supports.d.ts +0 -25
  271. package/dist/stream/aisdk/v5/model-supports.d.ts.map +0 -1
@@ -1,12 +1,12 @@
1
1
  import { DefaultVoice } from './chunk-42VT5WOB.js';
2
2
  import { STREAM_FORMAT_SYMBOL, EMITTER_SYMBOL } from './chunk-NLNKQD2T.js';
3
3
  import { InstrumentClass, Telemetry } from './chunk-2DVGQK2L.js';
4
- import { MastraLLMV1 } from './chunk-M2MHQQGJ.js';
5
- import { ModelRouterLanguageModel } from './chunk-BZ6BIHLE.js';
6
- import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-VSTMNPZJ.js';
4
+ import { MastraLLMV1 } from './chunk-UJXD5L66.js';
5
+ import { resolveModelConfig } from './chunk-CN3DPBSR.js';
6
+ import { MessageList, DefaultGeneratedFile, DefaultGeneratedFileWithType } from './chunk-O2WF4GIK.js';
7
7
  import { executeHook } from './chunk-TTELJD4F.js';
8
8
  import { zodToJsonSchema } from './chunk-PJKCPRYF.js';
9
- import { wrapMastra, selectFields, getOrCreateSpan, getValidTraceId, ensureToolProperties, makeCoreTool, createMastraProxy, delay } from './chunk-6ZSVXXMJ.js';
9
+ import { wrapMastra, selectFields, getOrCreateSpan, getValidTraceId, ensureToolProperties, makeCoreTool, createMastraProxy, delay } from './chunk-UAU56I6S.js';
10
10
  import { RuntimeContext } from './chunk-HLRWYUFN.js';
11
11
  import { MastraError, safeParseErrorObject } from './chunk-T3JFFQH2.js';
12
12
  import { ToolStream } from './chunk-A3QHQYMC.js';
@@ -20,19 +20,19 @@ import z9, { z } from 'zod';
20
20
  import * as crypto2 from 'crypto';
21
21
  import { randomUUID } from 'crypto';
22
22
  import { context, trace } from '@opentelemetry/api';
23
- import { getErrorMessage, TypeValidationError } from '@ai-sdk/provider-v5';
24
- import { generateId, createTextStreamResponse, createUIMessageStreamResponse, createUIMessageStream, asSchema, parsePartialJson, isDeepEqualData, jsonSchema, tool, stepCountIs } from 'ai-v5';
23
+ import { getErrorMessage, TypeValidationError } from '@ai-sdk/provider';
24
+ import { generateId, createTextStreamResponse, createUIMessageStreamResponse, createUIMessageStream, asSchema, parsePartialJson, isDeepEqualData, jsonSchema, tool, stepCountIs } from 'ai';
25
25
  import { OpenAIReasoningSchemaCompatLayer, OpenAISchemaCompatLayer, GoogleSchemaCompatLayer, AnthropicSchemaCompatLayer, DeepSeekSchemaCompatLayer, MetaSchemaCompatLayer, applyCompatLayer } from '@mastra/schema-compat';
26
26
  import { isEmpty, get } from 'radash';
27
- import { isAbortError, injectJsonInstructionIntoMessages } from '@ai-sdk/provider-utils-v5';
28
- import { isAbortError as isAbortError$1 } from '@ai-sdk/provider-utils';
27
+ import { isAbortError, injectJsonInstructionIntoMessages } from '@ai-sdk/provider-utils';
28
+ import { isAbortError as isAbortError$1 } from '@ai-sdk/provider-utils-v4';
29
29
  import sift from 'sift';
30
30
  import { createActor, assign, fromPromise, setup } from 'xstate';
31
31
  import { Tiktoken } from 'js-tiktoken/lite';
32
32
  import o200k_base from 'js-tiktoken/ranks/o200k_base';
33
33
 
34
34
  var require_fast_deep_equal=__commonJS({"../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports,module){module.exports=function equal(a,b){if(a===b)return true;if(a&&b&&typeof a=="object"&&typeof b=="object"){if(a.constructor!==b.constructor)return false;var length,i,keys;if(Array.isArray(a)){length=a.length;if(length!=b.length)return false;for(i=length;i--!==0;)if(!equal(a[i],b[i]))return false;return true;}if(a.constructor===RegExp)return a.source===b.source&&a.flags===b.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===b.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===b.toString();keys=Object.keys(a);length=keys.length;if(length!==Object.keys(b).length)return false;for(i=length;i--!==0;)if(!Object.prototype.hasOwnProperty.call(b,keys[i]))return false;for(i=length;i--!==0;){var key=keys[i];if(!equal(a[key],b[key]))return false;}return true;}return a!==a&&b!==b;};}});// src/stream/types.ts
35
- var ChunkFrom=/* @__PURE__ */(ChunkFrom2=>{ChunkFrom2["AGENT"]="AGENT";ChunkFrom2["USER"]="USER";ChunkFrom2["SYSTEM"]="SYSTEM";ChunkFrom2["WORKFLOW"]="WORKFLOW";return ChunkFrom2;})(ChunkFrom||{});// src/stream/base/output.ts
35
+ var ChunkFrom=/* @__PURE__ */(ChunkFrom2=>{ChunkFrom2["AGENT"]="AGENT";ChunkFrom2["USER"]="USER";ChunkFrom2["SYSTEM"]="SYSTEM";ChunkFrom2["WORKFLOW"]="WORKFLOW";ChunkFrom2["NETWORK"]="NETWORK";return ChunkFrom2;})(ChunkFrom||{});// src/stream/base/output.ts
36
36
  var UnicodeNormalizer=class{name="unicode-normalizer";options;constructor(options={}){this.options={stripControlChars:options.stripControlChars??false,preserveEmojis:options.preserveEmojis??true,collapseWhitespace:options.collapseWhitespace??true,trim:options.trim??true};}processInput(args){try{return args.messages.map(message=>({...message,content:{...message.content,parts:message.content.parts?.map(part=>{if(part.type==="text"&&"text"in part&&typeof part.text==="string"){return {...part,text:this.normalizeText(part.text)};}return part;}),content:typeof message.content.content==="string"?this.normalizeText(message.content.content):message.content.content}}));}catch{return args.messages;}}normalizeText(text){let normalized=text;normalized=normalized.normalize("NFKC");if(this.options.stripControlChars){if(this.options.preserveEmojis){normalized=normalized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g,"");}else {normalized=normalized.replace(/[^\x09\x0A\x0D\x20-\x7E\u00A0-\uFFFF]/g,"");}}if(this.options.collapseWhitespace){normalized=normalized.replace(/\r\n/g,"\n");normalized=normalized.replace(/\r/g,"\n");normalized=normalized.replace(/\n+/g,"\n");normalized=normalized.replace(/[ \t]+/g," ");}if(this.options.trim){normalized=normalized.trim();}return normalized;}};// src/agent/input-processor/processors/unicode-normalizer.ts
37
37
  var UnicodeNormalizerInputProcessor=class{name="unicode-normalizer";processor;constructor(options={}){this.processor=new UnicodeNormalizer(options);}process(args){return this.processor.processInput(args);}};// src/processors/processors/moderation.ts
38
38
  var noopSpanContext={traceId:"",spanId:"",traceFlags:0};var noopSpan={spanContext(){return noopSpanContext;},setAttribute(){return this;},setAttributes(){return this;},addEvent(){return this;},addLink(){return this;},addLinks(){return this;},setStatus(){return this;},updateName(){return this;},end(){return this;},isRecording(){return false;},recordException(){return this;}};var noopTracer={startSpan(){return noopSpan;},startActiveSpan(name,arg1,arg2,arg3){if(typeof arg1==="function"){return arg1(noopSpan);}if(typeof arg2==="function"){return arg2(noopSpan);}if(typeof arg3==="function"){return arg3(noopSpan);}}};// src/loop/telemetry/index.ts
@@ -40,12 +40,12 @@ function getTracer({isEnabled=false,tracer}={}){if(!isEnabled){return noopTracer
40
40
  ...Object.entries(settings).reduce((attributes,[key,value])=>{attributes[`stream.settings.${key}`]=value;return attributes;},{}),// add metadata as attributes:
41
41
  ...Object.entries(telemetry?.metadata??{}).reduce((attributes,[key,value])=>{attributes[`stream.telemetry.metadata.${key}`]=value;return attributes;},{}),// request headers
42
42
  ...Object.entries(headers??{}).reduce((attributes,[key,value])=>{if(value!==void 0){attributes[`stream.request.headers.${key}`]=value;}return attributes;},{})};}function getRootSpan({operationId,model,modelSettings,telemetry_settings,headers}){const tracer=getTracer({isEnabled:telemetry_settings?.isEnabled,tracer:telemetry_settings?.tracer});const baseTelemetryAttributes=getTelemetryAttributes({model:{modelId:model.modelId,provider:model.provider},settings:modelSettings??{maxRetries:2},telemetry:telemetry_settings,headers});const rootSpan=tracer.startSpan(operationId).setAttributes({...assembleOperationName({operationId,telemetry:telemetry_settings}),...baseTelemetryAttributes});return {rootSpan};}// src/agent/trip-wire.ts
43
- var TripWire=class extends Error{constructor(reason){super(reason);Object.setPrototypeOf(this,new.target.prototype);}};var getModelOutputForTripwire=async({tripwireReason,runId,tracingContext,options,model,messageList})=>{const tripwireStream=new ReadableStream$1({start(controller){controller.enqueue({type:"tripwire",runId,from:"AGENT"/* AGENT */,payload:{tripwireReason:tripwireReason||""}});controller.close();}});const{rootSpan}=getRootSpan({operationId:`mastra.stream.tripwire`,model:{modelId:model.modelId||"unknown",provider:model.provider||"unknown"},modelSettings:options.modelSettings,headers:options.modelSettings?.headers,telemetry_settings:options.telemetry});const modelOutput=new MastraModelOutput({model:{modelId:model.modelId,provider:model.provider,version:model.specificationVersion||"v2"},stream:tripwireStream,messageList,options:{runId,rootSpan,telemetry_settings:options.telemetry,output:options.output,tracingContext,onFinish:options.onFinish,// Fix these types after the types PR is merged
43
+ var TripWire=class extends Error{constructor(reason){super(reason);Object.setPrototypeOf(this,new.target.prototype);}};var getModelOutputForTripwire=async({tripwireReason,runId,tracingContext,options,model,messageList})=>{const tripwireStream=new ReadableStream$1({start(controller){controller.enqueue({type:"tripwire",runId,from:"AGENT"/* AGENT */,payload:{tripwireReason:tripwireReason||""}});controller.close();}});const{rootSpan}=getRootSpan({operationId:`mastra.stream.tripwire`,model:{modelId:model.modelId||"unknown",provider:model.provider||"unknown"},modelSettings:options.modelSettings,headers:options.modelSettings?.headers,telemetry_settings:options.telemetry});const modelOutput=new MastraModelOutput({model:{modelId:model.modelId,provider:model.provider,version:model.specificationVersion||"v2"},stream:tripwireStream,messageList,options:{runId,rootSpan,telemetry_settings:options.telemetry,structuredOutput:options.structuredOutput,tracingContext,onFinish:options.onFinish,// Fix these types after the types PR is merged
44
44
  onStepFinish:options.onStepFinish,returnScorerData:options.returnScorerData},messageId:randomUUID()});return modelOutput;};// src/processors/processors/moderation.ts
45
45
  var ModerationProcessor=class _ModerationProcessor{name="moderation";moderationAgent;categories;threshold;strategy;includeScores;chunkWindow;// Default OpenAI moderation categories
46
46
  static DEFAULT_CATEGORIES=["hate","hate/threatening","harassment","harassment/threatening","self-harm","self-harm/intent","self-harm/instructions","sexual","sexual/minors","violence","violence/graphic"];constructor(options){this.categories=options.categories||_ModerationProcessor.DEFAULT_CATEGORIES;this.threshold=options.threshold??0.5;this.strategy=options.strategy||"block";this.includeScores=options.includeScores??false;this.chunkWindow=options.chunkWindow??0;this.moderationAgent=new Agent({name:"content-moderator",instructions:options.instructions||this.createDefaultInstructions(),model:options.model,options:{tracingPolicy:{internal:15/* ALL */}}});}async processInput(args){try{const{messages,abort,tracingContext}=args;if(messages.length===0){return messages;}const passedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(!textContent.trim()){passedMessages.push(message);continue;}const moderationResult=await this.moderateContent(textContent,false,tracingContext);if(this.isModerationFlagged(moderationResult)){this.handleFlaggedContent(moderationResult,this.strategy,abort);if(this.strategy==="filter"){continue;}}passedMessages.push(message);}return passedMessages;}catch(error){if(error instanceof TripWire){throw error;}args.abort(`Moderation failed: ${error instanceof Error?error.message:"Unknown error"}`);}}async processOutputResult(args){return this.processInput(args);}async processOutputStream(args){try{const{part,streamParts,abort,tracingContext}=args;if(part.type!=="text-delta"){return part;}const contentToModerate=this.buildContextFromChunks(streamParts);const moderationResult=await this.moderateContent(contentToModerate,true,tracingContext);if(this.isModerationFlagged(moderationResult)){this.handleFlaggedContent(moderationResult,this.strategy,abort);if(this.strategy==="filter"){return null;}}return part;}catch(error){if(error instanceof TripWire){throw error;}console.warn("[ModerationProcessor] Stream moderation failed:",error);return args.part;}}/**
47
47
  * Moderate content using the internal agent
48
- */async moderateContent(content,isStream=false,tracingContext){const prompt=this.createModerationPrompt(content,isStream);try{const model=await this.moderationAgent.getModel();const schema=z9.object({category_scores:z9.object(this.categories.reduce((props,category)=>{props[category]=z9.number().min(0).max(1).optional();return props;},{})).optional(),reason:z9.string().optional()});let response;if(model.specificationVersion==="v2"){response=await this.moderationAgent.generate(prompt,{output:schema,modelSettings:{temperature:0},tracingContext});}else {response=await this.moderationAgent.generateLegacy(prompt,{output:schema,temperature:0,tracingContext});}const result=response.object;return result;}catch(error){console.warn("[ModerationProcessor] Agent moderation failed, allowing content:",error);return {};}}/**
48
+ */async moderateContent(content,isStream=false,tracingContext){const prompt=this.createModerationPrompt(content,isStream);try{const model=await this.moderationAgent.getModel();const schema=z9.object({category_scores:z9.object(this.categories.reduce((props,category)=>{props[category]=z9.number().min(0).max(1).optional();return props;},{})).optional(),reason:z9.string().optional()});let response;if(model.specificationVersion==="v2"){response=await this.moderationAgent.generate(prompt,{structuredOutput:{schema},modelSettings:{temperature:0},tracingContext});}else {response=await this.moderationAgent.generateLegacy(prompt,{output:schema,temperature:0,tracingContext});}const result=response.object;return result;}catch(error){console.warn("[ModerationProcessor] Agent moderation failed, allowing content:",error);return {};}}/**
49
49
  * Determine if content is flagged based on category scores above threshold
50
50
  */isModerationFlagged(result){if(result.category_scores){const scores=Object.values(result.category_scores).filter(score=>typeof score==="number");if(scores.length===0)return false;const maxScore=Math.max(...scores);return maxScore>=this.threshold;}return false;}/**
51
51
  * Handle flagged content based on strategy
@@ -83,7 +83,7 @@ static DEFAULT_DETECTION_TYPES=["injection",// General prompt injection attempts
83
83
  "role-manipulation"// Attempts to manipulate the AI's role or persona
84
84
  ];constructor(options){this.detectionTypes=options.detectionTypes||_PromptInjectionDetector.DEFAULT_DETECTION_TYPES;this.threshold=options.threshold??0.7;this.strategy=options.strategy||"block";this.includeScores=options.includeScores??false;this.detectionAgent=new Agent({name:"prompt-injection-detector",instructions:options.instructions||this.createDefaultInstructions(),model:options.model,options:{tracingPolicy:{internal:15/* ALL */}}});}async processInput(args){try{const{messages,abort,tracingContext}=args;if(messages.length===0){return messages;}const processedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(!textContent.trim()){processedMessages.push(message);continue;}const detectionResult=await this.detectPromptInjection(textContent,tracingContext);if(this.isInjectionFlagged(detectionResult)){const processedMessage=this.handleDetectedInjection(message,detectionResult,this.strategy,abort);if(this.strategy==="filter"){continue;}else if(this.strategy==="rewrite"){if(processedMessage){processedMessages.push(processedMessage);}continue;}}processedMessages.push(message);}return processedMessages;}catch(error){if(error instanceof TripWire){throw error;}throw new Error(`Prompt injection detection failed: ${error instanceof Error?error.stack:"Unknown error"}`);}}/**
85
85
  * Detect prompt injection using the internal agent
86
- */async detectPromptInjection(content,tracingContext){const prompt=this.createDetectionPrompt(content);try{const model=await this.detectionAgent.getModel();let response;const schema=z9.object({categories:z9.object(this.detectionTypes.reduce((props,type)=>{props[type]=z9.number().min(0).max(1).optional();return props;},{})).optional(),reason:z9.string().optional(),rewritten_content:z9.string().optional()});if(model.specificationVersion==="v2"){response=await this.detectionAgent.generate(prompt,{output:schema,modelSettings:{temperature:0},tracingContext});}else {response=await this.detectionAgent.generateLegacy(prompt,{output:schema,temperature:0,tracingContext});}const result=response.object;return result;}catch(error){console.warn("[PromptInjectionDetector] Detection agent failed, allowing content:",error);return {};}}/**
86
+ */async detectPromptInjection(content,tracingContext){const prompt=this.createDetectionPrompt(content);try{const model=await this.detectionAgent.getModel();let response;const schema=z9.object({categories:z9.object(this.detectionTypes.reduce((props,type)=>{props[type]=z9.number().min(0).max(1).optional();return props;},{})).optional(),reason:z9.string().optional(),rewritten_content:z9.string().optional()});if(model.specificationVersion==="v2"){response=await this.detectionAgent.generate(prompt,{structuredOutput:{schema},modelSettings:{temperature:0},tracingContext});}else {response=await this.detectionAgent.generateLegacy(prompt,{output:schema,temperature:0,tracingContext});}const result=response.object;return result;}catch(error){console.warn("[PromptInjectionDetector] Detection agent failed, allowing content:",error);return {};}}/**
87
87
  * Determine if prompt injection is flagged based on category scores above threshold
88
88
  */isInjectionFlagged(result){if(result.categories){const maxScore=Math.max(...Object.values(result.categories).filter(score=>typeof score==="number"));return maxScore>=this.threshold;}return false;}/**
89
89
  * Handle detected prompt injection based on strategy
@@ -124,7 +124,7 @@ static DEFAULT_DETECTION_TYPES=["email",// Email addresses
124
124
  "iban"// International Bank Account Numbers
125
125
  ];constructor(options){this.detectionTypes=options.detectionTypes||_PIIDetector.DEFAULT_DETECTION_TYPES;this.threshold=options.threshold??0.6;this.strategy=options.strategy||"redact";this.redactionMethod=options.redactionMethod||"mask";this.includeDetections=options.includeDetections??false;this.preserveFormat=options.preserveFormat??true;this.detectionAgent=new Agent({name:"pii-detector",instructions:options.instructions||this.createDefaultInstructions(),model:options.model,options:{tracingPolicy:{internal:15/* ALL */}}});}async processInput(args){try{const{messages,abort,tracingContext}=args;if(messages.length===0){return messages;}const processedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(!textContent.trim()){processedMessages.push(message);continue;}const detectionResult=await this.detectPII(textContent,tracingContext);if(this.isPIIFlagged(detectionResult)){const processedMessage=this.handleDetectedPII(message,detectionResult,this.strategy,abort);if(this.strategy==="filter"){continue;}else if(this.strategy==="redact"){if(processedMessage){processedMessages.push(processedMessage);}else {processedMessages.push(message);}continue;}}processedMessages.push(message);}return processedMessages;}catch(error){if(error instanceof TripWire){throw error;}throw new Error(`PII detection failed: ${error instanceof Error?error.stack:"Unknown error"}`);}}/**
126
126
  * Detect PII using the internal agent
127
- */async detectPII(content,tracingContext){const prompt=this.createDetectionPrompt(content);const schema=z9.object({categories:z9.object(this.detectionTypes.reduce((props,type)=>{props[type]=z9.number().min(0).max(1).optional();return props;},{})).optional(),detections:z9.array(z9.object({type:z9.string(),value:z9.string(),confidence:z9.number().min(0).max(1),start:z9.number(),end:z9.number(),redacted_value:z9.string().optional()})).optional(),redacted_content:z9.string().optional()});try{const model=await this.detectionAgent.getModel();let response;if(model.specificationVersion==="v2"){response=await this.detectionAgent.generate(prompt,{output:schema,modelSettings:{temperature:0},tracingContext});}else {response=await this.detectionAgent.generateLegacy(prompt,{output:schema,temperature:0,tracingContext});}const result=response.object;if(!result.redacted_content&&result.detections&&result.detections.length>0){result.redacted_content=this.applyRedactionMethod(content,result.detections);result.detections=result.detections.map(detection=>({...detection,redacted_value:detection.redacted_value||this.redactValue(detection.value,detection.type)}));}return result;}catch(error){console.warn("[PIIDetector] Detection agent failed, allowing content:",error);return {};}}/**
127
+ */async detectPII(content,tracingContext){const prompt=this.createDetectionPrompt(content);const schema=z9.object({categories:z9.object(this.detectionTypes.reduce((props,type)=>{props[type]=z9.number().min(0).max(1).optional();return props;},{})).optional(),detections:z9.array(z9.object({type:z9.string(),value:z9.string(),confidence:z9.number().min(0).max(1),start:z9.number(),end:z9.number(),redacted_value:z9.string().optional()})).optional(),redacted_content:z9.string().optional()});try{const model=await this.detectionAgent.getModel();let response;if(model.specificationVersion==="v2"){response=await this.detectionAgent.generate(prompt,{structuredOutput:{schema},modelSettings:{temperature:0},tracingContext});}else {response=await this.detectionAgent.generateLegacy(prompt,{output:schema,temperature:0,tracingContext});}const result=response.object;if(!result.redacted_content&&result.detections&&result.detections.length>0){result.redacted_content=this.applyRedactionMethod(content,result.detections);result.detections=result.detections.map(detection=>({...detection,redacted_value:detection.redacted_value||this.redactValue(detection.value,detection.type)}));}return result;}catch(error){console.warn("[PIIDetector] Detection agent failed, allowing content:",error);return {};}}/**
128
128
  * Determine if PII is flagged based on detections or category scores above threshold
129
129
  */isPIIFlagged(result){if(result.detections&&result.detections.length>0){return true;}if(result.categories){const maxScore=Math.max(...Object.values(result.categories).filter(score=>typeof score==="number"));return maxScore>=this.threshold;}return false;}/**
130
130
  * Handle detected PII based on strategy
@@ -166,7 +166,7 @@ var LanguageDetector=class _LanguageDetector{name="language-detector";detectionA
166
166
  static DEFAULT_TARGET_LANGUAGES=["English","en"];// Common language codes and names mapping
167
167
  static LANGUAGE_MAP={en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",pt:"Portuguese",ru:"Russian",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Chinese (Simplified)","zh-tw":"Chinese (Traditional)",ar:"Arabic",hi:"Hindi",th:"Thai",vi:"Vietnamese",tr:"Turkish",pl:"Polish",nl:"Dutch",sv:"Swedish",da:"Danish",no:"Norwegian",fi:"Finnish",el:"Greek",he:"Hebrew",cs:"Czech",hu:"Hungarian",ro:"Romanian",bg:"Bulgarian",hr:"Croatian",sk:"Slovak",sl:"Slovenian",et:"Estonian",lv:"Latvian",lt:"Lithuanian",uk:"Ukrainian",be:"Belarusian"};constructor(options){this.targetLanguages=options.targetLanguages||_LanguageDetector.DEFAULT_TARGET_LANGUAGES;this.threshold=options.threshold??0.7;this.strategy=options.strategy||"detect";this.preserveOriginal=options.preserveOriginal??true;this.minTextLength=options.minTextLength??10;this.includeDetectionDetails=options.includeDetectionDetails??false;this.translationQuality=options.translationQuality||"quality";this.detectionAgent=new Agent({name:"language-detector",instructions:options.instructions||this.createDefaultInstructions(),model:options.model,options:{tracingPolicy:{internal:15/* ALL */}}});}async processInput(args){try{const{messages,abort}=args;if(messages.length===0){return messages;}const processedMessages=[];for(const message of messages){const textContent=this.extractTextContent(message);if(textContent.length<this.minTextLength){processedMessages.push(message);continue;}const detectionResult=await this.detectLanguage(textContent);if(detectionResult.confidence&&detectionResult.confidence<this.threshold){processedMessages.push(message);continue;}if(!this.isNonTargetLanguage(detectionResult)){const targetLanguageCode=this.getLanguageCode(this.targetLanguages[0]);const targetMessage=this.addLanguageMetadata(message,{iso_code:targetLanguageCode,confidence:0.95});if(this.includeDetectionDetails){console.info(`[LanguageDetector] Content in target language: Language detected: ${this.getLanguageName(targetLanguageCode)} (${targetLanguageCode}) with confidence 0.95`);}processedMessages.push(targetMessage);continue;}const processedMessage=await this.handleDetectedLanguage(message,detectionResult,this.strategy,abort);if(processedMessage){processedMessages.push(processedMessage);}else {continue;}}return processedMessages;}catch(error){if(error instanceof TripWire){throw error;}args.abort(`Language detection failed: ${error instanceof Error?error.message:"Unknown error"}`);}}/**
168
168
  * Detect language using the internal agent
169
- */async detectLanguage(content){const prompt=this.createDetectionPrompt(content);try{const model=await this.detectionAgent.getModel();let response;const schema=z9.object({iso_code:z9.string().optional(),confidence:z9.number().min(0).max(1).optional(),translated_text:z9.string().optional()});if(model.specificationVersion==="v2"){response=await this.detectionAgent.generate(prompt,{output:schema,modelSettings:{temperature:0}});}else {response=await this.detectionAgent.generateLegacy(prompt,{output:schema,temperature:0});}if(response.object.translated_text&&!response.object.confidence){response.object.confidence=0.95;}return response.object;}catch(error){console.warn("[LanguageDetector] Detection agent failed, assuming target language:",error);return {};}}/**
169
+ */async detectLanguage(content){const prompt=this.createDetectionPrompt(content);try{const model=await this.detectionAgent.getModel();let response;const schema=z9.object({iso_code:z9.string().optional(),confidence:z9.number().min(0).max(1).optional(),translated_text:z9.string().optional()});if(model.specificationVersion==="v2"){response=await this.detectionAgent.generate(prompt,{structuredOutput:{schema},modelSettings:{temperature:0}});}else {response=await this.detectionAgent.generateLegacy(prompt,{output:schema,temperature:0});}if(response.object.translated_text&&!response.object.confidence){response.object.confidence=0.95;}return response.object;}catch(error){console.warn("[LanguageDetector] Detection agent failed, assuming target language:",error);return {};}}/**
170
170
  * Determine if language detection indicates non-target language
171
171
  */isNonTargetLanguage(result){if(result.iso_code&&result.confidence&&result.confidence>=this.threshold){return !this.isTargetLanguage(result.iso_code);}return false;}/**
172
172
  * Get detected language name from ISO code
@@ -229,7 +229,7 @@ suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort(
229
229
  // This prevents pending nested workflows from trying to resume instead of start
230
230
  resume:stepResults[step.id]?.status==="suspended"?{steps:resume?.steps?.slice(1)||[],resumePayload:resume?.resumePayload,// @ts-ignore
231
231
  runId:stepResults[step.id]?.suspendPayload?.__workflow_meta?.runId}:void 0,[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:stepCallId,name:step.id,runId},writableStream),// Disable scorers must be explicitly set to false they are on by default
232
- scorers:disableScorers===false?void 0:step.scorers,validateInputs:this.options?.validateInputs});if(step.scorers){await this.runScorers({scorers:step.scorers,runId,input:inputData,output:result,workflowId,stepId:step.id,runtimeContext,disableScorers,tracingContext:{currentSpan:tracingContext.currentSpan}});}if(suspended){execResults={status:"suspended",suspendPayload:suspended.payload,suspendedAt:Date.now()};}else if(bailed){execResults={status:"bailed",output:bailed.payload,endedAt:Date.now()};}else {execResults={status:"success",output:result,endedAt:Date.now()};}break;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_STEP_INVOKE_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId,stepId:step.id}},`Error executing step ${step.id}: `);stepAISpan?.error({error,attributes:{status:"failed"}});execResults={status:"failed",error:error?.stack,endedAt:Date.now()};}}if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,stepCallId,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,stepCallId,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,stepCallId,metadata:{}}});}}if(execResults.status!="failed"){stepAISpan?.end({output:execResults.output,attributes:{status:execResults.status}});}return {...stepInfo,...execResults};}async runScorers({scorers,runId,input,output,workflowId,stepId,runtimeContext,disableScorers,tracingContext}){let scorersToUse=scorers;if(typeof scorersToUse==="function"){try{scorersToUse=await scorersToUse({runtimeContext});}catch(error){this.preprocessExecutionError(error,{id:"WORKFLOW_FAILED_TO_FETCH_SCORERS",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{runId,workflowId,stepId}},"Error fetching scorers: ");}}if(!disableScorers&&scorersToUse&&Object.keys(scorersToUse||{}).length>0){for(const[_id,scorerObject]of Object.entries(scorersToUse||{})){runScorer({scorerId:scorerObject.name,scorerObject,runId,input,output,runtimeContext,entity:{id:workflowId,stepId},structuredOutput:true,source:"LIVE",entityType:"WORKFLOW",tracingContext});}}}async executeParallel({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const parallelSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_parallel"/* WORKFLOW_PARALLEL */,name:`parallel: '${entry.steps.length} branches'`,input:this.getStepOutput(stepResults,prevStep),attributes:{branchCount:entry.steps.length,parallelSteps:entry.steps.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)},tracingPolicy:this.options?.tracingPolicy});let execResults;const results=await Promise.all(entry.steps.map((step,i)=>this.executeEntry({workflowId,runId,resourceId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,i],suspendedPaths:executionContext.suspendedPaths,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:parallelSpan},emitter,abortController,runtimeContext,writableStream,disableScorers})));const hasFailed=results.find(result=>result.result.status==="failed");const hasSuspended=results.find(result=>result.result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.result.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.result.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:results.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[entry.steps[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){parallelSpan?.error({error:new Error(execResults.error)});}else {parallelSpan?.end({output:execResults.output||execResults});}return execResults;}async executeConditional({workflowId,runId,resourceId,entry,prevOutput,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const conditionalSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_conditional"/* WORKFLOW_CONDITIONAL */,name:`conditional: '${entry.conditions.length} conditions'`,input:prevOutput,attributes:{conditionCount:entry.conditions.length},tracingPolicy:this.options?.tracingPolicy});let execResults;const truthyIndexes=(await Promise.all(entry.conditions.map(async(cond,index)=>{const evalSpan=conditionalSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition '${index}'`,input:prevOutput,attributes:{conditionIndex:index},tracingPolicy:this.options?.tracingPolicy});try{const result=await cond({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
232
+ scorers:disableScorers===false?void 0:step.scorers,validateInputs:this.options?.validateInputs});if(step.scorers){await this.runScorers({scorers:step.scorers,runId,input:inputData,output:result,workflowId,stepId:step.id,runtimeContext,disableScorers,tracingContext:{currentSpan:stepAISpan}});}if(suspended){execResults={status:"suspended",suspendPayload:suspended.payload,suspendedAt:Date.now()};}else if(bailed){execResults={status:"bailed",output:bailed.payload,endedAt:Date.now()};}else {execResults={status:"success",output:result,endedAt:Date.now()};}break;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_STEP_INVOKE_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId,stepId:step.id}},`Error executing step ${step.id}: `);stepAISpan?.error({error,attributes:{status:"failed"}});execResults={status:"failed",error:error?.stack,endedAt:Date.now()};}}if(!skipEmits){await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,stepCallId,...execResults}});}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,stepCallId,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,stepCallId,metadata:{}}});}}if(execResults.status!="failed"){stepAISpan?.end({output:execResults.output,attributes:{status:execResults.status}});}return {...stepInfo,...execResults};}async runScorers({scorers,runId,input,output,workflowId,stepId,runtimeContext,disableScorers,tracingContext}){let scorersToUse=scorers;if(typeof scorersToUse==="function"){try{scorersToUse=await scorersToUse({runtimeContext});}catch(error){this.preprocessExecutionError(error,{id:"WORKFLOW_FAILED_TO_FETCH_SCORERS",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{runId,workflowId,stepId}},"Error fetching scorers: ");}}if(!disableScorers&&scorersToUse&&Object.keys(scorersToUse||{}).length>0){for(const[_id,scorerObject]of Object.entries(scorersToUse||{})){runScorer({scorerId:scorerObject.name,scorerObject,runId,input,output,runtimeContext,entity:{id:workflowId,stepId},structuredOutput:true,source:"LIVE",entityType:"WORKFLOW",tracingContext});}}}async executeParallel({workflowId,runId,resourceId,entry,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const parallelSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_parallel"/* WORKFLOW_PARALLEL */,name:`parallel: '${entry.steps.length} branches'`,input:this.getStepOutput(stepResults,prevStep),attributes:{branchCount:entry.steps.length,parallelSteps:entry.steps.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)},tracingPolicy:this.options?.tracingPolicy});let execResults;const results=await Promise.all(entry.steps.map((step,i)=>this.executeEntry({workflowId,runId,resourceId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,i],suspendedPaths:executionContext.suspendedPaths,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:parallelSpan},emitter,abortController,runtimeContext,writableStream,disableScorers})));const hasFailed=results.find(result=>result.result.status==="failed");const hasSuspended=results.find(result=>result.result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.result.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.result.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:results.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[entry.steps[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){parallelSpan?.error({error:new Error(execResults.error)});}else {parallelSpan?.end({output:execResults.output||execResults});}return execResults;}async executeConditional({workflowId,runId,resourceId,entry,prevOutput,prevStep,serializedStepGraph,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers}){const conditionalSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_conditional"/* WORKFLOW_CONDITIONAL */,name:`conditional: '${entry.conditions.length} conditions'`,input:prevOutput,attributes:{conditionCount:entry.conditions.length},tracingPolicy:this.options?.tracingPolicy});let execResults;const truthyIndexes=(await Promise.all(entry.conditions.map(async(cond,index)=>{const evalSpan=conditionalSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition '${index}'`,input:prevOutput,attributes:{conditionIndex:index},tracingPolicy:this.options?.tracingPolicy});try{const result=await cond({runId,workflowId,mastra:this.mastra,runtimeContext,inputData:prevOutput,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),// TODO: this function shouldn't have suspend probably?
233
233
  suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:randomUUID(),name:"conditional",runId},writableStream)});evalSpan?.end({output:result,attributes:{result:!!result}});return result?index:null;}catch(e){const error=this.preprocessExecutionError(e,{id:"WORKFLOW_CONDITION_EVALUATION_FAILED",domain:"MASTRA_WORKFLOW"/* MASTRA_WORKFLOW */,category:"USER"/* USER */,details:{workflowId,runId}},"Error evaluating condition: ");evalSpan?.error({error,attributes:{result:false}});return null;}}))).filter(index=>index!==null);const stepsToRun=entry.steps.filter((_,index)=>truthyIndexes.includes(index));conditionalSpan?.update({attributes:{truthyIndexes,selectedSteps:stepsToRun.map(s=>s.type==="step"?s.step.id:`control-${s.type}`)}});const stepsToExecute=stepsToRun.filter(step=>{if(resume&&step.type==="step"){const existingResult=stepResults[step.step.id];return !existingResult||existingResult.status==="suspended"||existingResult.status==="failed";}return true;});const results=await Promise.all(stepsToExecute.map((step,_index)=>this.executeEntry({workflowId,runId,resourceId,entry:step,prevStep,stepResults,serializedStepGraph,resume,executionContext:{workflowId,runId,executionPath:[...executionContext.executionPath,stepsToRun.indexOf(step)],suspendedPaths:executionContext.suspendedPaths,retryConfig:executionContext.retryConfig,executionSpan:executionContext.executionSpan,state:executionContext.state},tracingContext:{currentSpan:conditionalSpan},emitter,abortController,runtimeContext,writableStream,disableScorers})));const mergedStepResults={...stepResults};results.forEach(result=>{if("stepResults"in result&&result.stepResults){Object.assign(mergedStepResults,result.stepResults);}});const allResults=stepsToRun.map(step=>{if(step.type==="step"){const stepResult=mergedStepResults[step.step.id];if(stepResult){return {result:stepResult};}}return {result:{status:"success",output:{}}};}).filter(Boolean);const hasFailed=allResults.find(result=>result.result.status==="failed");const hasSuspended=allResults.find(result=>result.result.status==="suspended");if(hasFailed){execResults={status:"failed",error:hasFailed.result.error};}else if(hasSuspended){execResults={status:"suspended",payload:hasSuspended.result.suspendPayload};}else if(abortController?.signal?.aborted){execResults={status:"canceled"};}else {execResults={status:"success",output:allResults.reduce((acc,result,index)=>{if(result.result.status==="success"){acc[stepsToRun[index].step.id]=result.result.output;}return acc;},{})};}if(execResults.status==="failed"){conditionalSpan?.error({error:new Error(execResults.error)});}else {conditionalSpan?.end({output:execResults.output||execResults});}return execResults;}async executeLoop({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,condition}=entry;const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: '${entry.loopType}'`,input:prevOutput,attributes:{loopType:entry.loopType},tracingPolicy:this.options?.tracingPolicy});let isTrue=true;const prevIterationCount=stepResults[step.id]?.metadata?.iterationCount;let iteration=prevIterationCount?prevIterationCount-1:0;const prevPayload=stepResults[step.id]?.payload;let result={status:"success",output:prevPayload??prevOutput};let currentResume=resume;do{result=await this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:currentResume,prevOutput:result.output,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph,iterationCount:iteration+1});if(currentResume&&result.status!=="suspended"){currentResume=void 0;}if(result.status!=="success"){loopSpan?.end({attributes:{totalIterations:iteration}});return result;}const evalSpan=loopSpan?.createChildSpan({type:"workflow_conditional_eval"/* WORKFLOW_CONDITIONAL_EVAL */,name:`condition: '${entry.loopType}'`,input:selectFields(result.output,["stepResult","output.text","output.object","messages"]),attributes:{conditionIndex:iteration},tracingPolicy:this.options?.tracingPolicy});isTrue=await condition({workflowId,runId,mastra:this.mastra,runtimeContext,inputData:result.output,state:executionContext.state,setState:state=>{executionContext.state=state;},runCount:-1,tracingContext:{currentSpan:evalSpan},iterationCount:iteration+1,getInitData:()=>stepResults?.input,getStepResult:getStepResult.bind(this,stepResults),suspend:async _suspendPayload=>{},bail:()=>{},abort:()=>{abortController?.abort();},[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:executionContext.format,engine:{},abortSignal:abortController?.signal,writer:new ToolStream({prefix:"workflow-step",callId:randomUUID(),name:"loop",runId},writableStream)});evalSpan?.end({output:isTrue});iteration++;}while(entry.loopType==="dowhile"?isTrue:!isTrue);loopSpan?.end({output:result.output,attributes:{totalIterations:iteration}});return result;}async executeForeach({workflowId,runId,resourceId,entry,prevOutput,stepResults,resume,executionContext,tracingContext,emitter,abortController,runtimeContext,writableStream,disableScorers,serializedStepGraph}){const{step,opts}=entry;const results=[];const concurrency=opts.concurrency;const startTime=resume?.steps[0]===step.id?void 0:Date.now();const resumeTime=resume?.steps[0]===step.id?Date.now():void 0;const stepInfo={...stepResults[step.id],...(resume?.steps[0]===step.id?{resumePayload:resume?.resumePayload}:{payload:prevOutput}),...(startTime?{startedAt:startTime}:{}),...(resumeTime?{resumedAt:resumeTime}:{})};const loopSpan=tracingContext.currentSpan?.createChildSpan({type:"workflow_loop"/* WORKFLOW_LOOP */,name:`loop: 'foreach'`,input:prevOutput,attributes:{loopType:"foreach",concurrency},tracingPolicy:this.options?.tracingPolicy});await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,status:"running",...stepInfo},workflowState:{status:"running",steps:{...stepResults,[step.id]:{status:"running",...stepInfo}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-start",payload:{id:step.id,...stepInfo,status:"running"}});const prevPayload=stepResults[step.id];const resumeIndex=prevPayload?.status==="suspended"?prevPayload?.suspendPayload?.__workflow_meta?.foreachIndex||0:0;for(let i=resumeIndex;i<prevOutput.length;i+=concurrency){const items=prevOutput.slice(i,i+concurrency);const itemsResults=await Promise.all(items.map((item,j)=>{return this.executeStep({workflowId,runId,resourceId,step,stepResults,executionContext,resume:resumeIndex===i+j?resume:void 0,prevOutput:item,tracingContext:{currentSpan:loopSpan},emitter,abortController,runtimeContext,skipEmits:true,writableStream,disableScorers,serializedStepGraph});}));for(const result of itemsResults){if(result.status!=="success"){const{status,error,suspendPayload,suspendedAt,endedAt,output}=result;const execResults={status,error,suspendPayload,suspendedAt,endedAt,output};await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,...execResults},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,...execResults}},result:null,error:null}},eventTimestamp:Date.now()});if(execResults.status==="suspended"){await emitter.emit("watch-v2",{type:"workflow-step-suspended",payload:{id:step.id,...execResults}});return {...stepInfo,status:"suspended",suspendPayload:{...execResults.suspendPayload,__workflow_meta:{...execResults.suspendPayload?.__workflow_meta,foreachIndex:i}},//@ts-ignore
234
234
  endedAt:Date.now()};}else {await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,...execResults}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});return result;}}results.push(result?.output);}}await emitter.emit("watch",{type:"watch",payload:{currentStep:{id:step.id,...stepInfo,status:"success",output:results,endedAt:Date.now()},workflowState:{status:"running",steps:{...stepResults,[step.id]:{...stepInfo,status:"success",output:results,endedAt:Date.now()}},result:null,error:null}},eventTimestamp:Date.now()});await emitter.emit("watch-v2",{type:"workflow-step-result",payload:{id:step.id,status:"success",output:results,endedAt:Date.now()}});await emitter.emit("watch-v2",{type:"workflow-step-finish",payload:{id:step.id,metadata:{}}});loopSpan?.end({output:results});return {...stepInfo,status:"success",output:results,//@ts-ignore
235
235
  endedAt:Date.now()};}async persistStepUpdate({workflowId,runId,resourceId,stepResults,serializedStepGraph,executionContext,workflowStatus,result,error,runtimeContext}){const shouldPersistSnapshot=this.options?.shouldPersistSnapshot?.({stepResults,workflowStatus});if(!shouldPersistSnapshot){return;}const runtimeContextObj={};runtimeContext.forEach((value,key)=>{runtimeContextObj[key]=value;});await this.mastra?.getStorage()?.persistWorkflowSnapshot({workflowName:workflowId,runId,resourceId,snapshot:{runId,status:workflowStatus,value:executionContext.state,context:stepResults,activePaths:[],serializedStepGraph,suspendedPaths:executionContext.suspendedPaths,waitingPaths:{},result,error,runtimeContext:runtimeContextObj,// @ts-ignore
@@ -240,7 +240,7 @@ inputSchema:z.object({prompt:z.string()// resourceId: z.string().optional(),
240
240
  }),// @ts-ignore
241
241
  outputSchema:z.object({text:z.string()}),execute:async({inputData,[EMITTER_SYMBOL]:emitter,[STREAM_FORMAT_SYMBOL]:streamFormat,runtimeContext,abortSignal,abort,writer})=>{let streamPromise={};streamPromise.promise=new Promise((resolve,reject)=>{streamPromise.resolve=resolve;streamPromise.reject=reject;});const toolData={name:params.name,args:inputData};let stream;if((await params.getModel()).specificationVersion==="v1"){const{fullStream}=await params.streamLegacy(inputData.prompt,{// resourceId: inputData.resourceId,
242
242
  // threadId: inputData.threadId,
243
- runtimeContext,onFinish:result=>{streamPromise.resolve(result.text);},abortSignal});stream=fullStream;}else {const modelOutput=await params.stream(inputData.prompt,{runtimeContext,onFinish:result=>{streamPromise.resolve(result.text);},abortSignal});stream=modelOutput.fullStream;}if(streamFormat==="aisdk"){await emitter.emit("watch-v2",{type:"tool-call-streaming-start",...(toolData??{})});for await(const chunk of stream){if(chunk.type==="text-delta"){await emitter.emit("watch-v2",{type:"tool-call-delta",...(toolData??{}),argsTextDelta:chunk.textDelta});}}await emitter.emit("watch-v2",{type:"tool-call-streaming-finish",...(toolData??{})});}else {for await(const chunk of stream){await writer.write(chunk);}}if(abortSignal.aborted){return abort();}return {text:await streamPromise.promise};},component:params.component};}if(params instanceof Tool){if(!params.inputSchema||!params.outputSchema){throw new Error("Tool must have input and output schemas defined");}return {// TODO: tool probably should have strong id type
243
+ runtimeContext,onFinish:result=>{streamPromise.resolve(result.text);},abortSignal});stream=fullStream;}else {const modelOutput=await params.stream(inputData.prompt,{runtimeContext,onFinish:result=>{streamPromise.resolve(result.text);},abortSignal});stream=modelOutput.fullStream;}if(streamFormat==="legacy"){await emitter.emit("watch-v2",{type:"tool-call-streaming-start",...(toolData??{})});for await(const chunk of stream){if(chunk.type==="text-delta"){await emitter.emit("watch-v2",{type:"tool-call-delta",...(toolData??{}),argsTextDelta:chunk.textDelta});}}await emitter.emit("watch-v2",{type:"tool-call-streaming-finish",...(toolData??{})});}else {for await(const chunk of stream){await writer.write(chunk);}}if(abortSignal.aborted){return abort();}return {text:await streamPromise.promise};},component:params.component};}if(params instanceof Tool){if(!params.inputSchema||!params.outputSchema){throw new Error("Tool must have input and output schemas defined");}return {// TODO: tool probably should have strong id type
244
244
  // @ts-ignore
245
245
  id:params.id,description:params.description,inputSchema:params.inputSchema,outputSchema:params.outputSchema,execute:async({inputData,mastra,runtimeContext,tracingContext,suspend,resumeData})=>{return params.execute({context:inputData,mastra,runtimeContext,tracingContext,suspend,resumeData});},component:"TOOL"};}return {id:params.id,description:params.description,inputSchema:params.inputSchema,stateSchema:params.stateSchema,outputSchema:params.outputSchema,resumeSchema:params.resumeSchema,suspendSchema:params.suspendSchema,scorers:params.scorers,retries:params.retries,execute:params.execute.bind(params)};}function cloneStep(step,opts){return {id:opts.id,description:step.description,inputSchema:step.inputSchema,outputSchema:step.outputSchema,execute:step.execute,retries:step.retries,component:step.component};}function createWorkflow(params){return new Workflow(params);}function cloneWorkflow(workflow,opts){const wf=new Workflow({id:opts.id,inputSchema:workflow.inputSchema,outputSchema:workflow.outputSchema,steps:workflow.stepDefs,mastra:workflow.mastra});wf.setStepFlow(workflow.stepGraph);wf.commit();return wf;}var Workflow=class extends MastraBase{id;description;inputSchema;outputSchema;stateSchema;steps;stepDefs;stepFlow;serializedStepFlow;executionEngine;executionGraph;#options;retryConfig;#mastra;#runs=/* @__PURE__ */new Map();constructor({mastra,id,inputSchema,outputSchema,stateSchema,description,executionEngine,retryConfig,steps,options={}}){super({name:id,component:RegisteredLogger.WORKFLOW});this.id=id;this.description=description;this.inputSchema=inputSchema;this.outputSchema=outputSchema;this.stateSchema=stateSchema;this.retryConfig=retryConfig??{attempts:0,delay:0};this.executionGraph=this.buildExecutionGraph();this.stepFlow=[];this.serializedStepFlow=[];this.#mastra=mastra;this.steps={};this.stepDefs=steps;this.#options={validateInputs:options.validateInputs??false,shouldPersistSnapshot:options.shouldPersistSnapshot??(()=>true),tracingPolicy:options.tracingPolicy};if(!executionEngine){this.executionEngine=new DefaultExecutionEngine({mastra:this.#mastra,options:this.#options});}else {this.executionEngine=executionEngine;}this.#runs=/* @__PURE__ */new Map();}get runs(){return this.#runs;}get mastra(){return this.#mastra;}get options(){return this.#options;}__registerMastra(mastra){this.#mastra=mastra;this.executionEngine.__registerMastra(mastra);}__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}}setStepFlow(stepFlow){this.stepFlow=stepFlow;}/**
246
246
  * Adds a step to the workflow
@@ -310,11 +310,11 @@ async execute({runId,inputData,resumeData,state,setState,suspend,resume,[EMITTER
310
310
  * Starts the workflow execution with the provided input
311
311
  * @param input The input data for the workflow
312
312
  * @returns A promise that resolves to the workflow output
313
- */async start({inputData,initialState,runtimeContext,writableStream,tracingContext,tracingOptions,outputOptions}){return this._start({inputData,initialState,runtimeContext,writableStream,tracingContext,tracingOptions,format:"aisdk",outputOptions});}/**
313
+ */async start({inputData,initialState,runtimeContext,writableStream,tracingContext,tracingOptions,outputOptions}){return this._start({inputData,initialState,runtimeContext,writableStream,tracingContext,tracingOptions,format:"legacy",outputOptions});}/**
314
314
  * Starts the workflow execution with the provided input as a stream
315
315
  * @param input The input data for the workflow
316
316
  * @returns A promise that resolves to the workflow output
317
- */stream({inputData,runtimeContext,onChunk,tracingContext,tracingOptions}={}){if(this.closeStreamAction){return {stream:this.observeStream().stream,getWorkflowState:()=>this.executionResults};}const{readable,writable}=new TransformStream();const writer=writable.getWriter();const unwatch=this.watch(async event=>{try{const e={...event,type:event.type.replace("workflow-","")};await writer.write(e);if(onChunk){await onChunk(e);}}catch{}},"watch-v2");this.closeStreamAction=async()=>{this.emitter.emit("watch-v2",{type:"workflow-finish",payload:{runId:this.runId}});unwatch();await Promise.all(this.#observerHandlers.map(handler=>handler()));this.#observerHandlers=[];try{await writer.close();}catch(err){console.error("Error closing stream:",err);}finally{writer.releaseLock();}};this.emitter.emit("watch-v2",{type:"workflow-start",payload:{runId:this.runId}});this.executionResults=this._start({inputData,runtimeContext,format:"aisdk",tracingContext,tracingOptions}).then(result=>{if(result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}return result;});return {stream:readable,getWorkflowState:()=>this.executionResults};}/**
317
+ */stream({inputData,runtimeContext,onChunk,tracingContext,tracingOptions}={}){if(this.closeStreamAction){return {stream:this.observeStream().stream,getWorkflowState:()=>this.executionResults};}const{readable,writable}=new TransformStream();const writer=writable.getWriter();const unwatch=this.watch(async event=>{try{const e={...event,type:event.type.replace("workflow-","")};await writer.write(e);if(onChunk){await onChunk(e);}}catch{}},"watch-v2");this.closeStreamAction=async()=>{this.emitter.emit("watch-v2",{type:"workflow-finish",payload:{runId:this.runId}});unwatch();await Promise.all(this.#observerHandlers.map(handler=>handler()));this.#observerHandlers=[];try{await writer.close();}catch(err){console.error("Error closing stream:",err);}finally{writer.releaseLock();}};this.emitter.emit("watch-v2",{type:"workflow-start",payload:{runId:this.runId}});this.executionResults=this._start({inputData,runtimeContext,format:"legacy",tracingContext,tracingOptions}).then(result=>{if(result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}return result;});return {stream:readable,getWorkflowState:()=>this.executionResults};}/**
318
318
  * Observe the workflow stream
319
319
  * @returns A readable stream of the workflow events
320
320
  */observeStream(){const{readable,writable}=new TransformStream();const writer=writable.getWriter();const unwatch=this.watch(async event=>{try{const e={...event,type:event.type.replace("workflow-","")};await writer.write(e);}catch{}},"watch-v2");this.#observerHandlers.push(async()=>{unwatch();try{await writer.close();}catch(err){console.error("Error closing stream:",err);}finally{writer.releaseLock();}});return {stream:readable};}/**
@@ -324,11 +324,11 @@ async execute({runId,inputData,resumeData,state,setState,suspend,resume,[EMITTER
324
324
  * Starts the workflow execution with the provided input as a stream
325
325
  * @param input The input data for the workflow
326
326
  * @returns A promise that resolves to the workflow output
327
- */streamVNext({inputData,runtimeContext,tracingContext,tracingOptions,format,closeOnSuspend=true,onChunk}={}){if(this.closeStreamAction&&this.activeStream){return this.activeStream;}this.closeStreamAction=async()=>{};this.activeStream=new MastraWorkflowStream({run:this,createStream:()=>{const{readable,writable}=new TransformStream({transform(chunk,controller){controller.enqueue(chunk);}});let buffer=[];let isWriting=false;const tryWrite=async()=>{const chunkToWrite=buffer;buffer=[];if(chunkToWrite.length===0||isWriting){return;}isWriting=true;let watchWriter=writable.getWriter();try{for(const chunk of chunkToWrite){await watchWriter.write(chunk);if(onChunk){await onChunk(chunk);}}}finally{watchWriter.releaseLock();}isWriting=false;setImmediate(tryWrite);};const unwatch=this.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{buffer.push({type,runId:this.runId,from,payload:{stepName:payload.id,...payload}});await tryWrite();},"watch-v2");this.closeStreamAction=async()=>{unwatch();await Promise.all(this.#observerHandlers.map(handler=>handler()));this.#observerHandlers=[];try{await writable.close();}catch(err){console.error("Error closing stream:",err);}};const executionResults=this._start({inputData,runtimeContext,tracingContext,tracingOptions,writableStream:writable,format}).then(result=>{if(closeOnSuspend){this.closeStreamAction?.().catch(()=>{});}else if(result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}return result;});this.executionResults=executionResults;return readable;}});return this.activeStream;}/**
327
+ */streamVNext({inputData,runtimeContext,tracingContext,tracingOptions,closeOnSuspend=true,onChunk}={}){if(this.closeStreamAction&&this.activeStream){return this.activeStream;}this.closeStreamAction=async()=>{};this.activeStream=new MastraWorkflowStream({run:this,createStream:()=>{const{readable,writable}=new TransformStream({transform(chunk,controller){controller.enqueue(chunk);}});let buffer=[];let isWriting=false;const tryWrite=async()=>{const chunkToWrite=buffer;buffer=[];if(chunkToWrite.length===0||isWriting){return;}isWriting=true;let watchWriter=writable.getWriter();try{for(const chunk of chunkToWrite){await watchWriter.write(chunk);if(onChunk){await onChunk(chunk);}}}finally{watchWriter.releaseLock();}isWriting=false;setImmediate(tryWrite);};const unwatch=this.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{buffer.push({type,runId:this.runId,from,payload:{stepName:payload.id,...payload}});await tryWrite();},"watch-v2");this.closeStreamAction=async()=>{unwatch();await Promise.all(this.#observerHandlers.map(handler=>handler()));this.#observerHandlers=[];try{await writable.close();}catch(err){console.error("Error closing stream:",err);}};const executionResults=this._start({inputData,runtimeContext,tracingContext,tracingOptions,writableStream:writable}).then(result=>{if(closeOnSuspend){this.closeStreamAction?.().catch(()=>{});}else if(result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}return result;});this.executionResults=executionResults;return readable;}});return this.activeStream;}/**
328
328
  * Resumes the workflow execution with the provided input as a stream
329
329
  * @param input The input data for the workflow
330
330
  * @returns A promise that resolves to the workflow output
331
- */resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,tracingOptions,format,onChunk}={}){this.closeStreamAction=async()=>{};this.activeStream=new MastraWorkflowStream({run:this,createStream:()=>{const{readable,writable}=new TransformStream({transform(chunk,controller){controller.enqueue(chunk);}});let buffer=[];let isWriting=false;const tryWrite=async()=>{const chunkToWrite=buffer;buffer=[];if(chunkToWrite.length===0||isWriting){return;}isWriting=true;let watchWriter=writable.getWriter();try{for(const chunk of chunkToWrite){await watchWriter.write(chunk);if(onChunk){await onChunk(chunk);}}}finally{watchWriter.releaseLock();}isWriting=false;setImmediate(tryWrite);};const unwatch=this.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{buffer.push({type,runId:this.runId,from,payload:{stepName:payload.id,...payload}});await tryWrite();},"watch-v2");this.closeStreamAction=async()=>{unwatch();await Promise.all(this.#observerHandlers.map(handler=>handler()));this.#observerHandlers=[];try{await writable.close();}catch(err){console.error("Error closing stream:",err);}};const executionResults=this._resume({resumeData,step,runtimeContext,tracingContext,tracingOptions,writableStream:writable,format,isVNext:true}).then(result=>{this.closeStreamAction?.().catch(()=>{});return result;});this.executionResults=executionResults;return readable;}});return this.activeStream;}watch(cb,type="watch"){const watchCb=event=>{this.updateState(event.payload);cb({type:event.type,payload:this.getState(),eventTimestamp:event.eventTimestamp});};const nestedWatchCb=({event,workflowId})=>{try{const{type:type2,payload,eventTimestamp}=event;const prefixedSteps=Object.fromEntries(Object.entries(payload?.workflowState?.steps??{}).map(([stepId,step])=>[`${workflowId}.${stepId}`,step]));const newPayload={currentStep:{...payload?.currentStep,id:`${workflowId}.${payload?.currentStep?.id}`},workflowState:{steps:prefixedSteps}};this.updateState(newPayload);cb({type:type2,payload:this.getState(),eventTimestamp});}catch(e){console.error(e);}};const nestedWatchV2Cb=({event,workflowId})=>{this.emitter.emit("watch-v2",{...event,...(event.payload?.id?{payload:{...event.payload,id:`${workflowId}.${event.payload.id}`}}:{})});};if(type==="watch"){this.emitter.on("watch",watchCb);this.emitter.on("nested-watch",nestedWatchCb);}else if(type==="watch-v2"){this.emitter.on("watch-v2",cb);this.emitter.on("nested-watch-v2",nestedWatchV2Cb);}return ()=>{if(type==="watch-v2"){this.emitter.off("watch-v2",cb);this.emitter.off("nested-watch-v2",nestedWatchV2Cb);}else {this.emitter.off("watch",watchCb);this.emitter.off("nested-watch",nestedWatchCb);}};}async watchAsync(cb,type="watch"){return this.watch(cb,type);}async resume(params){return this._resume(params);}async _resume(params){const snapshot=await this.#mastra?.getStorage()?.loadWorkflowSnapshot({workflowName:this.workflowId,runId:this.runId});if(!snapshot){throw new Error("No snapshot found for this workflow run: "+this.workflowId+" "+this.runId);}let steps;if(params.step){steps=(Array.isArray(params.step)?params.step:[params.step]).map(step=>typeof step==="string"?step:step?.id);}else {const suspendedStepPaths=[];Object.entries(snapshot?.suspendedPaths??{}).forEach(([stepId,_executionPath])=>{const stepResult=snapshot?.context?.[stepId];if(stepResult&&typeof stepResult==="object"&&"status"in stepResult){const stepRes=stepResult;if(stepRes.status==="suspended"){const nestedPath=stepRes.suspendPayload?.__workflow_meta?.path;if(nestedPath&&Array.isArray(nestedPath)){suspendedStepPaths.push([stepId,...nestedPath]);}else {suspendedStepPaths.push([stepId]);}}}});if(suspendedStepPaths.length===0){throw new Error("No suspended steps found in this workflow run");}if(suspendedStepPaths.length===1){steps=suspendedStepPaths[0];}else {const pathStrings=suspendedStepPaths.map(path=>`[${path.join(", ")}]`);throw new Error(`Multiple suspended steps found: ${pathStrings.join(", ")}. Please specify which step to resume using the "step" parameter.`);}}if(!params.runCount){if(snapshot.status!=="suspended"){throw new Error("This workflow run was not suspended");}const suspendedStepIds=Object.keys(snapshot?.suspendedPaths??{});const isStepSuspended=suspendedStepIds.includes(steps?.[0]??"");if(!isStepSuspended){throw new Error(`This workflow step "${steps?.[0]}" was not suspended. Available suspended steps: [${suspendedStepIds.join(", ")}]`);}}const suspendedStep=this.workflowSteps[steps?.[0]??""];const resumeDataToUse=await this._validateResumeData(params.resumeData,suspendedStep);let runtimeContextInput;if(params.runCount&&params.runCount>0&&params.runtimeContext){runtimeContextInput=params.runtimeContext.get("__mastraWorflowInputData");params.runtimeContext.delete("__mastraWorflowInputData");}const stepResults={...(snapshot?.context??{}),input:runtimeContextInput??snapshot?.context?.input};let runtimeContextToUse=params.runtimeContext??new RuntimeContext();Object.entries(snapshot?.runtimeContext??{}).forEach(([key,value])=>{if(!runtimeContextToUse.has(key)){runtimeContextToUse.set(key,value);}});const workflowAISpan=getOrCreateSpan({type:"workflow_run"/* WORKFLOW_RUN */,name:`workflow run: '${this.workflowId}'`,input:resumeDataToUse,attributes:{workflowId:this.workflowId},tracingPolicy:this.tracingPolicy,tracingOptions:params.tracingOptions,tracingContext:params.tracingContext,runtimeContext:runtimeContextToUse});const traceId=getValidTraceId(workflowAISpan);const executionResultPromise=this.executionEngine.execute({workflowId:this.workflowId,runId:this.runId,resourceId:this.resourceId,graph:this.executionGraph,serializedStepGraph:this.serializedStepGraph,input:snapshot?.context?.input,initialState:snapshot?.value??{},resume:{steps,stepResults,resumePayload:resumeDataToUse,// @ts-ignore
331
+ */resumeStreamVNext({step,resumeData,runtimeContext,tracingContext,tracingOptions,onChunk}={}){this.closeStreamAction=async()=>{};this.activeStream=new MastraWorkflowStream({run:this,createStream:()=>{const{readable,writable}=new TransformStream({transform(chunk,controller){controller.enqueue(chunk);}});let buffer=[];let isWriting=false;const tryWrite=async()=>{const chunkToWrite=buffer;buffer=[];if(chunkToWrite.length===0||isWriting){return;}isWriting=true;let watchWriter=writable.getWriter();try{for(const chunk of chunkToWrite){await watchWriter.write(chunk);if(onChunk){await onChunk(chunk);}}}finally{watchWriter.releaseLock();}isWriting=false;setImmediate(tryWrite);};const unwatch=this.watch(async({type,from="WORKFLOW"/* WORKFLOW */,payload})=>{buffer.push({type,runId:this.runId,from,payload:{stepName:payload.id,...payload}});await tryWrite();},"watch-v2");this.closeStreamAction=async()=>{unwatch();await Promise.all(this.#observerHandlers.map(handler=>handler()));this.#observerHandlers=[];try{await writable.close();}catch(err){console.error("Error closing stream:",err);}};const executionResults=this._resume({resumeData,step,runtimeContext,tracingContext,tracingOptions,writableStream:writable,isVNext:true}).then(result=>{this.closeStreamAction?.().catch(()=>{});return result;});this.executionResults=executionResults;return readable;}});return this.activeStream;}watch(cb,type="watch"){const watchCb=event=>{this.updateState(event.payload);cb({type:event.type,payload:this.getState(),eventTimestamp:event.eventTimestamp});};const nestedWatchCb=({event,workflowId})=>{try{const{type:type2,payload,eventTimestamp}=event;const prefixedSteps=Object.fromEntries(Object.entries(payload?.workflowState?.steps??{}).map(([stepId,step])=>[`${workflowId}.${stepId}`,step]));const newPayload={currentStep:{...payload?.currentStep,id:`${workflowId}.${payload?.currentStep?.id}`},workflowState:{steps:prefixedSteps}};this.updateState(newPayload);cb({type:type2,payload:this.getState(),eventTimestamp});}catch(e){console.error(e);}};const nestedWatchV2Cb=({event,workflowId})=>{this.emitter.emit("watch-v2",{...event,...(event.payload?.id?{payload:{...event.payload,id:`${workflowId}.${event.payload.id}`}}:{})});};if(type==="watch"){this.emitter.on("watch",watchCb);this.emitter.on("nested-watch",nestedWatchCb);}else if(type==="watch-v2"){this.emitter.on("watch-v2",cb);this.emitter.on("nested-watch-v2",nestedWatchV2Cb);}return ()=>{if(type==="watch-v2"){this.emitter.off("watch-v2",cb);this.emitter.off("nested-watch-v2",nestedWatchV2Cb);}else {this.emitter.off("watch",watchCb);this.emitter.off("nested-watch",nestedWatchCb);}};}async watchAsync(cb,type="watch"){return this.watch(cb,type);}async resume(params){return this._resume(params);}async _resume(params){const snapshot=await this.#mastra?.getStorage()?.loadWorkflowSnapshot({workflowName:this.workflowId,runId:this.runId});if(!snapshot){throw new Error("No snapshot found for this workflow run: "+this.workflowId+" "+this.runId);}let steps;if(params.step){steps=(Array.isArray(params.step)?params.step:[params.step]).map(step=>typeof step==="string"?step:step?.id);}else {const suspendedStepPaths=[];Object.entries(snapshot?.suspendedPaths??{}).forEach(([stepId,_executionPath])=>{const stepResult=snapshot?.context?.[stepId];if(stepResult&&typeof stepResult==="object"&&"status"in stepResult){const stepRes=stepResult;if(stepRes.status==="suspended"){const nestedPath=stepRes.suspendPayload?.__workflow_meta?.path;if(nestedPath&&Array.isArray(nestedPath)){suspendedStepPaths.push([stepId,...nestedPath]);}else {suspendedStepPaths.push([stepId]);}}}});if(suspendedStepPaths.length===0){throw new Error("No suspended steps found in this workflow run");}if(suspendedStepPaths.length===1){steps=suspendedStepPaths[0];}else {const pathStrings=suspendedStepPaths.map(path=>`[${path.join(", ")}]`);throw new Error(`Multiple suspended steps found: ${pathStrings.join(", ")}. Please specify which step to resume using the "step" parameter.`);}}if(!params.runCount){if(snapshot.status!=="suspended"){throw new Error("This workflow run was not suspended");}const suspendedStepIds=Object.keys(snapshot?.suspendedPaths??{});const isStepSuspended=suspendedStepIds.includes(steps?.[0]??"");if(!isStepSuspended){throw new Error(`This workflow step "${steps?.[0]}" was not suspended. Available suspended steps: [${suspendedStepIds.join(", ")}]`);}}const suspendedStep=this.workflowSteps[steps?.[0]??""];const resumeDataToUse=await this._validateResumeData(params.resumeData,suspendedStep);let runtimeContextInput;if(params.runCount&&params.runCount>0&&params.runtimeContext){runtimeContextInput=params.runtimeContext.get("__mastraWorflowInputData");params.runtimeContext.delete("__mastraWorflowInputData");}const stepResults={...(snapshot?.context??{}),input:runtimeContextInput??snapshot?.context?.input};let runtimeContextToUse=params.runtimeContext??new RuntimeContext();Object.entries(snapshot?.runtimeContext??{}).forEach(([key,value])=>{if(!runtimeContextToUse.has(key)){runtimeContextToUse.set(key,value);}});const workflowAISpan=getOrCreateSpan({type:"workflow_run"/* WORKFLOW_RUN */,name:`workflow run: '${this.workflowId}'`,input:resumeDataToUse,attributes:{workflowId:this.workflowId},tracingPolicy:this.tracingPolicy,tracingOptions:params.tracingOptions,tracingContext:params.tracingContext,runtimeContext:runtimeContextToUse});const traceId=getValidTraceId(workflowAISpan);const executionResultPromise=this.executionEngine.execute({workflowId:this.workflowId,runId:this.runId,resourceId:this.resourceId,graph:this.executionGraph,serializedStepGraph:this.serializedStepGraph,input:snapshot?.context?.input,initialState:snapshot?.value??{},resume:{steps,stepResults,resumePayload:resumeDataToUse,// @ts-ignore
332
332
  resumePath:snapshot?.suspendedPaths?.[steps?.[0]]},format:params.format,emitter:{emit:(event,data)=>{this.emitter.emit(event,data);return Promise.resolve();},on:(event,callback)=>{this.emitter.on(event,callback);},off:(event,callback)=>{this.emitter.off(event,callback);},once:(event,callback)=>{this.emitter.once(event,callback);}},runtimeContext:runtimeContextToUse,abortController:this.abortController,workflowAISpan,outputOptions:params.outputOptions}).then(result=>{if(!params.isVNext&&result.status!=="suspended"){this.closeStreamAction?.().catch(()=>{});}result.traceId=traceId;return result;});this.executionResults=executionResultPromise;return executionResultPromise;}/**
333
333
  * Returns the current state of the workflow run
334
334
  * @returns The current state of the workflow run
@@ -359,9 +359,8 @@ case "redacted-reasoning":throw new Error('AISDKv5 chunk type "redacted-reasonin
359
359
  case "reasoning-end":return {type:"reasoning-end",id:chunk.payload.id,providerMetadata:chunk.payload.providerMetadata};case "source":if(chunk.payload.sourceType==="url"){return {type:"source",sourceType:"url",id:chunk.payload.id,url:chunk.payload.url,title:chunk.payload.title,providerMetadata:chunk.payload.providerMetadata};}else {return {type:"source",sourceType:"document",id:chunk.payload.id,mediaType:chunk.payload.mimeType,title:chunk.payload.title,filename:chunk.payload.filename,providerMetadata:chunk.payload.providerMetadata};}case "file":if(mode==="generate"){return {type:"file",file:new DefaultGeneratedFile({data:chunk.payload.data,mediaType:chunk.payload.mimeType})};}return {type:"file",file:new DefaultGeneratedFileWithType({data:chunk.payload.data,mediaType:chunk.payload.mimeType})};case "tool-call":return {type:"tool-call",toolCallId:chunk.payload.toolCallId,providerMetadata:chunk.payload.providerMetadata,providerExecuted:chunk.payload.providerExecuted,toolName:chunk.payload.toolName,input:chunk.payload.args};case "tool-call-input-streaming-start":return {type:"tool-input-start",id:chunk.payload.toolCallId,toolName:chunk.payload.toolName,dynamic:!!chunk.payload.dynamic,providerMetadata:chunk.payload.providerMetadata,providerExecuted:chunk.payload.providerExecuted};case "tool-call-input-streaming-end":return {type:"tool-input-end",id:chunk.payload.toolCallId,providerMetadata:chunk.payload.providerMetadata};case "tool-call-delta":return {type:"tool-input-delta",id:chunk.payload.toolCallId,delta:chunk.payload.argsTextDelta,providerMetadata:chunk.payload.providerMetadata};case "step-finish":{const{request:_request,providerMetadata,...rest2}=chunk.payload.metadata;return {type:"finish-step",response:{id:chunk.payload.id||"",timestamp:/* @__PURE__ */new Date(),modelId:rest2.modelId||"",...rest2},usage:chunk.payload.output.usage,finishReason:chunk.payload.stepResult.reason,providerMetadata};}case "text-delta":return {type:"text-delta",id:chunk.payload.id,text:chunk.payload.text,providerMetadata:chunk.payload.providerMetadata};case "text-end":return {type:"text-end",id:chunk.payload.id,providerMetadata:chunk.payload.providerMetadata};case "text-start":return {type:"text-start",id:chunk.payload.id,providerMetadata:chunk.payload.providerMetadata};case "tool-result":return {type:"tool-result",input:chunk.payload.args,toolCallId:chunk.payload.toolCallId,providerExecuted:chunk.payload.providerExecuted,toolName:chunk.payload.toolName,output:chunk.payload.result// providerMetadata: chunk.payload.providerMetadata, // AI v5 types don't show this?
360
360
  };case "tool-error":return {type:"tool-error",error:chunk.payload.error,input:chunk.payload.args,toolCallId:chunk.payload.toolCallId,providerExecuted:chunk.payload.providerExecuted,toolName:chunk.payload.toolName// providerMetadata: chunk.payload.providerMetadata, // AI v5 types don't show this?
361
361
  };case "abort":return {type:"abort"};case "error":return {type:"error",error:chunk.payload.error};case "object":return {type:"object",object:chunk.object};default:if(chunk.type&&"payload"in chunk&&chunk.payload){return {type:chunk.type,...(chunk.payload||{})};}return;}}// src/stream/aisdk/v5/input.ts
362
- var AISDKV5InputStream=class extends MastraModelInput{constructor({component,name}){super({component,name});}async transform({runId,stream,controller}){for await(const chunk of stream){const transformedChunk=convertFullStreamChunkToMastra(chunk,{runId});if(transformedChunk){controller.enqueue(transformedChunk);}}}};// src/stream/aisdk/v5/model-supports.ts
363
- function getModelSupport(modelId,provider){return modelSupports.find(m=>m.modelId===modelId&&m.provider===provider);}var modelSupports=[];// src/stream/aisdk/v5/execute.ts
364
- function execute({runId,model,providerOptions,inputMessages,tools,toolChoice,options,onResult,modelStreamSpan,telemetry_settings,includeRawChunks,modelSettings,output,headers,shouldThrowError}){const v5=new AISDKV5InputStream({component:"LLM",name:model.modelId});const toolsAndToolChoice=prepareToolsAndToolChoice({tools,toolChoice,activeTools:options?.activeTools});if(modelStreamSpan&&toolsAndToolChoice?.tools?.length&&telemetry_settings?.recordOutputs!==false){modelStreamSpan.setAttributes({"stream.prompt.tools":toolsAndToolChoice?.tools?.map(tool=>JSON.stringify(tool))});}const modelSupports2=getModelSupport(model.modelId,model.provider);const modelSupportsResponseFormat=modelSupports2?.capabilities.responseFormat?.support==="full";const responseFormat=output?getResponseFormat(output):void 0;let prompt=inputMessages;if(output&&responseFormat?.type==="json"&&!modelSupportsResponseFormat){prompt=injectJsonInstructionIntoMessages({messages:inputMessages,schema:responseFormat.schema});}const stream=v5.initialize({runId,onResult,createStream:async()=>{try{const streamResult=await model.doStream({...toolsAndToolChoice,prompt,providerOptions,abortSignal:options?.abortSignal,includeRawChunks,responseFormat:modelSupportsResponseFormat?responseFormat:void 0,...(modelSettings??{}),headers});return streamResult;}catch(error){console.error("Error creating stream",error);if(isAbortError$1(error)&&options?.abortSignal?.aborted){console.error("Abort error",error);}if(shouldThrowError){throw error;}return {stream:new ReadableStream({start:async controller=>{controller.enqueue({type:"error",error:{message:error instanceof Error?error.message:JSON.stringify(error),stack:error instanceof Error?error.stack:void 0}});controller.close();}}),warnings:[],request:{},rawResponse:{}};}}});return stream;}// src/stream/aisdk/v5/output-helpers.ts
362
+ var AISDKV5InputStream=class extends MastraModelInput{constructor({component,name}){super({component,name});}async transform({runId,stream,controller}){for await(const chunk of stream){const transformedChunk=convertFullStreamChunkToMastra(chunk,{runId});if(transformedChunk){controller.enqueue(transformedChunk);}}}};// src/stream/aisdk/v5/execute.ts
363
+ function execute({runId,model,providerOptions,inputMessages,tools,toolChoice,options,onResult,modelStreamSpan,telemetry_settings,includeRawChunks,modelSettings,structuredOutput,headers,shouldThrowError}){const v5=new AISDKV5InputStream({component:"LLM",name:model.modelId});const toolsAndToolChoice=prepareToolsAndToolChoice({tools,toolChoice,activeTools:options?.activeTools});if(modelStreamSpan&&toolsAndToolChoice?.tools?.length&&telemetry_settings?.recordOutputs!==false){modelStreamSpan.setAttributes({"stream.prompt.tools":toolsAndToolChoice?.tools?.map(tool=>JSON.stringify(tool))});}const structuredOutputMode=structuredOutput?.schema?structuredOutput?.model?"processor":"direct":void 0;const responseFormat=structuredOutput?.schema?getResponseFormat(structuredOutput?.schema):void 0;let prompt=inputMessages;if(structuredOutputMode==="direct"&&responseFormat?.type==="json"&&structuredOutput?.jsonPromptInjection){prompt=injectJsonInstructionIntoMessages({messages:inputMessages,schema:responseFormat.schema});}const stream=v5.initialize({runId,onResult,createStream:async()=>{try{const streamResult=await model.doStream({...toolsAndToolChoice,prompt,providerOptions,abortSignal:options?.abortSignal,includeRawChunks,responseFormat:structuredOutputMode==="direct"&&!structuredOutput?.jsonPromptInjection?responseFormat:void 0,...(modelSettings??{}),headers});return streamResult;}catch(error){console.error("Error creating stream",error);if(isAbortError$1(error)&&options?.abortSignal?.aborted){console.error("Abort error",error);}if(shouldThrowError){throw error;}return {stream:new ReadableStream({start:async controller=>{controller.enqueue({type:"error",error:{message:error instanceof Error?error.message:JSON.stringify(error),stack:error instanceof Error?error.stack:void 0}});controller.close();}}),warnings:[],request:{},rawResponse:{}};}}});return stream;}// src/stream/aisdk/v5/output-helpers.ts
365
364
  var DefaultStepResult=class{content;finishReason;usage;warnings;request;response;providerMetadata;constructor({content,finishReason,usage,warnings,request,response,providerMetadata}){this.content=content;this.finishReason=finishReason;this.usage=usage;this.warnings=warnings;this.request=request;this.response=response;this.providerMetadata=providerMetadata;}get text(){return this.content.filter(part=>part.type==="text").map(part=>part.text).join("");}get reasoning(){return this.content.filter(part=>part.type==="reasoning");}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(part=>part.text).join("");}get files(){return this.content.filter(part=>part.type==="file").map(part=>part.file);}get sources(){return this.content.filter(part=>part.type==="source");}get toolCalls(){return this.content.filter(part=>part.type==="tool-call");}get staticToolCalls(){return this.toolCalls.filter(toolCall=>toolCall.dynamic===false);}get dynamicToolCalls(){return this.toolCalls.filter(toolCall=>toolCall.dynamic===true);}get toolResults(){return this.content.filter(part=>part.type==="tool-result");}get staticToolResults(){return this.toolResults.filter(toolResult=>toolResult.dynamic===false);}get dynamicToolResults(){return this.toolResults.filter(toolResult=>toolResult.dynamic===true);}};// src/loop/workflows/run-state.ts
366
365
  var AgenticRunState=class{#state;constructor({_internal,model}){this.#state={responseMetadata:{id:_internal?.generateId?.(),timestamp:_internal?.currentDate?.(),modelId:model.modelId,modelVersion:model.specificationVersion,modelProvider:model.provider,headers:void 0},modelMetadata:{modelId:model.modelId,modelVersion:model.specificationVersion,modelProvider:model.provider},isReasoning:false,isStreaming:false,providerOptions:void 0,hasToolCallStreaming:false,hasErrored:false,reasoningDeltas:[],textDeltas:[],stepResult:void 0};}setState(state){this.#state={...this.#state,...state};}get state(){return this.#state;}};// src/loop/workflows/agentic-execution/llm-execution-step.ts
367
366
  async function processOutputStream({tools,messageId,messageList,outputStream,runState,options,controller,responseFromModel,includeRawChunks}){for await(const chunk of outputStream._getBaseStream()){if(!chunk){continue;}if(chunk.type=="object"||chunk.type=="object-result"){controller.enqueue(chunk);continue;}if(chunk.type!=="reasoning-delta"&&chunk.type!=="reasoning-signature"&&chunk.type!=="redacted-reasoning"&&runState.state.isReasoning){if(runState.state.reasoningDeltas.length){messageList.add({id:messageId,role:"assistant",content:[{type:"reasoning",text:runState.state.reasoningDeltas.join(""),signature:chunk.payload.signature,providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions}]},"response");}runState.setState({isReasoning:false,reasoningDeltas:[]});}if(chunk.type!=="text-delta"&&chunk.type!=="tool-call"&&// not 100% sure about this being the right fix.
@@ -372,7 +371,7 @@ async function processOutputStream({tools,messageId,messageList,outputStream,run
372
371
  // BUT does this cause other issues?
373
372
  // Alternative solution: in message list allow combining text deltas together when the message source is "response" and the text parts are directly next to each other
374
373
  // simple solution for now is to not flush text deltas on response-metadata
375
- chunk.type!=="response-metadata"&&runState.state.isStreaming){if(runState.state.textDeltas.length){const textStartPayload=chunk.payload;const providerMetadata=textStartPayload.providerMetadata??runState.state.providerOptions;messageList.add({id:messageId,role:"assistant",content:[providerMetadata?{type:"text",text:runState.state.textDeltas.join(""),providerOptions:providerMetadata}:{type:"text",text:runState.state.textDeltas.join("")}]},"response");}runState.setState({isStreaming:false,textDeltas:[]});}switch(chunk.type){case "response-metadata":runState.setState({responseMetadata:{id:chunk.payload.id,timestamp:chunk.payload.timestamp,modelId:chunk.payload.modelId,headers:chunk.payload.headers}});break;case "text-delta":{const textDeltasFromState=runState.state.textDeltas;textDeltasFromState.push(chunk.payload.text);runState.setState({textDeltas:textDeltasFromState,isStreaming:true});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-input-streaming-start":{const tool=tools?.[chunk.payload.toolName]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputStart"in tool){try{await tool?.onInputStart?.({toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputStart",error);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-delta":{const tool=tools?.[chunk.payload.toolName||""]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputDelta"in tool){try{await tool?.onInputDelta?.({inputTextDelta:chunk.payload.argsTextDelta,toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputDelta",error);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-start":{runState.setState({providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(Object.values(chunk.payload.providerMetadata||{}).find(v=>v?.redactedData)){messageList.add({id:messageId,role:"assistant",content:[{type:"reasoning",text:"",providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions}]},"response");if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-delta":{const reasoningDeltasFromState=runState.state.reasoningDeltas;reasoningDeltasFromState.push(chunk.payload.text);runState.setState({isReasoning:true,reasoningDeltas:reasoningDeltasFromState,providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "file":messageList.add({id:messageId,role:"assistant",content:[{type:"file",data:chunk.payload.data,mimeType:chunk.payload.mimeType}]},"response");controller.enqueue(chunk);break;case "source":messageList.add({id:messageId,role:"assistant",content:{format:2,parts:[{type:"source",source:{sourceType:"url",id:chunk.payload.id,url:chunk.payload.url||"",title:chunk.payload.title,providerMetadata:chunk.payload.providerMetadata}}]},createdAt:/* @__PURE__ */new Date()},"response");controller.enqueue(chunk);break;case "finish":runState.setState({providerOptions:chunk.payload.metadata.providerMetadata,stepResult:{reason:chunk.payload.reason,logprobs:chunk.payload.logprobs,warnings:responseFromModel.warnings,totalUsage:chunk.payload.totalUsage,headers:responseFromModel.rawResponse?.headers,messageId,isContinued:!["stop","error"].includes(chunk.payload.stepResult.reason),request:responseFromModel.request}});break;case "error":if(isAbortError(chunk.payload.error)&&options?.abortSignal?.aborted){break;}runState.setState({hasErrored:true});runState.setState({stepResult:{isContinued:false,reason:"error"}});let e=chunk.payload.error;if(typeof e==="object"){const errorMessage=safeParseErrorObject(e);e=new Error(errorMessage);Object.assign(e,chunk.payload.error);}controller.enqueue({...chunk,payload:{...chunk.payload,error:e}});await options?.onError?.({error:e});break;default:if(isControllerOpen(controller)){controller.enqueue(chunk);}}if(["text-delta","reasoning-delta","source","tool-call","tool-call-input-streaming-start","tool-call-delta","raw"].includes(chunk.type)){const transformedChunk=convertMastraChunkToAISDKv5({chunk});if(chunk.type==="raw"&&!includeRawChunks){return;}await options?.onChunk?.({chunk:transformedChunk});}if(runState.state.hasErrored){break;}}}function executeStreamWithFallbackModels(models){return async callback=>{let index=0;let finalResult;let done=false;for(const modelConfig of models){index++;const maxRetries=modelConfig.maxRetries||0;let attempt=0;if(done){break;}while(attempt<=maxRetries){try{const isLastModel=attempt===maxRetries&&index===models.length;const result=await callback(modelConfig.model,isLastModel);finalResult=result;done=true;break;}catch(err){attempt++;console.error(`Error executing model ${modelConfig.model.modelId}, attempt ${attempt}====`,err);if(attempt>maxRetries){break;}}}}if(typeof finalResult==="undefined"){console.error("Exhausted all fallback models and reached the maximum number of retries.");throw new Error("Exhausted all fallback models and reached the maximum number of retries.");}return finalResult;};}function createLLMExecutionStep({models,_internal,messageId,runId,modelStreamSpan,telemetry_settings,tools,toolChoice,messageList,includeRawChunks,modelSettings,providerOptions,options,toolCallStreaming,controller,output,outputProcessors,headers,downloadRetries,downloadConcurrency,processorStates}){return createStep({id:"llm-execution",inputSchema:llmIterationOutputSchema,outputSchema:llmIterationOutputSchema,execute:async({inputData,bail,tracingContext})=>{let modelResult;let warnings;let request;let rawResponse;const{outputStream,callBail,runState}=await executeStreamWithFallbackModels(models)(async(model,isLastModel)=>{const runState2=new AgenticRunState({_internal,model});switch(model.specificationVersion){case "v2":{const messageListPromptArgs={downloadRetries,downloadConcurrency,supportedUrls:model?.supportedUrls};let inputMessages=await messageList.get.all.aiV5.llmPrompt(messageListPromptArgs);let stepModel=model;let stepToolChoice=toolChoice;let stepTools=tools;if(options?.prepareStep){try{const prepareStepResult=await options.prepareStep({stepNumber:inputData.output?.steps?.length||0,steps:inputData.output?.steps||[],model,messages:messageList.get.all.aiV5.model()});if(prepareStepResult){if(prepareStepResult.model){stepModel=prepareStepResult.model;}if(prepareStepResult.toolChoice){stepToolChoice=prepareStepResult.toolChoice;}if(prepareStepResult.activeTools&&stepTools){const activeToolsSet=new Set(prepareStepResult.activeTools);stepTools=Object.fromEntries(Object.entries(stepTools).filter(([toolName])=>activeToolsSet.has(toolName)));}if(prepareStepResult.messages){const newMessages=prepareStepResult.messages;const newMessageList=new MessageList();for(const message of newMessages){if(message.role==="system"){newMessageList.addSystem(message);}else if(message.role==="user"){newMessageList.add(message,"input");}else if(message.role==="assistant"||message.role==="tool"){newMessageList.add(message,"response");}}inputMessages=await newMessageList.get.all.aiV5.llmPrompt(messageListPromptArgs);}}}catch(error){console.error("Error in prepareStep callback:",error);}}modelResult=execute({runId,model:stepModel,providerOptions,inputMessages,tools:stepTools,toolChoice:stepToolChoice,options,modelSettings,telemetry_settings,includeRawChunks,output,headers,onResult:({warnings:warningsFromStream,request:requestFromStream,rawResponse:rawResponseFromStream})=>{warnings=warningsFromStream;request=requestFromStream||{};rawResponse=rawResponseFromStream;if(!isControllerOpen(controller)){return;}controller.enqueue({runId,from:"AGENT"/* AGENT */,type:"step-start",payload:{request:request||{},warnings:warnings||[],messageId}});},modelStreamSpan,shouldThrowError:!isLastModel});break;}default:{throw new Error(`Unsupported model version: ${model.specificationVersion}`);}}const outputStream2=new MastraModelOutput({model:{modelId:model.modelId,provider:model.provider,version:model.specificationVersion},stream:modelResult,messageList,messageId,options:{runId,rootSpan:modelStreamSpan,toolCallStreaming,telemetry_settings,includeRawChunks,output,outputProcessors,isLLMExecutionStep:true,tracingContext,processorStates}});try{await processOutputStream({outputStream:outputStream2,includeRawChunks,tools,messageId,messageList,runState:runState2,options,controller,responseFromModel:{warnings,request,rawResponse}});}catch(error){console.error("Error in LLM Execution Step",error);if(isAbortError(error)&&options?.abortSignal?.aborted){await options?.onAbort?.({steps:inputData?.output?.steps??[]});if(isControllerOpen(controller)){controller.enqueue({type:"abort",runId,from:"AGENT"/* AGENT */,payload:{}});}return {callBail:true,outputStream:outputStream2,runState:runState2};}if(isLastModel){if(isControllerOpen(controller)){controller.enqueue({type:"error",runId,from:"AGENT"/* AGENT */,payload:{error}});}runState2.setState({hasErrored:true,stepResult:{isContinued:false,reason:"error"}});}else {throw error;}}return {outputStream:outputStream2,callBail:false,runState:runState2};});if(callBail){const usage2=outputStream._getImmediateUsage();const responseMetadata2=runState.state.responseMetadata;const text2=outputStream._getImmediateText();return bail({messageId,stepResult:{reason:"abort",warnings,isContinued:false},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata2,modelMetadata:runState.state.modelMetadata,headers:rawResponse?.headers,request},output:{text:text2,toolCalls:[],usage:usage2??inputData.output?.usage,steps:[]},messages:{all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()}});}if(outputStream.tripwire){runState.setState({stepResult:{isContinued:false,reason:"abort"}});}const toolCalls=outputStream._getImmediateToolCalls()?.map(chunk=>{return chunk.payload;});if(toolCalls.length>0){const assistantContent=[...toolCalls.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,args:toolCall.args};})];messageList.add({id:messageId,role:"assistant",content:assistantContent},"response");}const finishReason=runState?.state?.stepResult?.reason??outputStream._getImmediateFinishReason();const hasErrored=runState.state.hasErrored;const usage=outputStream._getImmediateUsage();const responseMetadata=runState.state.responseMetadata;const text=outputStream._getImmediateText();const object=outputStream._getImmediateObject();const tripwireTriggered=outputStream.tripwire;const steps=inputData.output?.steps||[];const existingResponseCount=inputData.messages?.nonUser?.length||0;const allResponseContent=messageList.get.response.aiV5.modelContent(steps.length);const currentIterationContent=allResponseContent.slice(existingResponseCount);steps.push(new DefaultStepResult({warnings:outputStream._getImmediateWarnings(),providerMetadata:runState.state.providerOptions,finishReason:runState.state.stepResult?.reason,content:currentIterationContent,response:{...responseMetadata,...rawResponse,messages:messageList.get.response.aiV5.model()},request,usage:outputStream._getImmediateUsage()}));const messages={all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()};return {messageId,stepResult:{reason:tripwireTriggered?"abort":hasErrored?"error":finishReason,warnings,isContinued:tripwireTriggered?false:!["stop","error"].includes(finishReason)},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata,...rawResponse,modelMetadata:runState.state.modelMetadata,headers:rawResponse?.headers,request},output:{text,toolCalls,usage:usage??inputData.output?.usage,steps,...(object?{object}:{})},messages};}});}// src/loop/workflows/agentic-execution/llm-mapping-step.ts
374
+ chunk.type!=="response-metadata"&&runState.state.isStreaming){if(runState.state.textDeltas.length){const textStartPayload=chunk.payload;const providerMetadata=textStartPayload.providerMetadata??runState.state.providerOptions;messageList.add({id:messageId,role:"assistant",content:[providerMetadata?{type:"text",text:runState.state.textDeltas.join(""),providerOptions:providerMetadata}:{type:"text",text:runState.state.textDeltas.join("")}]},"response");}runState.setState({isStreaming:false,textDeltas:[]});}switch(chunk.type){case "response-metadata":runState.setState({responseMetadata:{id:chunk.payload.id,timestamp:chunk.payload.timestamp,modelId:chunk.payload.modelId,headers:chunk.payload.headers}});break;case "text-delta":{const textDeltasFromState=runState.state.textDeltas;textDeltasFromState.push(chunk.payload.text);runState.setState({textDeltas:textDeltasFromState,isStreaming:true});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-input-streaming-start":{const tool=tools?.[chunk.payload.toolName]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputStart"in tool){try{await tool?.onInputStart?.({toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputStart",error);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "tool-call-delta":{const tool=tools?.[chunk.payload.toolName||""]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===chunk.payload.toolName);if(tool&&"onInputDelta"in tool){try{await tool?.onInputDelta?.({inputTextDelta:chunk.payload.argsTextDelta,toolCallId:chunk.payload.toolCallId,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputDelta",error);}}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-start":{runState.setState({providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(Object.values(chunk.payload.providerMetadata||{}).find(v=>v?.redactedData)){messageList.add({id:messageId,role:"assistant",content:[{type:"reasoning",text:"",providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions}]},"response");if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "reasoning-delta":{const reasoningDeltasFromState=runState.state.reasoningDeltas;reasoningDeltasFromState.push(chunk.payload.text);runState.setState({isReasoning:true,reasoningDeltas:reasoningDeltasFromState,providerOptions:chunk.payload.providerMetadata??runState.state.providerOptions});if(isControllerOpen(controller)){controller.enqueue(chunk);}break;}case "file":messageList.add({id:messageId,role:"assistant",content:[{type:"file",data:chunk.payload.data,mimeType:chunk.payload.mimeType}]},"response");controller.enqueue(chunk);break;case "source":messageList.add({id:messageId,role:"assistant",content:{format:2,parts:[{type:"source",source:{sourceType:"url",id:chunk.payload.id,url:chunk.payload.url||"",title:chunk.payload.title,providerMetadata:chunk.payload.providerMetadata}}]},createdAt:/* @__PURE__ */new Date()},"response");controller.enqueue(chunk);break;case "finish":runState.setState({providerOptions:chunk.payload.metadata.providerMetadata,stepResult:{reason:chunk.payload.reason,logprobs:chunk.payload.logprobs,warnings:responseFromModel.warnings,totalUsage:chunk.payload.totalUsage,headers:responseFromModel.rawResponse?.headers,messageId,isContinued:!["stop","error"].includes(chunk.payload.stepResult.reason),request:responseFromModel.request}});break;case "error":if(isAbortError(chunk.payload.error)&&options?.abortSignal?.aborted){break;}runState.setState({hasErrored:true});runState.setState({stepResult:{isContinued:false,reason:"error"}});let e=chunk.payload.error;if(typeof e==="object"){const errorMessage=safeParseErrorObject(e);e=new Error(errorMessage);Object.assign(e,chunk.payload.error);}controller.enqueue({...chunk,payload:{...chunk.payload,error:e}});await options?.onError?.({error:e});break;default:if(isControllerOpen(controller)){controller.enqueue(chunk);}}if(["text-delta","reasoning-delta","source","tool-call","tool-call-input-streaming-start","tool-call-delta","raw"].includes(chunk.type)){const transformedChunk=convertMastraChunkToAISDKv5({chunk});if(chunk.type==="raw"&&!includeRawChunks){return;}await options?.onChunk?.({chunk:transformedChunk});}if(runState.state.hasErrored){break;}}}function executeStreamWithFallbackModels(models){return async callback=>{let index=0;let finalResult;let done=false;for(const modelConfig of models){index++;const maxRetries=modelConfig.maxRetries||0;let attempt=0;if(done){break;}while(attempt<=maxRetries){try{const isLastModel=attempt===maxRetries&&index===models.length;const result=await callback(modelConfig.model,isLastModel);finalResult=result;done=true;break;}catch(err){attempt++;console.error(`Error executing model ${modelConfig.model.modelId}, attempt ${attempt}====`,err);if(attempt>maxRetries){break;}}}}if(typeof finalResult==="undefined"){console.error("Exhausted all fallback models and reached the maximum number of retries.");throw new Error("Exhausted all fallback models and reached the maximum number of retries.");}return finalResult;};}function createLLMExecutionStep({models,_internal,messageId,runId,modelStreamSpan,telemetry_settings,tools,toolChoice,messageList,includeRawChunks,modelSettings,providerOptions,options,toolCallStreaming,controller,structuredOutput,outputProcessors,headers,downloadRetries,downloadConcurrency,processorStates}){return createStep({id:"llm-execution",inputSchema:llmIterationOutputSchema,outputSchema:llmIterationOutputSchema,execute:async({inputData,bail,tracingContext})=>{let modelResult;let warnings;let request;let rawResponse;const{outputStream,callBail,runState}=await executeStreamWithFallbackModels(models)(async(model,isLastModel)=>{const runState2=new AgenticRunState({_internal,model});switch(model.specificationVersion){case "v2":{const messageListPromptArgs={downloadRetries,downloadConcurrency,supportedUrls:model?.supportedUrls};let inputMessages=await messageList.get.all.aiV5.llmPrompt(messageListPromptArgs);let stepModel=model;let stepToolChoice=toolChoice;let stepTools=tools;if(options?.prepareStep){try{const prepareStepResult=await options.prepareStep({stepNumber:inputData.output?.steps?.length||0,steps:inputData.output?.steps||[],model,messages:messageList.get.all.aiV5.model()});if(prepareStepResult){if(prepareStepResult.model){stepModel=prepareStepResult.model;}if(prepareStepResult.toolChoice){stepToolChoice=prepareStepResult.toolChoice;}if(prepareStepResult.activeTools&&stepTools){const activeToolsSet=new Set(prepareStepResult.activeTools);stepTools=Object.fromEntries(Object.entries(stepTools).filter(([toolName])=>activeToolsSet.has(toolName)));}if(prepareStepResult.messages){const newMessages=prepareStepResult.messages;const newMessageList=new MessageList();for(const message of newMessages){if(message.role==="system"){newMessageList.addSystem(message);}else if(message.role==="user"){newMessageList.add(message,"input");}else if(message.role==="assistant"||message.role==="tool"){newMessageList.add(message,"response");}}inputMessages=await newMessageList.get.all.aiV5.llmPrompt(messageListPromptArgs);}}}catch(error){console.error("Error in prepareStep callback:",error);}}modelResult=execute({runId,model:stepModel,providerOptions,inputMessages,tools:stepTools,toolChoice:stepToolChoice,options,modelSettings,telemetry_settings,includeRawChunks,structuredOutput,headers,onResult:({warnings:warningsFromStream,request:requestFromStream,rawResponse:rawResponseFromStream})=>{warnings=warningsFromStream;request=requestFromStream||{};rawResponse=rawResponseFromStream;if(!isControllerOpen(controller)){return;}controller.enqueue({runId,from:"AGENT"/* AGENT */,type:"step-start",payload:{request:request||{},warnings:warnings||[],messageId}});},modelStreamSpan,shouldThrowError:!isLastModel});break;}default:{throw new Error(`Unsupported model version: ${model.specificationVersion}`);}}const outputStream2=new MastraModelOutput({model:{modelId:model.modelId,provider:model.provider,version:model.specificationVersion},stream:modelResult,messageList,messageId,options:{runId,rootSpan:modelStreamSpan,toolCallStreaming,telemetry_settings,includeRawChunks,structuredOutput,outputProcessors,isLLMExecutionStep:true,tracingContext,processorStates}});try{await processOutputStream({outputStream:outputStream2,includeRawChunks,tools,messageId,messageList,runState:runState2,options,controller,responseFromModel:{warnings,request,rawResponse}});}catch(error){console.error("Error in LLM Execution Step",error);if(isAbortError(error)&&options?.abortSignal?.aborted){await options?.onAbort?.({steps:inputData?.output?.steps??[]});if(isControllerOpen(controller)){controller.enqueue({type:"abort",runId,from:"AGENT"/* AGENT */,payload:{}});}return {callBail:true,outputStream:outputStream2,runState:runState2};}if(isLastModel){if(isControllerOpen(controller)){controller.enqueue({type:"error",runId,from:"AGENT"/* AGENT */,payload:{error}});}runState2.setState({hasErrored:true,stepResult:{isContinued:false,reason:"error"}});}else {throw error;}}return {outputStream:outputStream2,callBail:false,runState:runState2};});if(callBail){const usage2=outputStream._getImmediateUsage();const responseMetadata2=runState.state.responseMetadata;const text2=outputStream._getImmediateText();return bail({messageId,stepResult:{reason:"abort",warnings,isContinued:false},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata2,modelMetadata:runState.state.modelMetadata,headers:rawResponse?.headers,request},output:{text:text2,toolCalls:[],usage:usage2??inputData.output?.usage,steps:[]},messages:{all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()}});}if(outputStream.tripwire){runState.setState({stepResult:{isContinued:false,reason:"abort"}});}const toolCalls=outputStream._getImmediateToolCalls()?.map(chunk=>{return chunk.payload;});if(toolCalls.length>0){const assistantContent=[...toolCalls.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,args:toolCall.args};})];messageList.add({id:messageId,role:"assistant",content:assistantContent},"response");}const finishReason=runState?.state?.stepResult?.reason??outputStream._getImmediateFinishReason();const hasErrored=runState.state.hasErrored;const usage=outputStream._getImmediateUsage();const responseMetadata=runState.state.responseMetadata;const text=outputStream._getImmediateText();const object=outputStream._getImmediateObject();const tripwireTriggered=outputStream.tripwire;const steps=inputData.output?.steps||[];const existingResponseCount=inputData.messages?.nonUser?.length||0;const allResponseContent=messageList.get.response.aiV5.modelContent(steps.length);const currentIterationContent=allResponseContent.slice(existingResponseCount);steps.push(new DefaultStepResult({warnings:outputStream._getImmediateWarnings(),providerMetadata:runState.state.providerOptions,finishReason:runState.state.stepResult?.reason,content:currentIterationContent,response:{...responseMetadata,...rawResponse,messages:messageList.get.response.aiV5.model()},request,usage:outputStream._getImmediateUsage()}));const messages={all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:messageList.get.response.aiV5.model()};return {messageId,stepResult:{reason:tripwireTriggered?"abort":hasErrored?"error":finishReason,warnings,isContinued:tripwireTriggered?false:!["stop","error"].includes(finishReason)},metadata:{providerMetadata:runState.state.providerOptions,...responseMetadata,...rawResponse,modelMetadata:runState.state.modelMetadata,headers:rawResponse?.headers,request},output:{text,toolCalls,usage:usage??inputData.output?.usage,steps,...(object?{object}:{})},messages};}});}// src/loop/workflows/agentic-execution/llm-mapping-step.ts
376
375
  function createLLMMappingStep({models,telemetry_settings,_internal,modelStreamSpan,...rest},llmExecutionStep){return createStep({id:"llmExecutionMappingStep",inputSchema:z9.array(toolCallOutputSchema),outputSchema:llmIterationOutputSchema,execute:async({inputData,getStepResult:getStepResult3,bail})=>{const initialResult=getStepResult3(llmExecutionStep);if(inputData?.every(toolCall=>toolCall?.result===void 0)){const errorResults=inputData.filter(toolCall=>toolCall?.error);const toolResultMessageId=rest.experimental_generateMessageId?.()||_internal?.generateId?.();if(errorResults?.length){errorResults.forEach(toolCall=>{const chunk={type:"tool-error",runId:rest.runId,from:"AGENT"/* AGENT */,payload:{error:toolCall.error,args:toolCall.args,toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,providerMetadata:toolCall.providerMetadata}};rest.controller.enqueue(chunk);});rest.messageList.add({id:toolResultMessageId,role:"tool",content:errorResults.map(toolCall=>{return {type:"tool-result",args:toolCall.args,toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,result:{tool_execution_error:toolCall.error?.message??toolCall.error}};})},"response");}initialResult.stepResult.isContinued=false;return bail(initialResult);}if(inputData?.length){for(const toolCall of inputData){const chunk={type:"tool-result",runId:rest.runId,from:"AGENT"/* AGENT */,payload:{args:toolCall.args,toolCallId:toolCall.toolCallId,toolName:toolCall.toolName,result:toolCall.result,providerMetadata:toolCall.providerMetadata,providerExecuted:toolCall.providerExecuted}};rest.controller.enqueue(chunk);if(initialResult?.metadata?.modelVersion==="v2"){await rest.options?.onChunk?.({chunk:convertMastraChunkToAISDKv5({chunk})});}const toolResultMessageId=rest.experimental_generateMessageId?.()||_internal?.generateId?.();rest.messageList.add({id:toolResultMessageId,role:"tool",content:inputData.map(toolCall2=>{return {type:"tool-result",args:toolCall2.args,toolCallId:toolCall2.toolCallId,toolName:toolCall2.toolName,result:toolCall2.result};})},"response");}return {...initialResult,messages:{all:rest.messageList.get.all.aiV5.model(),user:rest.messageList.get.input.aiV5.model(),nonUser:rest.messageList.get.response.aiV5.model()}};}}});}// src/loop/workflows/agentic-execution/tool-call-step.ts
377
376
  function createToolCallStep({tools,messageList,options,telemetry_settings,writer,requireToolApproval,controller,runId,streamState}){return createStep({id:"toolCallStep",inputSchema:toolCallInputSchema,outputSchema:toolCallOutputSchema,execute:async({inputData,suspend,resumeData})=>{if(inputData.providerExecuted){const tracer2=getTracer({isEnabled:telemetry_settings?.isEnabled,tracer:telemetry_settings?.tracer});const span2=tracer2.startSpan("mastra.stream.toolCall").setAttributes({...assembleOperationName({operationId:"mastra.stream.toolCall",telemetry:telemetry_settings}),"stream.toolCall.toolName":inputData.toolName,"stream.toolCall.toolCallId":inputData.toolCallId,"stream.toolCall.args":JSON.stringify(inputData.args),"stream.toolCall.providerExecuted":true});if(inputData.output){span2.setAttributes({"stream.toolCall.result":JSON.stringify(inputData.output)});}span2.end();return {...inputData,result:inputData.output};}const tool=tools?.[inputData.toolName]||Object.values(tools||{})?.find(tool2=>`id`in tool2&&tool2.id===inputData.toolName);if(!tool){throw new Error(`Tool ${inputData.toolName} not found`);}if(tool&&"onInputAvailable"in tool){try{await tool?.onInputAvailable?.({toolCallId:inputData.toolCallId,input:inputData.args,messages:messageList.get.input.aiV5.model(),abortSignal:options?.abortSignal});}catch(error){console.error("Error calling onInputAvailable",error);}}if(!tool.execute){return inputData;}const tracer=getTracer({isEnabled:telemetry_settings?.isEnabled,tracer:telemetry_settings?.tracer});const span=tracer.startSpan("mastra.stream.toolCall").setAttributes({...assembleOperationName({operationId:"mastra.stream.toolCall",telemetry:telemetry_settings}),"stream.toolCall.toolName":inputData.toolName,"stream.toolCall.toolCallId":inputData.toolCallId,"stream.toolCall.args":JSON.stringify(inputData.args)});try{if(requireToolApproval||tool.requireApproval){if(!resumeData){controller.enqueue({type:"tool-call-approval",runId,from:"AGENT"/* AGENT */,payload:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,args:inputData.args}});await suspend({requireToolApproval:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,args:inputData.args},__streamState:streamState.serialize()});}else {if(!resumeData.approved){const error=new Error("Tool call was declined: "+JSON.stringify({toolCallId:inputData.toolCallId,toolName:inputData.toolName,args:inputData.args}));return {error,...inputData};}}}const result=await tool.execute(inputData.args,{abortSignal:options?.abortSignal,toolCallId:inputData.toolCallId,messages:messageList.get.input.aiV5.model(),writableStream:writer,suspend:async suspendPayload=>{controller.enqueue({type:"tool-call-suspended",runId,from:"AGENT"/* AGENT */,payload:{toolCallId:inputData.toolCallId,toolName:inputData.toolName,suspendPayload}});return await suspend({toolCallSuspended:suspendPayload,__streamState:streamState.serialize()});},resumeData});span.setAttributes({"stream.toolCall.result":JSON.stringify(result)});span.end();return {result,...inputData};}catch(error){span.setStatus({code:2,message:error?.message??error});span.recordException(error);return {error,...inputData};}}});}// src/loop/workflows/agentic-execution/index.ts
378
377
  function createAgenticExecutionWorkflow({models,telemetry_settings,_internal,modelStreamSpan,...rest}){const llmExecutionStep=createLLMExecutionStep({models,_internal,modelStreamSpan,telemetry_settings,...rest});const toolCallStep=createToolCallStep({telemetry_settings,...rest});const llmMappingStep=createLLMMappingStep({models,telemetry_settings,_internal,modelStreamSpan,...rest},llmExecutionStep);return createWorkflow({id:"executionWorkflow",inputSchema:llmIterationOutputSchema,outputSchema:llmIterationOutputSchema,options:{tracingPolicy:{// mark all workflow spans related to the
@@ -386,9 +385,9 @@ finishReason:typedInputData.stepResult?.reason||"unknown",warnings:typedInputDat
386
385
  payload:typedInputData});}}modelStreamSpan.setAttributes({"stream.response.id":typedInputData.metadata?.id,"stream.response.model":typedInputData.metadata?.modelId,...(typedInputData.metadata?.providerMetadata?{"stream.response.providerMetadata":JSON.stringify(typedInputData.metadata.providerMetadata)}:{}),"stream.response.finishReason":typedInputData.stepResult?.reason,"stream.usage.inputTokens":typedInputData.output.usage?.inputTokens,"stream.usage.outputTokens":typedInputData.output.usage?.outputTokens,"stream.usage.totalTokens":typedInputData.output.usage?.totalTokens,...(telemetry_settings?.recordOutputs!==false?{"stream.response.text":typedInputData.output.text,"stream.prompt.messages":JSON.stringify(messageList.get.input.aiV5.model())}:{})});modelStreamSpan.end();const reason=typedInputData.stepResult?.reason;if(reason===void 0){return false;}return typedInputData.stepResult?.isContinued??false;}).commit();}// src/loop/workflows/stream.ts
387
386
  function isControllerOpen(controller){return controller.desiredSize!==0&&controller.desiredSize!==null;}function workflowLoopStream({resumeContext,requireToolApproval,telemetry_settings,models,toolChoice,modelSettings,_internal,modelStreamSpan,llmAISpan,messageId,runId,messageList,startTimestamp,streamState,agentId,...rest}){return new ReadableStream$1({start:async controller=>{const writer=new WritableStream({write:chunk=>{controller.enqueue(chunk);}});modelStreamSpan.setAttributes({...(telemetry_settings?.recordInputs!==false?{"stream.prompt.toolChoice":toolChoice?JSON.stringify(toolChoice):"auto"}:{})});const agenticLoopWorkflow=createAgenticLoopWorkflow({resumeContext,requireToolApproval,messageId,models,telemetry_settings,_internal,modelSettings,toolChoice,modelStreamSpan,controller,writer,runId,messageList,startTimestamp,streamState,agentId,...rest});if(rest.mastra){agenticLoopWorkflow.__registerMastra(rest.mastra);}const initialData={messageId,messages:{all:messageList.get.all.aiV5.model(),user:messageList.get.input.aiV5.model(),nonUser:[]},output:{steps:[],usage:{inputTokens:0,outputTokens:0,totalTokens:0}},metadata:{},stepResult:{reason:"undefined",warnings:[],isContinued:true,totalUsage:{inputTokens:0,outputTokens:0,totalTokens:0}}};const msToFirstChunk=_internal?.now?.()-startTimestamp;modelStreamSpan.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":msToFirstChunk});modelStreamSpan.setAttributes({"stream.response.timestamp":new Date(startTimestamp).toISOString(),"stream.response.msToFirstChunk":msToFirstChunk});if(!resumeContext){controller.enqueue({type:"start",runId,from:"AGENT"/* AGENT */,payload:{id:agentId}});}const existingSnapshot=await rest.mastra?.getStorage()?.loadWorkflowSnapshot({workflowName:"agentic-loop",runId});if(existingSnapshot){for(const key in existingSnapshot?.context){const step=existingSnapshot?.context[key];if(step&&step.status==="suspended"&&step.suspendPayload?.__streamState){streamState.deserialize(step.suspendPayload?.__streamState);break;}}}const run=await agenticLoopWorkflow.createRunAsync({runId});const executionResult=resumeContext?await run.resume({resumeData:resumeContext,tracingContext:{currentSpan:llmAISpan}}):await run.start({inputData:initialData,tracingContext:{currentSpan:llmAISpan}});if(executionResult.status!=="success"){controller.close();return;}if(executionResult.result.stepResult?.reason==="abort"){controller.close();return;}controller.enqueue({type:"finish",runId,from:"AGENT"/* AGENT */,payload:{...executionResult.result,stepResult:{...executionResult.result.stepResult,// @ts-ignore we add 'abort' for tripwires so the type is not compatible
388
387
  reason:executionResult.result.stepResult.reason}}});const msToFinish=(_internal?.now?.()??Date.now())-startTimestamp;modelStreamSpan.addEvent("ai.stream.finish");modelStreamSpan.setAttributes({"stream.response.msToFinish":msToFinish,"stream.response.avgOutputTokensPerSecond":1e3*(executionResult?.result?.output?.usage?.outputTokens??0)/msToFinish});controller.close();}});}// src/loop/loop.ts
389
- function loop({resumeContext,models,logger,runId,idGenerator,telemetry_settings,messageList,includeRawChunks,modelSettings,tools,_internal,mode="stream",outputProcessors,returnScorerData,llmAISpan,requireToolApproval,agentId,...rest}){let loggerToUse=logger||new ConsoleLogger({level:"debug"});if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});loggerToUse.trackException(mastraError);loggerToUse.error(mastraError.toString());throw mastraError;}const firstModel=models[0];let runIdToUse=runId;if(!runIdToUse){runIdToUse=idGenerator?.()||crypto.randomUUID();}const internalToUse={now:_internal?.now||(()=>Date.now()),generateId:_internal?.generateId||(()=>generateId()),currentDate:_internal?.currentDate||(()=>/* @__PURE__ */new Date())};let startTimestamp=internalToUse.now?.();const{rootSpan}=getRootSpan({operationId:mode==="stream"?`mastra.stream`:`mastra.generate`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});rootSpan.setAttributes({...(telemetry_settings?.recordOutputs!==false?{"stream.prompt.messages":JSON.stringify(messageList.get.input.aiV5.model())}:{})});const{rootSpan:modelStreamSpan}=getRootSpan({operationId:`mastra.${mode}.aisdk.doStream`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});const messageId=rest.experimental_generateMessageId?.()||internalToUse.generateId?.();let modelOutput;const serializeStreamState=()=>{return modelOutput?.serializeState();};const deserializeStreamState=state=>{modelOutput?.deserializeState(state);};const processorStates=outputProcessors&&outputProcessors.length>0?/* @__PURE__ */new Map():void 0;const workflowLoopProps={resumeContext,models,runId:runIdToUse,logger:loggerToUse,startTimestamp,messageList,includeRawChunks:!!includeRawChunks,_internal:internalToUse,tools,modelStreamSpan,telemetry_settings,modelSettings,outputProcessors,llmAISpan,messageId,agentId,requireToolApproval,streamState:{serialize:serializeStreamState,deserialize:deserializeStreamState},processorStates,...rest};const stream=workflowLoopStream(workflowLoopProps);modelOutput=new MastraModelOutput({model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider,version:firstModel.model.specificationVersion},stream,messageList,messageId,options:{runId:runIdToUse,telemetry_settings,rootSpan,toolCallStreaming:rest.toolCallStreaming,onFinish:rest.options?.onFinish,onStepFinish:rest.options?.onStepFinish,includeRawChunks:!!includeRawChunks,output:rest.output,outputProcessors,returnScorerData,tracingContext:{currentSpan:llmAISpan}}});return createDestructurableOutput(modelOutput);}// src/llm/model/model.loop.ts
390
- var MastraLLMVNext=class extends MastraBase{#models;#mastra;#options;#firstModel;constructor({mastra,models,options}){super({name:"aisdk"});this.#options=options;if(mastra){this.#mastra=mastra;if(mastra.getLogger()){this.__setLogger(this.#mastra.getLogger());}}if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LLM_LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}else {this.#models=models;this.#firstModel=models[0];}}__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}}__registerMastra(p){this.#mastra=p;}getProvider(){return this.#firstModel.model.provider;}getModelId(){return this.#firstModel.model.modelId;}getModel(){return this.#firstModel.model;}_applySchemaCompat(schema){const model=this.#firstModel.model;const schemaCompatLayers=[];if(model){const modelInfo={modelId:model.modelId,supportsStructuredOutputs:true,provider:model.provider};schemaCompatLayers.push(new OpenAIReasoningSchemaCompatLayer(modelInfo),new OpenAISchemaCompatLayer(modelInfo),new GoogleSchemaCompatLayer(modelInfo),new AnthropicSchemaCompatLayer(modelInfo),new DeepSeekSchemaCompatLayer(modelInfo),new MetaSchemaCompatLayer(modelInfo));}return applyCompatLayer({schema,compatLayers:schemaCompatLayers,mode:"aiSdkSchema"});}convertToMessages(messages){if(Array.isArray(messages)){return messages.map(m=>{if(typeof m==="string"){return {role:"user",content:m};}return m;});}return [{role:"user",content:messages}];}stream({resumeContext,runId,stopWhen=stepCountIs(5),maxSteps,tools={},modelSettings,toolChoice="auto",telemetry_settings,threadId,resourceId,output,structuredOutput,options,outputProcessors,returnScorerData,providerOptions,tracingContext,messageList,requireToolApproval,_internal,agentId// ...rest
391
- }){let stopWhenToUse;if(maxSteps&&typeof maxSteps==="number"){stopWhenToUse=stepCountIs(maxSteps);}else {stopWhenToUse=stopWhen;}let effectiveOutput=output;if(structuredOutput&&!structuredOutput.model){effectiveOutput=structuredOutput.schema;}const messages=messageList.get.all.aiV5.model();const firstModel=this.#firstModel.model;this.logger.debug(`[LLM] - Streaming text`,{runId,threadId,resourceId,messages,tools:Object.keys(tools||{})});const llmAISpan=tracingContext?.currentSpan?.createChildSpan({name:`llm: '${firstModel.modelId}'`,type:"llm_generation"/* LLM_GENERATION */,input:{messages:[...messageList.getSystemMessages(),...messages]},attributes:{model:firstModel.modelId,provider:firstModel.provider,streaming:true,parameters:modelSettings},metadata:{runId,threadId,resourceId},tracingPolicy:this.#options?.tracingPolicy});try{const loopOptions={mastra:this.#mastra,resumeContext,runId,messageList,models:this.#models,tools,stopWhen:stopWhenToUse,toolChoice,modelSettings,providerOptions,telemetry_settings:{...this.experimental_telemetry,...telemetry_settings},_internal,output:effectiveOutput,outputProcessors,returnScorerData,llmAISpan,requireToolApproval,agentId,options:{...options,onStepFinish:async props=>{try{await options?.onStepFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_STEP_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}this.logger.debug("[LLM] - Stream Step Change:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId});if(props?.response?.headers?.["x-ratelimit-remaining-tokens"]&&parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"],10)<2e3){this.logger.warn("Rate limit approaching, waiting 10 seconds",{runId});await delay(10*1e3);}},onFinish:async props=>{try{await options?.onFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}llmAISpan?.end({output:{files:props?.files,object:props?.object,reasoning:props?.reasoning,reasoningText:props?.reasoningText,sources:props?.sources,text:props?.text,warnings:props?.warnings},attributes:{finishReason:props?.finishReason,usage:{inputTokens:props?.totalUsage?.inputTokens,outputTokens:props?.totalUsage?.outputTokens,totalTokens:props?.totalUsage?.totalTokens,reasoningTokens:props?.totalUsage?.reasoningTokens,cachedInputTokens:props?.totalUsage?.cachedInputTokens}}});this.logger.debug("[LLM] - Stream Finished:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId,threadId,resourceId});}}};return loop(loopOptions);}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_TEXT_AI_SDK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"THIRD_PARTY"/* THIRD_PARTY */,details:{modelId:firstModel.modelId,modelProvider:firstModel.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown"}},e);llmAISpan?.error({error:mastraError});throw mastraError;}}};// src/loop/network/index.ts
388
+ function loop({resumeContext,models,logger,runId,idGenerator,telemetry_settings,messageList,includeRawChunks,modelSettings,tools,_internal,mode="stream",outputProcessors,returnScorerData,llmAISpan,requireToolApproval,agentId,...rest}){let loggerToUse=logger||new ConsoleLogger({level:"debug"});if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});loggerToUse.trackException(mastraError);loggerToUse.error(mastraError.toString());throw mastraError;}const firstModel=models[0];let runIdToUse=runId;if(!runIdToUse){runIdToUse=idGenerator?.()||crypto.randomUUID();}const internalToUse={now:_internal?.now||(()=>Date.now()),generateId:_internal?.generateId||(()=>generateId()),currentDate:_internal?.currentDate||(()=>/* @__PURE__ */new Date())};let startTimestamp=internalToUse.now?.();const{rootSpan}=getRootSpan({operationId:mode==="stream"?`mastra.stream`:`mastra.generate`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});rootSpan.setAttributes({...(telemetry_settings?.recordOutputs!==false?{"stream.prompt.messages":JSON.stringify(messageList.get.input.aiV5.model())}:{})});const{rootSpan:modelStreamSpan}=getRootSpan({operationId:`mastra.${mode}.aisdk.doStream`,model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider},modelSettings,headers:modelSettings?.headers??rest.headers,telemetry_settings});const messageId=rest.experimental_generateMessageId?.()||internalToUse.generateId?.();let modelOutput;const serializeStreamState=()=>{return modelOutput?.serializeState();};const deserializeStreamState=state=>{modelOutput?.deserializeState(state);};const processorStates=outputProcessors&&outputProcessors.length>0?/* @__PURE__ */new Map():void 0;const workflowLoopProps={resumeContext,models,runId:runIdToUse,logger:loggerToUse,startTimestamp,messageList,includeRawChunks:!!includeRawChunks,_internal:internalToUse,tools,modelStreamSpan,telemetry_settings,modelSettings,outputProcessors,llmAISpan,messageId,agentId,requireToolApproval,streamState:{serialize:serializeStreamState,deserialize:deserializeStreamState},processorStates,...rest};const stream=workflowLoopStream(workflowLoopProps);modelOutput=new MastraModelOutput({model:{modelId:firstModel.model.modelId,provider:firstModel.model.provider,version:firstModel.model.specificationVersion},stream,messageList,messageId,options:{runId:runIdToUse,telemetry_settings,rootSpan,toolCallStreaming:rest.toolCallStreaming,onFinish:rest.options?.onFinish,onStepFinish:rest.options?.onStepFinish,includeRawChunks:!!includeRawChunks,structuredOutput:rest.structuredOutput,outputProcessors,returnScorerData,tracingContext:{currentSpan:llmAISpan}}});return createDestructurableOutput(modelOutput);}// src/llm/model/model.loop.ts
389
+ var MastraLLMVNext=class extends MastraBase{#models;#mastra;#options;#firstModel;constructor({mastra,models,options}){super({name:"aisdk"});this.#options=options;if(mastra){this.#mastra=mastra;if(mastra.getLogger()){this.__setLogger(this.#mastra.getLogger());}}if(models.length===0||!models[0]){const mastraError=new MastraError({id:"LLM_LOOP_MODELS_EMPTY",domain:"LLM"/* LLM */,category:"USER"/* USER */});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}else {this.#models=models;this.#firstModel=models[0];}}__registerPrimitives(p){if(p.telemetry){this.__setTelemetry(p.telemetry);}if(p.logger){this.__setLogger(p.logger);}}__registerMastra(p){this.#mastra=p;}getProvider(){return this.#firstModel.model.provider;}getModelId(){return this.#firstModel.model.modelId;}getModel(){return this.#firstModel.model;}_applySchemaCompat(schema){const model=this.#firstModel.model;const schemaCompatLayers=[];if(model){const modelInfo={modelId:model.modelId,supportsStructuredOutputs:true,provider:model.provider};schemaCompatLayers.push(new OpenAIReasoningSchemaCompatLayer(modelInfo),new OpenAISchemaCompatLayer(modelInfo),new GoogleSchemaCompatLayer(modelInfo),new AnthropicSchemaCompatLayer(modelInfo),new DeepSeekSchemaCompatLayer(modelInfo),new MetaSchemaCompatLayer(modelInfo));}return applyCompatLayer({schema,compatLayers:schemaCompatLayers,mode:"aiSdkSchema"});}convertToMessages(messages){if(Array.isArray(messages)){return messages.map(m=>{if(typeof m==="string"){return {role:"user",content:m};}return m;});}return [{role:"user",content:messages}];}stream({resumeContext,runId,stopWhen=stepCountIs(5),maxSteps,tools={},modelSettings,toolChoice="auto",telemetry_settings,threadId,resourceId,structuredOutput,options,outputProcessors,returnScorerData,providerOptions,tracingContext,messageList,requireToolApproval,_internal,agentId// ...rest
390
+ }){let stopWhenToUse;if(maxSteps&&typeof maxSteps==="number"){stopWhenToUse=stepCountIs(maxSteps);}else {stopWhenToUse=stopWhen;}const messages=messageList.get.all.aiV5.model();const firstModel=this.#firstModel.model;this.logger.debug(`[LLM] - Streaming text`,{runId,threadId,resourceId,messages,tools:Object.keys(tools||{})});const llmAISpan=tracingContext?.currentSpan?.createChildSpan({name:`llm: '${firstModel.modelId}'`,type:"llm_generation"/* LLM_GENERATION */,input:{messages:[...messageList.getSystemMessages(),...messages]},attributes:{model:firstModel.modelId,provider:firstModel.provider,streaming:true,parameters:modelSettings},metadata:{runId,threadId,resourceId},tracingPolicy:this.#options?.tracingPolicy});try{const loopOptions={mastra:this.#mastra,resumeContext,runId,messageList,models:this.#models,tools,stopWhen:stopWhenToUse,toolChoice,modelSettings,providerOptions,telemetry_settings:{...this.experimental_telemetry,...telemetry_settings},_internal,structuredOutput,outputProcessors,returnScorerData,llmAISpan,requireToolApproval,agentId,options:{...options,onStepFinish:async props=>{try{await options?.onStepFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_STEP_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}this.logger.debug("[LLM] - Stream Step Change:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId});if(props?.response?.headers?.["x-ratelimit-remaining-tokens"]&&parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"],10)<2e3){this.logger.warn("Rate limit approaching, waiting 10 seconds",{runId});await delay(10*1e3);}},onFinish:async props=>{try{await options?.onFinish?.({...props,runId});}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_ON_FINISH_CALLBACK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"USER"/* USER */,details:{modelId:props.model?.modelId,modelProvider:props.model?.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown",finishReason:props?.finishReason,toolCalls:props?.toolCalls?JSON.stringify(props.toolCalls):"",toolResults:props?.toolResults?JSON.stringify(props.toolResults):"",usage:props?.usage?JSON.stringify(props.usage):""}},e);llmAISpan?.error({error:mastraError});this.logger.trackException(mastraError);throw mastraError;}llmAISpan?.end({output:{files:props?.files,object:props?.object,reasoning:props?.reasoning,reasoningText:props?.reasoningText,sources:props?.sources,text:props?.text,warnings:props?.warnings},attributes:{finishReason:props?.finishReason,usage:{inputTokens:props?.totalUsage?.inputTokens,outputTokens:props?.totalUsage?.outputTokens,totalTokens:props?.totalUsage?.totalTokens,reasoningTokens:props?.totalUsage?.reasoningTokens,cachedInputTokens:props?.totalUsage?.cachedInputTokens}}});this.logger.debug("[LLM] - Stream Finished:",{text:props?.text,toolCalls:props?.toolCalls,toolResults:props?.toolResults,finishReason:props?.finishReason,usage:props?.usage,runId,threadId,resourceId});}}};return loop(loopOptions);}catch(e){const mastraError=new MastraError({id:"LLM_STREAM_TEXT_AI_SDK_EXECUTION_FAILED",domain:"LLM"/* LLM */,category:"THIRD_PARTY"/* THIRD_PARTY */,details:{modelId:firstModel.modelId,modelProvider:firstModel.provider,runId:runId??"unknown",threadId:threadId??"unknown",resourceId:resourceId??"unknown"}},e);llmAISpan?.error({error:mastraError});throw mastraError;}}};// src/loop/network/index.ts
392
391
  var MastraAgentNetworkStream=class extends ReadableStream$1{#usageCount={inputTokens:0,outputTokens:0,totalTokens:0};#streamPromise;#run;constructor({createStream,run}){const deferredPromise={promise:null,resolve:null,reject:null};deferredPromise.promise=new Promise((resolve,reject)=>{deferredPromise.resolve=resolve;deferredPromise.reject=reject;});const updateUsageCount=usage=>{this.#usageCount.inputTokens+=parseInt(usage?.inputTokens?.toString()??"0",10);this.#usageCount.outputTokens+=parseInt(usage?.outputTokens?.toString()??"0",10);this.#usageCount.totalTokens+=parseInt(usage?.totalTokens?.toString()??"0",10);};super({start:async controller=>{const writer=new WritableStream({write:chunk=>{if(chunk.type==="step-output"&&chunk.payload?.output?.from==="AGENT"&&chunk.payload?.output?.type==="finish"||chunk.type==="step-output"&&chunk.payload?.output?.from==="WORKFLOW"&&chunk.payload?.output?.type==="finish"){const output=chunk.payload?.output;if(output&&"payload"in output&&output.payload){const finishPayload=output.payload;if("usage"in finishPayload&&finishPayload.usage){updateUsageCount(finishPayload.usage);}}}controller.enqueue(chunk);}});const stream=await createStream(writer);for await(const chunk of stream){if(chunk.type==="workflow-step-output"){const innerChunk=chunk.payload.output;if(innerChunk&&typeof innerChunk==="object"&&"payload"in innerChunk){const nestedOutput=innerChunk.payload;if(nestedOutput&&typeof nestedOutput==="object"&&"output"in nestedOutput&&nestedOutput.output){controller.enqueue(nestedOutput.output);}}}}controller.close();deferredPromise.resolve();}});this.#run=run;this.#streamPromise=deferredPromise;}get status(){return this.#streamPromise.promise.then(()=>this.#run._getExecutionResults()).then(res=>res.status);}get result(){return this.#streamPromise.promise.then(()=>this.#run._getExecutionResults());}get usage(){return this.#streamPromise.promise.then(()=>this.#usageCount);}};// src/loop/types.ts
393
392
  var PRIMITIVE_TYPES=z9.enum(["agent","workflow","none","tool"]);// src/loop/network/index.ts
394
393
  async function getRoutingAgent({runtimeContext,agent}){const instructionsToUse=await agent.getInstructions({runtimeContext});const agentsToUse=await agent.listAgents({runtimeContext});const workflowsToUse=await agent.getWorkflows({runtimeContext});const toolsToUse=await agent.getTools({runtimeContext});const model=await agent.getModel({runtimeContext});const memoryToUse=await agent.getMemory({runtimeContext});const agentList=Object.entries(agentsToUse).map(([name,agent2])=>{return ` - **${name}**: ${agent2.getDescription()}`;}).join("\n");const workflowList=Object.entries(workflowsToUse).map(([name,workflow])=>{return ` - **${name}**: ${workflow.description}, input schema: ${JSON.stringify(zodToJsonSchema(workflow.inputSchema))}`;}).join("\n");const memoryTools=await memoryToUse?.getTools?.();const toolList=Object.entries({...toolsToUse,...memoryTools}).map(([name,tool])=>{return ` - **${name}**: ${tool.description}, input schema: ${JSON.stringify(zodToJsonSchema(tool.inputSchema||z9.object({})))}`;}).join("\n");const instructions=`
@@ -413,7 +412,7 @@ async function getRoutingAgent({runtimeContext,agent}){const instructionsToUse=a
413
412
  When calling an agent, the prompt should be a text value, like you would call an LLM in a chat interface.
414
413
  Keep in mind that the user only sees the final result of the task. When reviewing completion, you should know that the user will not see the intermediate results.
415
414
  `;return new Agent({name:"routing-agent",instructions,model,memory:memoryToUse,// @ts-ignore
416
- _agentNetworkAppend:true});}function getLastMessage(messages){let message="";if(typeof messages==="string"){message=messages;}else {const lastMessage=Array.isArray(messages)?messages[messages.length-1]:messages;if(typeof lastMessage==="string"){message=lastMessage;}else if(lastMessage&&`content`in lastMessage&&lastMessage?.content){const lastMessageContent=lastMessage.content;if(typeof lastMessageContent==="string"){message=lastMessageContent;}else if(Array.isArray(lastMessageContent)){const lastPart=lastMessageContent[lastMessageContent.length-1];if(lastPart?.type==="text"){message=lastPart.text;}}}}return message;}async function prepareMemoryStep({threadId,resourceId,messages,routingAgent,runtimeContext,generateId:generateId3}){const memory=await routingAgent.getMemory({runtimeContext});let thread=await memory?.getThreadById({threadId});if(!thread){thread=await memory?.createThread({threadId,title:"",resourceId});}if(typeof messages==="string"){await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"user",content:{parts:[{type:"text",text:messages}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:thread?.id,resourceId:thread?.resourceId}],format:"v2"});}else {const messageList=new MessageList({threadId:thread?.id,resourceId:thread?.resourceId});messageList.add(messages,"user");const messagesToSave=messageList.get.all.v2();await memory?.saveMessages({messages:messagesToSave,format:"v2"});}return {thread};}async function createNetworkLoop({networkName,runtimeContext,runId,agent,generateId:generateId3,routingAgentOptions}){const routingStep=createStep({id:"routing-agent-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),execute:async({inputData,getInitData,writer})=>{const initData=await getInitData();const completionSchema=z9.object({isComplete:z9.boolean(),finalResult:z9.string(),completionReason:z9.string()});const routingAgent=await getRoutingAgent({runtimeContext,agent});let completionResult;let iterationCount=inputData.iteration?inputData.iteration+1:0;await writer.write({type:"routing-agent-start",payload:{inputData:{...inputData,iteration:iterationCount}}});if(inputData.primitiveType!=="none"&&inputData?.result){const completionPrompt=`
415
+ _agentNetworkAppend:true});}function getLastMessage(messages){let message="";if(typeof messages==="string"){message=messages;}else {const lastMessage=Array.isArray(messages)?messages[messages.length-1]:messages;if(typeof lastMessage==="string"){message=lastMessage;}else if(lastMessage&&`content`in lastMessage&&lastMessage?.content){const lastMessageContent=lastMessage.content;if(typeof lastMessageContent==="string"){message=lastMessageContent;}else if(Array.isArray(lastMessageContent)){const lastPart=lastMessageContent[lastMessageContent.length-1];if(lastPart?.type==="text"){message=lastPart.text;}}}}return message;}async function prepareMemoryStep({threadId,resourceId,messages,routingAgent,runtimeContext,generateId:generateId3}){const memory=await routingAgent.getMemory({runtimeContext});let thread=await memory?.getThreadById({threadId});if(!thread){thread=await memory?.createThread({threadId,title:"",resourceId});}if(typeof messages==="string"){await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"user",content:{parts:[{type:"text",text:messages}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:thread?.id,resourceId:thread?.resourceId}],format:"v2"});}else {const messageList=new MessageList({threadId:thread?.id,resourceId:thread?.resourceId});messageList.add(messages,"user");const messagesToSave=messageList.get.all.v2();await memory?.saveMessages({messages:messagesToSave,format:"v2"});}return {thread};}async function createNetworkLoop({networkName,runtimeContext,runId,agent,generateId:generateId3,routingAgentOptions}){const routingStep=createStep({id:"routing-agent-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),execute:async({inputData,getInitData,writer})=>{const initData=await getInitData();const completionSchema=z9.object({isComplete:z9.boolean(),finalResult:z9.string(),completionReason:z9.string()});const routingAgent=await getRoutingAgent({runtimeContext,agent});let completionResult;let iterationCount=inputData.iteration?inputData.iteration+1:0;await writer.write({type:"routing-agent-start",payload:{agentId:routingAgent.id,runId,inputData:{...inputData,iteration:iterationCount}},from:"NETWORK"/* NETWORK */});if(inputData.primitiveType!=="none"&&inputData?.result){const completionPrompt=`
417
416
  The ${inputData.primitiveType} ${inputData.primitiveId} has contributed to the task.
418
417
  This is the result from the agent: ${typeof inputData.result==="object"?JSON.stringify(inputData.result):inputData.result}
419
418
 
@@ -429,7 +428,7 @@ _agentNetworkAppend:true});}function getLastMessage(messages){let message="";if(
429
428
  "completionReason": string,
430
429
  "finalResult": string
431
430
  }
432
- `;completionResult=await routingAgent.generate([{role:"assistant",content:completionPrompt}],{structuredOutput:{schema:completionSchema},runtimeContext,maxSteps:1,memory:{thread:initData?.threadId??runId,resource:initData?.threadResourceId??networkName,readOnly:true},...routingAgentOptions});if(completionResult?.object?.isComplete){const endPayload2={task:inputData.task,primitiveId:"",primitiveType:"none",prompt:"",result:completionResult.object.finalResult,isComplete:true,selectionReason:completionResult.object.completionReason||"",iteration:iterationCount};await writer.write({type:"routing-agent-end",payload:endPayload2});const memory=await agent.getMemory({runtimeContext});await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:completionResult?.object?.finalResult||""}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId,resourceId:initData?.threadResourceId||networkName}],format:"v2"});return endPayload2;}}const prompt=[{role:"assistant",content:`
431
+ `;completionResult=await tryGenerateWithJsonFallback(routingAgent,completionPrompt,{structuredOutput:{schema:completionSchema},runtimeContext,maxSteps:1,memory:{thread:initData?.threadId??runId,resource:initData?.threadResourceId??networkName,readOnly:true},...routingAgentOptions});if(completionResult?.object?.isComplete){const endPayload2={task:inputData.task,primitiveId:"",primitiveType:"none",prompt:"",result:completionResult.object.finalResult,isComplete:true,selectionReason:completionResult.object.completionReason||"",iteration:iterationCount,runId};await writer.write({type:"routing-agent-end",payload:endPayload2,from:"NETWORK"/* NETWORK */});const memory=await agent.getMemory({runtimeContext});await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:completionResult?.object?.finalResult||""}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId,resourceId:initData?.threadResourceId||networkName}],format:"v2"});return endPayload2;}}const prompt=[{role:"assistant",content:`
433
432
  ${inputData.isOneOff?"You are executing just one primitive based on the user task. Make sure to pick the primitive that is the best suited to accomplish the whole task. Primitives that execute only part of the task should be avoided.":"You will be calling just *one* primitive at a time to accomplish the user task, every call to you is one decision in the process of accomplishing the user task. Make sure to pick primitives that are the best suited to accomplish the whole task. Completeness is the highest priority."}
434
433
 
435
434
  The user has given you the following task:
@@ -460,10 +459,10 @@ ${completionResult?.object?.finalResult}`:""}
460
459
  }
461
460
 
462
461
  The 'selectionReason' property should explain why you picked the primitive${inputData.verboseIntrospection?", as well as why the other primitives were not picked.":"."}
463
- `}];const options={structuredOutput:{schema:z9.object({primitiveId:z9.string().describe("The id of the primitive to be called"),primitiveType:PRIMITIVE_TYPES.describe("The type of the primitive to be called"),prompt:z9.string().describe("The json string or text value to be sent to the primitive"),selectionReason:z9.string().describe("The reason you picked the primitive")})},runtimeContext,maxSteps:1,memory:{thread:initData?.threadId??runId,resource:initData?.threadResourceId??networkName,readOnly:true},...routingAgentOptions};const result=await routingAgent.generate(prompt,options);const object=result.object;const endPayload={task:inputData.task,result:"",primitiveId:object.primitiveId,primitiveType:object.primitiveType,prompt:object.prompt,isComplete:object.primitiveId==="none"&&object.primitiveType==="none",selectionReason:object.selectionReason,iteration:iterationCount};await writer.write({type:"routing-agent-end",payload:endPayload});return endPayload;}});const agentStep=createStep({id:"agent-execution-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string(),isComplete:z9.boolean().optional(),iteration:z9.number()}),execute:async({inputData,writer,getInitData})=>{const agentsMap=await agent.listAgents({runtimeContext});const agentId=inputData.primitiveId;const agentForStep=agentsMap[agentId];if(!agentForStep){const mastraError=new MastraError({id:"AGENT_NETWORK_AGENT_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Agent ${agentId} not found`});throw mastraError;}const runId2=generateId3();await writer.write({type:"agent-execution-start",payload:{agentId:inputData.primitiveId,args:inputData,runId:runId2}});const result=await agentForStep.stream(inputData.prompt,{// resourceId: inputData.resourceId,
462
+ `}];const options={structuredOutput:{schema:z9.object({primitiveId:z9.string().describe("The id of the primitive to be called"),primitiveType:PRIMITIVE_TYPES.describe("The type of the primitive to be called"),prompt:z9.string().describe("The json string or text value to be sent to the primitive"),selectionReason:z9.string().describe("The reason you picked the primitive")})},runtimeContext,maxSteps:1,memory:{thread:initData?.threadId??runId,resource:initData?.threadResourceId??networkName,readOnly:true},...routingAgentOptions};const result=await tryGenerateWithJsonFallback(routingAgent,prompt,options);const object=result.object;const endPayload={task:inputData.task,result:"",primitiveId:object.primitiveId,primitiveType:object.primitiveType,prompt:object.prompt,isComplete:object.primitiveId==="none"&&object.primitiveType==="none",selectionReason:object.selectionReason,iteration:iterationCount,runId};await writer.write({type:"routing-agent-end",payload:endPayload,from:"NETWORK"/* NETWORK */});return endPayload;}});const agentStep=createStep({id:"agent-execution-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string(),isComplete:z9.boolean().optional(),iteration:z9.number()}),execute:async({inputData,writer,getInitData})=>{const agentsMap=await agent.listAgents({runtimeContext});const agentId=inputData.primitiveId;const agentForStep=agentsMap[agentId];if(!agentForStep){const mastraError=new MastraError({id:"AGENT_NETWORK_AGENT_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Agent ${agentId} not found`});throw mastraError;}const runId2=generateId3();await writer.write({type:"agent-execution-start",payload:{agentId:inputData.primitiveId,args:inputData,runId:runId2},from:"NETWORK"/* NETWORK */});const result=await agentForStep.stream(inputData.prompt,{// resourceId: inputData.resourceId,
464
463
  // threadId: inputData.threadId,
465
- runtimeContext,runId:runId2});for await(const chunk of result.fullStream){await writer.write({type:`agent-execution-event-${chunk.type}`,payload:chunk});}const memory=await agent.getMemory({runtimeContext});const initData=await getInitData();const messages=result.messageList.get.all.v1();await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:inputData.primitiveId,input:inputData.prompt,finalResult:{text:await result.text,toolCalls:await result.toolCalls,messages}})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId2,resourceId:initData?.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,agentId:inputData.primitiveId,result:await result.text,isComplete:false,iteration:inputData.iteration};await writer.write({type:"agent-execution-end",payload:endPayload});return {task:inputData.task,primitiveId:inputData.primitiveId,primitiveType:inputData.primitiveType,result:await result.text,isComplete:false,iteration:inputData.iteration};}});const workflowStep=createStep({id:"workflow-execution-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string(),isComplete:z9.boolean().optional(),iteration:z9.number()}),execute:async({inputData,writer,getInitData})=>{const workflowsMap=await agent.getWorkflows({runtimeContext});const workflowId=inputData.primitiveId;const wf=workflowsMap[workflowId];if(!wf){const mastraError=new MastraError({id:"AGENT_NETWORK_WORKFLOW_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Workflow ${workflowId} not found`});throw mastraError;}let input;try{input=JSON.parse(inputData.prompt);}catch(e){const mastraError=new MastraError({id:"WORKFLOW_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Invalid task input: ${inputData.task}`},e);throw mastraError;}const run=await wf.createRunAsync();const toolData={name:wf.name,args:inputData,runId:run.runId};await writer?.write({type:"workflow-execution-start",payload:toolData});const stream=run.streamVNext({inputData:input,runtimeContext});let chunks=[];for await(const chunk of stream){chunks.push(chunk);await writer?.write({type:`workflow-execution-event-${chunk.type}`,payload:chunk});}let runSuccess=true;const workflowState=await stream.result;if(!workflowState?.status||workflowState?.status==="failed"){runSuccess=false;}const finalResult=JSON.stringify({isNetwork:true,primitiveType:inputData.primitiveType,primitiveId:inputData.primitiveId,selectionReason:inputData.selectionReason,input,finalResult:{runId:run.runId,runResult:workflowState,chunks,runSuccess}});const memory=await agent.getMemory({runtimeContext});const initData=await getInitData();await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:finalResult}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId,resourceId:initData?.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:inputData.primitiveId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration};await writer?.write({type:"workflow-execution-end",payload:endPayload});return endPayload;}});const toolStep=createStep({id:"tool-execution-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string(),isComplete:z9.boolean().optional(),iteration:z9.number()}),execute:async({inputData,getInitData,writer})=>{const initData=await getInitData();const agentTools=await agent.getTools({runtimeContext});const memory=await agent.getMemory({runtimeContext});const memoryTools=await memory?.getTools?.();const toolsMap={...agentTools,...memoryTools};const toolId=inputData.primitiveId;let tool=toolsMap[toolId];if(!tool){const mastraError=new MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Tool ${toolId} not found`});throw mastraError;}if(!tool.execute){const mastraError=new MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Tool ${toolId} does not have an execute function`});throw mastraError;}let inputDataToUse;try{inputDataToUse=JSON.parse(inputData.prompt);}catch(e){const mastraError=new MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Invalid task input: ${inputData.task}`},e);throw mastraError;}const toolCallId=generateId3();await writer?.write({type:"tool-execution-start",payload:{args:{...inputData,args:inputDataToUse,toolName:toolId,toolCallId},runId}});const finalResult=await tool.execute({runtimeContext,mastra:agent.getMastraInstance(),resourceId:initData.threadResourceId||networkName,threadId:initData.threadId,runId,memory,context:inputDataToUse,// TODO: Pass proper tracing context when network supports tracing
466
- tracingContext:{currentSpan:void 0},writer},{toolCallId,messages:[]});await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:toolId,finalResult:{result:finalResult,toolCallId},input:inputDataToUse})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData.threadId||runId,resourceId:initData.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:toolId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration,toolCallId,toolName:toolId};await writer?.write({type:"tool-execution-end",payload:endPayload});return endPayload;}});const finishStep=createStep({id:"finish-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),result:z9.string(),isComplete:z9.boolean(),iteration:z9.number()}),execute:async({inputData,writer})=>{let endResult=inputData.result;if(inputData.primitiveId==="none"&&inputData.primitiveType==="none"&&!inputData.result){endResult=inputData.selectionReason;}const endPayload={task:inputData.task,result:endResult,isComplete:!!inputData.isComplete,iteration:inputData.iteration};await writer?.write({type:"network-execution-event-step-finish",payload:endPayload});return endPayload;}});const networkWorkflow=createWorkflow({id:"Agent-Network-Outer-Workflow",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),completionReason:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean()}),options:{shouldPersistSnapshot:({workflowStatus})=>workflowStatus==="suspended"}});networkWorkflow.then(routingStep).branch([[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="agent",agentStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="workflow",workflowStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="tool",toolStep],[async({inputData})=>!!inputData.isComplete,finishStep]]).map({task:{step:[routingStep,agentStep,workflowStep,toolStep],path:"task"},isComplete:{step:[agentStep,workflowStep,toolStep,finishStep],path:"isComplete"},completionReason:{step:[routingStep,agentStep,workflowStep,toolStep,finishStep],path:"completionReason"},result:{step:[agentStep,workflowStep,toolStep,finishStep],path:"result"},primitiveId:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveId"},primitiveType:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveType"},iteration:{step:[routingStep,agentStep,workflowStep,toolStep],path:"iteration"},isOneOff:{initData:networkWorkflow,path:"isOneOff"},threadId:{initData:networkWorkflow,path:"threadId"},threadResourceId:{initData:networkWorkflow,path:"threadResourceId"}}).commit();return {networkWorkflow};}async function networkLoop({networkName,runtimeContext,runId,routingAgent,routingAgentOptions,generateId:generateId3,maxIterations,threadId,resourceId,messages}){const memoryToUse=await routingAgent.getMemory({runtimeContext});if(!memoryToUse){throw new MastraError({id:"AGENT_NETWORK_MEMORY_REQUIRED",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:"Memory is required for the agent network to function properly. Please configure memory for the agent.",details:{status:400}});}const{networkWorkflow}=await createNetworkLoop({networkName,runtimeContext,runId,agent:routingAgent,routingAgentOptions,generateId:generateId3});const finalStep=createStep({id:"final-step",inputSchema:networkWorkflow.outputSchema,outputSchema:networkWorkflow.outputSchema,execute:async({inputData,writer})=>{if(inputData.iteration>=maxIterations){await writer?.write({type:"network-execution-event-finish",payload:{...inputData,completionReason:`Max iterations reached: ${maxIterations}`}});return {...inputData,completionReason:`Max iterations reached: ${maxIterations}`};}return inputData;}});const mainWorkflow=createWorkflow({id:"agent-loop-main-workflow",inputSchema:z9.object({iteration:z9.number(),task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),completionReason:z9.string().optional(),iteration:z9.number()}),options:{shouldPersistSnapshot:({workflowStatus})=>workflowStatus==="suspended"}}).dountil(networkWorkflow,async({inputData})=>{return inputData.isComplete||inputData.iteration>=maxIterations;}).then(finalStep).commit();const run=await mainWorkflow.createRunAsync({runId});const{thread}=await prepareMemoryStep({runtimeContext,threadId:threadId||run.runId,resourceId:resourceId||networkName,messages,routingAgent,generateId:generateId3});const task=getLastMessage(messages);return new MastraAgentNetworkStream({run,createStream:()=>{return run.streamVNext({inputData:{task,primitiveId:"",primitiveType:"none",iteration:0,threadResourceId:thread?.resourceId,threadId:thread?.id,isOneOff:false,verboseIntrospection:true}});}});}// src/processors/runner.ts
464
+ runtimeContext,runId:runId2});for await(const chunk of result.fullStream){await writer.write({type:`agent-execution-event-${chunk.type}`,payload:chunk,from:"NETWORK"/* NETWORK */});}const memory=await agent.getMemory({runtimeContext});const initData=await getInitData();const messages=result.messageList.get.all.v1();await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:inputData.primitiveId,input:inputData.prompt,finalResult:{text:await result.text,toolCalls:await result.toolCalls,messages}})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId2,resourceId:initData?.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,agentId:inputData.primitiveId,result:await result.text,isComplete:false,iteration:inputData.iteration};await writer.write({type:"agent-execution-end",payload:endPayload,from:"NETWORK"/* NETWORK */});return {task:inputData.task,primitiveId:inputData.primitiveId,primitiveType:inputData.primitiveType,result:await result.text,isComplete:false,iteration:inputData.iteration};}});const workflowStep=createStep({id:"workflow-execution-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string(),isComplete:z9.boolean().optional(),iteration:z9.number()}),execute:async({inputData,writer,getInitData})=>{const workflowsMap=await agent.getWorkflows({runtimeContext});const workflowId=inputData.primitiveId;const wf=workflowsMap[workflowId];if(!wf){const mastraError=new MastraError({id:"AGENT_NETWORK_WORKFLOW_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Workflow ${workflowId} not found`});throw mastraError;}let input;try{input=JSON.parse(inputData.prompt);}catch(e){const mastraError=new MastraError({id:"WORKFLOW_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Invalid task input: ${inputData.task}`},e);throw mastraError;}const run=await wf.createRunAsync({runId});const toolData={name:wf.name,args:inputData,runId};await writer?.write({type:"workflow-execution-start",payload:toolData,from:"NETWORK"/* NETWORK */});const stream=run.streamVNext({inputData:input,runtimeContext});let chunks=[];for await(const chunk of stream){chunks.push(chunk);await writer?.write({type:`workflow-execution-event-${chunk.type}`,payload:chunk,from:"NETWORK"/* NETWORK */});}let runSuccess=true;const workflowState=await stream.result;if(!workflowState?.status||workflowState?.status==="failed"){runSuccess=false;}const finalResult=JSON.stringify({isNetwork:true,primitiveType:inputData.primitiveType,primitiveId:inputData.primitiveId,selectionReason:inputData.selectionReason,input,finalResult:{runId:run.runId,runResult:workflowState,chunks,runSuccess}});const memory=await agent.getMemory({runtimeContext});const initData=await getInitData();await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:finalResult}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData?.threadId||runId,resourceId:initData?.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:inputData.primitiveId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration};await writer?.write({type:"workflow-execution-end",payload:endPayload,from:"NETWORK"/* NETWORK */});return endPayload;}});const toolStep=createStep({id:"tool-execution-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string(),isComplete:z9.boolean().optional(),iteration:z9.number()}),execute:async({inputData,getInitData,writer})=>{const initData=await getInitData();const agentTools=await agent.getTools({runtimeContext});const memory=await agent.getMemory({runtimeContext});const memoryTools=await memory?.getTools?.();const toolsMap={...agentTools,...memoryTools};const toolId=inputData.primitiveId;let tool=toolsMap[toolId];if(!tool){const mastraError=new MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Tool ${toolId} not found`});throw mastraError;}if(!tool.execute){const mastraError=new MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Tool ${toolId} does not have an execute function`});throw mastraError;}let inputDataToUse;try{inputDataToUse=JSON.parse(inputData.prompt);}catch(e){const mastraError=new MastraError({id:"AGENT_NETWORK_TOOL_EXECUTION_STEP_INVALID_TASK_INPUT",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:`Invalid task input: ${inputData.task}`},e);throw mastraError;}const toolCallId=generateId3();await writer?.write({type:"tool-execution-start",payload:{args:{...inputData,args:inputDataToUse,toolName:toolId,toolCallId},runId},from:"NETWORK"/* NETWORK */});const finalResult=await tool.execute({runtimeContext,mastra:agent.getMastraInstance(),resourceId:initData.threadResourceId||networkName,threadId:initData.threadId,runId,memory,context:inputDataToUse,// TODO: Pass proper tracing context when network supports tracing
465
+ tracingContext:{currentSpan:void 0},writer},{toolCallId,messages:[]});await memory?.saveMessages({messages:[{id:generateId3(),type:"text",role:"assistant",content:{parts:[{type:"text",text:JSON.stringify({isNetwork:true,selectionReason:inputData.selectionReason,primitiveType:inputData.primitiveType,primitiveId:toolId,finalResult:{result:finalResult,toolCallId},input:inputDataToUse})}],format:2},createdAt:/* @__PURE__ */new Date(),threadId:initData.threadId||runId,resourceId:initData.threadResourceId||networkName}],format:"v2"});const endPayload={task:inputData.task,primitiveId:toolId,primitiveType:inputData.primitiveType,result:finalResult,isComplete:false,iteration:inputData.iteration,toolCallId,toolName:toolId};await writer?.write({type:"tool-execution-end",payload:endPayload,from:"NETWORK"/* NETWORK */});return endPayload;}});const finishStep=createStep({id:"finish-step",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),selectionReason:z9.string(),iteration:z9.number()}),outputSchema:z9.object({task:z9.string(),result:z9.string(),isComplete:z9.boolean(),iteration:z9.number()}),execute:async({inputData,writer})=>{let endResult=inputData.result;if(inputData.primitiveId==="none"&&inputData.primitiveType==="none"&&!inputData.result){endResult=inputData.selectionReason;}const endPayload={task:inputData.task,result:endResult,isComplete:!!inputData.isComplete,iteration:inputData.iteration,runId};await writer?.write({type:"network-execution-event-step-finish",payload:endPayload,from:"NETWORK"/* NETWORK */});return endPayload;}});const networkWorkflow=createWorkflow({id:"Agent-Network-Outer-Workflow",inputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),completionReason:z9.string().optional(),iteration:z9.number(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean()}),options:{shouldPersistSnapshot:({workflowStatus})=>workflowStatus==="suspended"}});networkWorkflow.then(routingStep).branch([[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="agent",agentStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="workflow",workflowStep],[async({inputData})=>!inputData.isComplete&&inputData.primitiveType==="tool",toolStep],[async({inputData})=>!!inputData.isComplete,finishStep]]).map({task:{step:[routingStep,agentStep,workflowStep,toolStep],path:"task"},isComplete:{step:[agentStep,workflowStep,toolStep,finishStep],path:"isComplete"},completionReason:{step:[routingStep,agentStep,workflowStep,toolStep,finishStep],path:"completionReason"},result:{step:[agentStep,workflowStep,toolStep,finishStep],path:"result"},primitiveId:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveId"},primitiveType:{step:[routingStep,agentStep,workflowStep,toolStep],path:"primitiveType"},iteration:{step:[routingStep,agentStep,workflowStep,toolStep],path:"iteration"},isOneOff:{initData:networkWorkflow,path:"isOneOff"},threadId:{initData:networkWorkflow,path:"threadId"},threadResourceId:{initData:networkWorkflow,path:"threadResourceId"}}).commit();return {networkWorkflow};}async function networkLoop({networkName,runtimeContext,runId,routingAgent,routingAgentOptions,generateId:generateId3,maxIterations,threadId,resourceId,messages}){const memoryToUse=await routingAgent.getMemory({runtimeContext});if(!memoryToUse){throw new MastraError({id:"AGENT_NETWORK_MEMORY_REQUIRED",domain:"AGENT_NETWORK"/* AGENT_NETWORK */,category:"USER"/* USER */,text:"Memory is required for the agent network to function properly. Please configure memory for the agent.",details:{status:400}});}const{networkWorkflow}=await createNetworkLoop({networkName,runtimeContext,runId,agent:routingAgent,routingAgentOptions,generateId:generateId3});const finalStep=createStep({id:"final-step",inputSchema:networkWorkflow.outputSchema,outputSchema:networkWorkflow.outputSchema,execute:async({inputData,writer})=>{if(inputData.iteration>=maxIterations){await writer?.write({type:"network-execution-event-finish",payload:{...inputData,completionReason:`Max iterations reached: ${maxIterations}`}});return {...inputData,completionReason:`Max iterations reached: ${maxIterations}`};}return inputData;}});const mainWorkflow=createWorkflow({id:"agent-loop-main-workflow",inputSchema:z9.object({iteration:z9.number(),task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,result:z9.string().optional(),threadId:z9.string().optional(),threadResourceId:z9.string().optional(),isOneOff:z9.boolean(),verboseIntrospection:z9.boolean()}),outputSchema:z9.object({task:z9.string(),primitiveId:z9.string(),primitiveType:PRIMITIVE_TYPES,prompt:z9.string(),result:z9.string(),isComplete:z9.boolean().optional(),completionReason:z9.string().optional(),iteration:z9.number()}),options:{shouldPersistSnapshot:({workflowStatus})=>workflowStatus==="suspended"}}).dountil(networkWorkflow,async({inputData})=>{return inputData.isComplete||inputData.iteration>=maxIterations;}).then(finalStep).commit();const run=await mainWorkflow.createRunAsync({runId});const{thread}=await prepareMemoryStep({runtimeContext,threadId:threadId||run.runId,resourceId:resourceId||networkName,messages,routingAgent,generateId:generateId3});const task=getLastMessage(messages);return new MastraAgentNetworkStream({run,createStream:()=>{return run.streamVNext({inputData:{task,primitiveId:"",primitiveType:"none",iteration:0,threadResourceId:thread?.resourceId,threadId:thread?.id,isOneOff:false,verboseIntrospection:true}});}});}// src/processors/runner.ts
467
466
  var ProcessorState=class{accumulatedText="";customState={};streamParts=[];constructor(_processorName){}// Internal methods for the runner
468
467
  addPart(part){if(part.type==="text-delta"){this.accumulatedText+=part.payload.text;}this.streamParts.push(part);}};var ProcessorRunner=class{inputProcessors;outputProcessors;logger;agentName;constructor({inputProcessors,outputProcessors,logger,agentName}){this.inputProcessors=inputProcessors??[];this.outputProcessors=outputProcessors??[];this.logger=logger;this.agentName=agentName;}async runOutputProcessors(messageList,tracingContext,telemetry){const responseMessages=messageList.clear.response.v2();let processableMessages=[...responseMessages];const ctx={abort:()=>{throw new TripWire("Tripwire triggered");}};for(const[index,processor]of this.outputProcessors.entries()){const abort=reason=>{throw new TripWire(reason||`Tripwire triggered by ${processor.name}`);};ctx.abort=abort;const processMethod=processor.processOutputResult?.bind(processor);if(!processMethod){continue;}if(!telemetry){processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext});}else {await telemetry.traceMethod(async()=>{processableMessages=await processMethod({messages:processableMessages,abort:ctx.abort,tracingContext});return processableMessages;},{spanName:`agent.outputProcessor.${processor.name}`,attributes:{"processor.name":processor.name,"processor.index":index.toString(),"processor.total":this.outputProcessors.length.toString()}})();}}if(processableMessages.length>0){messageList.add(processableMessages,"response");}return messageList;}/**
469
468
  * Process a stream part through all output processors with state management
@@ -555,9 +554,9 @@ var SaveQueueManager=class _SaveQueueManager{logger;debounceMs;memory;static MAX
555
554
  * @param threadId - The ID of the thread whose messages are being saved.
556
555
  * @param memoryConfig - Optional memory configuration for saving.
557
556
  */async flushMessages(messageList,threadId,memoryConfig){if(!threadId)return;this.clearDebounce(threadId);return this.enqueueSave(threadId,messageList,memoryConfig);}};// src/agent/workflows/prepare-stream/index.ts
558
- var STRUCTURED_OUTPUT_PROCESSOR_NAME="structured-output";var StructuredOutputProcessor=class{name=STRUCTURED_OUTPUT_PROCESSOR_NAME;schema;structuringAgent;errorStrategy;fallbackValue;isStructuringAgentStreamStarted=false;constructor(options,fallbackModel){this.schema=options.schema;this.errorStrategy=options.errorStrategy??"strict";this.fallbackValue=options.fallbackValue;const modelToUse=options.model||fallbackModel;if(!modelToUse){throw new Error("StructuredOutputProcessor requires a model to be provided either in options or as fallback");}this.structuringAgent=new Agent({name:"structured-output-structurer",instructions:options.instructions||this.generateInstructions(),model:modelToUse,options:{tracingPolicy:{internal:15/* ALL */}}});}async processOutputStream(args){const{part,state,streamParts,abort}=args;const controller=state.controller;switch(part.type){case "finish":await this.processAndEmitStructuredOutput(streamParts,controller,abort);return part;default:return part;}}async processAndEmitStructuredOutput(streamParts,controller,abort){if(this.isStructuringAgentStreamStarted)return;this.isStructuringAgentStreamStarted=true;try{const structuringPrompt=this.buildStructuringPrompt(streamParts);const prompt=`Extract and structure the key information from the following text according to the specified schema. Keep the original meaning and details:
557
+ var STRUCTURED_OUTPUT_PROCESSOR_NAME="structured-output";var StructuredOutputProcessor=class{name=STRUCTURED_OUTPUT_PROCESSOR_NAME;schema;structuringAgent;errorStrategy;fallbackValue;isStructuringAgentStreamStarted=false;jsonPromptInjection;constructor(options){if(!options.schema){throw new MastraError({id:"STRUCTURED_OUTPUT_PROCESSOR_SCHEMA_REQUIRED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"StructuredOutputProcessor requires a schema to be provided"});}if(!options.model){throw new MastraError({id:"STRUCTURED_OUTPUT_PROCESSOR_MODEL_REQUIRED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"StructuredOutputProcessor requires a model to be provided either in options or as fallback"});}this.schema=options.schema;this.errorStrategy=options.errorStrategy??"strict";this.fallbackValue=options.fallbackValue;this.jsonPromptInjection=options.jsonPromptInjection;this.structuringAgent=new Agent({name:"structured-output-structurer",instructions:options.instructions||this.generateInstructions(),model:options.model,options:{tracingPolicy:{internal:15/* ALL */}}});}async processOutputStream(args){const{part,state,streamParts,abort}=args;const controller=state.controller;switch(part.type){case "finish":await this.processAndEmitStructuredOutput(streamParts,controller,abort);return part;default:return part;}}async processAndEmitStructuredOutput(streamParts,controller,abort){if(this.isStructuringAgentStreamStarted)return;this.isStructuringAgentStreamStarted=true;try{const structuringPrompt=this.buildStructuringPrompt(streamParts);const prompt=`Extract and structure the key information from the following text according to the specified schema. Keep the original meaning and details:
559
558
 
560
- ${structuringPrompt}`;const structuringAgentStream=await this.structuringAgent.stream(prompt,{output:this.schema});const excludedChunkTypes=["start","finish","text-start","text-delta","text-end","step-start","step-finish"];for await(const chunk of structuringAgentStream.fullStream){if(excludedChunkTypes.includes(chunk.type)){continue;}if(chunk.type==="error"){this.handleError("Structuring failed","Internal agent did not generate structured output",abort);if(this.errorStrategy==="warn"){break;}if(this.errorStrategy==="fallback"&&this.fallbackValue!==void 0){const fallbackChunk={runId:chunk.runId,from:"AGENT"/* AGENT */,type:"object-result",object:this.fallbackValue,metadata:{from:"structured-output",fallback:true}};controller.enqueue(fallbackChunk);break;}}const newChunk={...chunk,metadata:{from:"structured-output"}};controller.enqueue(newChunk);}}catch(error){this.handleError("Structured output processing failed",error instanceof Error?error.message:"Unknown error",abort);}}/**
559
+ ${structuringPrompt}`;const structuringAgentStream=await this.structuringAgent.stream(prompt,{structuredOutput:{schema:this.schema,jsonPromptInjection:this.jsonPromptInjection}});const excludedChunkTypes=["start","finish","text-start","text-delta","text-end","step-start","step-finish"];for await(const chunk of structuringAgentStream.fullStream){if(excludedChunkTypes.includes(chunk.type)){continue;}if(chunk.type==="error"){this.handleError("Structuring failed","Internal agent did not generate structured output",abort);if(this.errorStrategy==="warn"){break;}if(this.errorStrategy==="fallback"&&this.fallbackValue!==void 0){const fallbackChunk={runId:chunk.runId,from:"AGENT"/* AGENT */,type:"object-result",object:this.fallbackValue,metadata:{from:"structured-output",fallback:true}};controller.enqueue(fallbackChunk);break;}}const newChunk={...chunk,metadata:{from:"structured-output"}};controller.enqueue(newChunk);}}catch(error){this.handleError("Structured output processing failed",error instanceof Error?error.message:"Unknown error",abort);}}/**
561
560
  * Build a structured markdown prompt from stream parts
562
561
  * Collects chunks by type and formats them in a consistent structure
563
562
  */buildStructuringPrompt(streamParts){const textChunks=[];const reasoningChunks=[];const toolCalls=[];const toolResults=[];for(const part of streamParts){switch(part.type){case "text-delta":textChunks.push(part.payload.text);break;case "reasoning-delta":reasoningChunks.push(part.payload.text);break;case "tool-call":toolCalls.push(part);break;case "tool-result":toolResults.push(part);break;}}const sections=[];if(reasoningChunks.length>0){sections.push(`# Assistant Reasoning
@@ -605,7 +604,7 @@ case "redact":default:const redactedText=detectionResult.redacted_content||this.
605
604
  * Removes or redacts system prompts from assistant messages
606
605
  */async processOutputResult({messages,abort}){const processedMessages=[];for(const message of messages){if(message.role!=="assistant"||!message.content?.parts){processedMessages.push(message);continue;}const textContent=this.extractTextFromMessage(message);if(!textContent){processedMessages.push(message);continue;}try{const detectionResult=await this.detectSystemPrompts(textContent);if(detectionResult.detections&&detectionResult.detections.length>0){const detectedTypes=detectionResult.detections.map(detection=>detection.type);switch(this.strategy){case "block":abort(`System prompt detected: ${detectedTypes.join(", ")}`);break;case "filter":continue;case "warn":console.warn(`[SystemPromptScrubber] System prompt detected: ${detectedTypes.join(", ")}`);if(this.includeDetections&&detectionResult.detections){console.warn(`[SystemPromptScrubber] Detections: ${detectionResult.detections.length} items`);}processedMessages.push(message);break;case "redact":default:const redactedText=detectionResult.redacted_content||this.redactText(textContent,detectionResult.detections||[]);const redactedMessage=this.createRedactedMessage(message,redactedText);processedMessages.push(redactedMessage);break;}}else {processedMessages.push(message);}}catch(error){if(error instanceof Error&&error.message.includes("System prompt detected:")){throw error;}console.warn("[SystemPromptScrubber] Detection failed, allowing content:",error);processedMessages.push(message);}}return processedMessages;}/**
607
606
  * Detect system prompts in text using the detection agent
608
- */async detectSystemPrompts(text,tracingContext){try{const model=await this.detectionAgent.getModel();let result;const schema=z.object({detections:z.array(z.object({type:z.string(),value:z.string(),confidence:z.number().min(0).max(1),start:z.number(),end:z.number(),redacted_value:z.string().optional()})).optional(),redacted_content:z.string().optional()});if(model.specificationVersion==="v2"){result=await this.detectionAgent.generate(text,{output:schema,tracingContext});}else {result=await this.detectionAgent.generateLegacy(text,{output:schema,tracingContext});}return result.object;}catch(error){console.warn("[SystemPromptScrubber] Detection agent failed:",error);return {};}}/**
607
+ */async detectSystemPrompts(text,tracingContext){try{const model=await this.detectionAgent.getModel();let result;const schema=z.object({detections:z.array(z.object({type:z.string(),value:z.string(),confidence:z.number().min(0).max(1),start:z.number(),end:z.number(),redacted_value:z.string().optional()})).optional(),redacted_content:z.string().optional()});if(model.specificationVersion==="v2"){result=await this.detectionAgent.generate(text,{structuredOutput:{schema},tracingContext});}else {result=await this.detectionAgent.generateLegacy(text,{output:schema,tracingContext});}return result.object;}catch(error){console.warn("[SystemPromptScrubber] Detection agent failed:",error);return {};}}/**
609
608
  * Redact text based on detected system prompts
610
609
  */redactText(text,detections){if(detections.length===0){return text;}const sortedDetections=[...detections].sort((a,b)=>b.start-a.start);let redactedText=text;for(const detection of sortedDetections){const before=redactedText.substring(0,detection.start);const after=redactedText.substring(detection.end);let replacement;switch(this.redactionMethod){case "mask":replacement="*".repeat(detection.value.length);break;case "placeholder":replacement=detection.redacted_value||this.placeholderText;break;case "remove":replacement="";break;default:replacement="*".repeat(detection.value.length);}redactedText=before+replacement+after;}return redactedText;}/**
611
610
  * Extract text content from a message
@@ -626,7 +625,7 @@ Look for:
626
625
  ${this.customPatterns.length>0?`Additional custom patterns to detect: ${this.customPatterns.join(", ")}`:""}
627
626
 
628
627
  Be thorough but avoid false positives. Only flag content that genuinely represents a security risk.`;}};// src/agent/workflows/prepare-stream/map-results-step.ts
629
- function createMapResultsStep({capabilities,options,resourceId,runId,runtimeContext,memory,memoryConfig,saveQueueManager,agentAISpan,instructions,agentId}){return async({inputData,bail,tracingContext})=>{const toolsData=inputData["prepare-tools-step"];const memoryData=inputData["prepare-memory-step"];const result={...options,tools:toolsData.convertedTools,toolChoice:options.toolChoice,thread:memoryData.thread,threadId:memoryData.thread?.id,resourceId,runtimeContext,onStepFinish:async props=>{if(options.savePerStep){if(!memoryData.threadExists&&memory&&memoryData.thread){await memory.createThread({threadId:memoryData.thread?.id,title:memoryData.thread?.title,metadata:memoryData.thread?.metadata,resourceId:memoryData.thread?.resourceId,memoryConfig});memoryData.threadExists=true;}await capabilities.saveStepMessages({saveQueueManager,result:props,messageList:memoryData.messageList,threadId:memoryData.thread?.id,memoryConfig,runId});}return options.onStepFinish?.({...props,runId});},...(memoryData.tripwire&&{tripwire:memoryData.tripwire,tripwireReason:memoryData.tripwireReason})};if(result.tripwire){const agentModel=await capabilities.getModel({runtimeContext:result.runtimeContext});const modelOutput=await getModelOutputForTripwire({tripwireReason:result.tripwireReason,runId,tracingContext,options,model:agentModel,messageList:memoryData.messageList});return bail(modelOutput);}let effectiveOutputProcessors=options.outputProcessors||(capabilities.outputProcessors?typeof capabilities.outputProcessors==="function"?await capabilities.outputProcessors({runtimeContext:result.runtimeContext}):capabilities.outputProcessors:[]);if(options.structuredOutput?.model){const structuredProcessor=new StructuredOutputProcessor(options.structuredOutput);effectiveOutputProcessors=effectiveOutputProcessors?[...effectiveOutputProcessors,structuredProcessor]:[structuredProcessor];}const messageList=memoryData.messageList;const loopOptions={agentId,runtimeContext:result.runtimeContext,tracingContext:{currentSpan:agentAISpan},runId,toolChoice:result.toolChoice,tools:result.tools,resourceId:result.resourceId,threadId:result.threadId,structuredOutput:result.structuredOutput,stopWhen:result.stopWhen,maxSteps:result.maxSteps,providerOptions:result.providerOptions,options:{...(options.prepareStep&&{prepareStep:options.prepareStep}),onFinish:async payload=>{if(payload.finishReason==="error"){capabilities.logger.error("Error in agent stream",{error:payload.error,runId});return;}try{const outputText=messageList.get.all.core().map(m=>m.content).join("\n");await capabilities.executeOnFinish({result:payload,outputText,instructions,thread:result.thread,threadId:result.threadId,readOnlyMemory:options.memory?.readOnly,resourceId,memoryConfig,runtimeContext,agentAISpan,runId,messageList,threadExists:memoryData.threadExists,structuredOutput:!!options.output,saveQueueManager,overrideScorers:options.scorers});}catch(e){capabilities.logger.error("Error saving memory on finish",{error:e,runId});}await options?.onFinish?.({...payload,runId,messages:messageList.get.response.aiV5.model(),usage:payload.usage,totalUsage:payload.totalUsage});},onStepFinish:result.onStepFinish,onChunk:options.onChunk,onError:options.onError,onAbort:options.onAbort,activeTools:options.activeTools,abortSignal:options.abortSignal},output:options.output,outputProcessors:effectiveOutputProcessors,modelSettings:{temperature:0,...(options.modelSettings||{})},messageList:memoryData.messageList};return loopOptions;};}// src/agent/workflows/prepare-stream/prepare-memory-step.ts
628
+ function createMapResultsStep({capabilities,options,resourceId,runId,runtimeContext,memory,memoryConfig,saveQueueManager,agentAISpan,instructions,agentId}){return async({inputData,bail,tracingContext})=>{const toolsData=inputData["prepare-tools-step"];const memoryData=inputData["prepare-memory-step"];const result={...options,tools:toolsData.convertedTools,toolChoice:options.toolChoice,thread:memoryData.thread,threadId:memoryData.thread?.id,resourceId,runtimeContext,onStepFinish:async props=>{if(options.savePerStep){if(!memoryData.threadExists&&memory&&memoryData.thread){await memory.createThread({threadId:memoryData.thread?.id,title:memoryData.thread?.title,metadata:memoryData.thread?.metadata,resourceId:memoryData.thread?.resourceId,memoryConfig});memoryData.threadExists=true;}await capabilities.saveStepMessages({saveQueueManager,result:props,messageList:memoryData.messageList,threadId:memoryData.thread?.id,memoryConfig,runId});}return options.onStepFinish?.({...props,runId});},...(memoryData.tripwire&&{tripwire:memoryData.tripwire,tripwireReason:memoryData.tripwireReason})};if(result.tripwire){const agentModel=await capabilities.getModel({runtimeContext:result.runtimeContext});const modelOutput=await getModelOutputForTripwire({tripwireReason:result.tripwireReason,runId,tracingContext,options,model:agentModel,messageList:memoryData.messageList});return bail(modelOutput);}let effectiveOutputProcessors=options.outputProcessors||(capabilities.outputProcessors?typeof capabilities.outputProcessors==="function"?await capabilities.outputProcessors({runtimeContext:result.runtimeContext}):capabilities.outputProcessors:[]);if(options.structuredOutput?.model){const structuredProcessor=new StructuredOutputProcessor(options.structuredOutput);effectiveOutputProcessors=effectiveOutputProcessors?[...effectiveOutputProcessors,structuredProcessor]:[structuredProcessor];}const messageList=memoryData.messageList;const loopOptions={agentId,runtimeContext:result.runtimeContext,tracingContext:{currentSpan:agentAISpan},runId,toolChoice:result.toolChoice,tools:result.tools,resourceId:result.resourceId,threadId:result.threadId,stopWhen:result.stopWhen,maxSteps:result.maxSteps,providerOptions:result.providerOptions,options:{...(options.prepareStep&&{prepareStep:options.prepareStep}),onFinish:async payload=>{if(payload.finishReason==="error"){capabilities.logger.error("Error in agent stream",{error:payload.error,runId});return;}try{const outputText=messageList.get.all.core().map(m=>m.content).join("\n");await capabilities.executeOnFinish({result:payload,outputText,instructions,thread:result.thread,threadId:result.threadId,readOnlyMemory:options.memory?.readOnly,resourceId,memoryConfig,runtimeContext,agentAISpan,runId,messageList,threadExists:memoryData.threadExists,structuredOutput:!!options.structuredOutput?.schema,saveQueueManager,overrideScorers:options.scorers});}catch(e){capabilities.logger.error("Error saving memory on finish",{error:e,runId});}await options?.onFinish?.({...payload,runId,messages:messageList.get.response.aiV5.model(),usage:payload.usage,totalUsage:payload.totalUsage});},onStepFinish:result.onStepFinish,onChunk:options.onChunk,onError:options.onError,onAbort:options.onAbort,activeTools:options.activeTools,abortSignal:options.abortSignal},structuredOutput:options.structuredOutput,outputProcessors:effectiveOutputProcessors,modelSettings:{temperature:0,...(options.modelSettings||{})},messageList:memoryData.messageList};return loopOptions;};}// src/agent/workflows/prepare-stream/prepare-memory-step.ts
630
629
  var import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var coreToolSchema=z.object({id:z.string().optional(),description:z.string().optional(),parameters:z.union([z.record(z.string(),z.any()),// JSON Schema as object
631
630
  z.any()// Zod schema or other schema types - validated at tool execution
632
631
  ]),outputSchema:z.union([z.record(z.string(),z.any()),z.any()]).optional(),execute:z.function(z.tuple([z.any(),z.any()]),z.promise(z.any())).optional(),type:z.union([z.literal("function"),z.literal("provider-defined"),z.undefined()]).optional(),args:z.record(z.string(),z.any()).optional()});var storageThreadSchema=z.object({id:z.string(),title:z.string().optional(),resourceId:z.string(),createdAt:z.date(),updatedAt:z.date(),metadata:z.record(z.string(),z.any()).optional()});var prepareToolsStepOutputSchema=z.object({convertedTools:z.record(z.string(),coreToolSchema)});var prepareMemoryStepOutputSchema=z.object({threadExists:z.boolean(),thread:storageThreadSchema.optional(),messageList:z.instanceof(MessageList),tripwire:z.boolean().optional(),tripwireReason:z.string().optional()});// src/agent/workflows/prepare-stream/prepare-memory-step.ts
@@ -640,10 +639,10 @@ the following messages are from ${ymd}
640
639
  <end_remembered_from_other_conversation>`;}if(memorySystemMessage){messageList.addSystem(memorySystemMessage,"memory");}messageList.add(memoryMessages.filter(m=>m.threadId===threadObject.id),"memory").add(options.messages,"user");const{tripwireTriggered,tripwireReason}=await capabilities.runInputProcessors({runtimeContext,tracingContext,messageList});const systemMessages=messageList.getSystemMessages();const systemMessage=[...systemMessages,...messageList.getSystemMessages("memory")]?.map(m=>m.content)?.join(`
641
640
  `)??void 0;const processedMemoryMessages=await memory.processMessages({messages:messageList.get.remembered.v1(),newMessages:messageList.get.input.v1(),systemMessage,memorySystemMessage:memorySystemMessage||void 0});const processedList=new MessageList({threadId:threadObject.id,resourceId,generateMessageId:capabilities.generateMessageId,// @ts-ignore Flag for agent network messages
642
641
  _agentNetworkAppend:capabilities._agentNetworkAppend});addSystemMessage(processedList,instructions);processedList.addSystem(memorySystemMessage).addSystem(systemMessages).add(options.context||[],"context");addSystemMessage(processedList,options.system,"user-provided");processedList.add(processedMemoryMessages,"memory").add(messageList.get.input.v2(),"user");return {thread:threadObject,messageList:processedList,...(tripwireTriggered&&{tripwire:true,tripwireReason}),threadExists:!!existingThread};}});}// src/agent/workflows/prepare-stream/prepare-tools-step.ts
643
- function createPrepareToolsStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,memory}){return createStep({id:"prepare-tools-step",inputSchema:z.object({}),outputSchema:prepareToolsStepOutputSchema,execute:async()=>{const toolEnhancements=[options?.toolsets&&Object.keys(options?.toolsets||{}).length>0?`toolsets present (${Object.keys(options?.toolsets||{}).length} tools)`:void 0,memory&&resourceId?"memory and resourceId available":void 0].filter(Boolean).join(", ");capabilities.logger.debug(`[Agent:${capabilities.agentName}] - Enhancing tools: ${toolEnhancements}`,{runId,toolsets:options?.toolsets?Object.keys(options?.toolsets):void 0,clientTools:options?.clientTools?Object.keys(options?.clientTools):void 0,hasMemory:!!memory,hasResourceId:!!resourceId});const threadId=threadFromArgs?.id;const convertedTools=await capabilities.convertTools({toolsets:options?.toolsets,clientTools:options?.clientTools,threadId,resourceId,runId,runtimeContext,tracingContext:{currentSpan:agentAISpan},writableStream:options.writableStream,methodType,format});return {convertedTools};}});}// src/agent/workflows/prepare-stream/stream-step.ts
642
+ function createPrepareToolsStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,memory}){return createStep({id:"prepare-tools-step",inputSchema:z.object({}),outputSchema:prepareToolsStepOutputSchema,execute:async()=>{const toolEnhancements=[options?.toolsets&&Object.keys(options?.toolsets||{}).length>0?`toolsets present (${Object.keys(options?.toolsets||{}).length} tools)`:void 0,memory&&resourceId?"memory and resourceId available":void 0].filter(Boolean).join(", ");capabilities.logger.debug(`[Agent:${capabilities.agentName}] - Enhancing tools: ${toolEnhancements}`,{runId,toolsets:options?.toolsets?Object.keys(options?.toolsets):void 0,clientTools:options?.clientTools?Object.keys(options?.clientTools):void 0,hasMemory:!!memory,hasResourceId:!!resourceId});const threadId=threadFromArgs?.id;const convertedTools=await capabilities.convertTools({toolsets:options?.toolsets,clientTools:options?.clientTools,threadId,resourceId,runId,runtimeContext,tracingContext:{currentSpan:agentAISpan},writableStream:options.writableStream,methodType});return {convertedTools};}});}// src/agent/workflows/prepare-stream/stream-step.ts
644
643
  function createStreamStep({capabilities,runId,returnScorerData,format="mastra",requireToolApproval,resumeContext,agentId}){return createStep({id:"stream-text-step",inputSchema:z.any(),// tried to type this in various ways but it's too complex
645
644
  outputSchema:z.union([z.instanceof(MastraModelOutput),z.instanceof(AISDKV5OutputStream)]),execute:async({inputData,tracingContext})=>{const validatedInputData=inputData;capabilities.logger.debug(`Starting agent ${capabilities.agentName} llm stream call`,{runId});const processors=validatedInputData.outputProcessors||(capabilities.outputProcessors?typeof capabilities.outputProcessors==="function"?await capabilities.outputProcessors({runtimeContext:validatedInputData.runtimeContext||new RuntimeContext()}):capabilities.outputProcessors:[]);const streamResult=capabilities.llm.stream({...validatedInputData,outputProcessors:processors,returnScorerData,tracingContext,requireToolApproval,resumeContext,_internal:{generateId:capabilities.generateMessageId},agentId});if(format==="aisdk"){return streamResult.aisdk.v5;}return streamResult;}});}// src/agent/workflows/prepare-stream/index.ts
646
- function createPrepareStreamWorkflow({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,instructions,memoryConfig,memory,saveQueueManager,returnScorerData,requireToolApproval,resumeContext,agentId}){const prepareToolsStep=createPrepareToolsStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,memory});const prepareMemoryStep2=createPrepareMemoryStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,instructions,memoryConfig,memory});const streamStep=createStreamStep({capabilities,runId,returnScorerData,format,requireToolApproval,resumeContext,agentId});const mapResultsStep=createMapResultsStep({capabilities,options,resourceId,runId,runtimeContext,memory,memoryConfig,saveQueueManager,agentAISpan,instructions,agentId});return createWorkflow({id:"execution-workflow",inputSchema:z.object({}),outputSchema:z.union([z.instanceof(MastraModelOutput),z.instanceof(AISDKV5OutputStream)]),steps:[prepareToolsStep,prepareMemoryStep2,streamStep],options:{tracingPolicy:{internal:1/* WORKFLOW */}}}).parallel([prepareToolsStep,prepareMemoryStep2]).map(mapResultsStep).then(streamStep).commit();}// src/agent/agent.ts
645
+ function createPrepareStreamWorkflow({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,format,instructions,memoryConfig,memory,saveQueueManager,returnScorerData,requireToolApproval,resumeContext,agentId}){const prepareToolsStep=createPrepareToolsStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,agentAISpan,methodType,memory});const prepareMemoryStep2=createPrepareMemoryStep({capabilities,options,threadFromArgs,resourceId,runId,runtimeContext,instructions,memoryConfig,memory});const streamStep=createStreamStep({capabilities,runId,returnScorerData,format,requireToolApproval,resumeContext,agentId});const mapResultsStep=createMapResultsStep({capabilities,options,resourceId,runId,runtimeContext,memory,memoryConfig,saveQueueManager,agentAISpan,instructions,agentId});return createWorkflow({id:"execution-workflow",inputSchema:z.object({}),outputSchema:z.union([z.instanceof(MastraModelOutput),z.instanceof(AISDKV5OutputStream)]),steps:[prepareToolsStep,prepareMemoryStep2,streamStep],options:{tracingPolicy:{internal:1/* WORKFLOW */}}}).parallel([prepareToolsStep,prepareMemoryStep2]).map(mapResultsStep).then(streamStep).commit();}// src/agent/agent.ts
647
646
  function resolveMaybePromise(value,cb){if(value instanceof Promise){return value.then(cb);}return cb(value);}function resolveThreadIdFromArgs(args){if(args?.memory?.thread){if(typeof args.memory.thread==="string")return {id:args.memory.thread};if(typeof args.memory.thread==="object"&&args.memory.thread.id)return args.memory.thread;}if(args?.threadId)return {id:args.threadId};return void 0;}var _Agent_decorators,_init,_a;_Agent_decorators=[InstrumentClass({prefix:"agent",excludeMethods:["hasOwnMemory","getMemory","__primitive","__registerMastra","__registerPrimitives","__runInputProcessors","__runOutputProcessors","_wrapToolsWithAITracing","getProcessorRunner","__setTools","__setLogger","__setTelemetry","log","listAgents","getModel","getInstructions","getTools","getLLM","getWorkflows","getDefaultGenerateOptions","getDefaultStreamOptions","getDescription","getScorers","getVoice"]})];var Agent=class extends(_a=MastraBase){id;name;#instructions;#description;model;maxRetries;#mastra;#memory;#workflows;#defaultGenerateOptions;#defaultStreamOptions;#defaultVNextStreamOptions;#tools;evals;#scorers;#agents;#voice;#inputProcessors;#outputProcessors;#options;// This flag is for agent network messages. We should change the agent network formatting and remove this flag after.
648
647
  _agentNetworkAppend=false;/**
649
648
  * Creates a new Agent instance with the specified configuration.
@@ -770,7 +769,7 @@ _agentNetworkAppend=false;/**
770
769
  * const options = await agent.getDefaultVNextStreamOptions();
771
770
  * console.log(options.maxSteps); // 5
772
771
  * ```
773
- */getDefaultVNextStreamOptions({runtimeContext=new RuntimeContext()}={}){if(typeof this.#defaultVNextStreamOptions!=="function"){return this.#defaultVNextStreamOptions;}const result=this.#defaultVNextStreamOptions({runtimeContext,mastra:this.#mastra});return resolveMaybePromise(result,options=>{if(!options){const mastraError=new MastraError({id:"AGENT_GET_DEFAULT_VNEXT_STREAM_OPTIONS_FUNCTION_EMPTY_RETURN",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Function-based default vnext stream options returned empty value`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return options;});}get tools(){this.logger.warn("The tools property is deprecated. Please use getTools() instead.");if(typeof this.#tools==="function"){const mastraError=new MastraError({id:"AGENT_GET_TOOLS_FUNCTION_INCOMPATIBLE_WITH_TOOL_FUNCTION_TYPE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:"Tools are not compatible when tools are a function. Please use getTools() instead."});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return ensureToolProperties(this.#tools);}/**
772
+ */getDefaultVNextStreamOptions({runtimeContext=new RuntimeContext()}={}){if(typeof this.#defaultVNextStreamOptions!=="function"){if(this.#defaultVNextStreamOptions.output&&this.#defaultVNextStreamOptions.structuredOutput){throw new MastraError({id:"AGENT_GET_DEFAULT_VNEXT_STREAM_OPTIONS_OUTPUT_AND_STRUCTURED_OUTPUT_PROVIDED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"output and structuredOutput cannot be provided at the same time"});}const{output,...defaultVNextStreamOptions}=this.#defaultVNextStreamOptions;return {...(output?{structuredOutput:{schema:output}}:{}),...defaultVNextStreamOptions};}const result=this.#defaultVNextStreamOptions({runtimeContext,mastra:this.#mastra});return resolveMaybePromise(result,options=>{if(!options){const mastraError=new MastraError({id:"AGENT_GET_DEFAULT_VNEXT_STREAM_OPTIONS_FUNCTION_EMPTY_RETURN",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - Function-based default vnext stream options returned empty value`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}if(options.output&&options.structuredOutput){throw new MastraError({id:"AGENT_GET_DEFAULT_VNEXT_STREAM_OPTIONS_OUTPUT_AND_STRUCTURED_OUTPUT_PROVIDED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"output and structuredOutput cannot be provided at the same time"});}const{output,...restOptions}=options;return {...(output?{structuredOutput:{schema:output}}:{}),...restOptions};});}get tools(){this.logger.warn("The tools property is deprecated. Please use getTools() instead.");if(typeof this.#tools==="function"){const mastraError=new MastraError({id:"AGENT_GET_TOOLS_FUNCTION_INCOMPATIBLE_WITH_TOOL_FUNCTION_TYPE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:"Tools are not compatible when tools are a function. Please use getTools() instead."});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}return ensureToolProperties(this.#tools);}/**
774
773
  * Gets the tools configured for this agent, resolving function-based tools if necessary.
775
774
  * Tools extend the agent's capabilities, allowing it to perform specific actions or access external systems.
776
775
  *
@@ -790,14 +789,11 @@ _agentNetworkAppend=false;/**
790
789
  * const customLlm = await agent.getLLM({ model: 'openai/gpt-5' });
791
790
  * ```
792
791
  */getLLM({runtimeContext=new RuntimeContext(),model}={}){const modelToUse=this.getModel({modelConfig:model,runtimeContext});return resolveMaybePromise(modelToUse,resolvedModel=>{let llm;if(resolvedModel.specificationVersion==="v2"){const modelsPromise=Array.isArray(this.model)&&!model?this.prepareModels(runtimeContext):this.prepareModels(runtimeContext,resolvedModel);llm=modelsPromise.then(models=>{const enabledModels=models.filter(model2=>model2.enabled);return new MastraLLMVNext({models:enabledModels,mastra:this.#mastra,options:{tracingPolicy:this.#options?.tracingPolicy}});});}else {llm=new MastraLLMV1({model:resolvedModel,mastra:this.#mastra,options:{tracingPolicy:this.#options?.tracingPolicy}});}return resolveMaybePromise(llm,resolvedLLM=>{if(this.#primitives){resolvedLLM.__registerPrimitives(this.#primitives);}if(this.#mastra){resolvedLLM.__registerMastra(this.#mastra);}return resolvedLLM;});});}/**
793
- * Returns true for model router config object
794
- * @internal
795
- */isOpenaiCompatibleObjectConfig(modelConfig){if(typeof modelConfig==="object"&&"specificationVersion"in modelConfig)return false;if(typeof modelConfig==="object"&&"id"in modelConfig&&!("model"in modelConfig))return true;return false;}/**
796
792
  * Resolves a model configuration to a LanguageModel instance
797
793
  * @param modelConfig The model configuration (magic string, config object, or LanguageModel)
798
794
  * @returns A LanguageModel instance
799
795
  * @internal
800
- */async resolveModelConfig(modelConfig,runtimeContext){if(typeof modelConfig==="object"&&"specificationVersion"in modelConfig){return modelConfig;}if(typeof modelConfig==="string"||this.isOpenaiCompatibleObjectConfig(modelConfig)){return new ModelRouterLanguageModel(modelConfig);}if(typeof modelConfig===`function`){const fromDynamic=await modelConfig({runtimeContext,mastra:this.#mastra});if(typeof fromDynamic===`string`||this.isOpenaiCompatibleObjectConfig(fromDynamic)){return new ModelRouterLanguageModel(fromDynamic);}return fromDynamic;}const mastraError=new MastraError({id:"AGENT_GET_MODEL_MISSING_MODEL_INSTANCE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name},text:`[Agent:${this.name}] - No model provided`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}/**
796
+ */async resolveModelConfig(modelConfig,runtimeContext){try{return await resolveModelConfig(modelConfig,runtimeContext,this.#mastra);}catch(error){const mastraError=new MastraError({id:"AGENT_GET_MODEL_MISSING_MODEL_INSTANCE",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name,originalError:error instanceof Error?error.message:String(error)},text:`[Agent:${this.name}] - Failed to resolve model configuration`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}}/**
801
797
  * Gets the model instance, resolving it if it's a function or model configuration.
802
798
  * When the agent has multiple models configured, returns the first enabled model.
803
799
  *
@@ -865,12 +861,12 @@ vectorMessageSearch}).then(r=>r.messagesV2);}/**
865
861
  */async getClientTools({runId,threadId,resourceId,runtimeContext,tracingContext,mastraProxy,clientTools}){let toolsForRequest={};const memory=await this.getMemory({runtimeContext});const clientToolsForInput=Object.entries(clientTools||{});if(clientToolsForInput.length>0){this.logger.debug(`[Agent:${this.name}] - Adding client tools ${Object.keys(clientTools||{}).join(", ")}`,{runId});for(const[toolName,tool]of clientToolsForInput){const{execute:execute2,...rest}=tool;const options={name:toolName,runId,threadId,resourceId,logger:this.logger,mastra:mastraProxy,memory,agentName:this.name,runtimeContext,tracingContext,model:await this.getModel({runtimeContext}),tracingPolicy:this.#options?.tracingPolicy};const convertedToCoreTool=makeCoreTool(rest,options,"client-tool");toolsForRequest[toolName]=convertedToCoreTool;}}return toolsForRequest;}/**
866
862
  * Retrieves and converts workflow tools to CoreTool format.
867
863
  * @internal
868
- */async getWorkflowTools({runId,threadId,resourceId,runtimeContext,tracingContext,methodType,format}){const convertedWorkflowTools={};const workflows=await this.getWorkflows({runtimeContext});if(Object.keys(workflows).length>0){for(const[workflowName,workflow]of Object.entries(workflows)){const toolObj=createTool({id:workflowName,description:workflow.description||`Workflow: ${workflowName}`,inputSchema:workflow.inputSchema,outputSchema:workflow.outputSchema,mastra:this.#mastra,// manually wrap workflow tools with ai tracing, so that we can pass the
864
+ */async getWorkflowTools({runId,threadId,resourceId,runtimeContext,tracingContext,methodType}){const convertedWorkflowTools={};const workflows=await this.getWorkflows({runtimeContext});if(Object.keys(workflows).length>0){for(const[workflowName,workflow]of Object.entries(workflows)){const toolObj=createTool({id:workflowName,description:workflow.description||`Workflow: ${workflowName}`,inputSchema:workflow.inputSchema,outputSchema:workflow.outputSchema,mastra:this.#mastra,// manually wrap workflow tools with ai tracing, so that we can pass the
869
865
  // current tool span onto the workflow to maintain continuity of the trace
870
- execute:async({context,writer,tracingContext:innerTracingContext})=>{try{this.logger.debug(`[Agent:${this.name}] - Executing workflow as tool ${workflowName}`,{name:workflowName,description:workflow.description,args:context,runId,threadId,resourceId});const run=await workflow.createRunAsync();let result;if(methodType==="generate"||methodType==="generateLegacy"){result=await run.start({inputData:context,runtimeContext,tracingContext:innerTracingContext});}else if(methodType==="streamLegacy"){const streamResult=run.stream({inputData:context,runtimeContext,tracingContext:innerTracingContext});if(writer){await streamResult.stream.pipeTo(writer);}else {for await(const _chunk of streamResult.stream){}}result=await streamResult.getWorkflowState();}else if(methodType==="stream"){const streamResult=run.streamVNext({inputData:context,runtimeContext,tracingContext:innerTracingContext,format});if(writer){await streamResult.pipeTo(writer);}result=await streamResult.result;}return {result,runId:run.runId};}catch(err){const mastraError=new MastraError({id:"AGENT_WORKFLOW_TOOL_EXECUTION_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name,runId:runId||"",threadId:threadId||"",resourceId:resourceId||""},text:`[Agent:${this.name}] - Failed workflow tool execution`},err);this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}}});const options={name:workflowName,runId,threadId,resourceId,logger:this.logger,mastra:this.#mastra,memory:await this.getMemory({runtimeContext}),agentName:this.name,runtimeContext,model:await this.getModel({runtimeContext}),tracingContext,tracingPolicy:this.#options?.tracingPolicy};convertedWorkflowTools[workflowName]=makeCoreTool(toolObj,options);}}return convertedWorkflowTools;}/**
866
+ execute:async({context,writer,tracingContext:innerTracingContext})=>{try{this.logger.debug(`[Agent:${this.name}] - Executing workflow as tool ${workflowName}`,{name:workflowName,description:workflow.description,args:context,runId,threadId,resourceId});const run=await workflow.createRunAsync();let result;if(methodType==="generate"||methodType==="generateLegacy"){result=await run.start({inputData:context,runtimeContext,tracingContext:innerTracingContext});}else if(methodType==="streamLegacy"){const streamResult=run.stream({inputData:context,runtimeContext,tracingContext:innerTracingContext});if(writer){await streamResult.stream.pipeTo(writer);}else {for await(const _chunk of streamResult.stream){}}result=await streamResult.getWorkflowState();}else if(methodType==="stream"){const streamResult=run.streamVNext({inputData:context,runtimeContext,tracingContext:innerTracingContext});if(writer){await streamResult.pipeTo(writer);}result=await streamResult.result;}return {result,runId:run.runId};}catch(err){const mastraError=new MastraError({id:"AGENT_WORKFLOW_TOOL_EXECUTION_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name,runId:runId||"",threadId:threadId||"",resourceId:resourceId||""},text:`[Agent:${this.name}] - Failed workflow tool execution`},err);this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}}});const options={name:workflowName,runId,threadId,resourceId,logger:this.logger,mastra:this.#mastra,memory:await this.getMemory({runtimeContext}),agentName:this.name,runtimeContext,model:await this.getModel({runtimeContext}),tracingContext,tracingPolicy:this.#options?.tracingPolicy};convertedWorkflowTools[workflowName]=makeCoreTool(toolObj,options);}}return convertedWorkflowTools;}/**
871
867
  * Assembles all tools from various sources into a unified CoreTool dictionary.
872
868
  * @internal
873
- */async convertTools({toolsets,clientTools,threadId,resourceId,runId,runtimeContext,tracingContext,writableStream,methodType,format}){let mastraProxy=void 0;const logger=this.logger;if(this.#mastra){mastraProxy=createMastraProxy({mastra:this.#mastra,logger});}const assignedTools=await this.getAssignedTools({runId,resourceId,threadId,runtimeContext,tracingContext,mastraProxy,writableStream});const memoryTools=await this.getMemoryTools({runId,resourceId,threadId,runtimeContext,tracingContext,mastraProxy});const toolsetTools=await this.getToolsets({runId,resourceId,threadId,runtimeContext,tracingContext,mastraProxy,toolsets});const clientSideTools=await this.getClientTools({runId,resourceId,threadId,runtimeContext,tracingContext,mastraProxy,clientTools});const workflowTools=await this.getWorkflowTools({runId,resourceId,threadId,runtimeContext,methodType,format,tracingContext});return this.formatTools({...assignedTools,...memoryTools,...toolsetTools,...clientSideTools,...workflowTools});}/**
869
+ */async convertTools({toolsets,clientTools,threadId,resourceId,runId,runtimeContext,tracingContext,writableStream,methodType}){let mastraProxy=void 0;const logger=this.logger;if(this.#mastra){mastraProxy=createMastraProxy({mastra:this.#mastra,logger});}const assignedTools=await this.getAssignedTools({runId,resourceId,threadId,runtimeContext,tracingContext,mastraProxy,writableStream});const memoryTools=await this.getMemoryTools({runId,resourceId,threadId,runtimeContext,tracingContext,mastraProxy});const toolsetTools=await this.getToolsets({runId,resourceId,threadId,runtimeContext,tracingContext,mastraProxy,toolsets});const clientSideTools=await this.getClientTools({runId,resourceId,threadId,runtimeContext,tracingContext,mastraProxy,clientTools});const workflowTools=await this.getWorkflowTools({runId,resourceId,threadId,runtimeContext,methodType,tracingContext});return this.formatTools({...assignedTools,...memoryTools,...toolsetTools,...clientSideTools,...workflowTools});}/**
874
870
  * Formats and validates tool names to comply with naming restrictions.
875
871
  * @internal
876
872
  */formatTools(tools){const INVALID_CHAR_REGEX=/[^a-zA-Z0-9_\-]/g;const STARTING_CHAR_REGEX=/[a-zA-Z_]/;for(const key of Object.keys(tools)){if(tools[key]&&(key.length>63||key.match(INVALID_CHAR_REGEX)||!key[0].match(STARTING_CHAR_REGEX))){let newKey=key.replace(INVALID_CHAR_REGEX,"_");if(!newKey[0].match(STARTING_CHAR_REGEX)){newKey="_"+newKey;}newKey=newKey.slice(0,63);if(tools[newKey]){const mastraError=new MastraError({id:"AGENT_TOOL_NAME_COLLISION",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,details:{agentName:this.name,toolName:newKey},text:`Two or more tools resolve to the same name "${newKey}". Please rename one of the tools to avoid this collision.`});this.logger.trackException(mastraError);this.logger.error(mastraError.toString());throw mastraError;}tools[newKey]=tools[key];delete tools[key];}}return tools;}/**
@@ -948,9 +944,9 @@ _agentNetworkAppend:this._agentNetworkAppend}).add(result.response.messages,"res
948
944
  * ```
949
945
  */async network(messages,options){const runId=options?.runId||this.#mastra?.generateId()||randomUUID();const runtimeContextToUse=options?.runtimeContext||new RuntimeContext();return await networkLoop({networkName:this.name,runtimeContext:runtimeContextToUse,runId,routingAgent:this,routingAgentOptions:{telemetry:options?.telemetry,modelSettings:options?.modelSettings},generateId:()=>this.#mastra?.generateId()||randomUUID(),maxIterations:options?.maxSteps||1,messages,threadId:typeof options?.memory?.thread==="string"?options?.memory?.thread:options?.memory?.thread?.id,resourceId:options?.memory?.resource});}/**
950
946
  * @deprecated `generateVNext()` has been renamed to `generate()`. Please use `generate()` instead.
951
- */async generateVNext(_messages,_options){throw new MastraError({id:"AGENT_GENERATE_VNEXT_DEPRECATED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"generateVNext has been renamed to generate. Please use generate instead."});}async generate(messages,options){const result=await this.stream(messages,options);const fullOutput=await result.getFullOutput();const error=fullOutput.error;if(fullOutput.finishReason==="error"&&error){throw error;}return fullOutput;}/**
947
+ */async generateVNext(_messages,_options){throw new MastraError({id:"AGENT_GENERATE_VNEXT_DEPRECATED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"generateVNext has been renamed to generate. Please use generate instead."});}async generate(messages,options){if(options?.structuredOutput?.schema&&options?.output){throw new MastraError({id:"AGENT_GENERATE_STRUCTURED_OUTPUT_AND_OUTPUT_PROVIDED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput and output cannot be provided at the same time to agent.generate"});}const normalizedOptions=options?.output?{structuredOutput:{schema:options.output,...options.structuredOutput},...options,output:void 0}:options;const result=await this.stream(messages,normalizedOptions);const fullOutput=await result.getFullOutput();const error=fullOutput.error;if(fullOutput.finishReason==="error"&&error){throw error;}return fullOutput;}/**
952
948
  * @deprecated `streamVNext()` has been renamed to `stream()`. Please use `stream()` instead.
953
- */async streamVNext(_messages,_streamOptions){throw new MastraError({id:"AGENT_STREAM_VNEXT_DEPRECATED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"streamVNext has been renamed to stream. Please use stream instead."});}async stream(messages,streamOptions){const defaultStreamOptions=await this.getDefaultVNextStreamOptions({runtimeContext:streamOptions?.runtimeContext});if(defaultStreamOptions.structuredOutput&&defaultStreamOptions.output||streamOptions?.structuredOutput&&streamOptions.output){throw new MastraError({id:"AGENT_STREAM_STRUCTURED_OUTPUT_AND_OUTPUT_PROVIDED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput and output cannot be provided at the same time"});}let adjustedDefaultStreamOptions={...defaultStreamOptions};if(streamOptions?.structuredOutput||streamOptions?.output){const{output,structuredOutput,...restDefaultOptions}=adjustedDefaultStreamOptions;adjustedDefaultStreamOptions=restDefaultOptions;}let mergedStreamOptions={...adjustedDefaultStreamOptions,...(streamOptions??{}),onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions)};const llm=await this.getLLM({runtimeContext:mergedStreamOptions.runtimeContext});if(llm.getModel().specificationVersion!=="v2"){const modelInfo=llm.getModel();const modelId=modelInfo.modelId||"unknown";const provider=modelInfo.provider||"unknown";throw new MastraError({id:"AGENT_STREAM_V1_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:`Agent "${this.name}" is using AI SDK v4 model (${provider}:${modelId}) which is not compatible with stream(). Please use AI SDK v5 models or call the streamLegacy() method instead. See https://mastra.ai/en/docs/streaming/overview for more information.`,details:{agentName:this.name,modelId,provider,specificationVersion:modelInfo.specificationVersion}});}const executeOptions={...mergedStreamOptions,messages,methodType:"stream"};const result=await this.#execute(executeOptions);if(result.status!=="success"){if(result.status==="failed"){throw new MastraError({id:"AGENT_STREAM_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:result.error.message,details:{error:result.error.message}});}throw new MastraError({id:"AGENT_STREAM_UNKNOWN_ERROR",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"An unknown error occurred while streaming"});}return result.result;}/**
949
+ */async streamVNext(_messages,_streamOptions){throw new MastraError({id:"AGENT_STREAM_VNEXT_DEPRECATED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"streamVNext has been renamed to stream. Please use stream instead."});}async stream(messages,streamOptions){const defaultStreamOptions=await this.getDefaultVNextStreamOptions({runtimeContext:streamOptions?.runtimeContext});if(streamOptions?.structuredOutput?.schema&&streamOptions?.output){throw new MastraError({id:"AGENT_STREAM_STRUCTURED_OUTPUT_AND_OUTPUT_PROVIDED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput and output cannot be provided at the same time to agent.stream"});}const baseStreamOptions={...defaultStreamOptions,...(streamOptions??{}),onFinish:this.#mergeOnFinishWithTelemetry(streamOptions,defaultStreamOptions)};const mergedStreamOptions=baseStreamOptions.output?{structuredOutput:{schema:baseStreamOptions.output,...baseStreamOptions.structuredOutput},...baseStreamOptions,output:void 0}:baseStreamOptions;const llm=await this.getLLM({runtimeContext:mergedStreamOptions.runtimeContext});if(llm.getModel().specificationVersion!=="v2"){const modelInfo=llm.getModel();const modelId=modelInfo.modelId||"unknown";const provider=modelInfo.provider||"unknown";throw new MastraError({id:"AGENT_STREAM_V1_MODEL_NOT_SUPPORTED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:`Agent "${this.name}" is using AI SDK v4 model (${provider}:${modelId}) which is not compatible with stream(). Please use AI SDK v5 models or call the streamLegacy() method instead. See https://mastra.ai/en/docs/streaming/overview for more information.`,details:{agentName:this.name,modelId,provider,specificationVersion:modelInfo.specificationVersion}});}const executeOptions={...mergedStreamOptions,messages,methodType:"stream"};const result=await this.#execute(executeOptions);if(result.status!=="success"){if(result.status==="failed"){throw new MastraError({id:"AGENT_STREAM_FAILED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:result.error.message,details:{error:result.error.message}});}throw new MastraError({id:"AGENT_STREAM_UNKNOWN_ERROR",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"An unknown error occurred while streaming"});}return result.result;}/**
954
950
  * Resumes a previously suspended VNext stream execution.
955
951
  * Used to continue execution after a suspension point (e.g., tool approval, workflow suspend).
956
952
  *
@@ -1035,8 +1031,9 @@ _agentNetworkAppend:this._agentNetworkAppend}).add(result.response.messages,"res
1035
1031
  - ensure it is not more than 80 characters long
1036
1032
  - the title should be a summary of the user's message
1037
1033
  - do not use quotes or colons
1038
- - the entire text you return will be used as the title`;if(!instructions){return DEFAULT_TITLE_INSTRUCTIONS;}if(typeof instructions==="string"){return instructions;}else {const result=instructions({runtimeContext,mastra:this.#mastra});return resolveMaybePromise(result,resolvedInstructions=>{return resolvedInstructions||DEFAULT_TITLE_INSTRUCTIONS;});}}};Agent=/*@__PURE__*/(_=>{_init=__decoratorStart(_a);Agent=__decorateElement(_init,0,"Agent",_Agent_decorators,Agent);__runInitializers(_init,1,Agent);// src/stream/aisdk/v5/output.ts
1039
- return Agent;})();// src/stream/aisdk/v5/output.ts
1034
+ - the entire text you return will be used as the title`;if(!instructions){return DEFAULT_TITLE_INSTRUCTIONS;}if(typeof instructions==="string"){return instructions;}else {const result=instructions({runtimeContext,mastra:this.#mastra});return resolveMaybePromise(result,resolvedInstructions=>{return resolvedInstructions||DEFAULT_TITLE_INSTRUCTIONS;});}}};Agent=/*@__PURE__*/(_=>{_init=__decoratorStart(_a);Agent=__decorateElement(_init,0,"Agent",_Agent_decorators,Agent);__runInitializers(_init,1,Agent);// src/agent/utils.ts
1035
+ return Agent;})();// src/agent/utils.ts
1036
+ async function tryGenerateWithJsonFallback(agent,prompt,options){if(!options.structuredOutput?.schema){throw new MastraError({id:"STRUCTURED_OUTPUT_OPTIONS_REQUIRED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput is required to use tryGenerateWithJsonFallback"});}try{return await agent.generate(prompt,options);}catch(error){console.warn("Error in tryGenerateWithJsonFallback. Attempting fallback.",error);return await agent.generate(prompt,{...options,structuredOutput:{...options.structuredOutput,jsonPromptInjection:true}});}}async function tryStreamWithJsonFallback(agent,prompt,options){if(!options.structuredOutput?.schema){throw new MastraError({id:"STRUCTURED_OUTPUT_OPTIONS_REQUIRED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput is required to use tryStreamWithJsonFallback"});}try{const result=await agent.stream(prompt,options);const object=await result.object;if(!object){throw new MastraError({id:"STRUCTURED_OUTPUT_OBJECT_UNDEFINED",domain:"AGENT"/* AGENT */,category:"USER"/* USER */,text:"structuredOutput object is undefined"});}return result;}catch(error){console.warn("Error in tryStreamWithJsonFallback. Attempting fallback.",error);return await agent.stream(prompt,{...options,structuredOutput:{...options.structuredOutput,jsonPromptInjection:true}});}}// src/stream/aisdk/v5/output.ts
1040
1037
  var AISDKV5OutputStream=class{#modelOutput;#options;#messageList;/**
1041
1038
  * Trace ID used on the execution (if the execution was traced).
1042
1039
  */traceId;constructor({modelOutput,options,messageList}){this.#modelOutput=modelOutput;this.#options=options;this.#messageList=messageList;this.traceId=getValidTraceId(options.tracingContext?.currentSpan);}toTextStreamResponse(init){return createTextStreamResponse({// Type assertion needed due to ReadableStream type mismatch between Node.js (stream/web) and DOM types
@@ -1066,9 +1063,9 @@ var BaseFormatHandler=class{/**
1066
1063
  * If multiple values match, returns the partial string. If only one matches, returns that value.
1067
1064
  * @param partialResult - Partial enum string from streaming
1068
1065
  * @returns Best matching enum value or undefined if no matches
1069
- */findBestEnumMatch(partialResult){if(!this.schema?.jsonSchema?.enum){return void 0;}const enumValues=this.schema.jsonSchema.enum;const possibleEnumValues=enumValues.filter(value=>typeof value==="string").filter(enumValue=>enumValue.startsWith(partialResult));if(possibleEnumValues.length===0){return void 0;}const firstMatch=possibleEnumValues[0];return possibleEnumValues.length===1&&firstMatch!==void 0?firstMatch:partialResult;}async processPartialChunk({accumulatedText,previousObject}){const processedAccumulatedText=this.preprocessText(accumulatedText);const{value:currentObjectJson}=await parsePartialJson(processedAccumulatedText);if(currentObjectJson!==void 0&&currentObjectJson!==null&&typeof currentObjectJson==="object"&&!Array.isArray(currentObjectJson)&&"result"in currentObjectJson&&typeof currentObjectJson.result==="string"&&!isDeepEqualData(previousObject,currentObjectJson)){const partialResult=currentObjectJson.result;const bestMatch=this.findBestEnumMatch(partialResult);if(partialResult.length>0&&bestMatch&&bestMatch!==this.textPreviousEnumResult){this.textPreviousEnumResult=bestMatch;return {shouldEmit:true,emitValue:bestMatch,newPreviousResult:currentObjectJson};}}return {shouldEmit:false};}async validateAndTransformFinal(rawFinalValue){const processedValue=this.preprocessText(rawFinalValue);const{value}=await parsePartialJson(processedValue);if(!(typeof value==="object"&&value!==null&&"result"in value)){return {success:false,error:new Error("Invalid enum format: expected object with result property")};}const finalValue=value;if(!finalValue||typeof finalValue!=="object"||typeof finalValue.result!=="string"){return {success:false,error:new Error("Invalid enum format: expected object with result property")};}if(!this.schema){return {success:true,value:finalValue.result};}try{const result=await safeValidateTypes({value:finalValue.result,schema:this.schema});if(result.success){return {success:true,value:result.value};}else {return {success:false,error:result.error??new Error("Enum validation failed")};}}catch(error){return {success:false,error:error instanceof Error?error:new Error("Validation failed")};}}};function createOutputHandler({schema,transformedSchema}){switch(transformedSchema?.outputFormat){case "array":return new ArrayFormatHandler(schema);case "enum":return new EnumFormatHandler(schema);case "object":default:return new ObjectFormatHandler(schema);}}function createObjectStreamTransformer({isLLMExecutionStep,schema}){const transformedSchema=getTransformedSchema(schema);const handler=createOutputHandler({transformedSchema,schema});let accumulatedText="";let previousObject=void 0;let finishReason;let currentRunId;return new TransformStream({async transform(chunk,controller){if(!isLLMExecutionStep||!schema){controller.enqueue(chunk);return;}if(chunk.runId){currentRunId=chunk.runId;}if(chunk.type==="finish"){finishReason=chunk.payload.stepResult.reason;controller.enqueue(chunk);return;}if(chunk.type==="text-delta"&&typeof chunk.payload?.text==="string"){accumulatedText+=chunk.payload.text;const result=await handler.processPartialChunk({accumulatedText,previousObject});if(result.shouldEmit){previousObject=result.newPreviousResult??previousObject;const chunkData={from:chunk.from,runId:chunk.runId,type:"object",object:result.emitValue// TODO: handle partial runtime type validation of json chunks
1070
- };controller.enqueue(chunkData);}}controller.enqueue(chunk);},async flush(controller){if(!isLLMExecutionStep||!schema){return;}if(["tool-calls"].includes(finishReason??"")){return;}const finalResult=await handler.validateAndTransformFinal(accumulatedText);if(!finalResult.success){controller.enqueue({from:"AGENT"/* AGENT */,runId:currentRunId??"",type:"error",payload:{error:new MastraError({domain:"AGENT",category:"SYSTEM",id:"OUTPUT_SCHEMA_VALIDATION_FAILED",text:finalResult.error.message},{cause:finalResult.error})}});return;}controller.enqueue({from:"AGENT"/* AGENT */,runId:currentRunId??"",type:"object-result",object:finalResult.value});return;}});}function createJsonTextStreamTransformer(schema){let previousArrayLength=0;let hasStartedArray=false;let chunkCount=0;const outputSchema=getTransformedSchema(schema);return new TransformStream({transform(chunk,controller){if(chunk.type!=="object"||!chunk.object){return;}if(outputSchema?.outputFormat==="array"){chunkCount++;if(chunkCount===1){if(chunk.object.length>0){controller.enqueue(JSON.stringify(chunk.object));previousArrayLength=chunk.object.length;hasStartedArray=true;return;}}if(!hasStartedArray){controller.enqueue("[");hasStartedArray=true;}for(let i=previousArrayLength;i<chunk.object.length;i++){const elementJson=JSON.stringify(chunk.object[i]);if(i>0){controller.enqueue(","+elementJson);}else {controller.enqueue(elementJson);}}previousArrayLength=chunk.object.length;}else {controller.enqueue(JSON.stringify(chunk.object));}},flush(controller){if(hasStartedArray&&outputSchema?.outputFormat==="array"&&chunkCount>1){controller.enqueue("]");}}});}// src/stream/base/output.ts
1071
- function createDestructurableOutput(output){return new Proxy(output,{get(target,prop,_receiver){const originalValue=Reflect.get(target,prop,target);if(typeof originalValue==="function"){return originalValue.bind(target);}return originalValue;}});}var MastraModelOutput=class extends MastraBase{#status="running";#aisdkv5;#error;#baseStream;#bufferedChunks=[];#streamFinished=false;#emitter=new EventEmitter$1();#bufferedSteps=[];#bufferedReasoningDetails={};#bufferedByStep={text:"",reasoning:[],sources:[],files:[],toolCalls:[],toolResults:[],dynamicToolCalls:[],dynamicToolResults:[],staticToolCalls:[],staticToolResults:[],content:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},warnings:[],request:{},response:{id:"",timestamp:/* @__PURE__ */new Date(),modelId:"",messages:[],uiMessages:[]},reasoningText:"",providerMetadata:void 0,finishReason:void 0};#bufferedText=[];#bufferedObject;#bufferedTextChunks={};#bufferedSources=[];#bufferedReasoning=[];#bufferedFiles=[];#toolCallArgsDeltas={};#toolCallDeltaIdNameMap={};#toolCalls=[];#toolResults=[];#warnings=[];#finishReason=void 0;#request={};#usageCount={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};#tripwire=false;#tripwireReason="";#delayedPromises={suspendPayload:new DelayedPromise(),object:new DelayedPromise(),finishReason:new DelayedPromise(),usage:new DelayedPromise(),warnings:new DelayedPromise(),providerMetadata:new DelayedPromise(),response:new DelayedPromise(),request:new DelayedPromise(),text:new DelayedPromise(),reasoning:new DelayedPromise(),reasoningText:new DelayedPromise(),sources:new DelayedPromise(),files:new DelayedPromise(),toolCalls:new DelayedPromise(),toolResults:new DelayedPromise(),steps:new DelayedPromise(),totalUsage:new DelayedPromise(),content:new DelayedPromise()};#consumptionStarted=false;#returnScorerData=false;#model;/**
1066
+ */findBestEnumMatch(partialResult){if(!this.schema?.jsonSchema?.enum){return void 0;}const enumValues=this.schema.jsonSchema.enum;const possibleEnumValues=enumValues.filter(value=>typeof value==="string").filter(enumValue=>enumValue.startsWith(partialResult));if(possibleEnumValues.length===0){return void 0;}const firstMatch=possibleEnumValues[0];return possibleEnumValues.length===1&&firstMatch!==void 0?firstMatch:partialResult;}async processPartialChunk({accumulatedText,previousObject}){const processedAccumulatedText=this.preprocessText(accumulatedText);const{value:currentObjectJson}=await parsePartialJson(processedAccumulatedText);if(currentObjectJson!==void 0&&currentObjectJson!==null&&typeof currentObjectJson==="object"&&!Array.isArray(currentObjectJson)&&"result"in currentObjectJson&&typeof currentObjectJson.result==="string"&&!isDeepEqualData(previousObject,currentObjectJson)){const partialResult=currentObjectJson.result;const bestMatch=this.findBestEnumMatch(partialResult);if(partialResult.length>0&&bestMatch&&bestMatch!==this.textPreviousEnumResult){this.textPreviousEnumResult=bestMatch;return {shouldEmit:true,emitValue:bestMatch,newPreviousResult:currentObjectJson};}}return {shouldEmit:false};}async validateAndTransformFinal(rawFinalValue){const processedValue=this.preprocessText(rawFinalValue);const{value}=await parsePartialJson(processedValue);if(!(typeof value==="object"&&value!==null&&"result"in value)){return {success:false,error:new Error("Invalid enum format: expected object with result property")};}const finalValue=value;if(!finalValue||typeof finalValue!=="object"||typeof finalValue.result!=="string"){return {success:false,error:new Error("Invalid enum format: expected object with result property")};}if(!this.schema){return {success:true,value:finalValue.result};}try{const result=await safeValidateTypes({value:finalValue.result,schema:this.schema});if(result.success){return {success:true,value:result.value};}else {return {success:false,error:result.error??new Error("Enum validation failed")};}}catch(error){return {success:false,error:error instanceof Error?error:new Error("Validation failed")};}}};function createOutputHandler({schema,transformedSchema}){switch(transformedSchema?.outputFormat){case "array":return new ArrayFormatHandler(schema);case "enum":return new EnumFormatHandler(schema);case "object":default:return new ObjectFormatHandler(schema);}}function createObjectStreamTransformer({isLLMExecutionStep,structuredOutput}){const transformedSchema=getTransformedSchema(structuredOutput?.schema);const handler=createOutputHandler({transformedSchema,schema:structuredOutput?.schema});let accumulatedText="";let previousObject=void 0;let finishReason;let currentRunId;return new TransformStream({async transform(chunk,controller){if(!isLLMExecutionStep){controller.enqueue(chunk);return;}if(chunk.runId){currentRunId=chunk.runId;}if(chunk.type==="finish"){finishReason=chunk.payload.stepResult.reason;controller.enqueue(chunk);return;}if(chunk.type==="text-delta"&&typeof chunk.payload?.text==="string"){accumulatedText+=chunk.payload.text;const result=await handler.processPartialChunk({accumulatedText,previousObject});if(result.shouldEmit){previousObject=result.newPreviousResult??previousObject;const chunkData={from:chunk.from,runId:chunk.runId,type:"object",object:result.emitValue// TODO: handle partial runtime type validation of json chunks
1067
+ };controller.enqueue(chunkData);}}controller.enqueue(chunk);},async flush(controller){if(!isLLMExecutionStep){return;}if(["tool-calls"].includes(finishReason??"")){return;}const finalResult=await handler.validateAndTransformFinal(accumulatedText);if(!finalResult.success){controller.enqueue({from:"AGENT"/* AGENT */,runId:currentRunId??"",type:"error",payload:{error:new MastraError({domain:"AGENT",category:"SYSTEM",id:"OUTPUT_SCHEMA_VALIDATION_FAILED",text:finalResult.error.message},{cause:finalResult.error})}});return;}controller.enqueue({from:"AGENT"/* AGENT */,runId:currentRunId??"",type:"object-result",object:finalResult.value});return;}});}function createJsonTextStreamTransformer(schema){let previousArrayLength=0;let hasStartedArray=false;let chunkCount=0;const outputSchema=getTransformedSchema(schema);return new TransformStream({transform(chunk,controller){if(chunk.type!=="object"||!chunk.object){return;}if(outputSchema?.outputFormat==="array"){chunkCount++;if(chunkCount===1){if(chunk.object.length>0){controller.enqueue(JSON.stringify(chunk.object));previousArrayLength=chunk.object.length;hasStartedArray=true;return;}}if(!hasStartedArray){controller.enqueue("[");hasStartedArray=true;}for(let i=previousArrayLength;i<chunk.object.length;i++){const elementJson=JSON.stringify(chunk.object[i]);if(i>0){controller.enqueue(","+elementJson);}else {controller.enqueue(elementJson);}}previousArrayLength=chunk.object.length;}else {controller.enqueue(JSON.stringify(chunk.object));}},flush(controller){if(hasStartedArray&&outputSchema?.outputFormat==="array"&&chunkCount>1){controller.enqueue("]");}}});}// src/stream/base/output.ts
1068
+ function createDestructurableOutput(output){return new Proxy(output,{get(target,prop,_receiver){const originalValue=Reflect.get(target,prop,target);if(typeof originalValue==="function"){return originalValue.bind(target);}return originalValue;}});}var MastraModelOutput=class extends MastraBase{#status="running";#aisdkv5;#error;#baseStream;#bufferedChunks=[];#streamFinished=false;#emitter=new EventEmitter$1();#bufferedSteps=[];#bufferedReasoningDetails={};#bufferedByStep={text:"",reasoning:[],sources:[],files:[],toolCalls:[],toolResults:[],dynamicToolCalls:[],dynamicToolResults:[],staticToolCalls:[],staticToolResults:[],content:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},warnings:[],request:{},response:{id:"",timestamp:/* @__PURE__ */new Date(),modelId:"",messages:[],uiMessages:[]},reasoningText:"",providerMetadata:void 0,finishReason:void 0};#bufferedText=[];#bufferedObject;#bufferedTextChunks={};#bufferedSources=[];#bufferedReasoning=[];#bufferedFiles=[];#toolCallArgsDeltas={};#toolCallDeltaIdNameMap={};#toolCalls=[];#toolResults=[];#warnings=[];#finishReason=void 0;#request={};#usageCount={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};#tripwire=false;#tripwireReason="";#delayedPromises={suspendPayload:new DelayedPromise(),object:new DelayedPromise(),finishReason:new DelayedPromise(),usage:new DelayedPromise(),warnings:new DelayedPromise(),providerMetadata:new DelayedPromise(),response:new DelayedPromise(),request:new DelayedPromise(),text:new DelayedPromise(),reasoning:new DelayedPromise(),reasoningText:new DelayedPromise(),sources:new DelayedPromise(),files:new DelayedPromise(),toolCalls:new DelayedPromise(),toolResults:new DelayedPromise(),steps:new DelayedPromise(),totalUsage:new DelayedPromise(),content:new DelayedPromise()};#consumptionStarted=false;#returnScorerData=false;#structuredOutputMode=void 0;#model;/**
1072
1069
  * Unique identifier for this execution run.
1073
1070
  */runId;#options;/**
1074
1071
  * The processor runner for this stream.
@@ -1076,11 +1073,11 @@ function createDestructurableOutput(output){return new Proxy(output,{get(target,
1076
1073
  * The message list for this stream.
1077
1074
  */messageList;/**
1078
1075
  * Trace ID used on the execution (if the execution was traced).
1079
- */traceId;messageId;constructor({model:_model,stream,messageList,options,messageId}){super({component:"LLM",name:"MastraModelOutput"});this.#options=options;this.#returnScorerData=!!options.returnScorerData;this.runId=options.runId;this.traceId=getValidTraceId(options.tracingContext?.currentSpan);this.#model=_model;this.messageId=messageId;if(options.outputProcessors?.length){this.processorRunner=new ProcessorRunner({inputProcessors:[],outputProcessors:options.outputProcessors,logger:this.logger,agentName:"MastraModelOutput"});}this.messageList=messageList;const self=this;let processedStream=stream;const processorRunner=this.processorRunner;if(processorRunner&&options.isLLMExecutionStep){const processorStates=options.processorStates||/* @__PURE__ */new Map();processedStream=stream.pipeThrough(new TransformStream({async transform(chunk,controller){if(chunk.type==="finish"&&chunk.payload?.stepResult?.reason==="tool-calls"){controller.enqueue(chunk);return;}else {if(!processorStates.has(STRUCTURED_OUTPUT_PROCESSOR_NAME)){const structuredOutputProcessorState=new ProcessorState(STRUCTURED_OUTPUT_PROCESSOR_NAME);structuredOutputProcessorState.customState={controller};processorStates.set(STRUCTURED_OUTPUT_PROCESSOR_NAME,structuredOutputProcessorState);}else {const structuredOutputProcessorState=processorStates.get(STRUCTURED_OUTPUT_PROCESSOR_NAME);if(structuredOutputProcessorState){structuredOutputProcessorState.customState.controller=controller;}}const{part:processed,blocked,reason}=await processorRunner.processPart(chunk,processorStates);if(blocked){controller.enqueue({type:"tripwire",payload:{tripwireReason:reason||"Output processor blocked content"}});return;}if(processed){controller.enqueue(processed);}}}}));}processedStream=processedStream.pipeThrough(createObjectStreamTransformer({isLLMExecutionStep:self.#options.isLLMExecutionStep,schema:self.#options.output}));this.#baseStream=processedStream.pipeThrough(new TransformStream({transform:async(chunk,controller)=>{switch(chunk.type){case "tool-call-suspended":case "tool-call-approval":self.#status="suspended";self.#delayedPromises.suspendPayload.resolve(chunk.payload);break;case "raw":if(!self.#options.includeRawChunks){return;}break;case "object-result":self.#bufferedObject=chunk.object;if(self.#delayedPromises.object.status.type==="pending"){self.#delayedPromises.object.resolve(chunk.object);}break;case "source":self.#bufferedSources.push(chunk);self.#bufferedByStep.sources.push(chunk);break;case "text-delta":self.#bufferedText.push(chunk.payload.text);self.#bufferedByStep.text+=chunk.payload.text;if(chunk.payload.id){const ary=self.#bufferedTextChunks[chunk.payload.id]??[];ary.push(chunk.payload.text);self.#bufferedTextChunks[chunk.payload.id]=ary;}break;case "tool-call-input-streaming-start":self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId]=chunk.payload.toolName;break;case "tool-call-delta":if(!self.#toolCallArgsDeltas[chunk.payload.toolCallId]){self.#toolCallArgsDeltas[chunk.payload.toolCallId]=[];}self.#toolCallArgsDeltas?.[chunk.payload.toolCallId]?.push(chunk.payload.argsTextDelta);chunk.payload.toolName||=self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId];break;case "file":self.#bufferedFiles.push(chunk);self.#bufferedByStep.files.push(chunk);break;case "reasoning-start":self.#bufferedReasoningDetails[chunk.payload.id]={type:"reasoning",runId:chunk.runId,from:chunk.from,payload:{id:chunk.payload.id,providerMetadata:chunk.payload.providerMetadata,text:""}};break;case "reasoning-delta":{self.#bufferedReasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});self.#bufferedByStep.reasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(bufferedReasoning){bufferedReasoning.payload.text+=chunk.payload.text;if(chunk.payload.providerMetadata){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}}break;}case "reasoning-end":{const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(chunk.payload.providerMetadata&&bufferedReasoning){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}break;}case "tool-call":self.#toolCalls.push(chunk);self.#bufferedByStep.toolCalls.push(chunk);const toolCallPayload=chunk.payload;if(toolCallPayload?.output?.from==="AGENT"&&toolCallPayload?.output?.type==="finish"){const finishPayload=toolCallPayload.output.payload;if(finishPayload?.usage){self.updateUsageCount(finishPayload.usage);}}break;case "tool-result":self.#toolResults.push(chunk);self.#bufferedByStep.toolResults.push(chunk);break;case "step-finish":{self.updateUsageCount(chunk.payload.output.usage);self.#warnings=chunk.payload.stepResult.warnings||[];if(chunk.payload.metadata.request){self.#request=chunk.payload.metadata.request;}const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;const stepResult={stepType:self.#bufferedSteps.length===0?"initial":"tool-result",sources:self.#bufferedByStep.sources,files:self.#bufferedByStep.files,toolCalls:self.#bufferedByStep.toolCalls,toolResults:self.#bufferedByStep.toolResults,content:messageList.get.response.aiV5.modelContent(-1),text:self.#bufferedByStep.text,reasoningText:self.#bufferedReasoning.map(reasoningPart=>reasoningPart.payload.text).join(""),reasoning:self.#bufferedByStep.reasoning,get staticToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===false);},get dynamicToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===true);},get staticToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===false);},get dynamicToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===true);},finishReason:chunk.payload.stepResult.reason,usage:chunk.payload.output.usage,warnings:self.#warnings,request:request||{},response:{id:chunk.payload.id||"",timestamp:chunk.payload.metadata?.timestamp||/* @__PURE__ */new Date(),modelId:chunk.payload.metadata?.modelId||chunk.payload.metadata?.model||"",...otherMetadata,messages:chunk.payload.messages?.nonUser||[],// We have to cast this until messageList can take generics also and type metadata, it was too
1076
+ */traceId;messageId;constructor({model:_model,stream,messageList,options,messageId}){super({component:"LLM",name:"MastraModelOutput"});this.#options=options;this.#returnScorerData=!!options.returnScorerData;this.runId=options.runId;this.traceId=getValidTraceId(options.tracingContext?.currentSpan);this.#model=_model;this.messageId=messageId;if(options.structuredOutput?.schema){this.#structuredOutputMode=options.structuredOutput.model?"processor":"direct";}if(options.outputProcessors?.length){this.processorRunner=new ProcessorRunner({inputProcessors:[],outputProcessors:options.outputProcessors,logger:this.logger,agentName:"MastraModelOutput"});}this.messageList=messageList;const self=this;let processedStream=stream;const processorRunner=this.processorRunner;if(processorRunner&&options.isLLMExecutionStep){const processorStates=options.processorStates||/* @__PURE__ */new Map();processedStream=stream.pipeThrough(new TransformStream({async transform(chunk,controller){if(chunk.type==="finish"&&chunk.payload?.stepResult?.reason==="tool-calls"){controller.enqueue(chunk);return;}else {if(!processorStates.has(STRUCTURED_OUTPUT_PROCESSOR_NAME)){const structuredOutputProcessorState=new ProcessorState(STRUCTURED_OUTPUT_PROCESSOR_NAME);structuredOutputProcessorState.customState={controller};processorStates.set(STRUCTURED_OUTPUT_PROCESSOR_NAME,structuredOutputProcessorState);}else {const structuredOutputProcessorState=processorStates.get(STRUCTURED_OUTPUT_PROCESSOR_NAME);if(structuredOutputProcessorState){structuredOutputProcessorState.customState.controller=controller;}}const{part:processed,blocked,reason}=await processorRunner.processPart(chunk,processorStates);if(blocked){controller.enqueue({type:"tripwire",payload:{tripwireReason:reason||"Output processor blocked content"}});return;}if(processed){controller.enqueue(processed);}}}}));}if(self.#structuredOutputMode==="direct"){processedStream=processedStream.pipeThrough(createObjectStreamTransformer({isLLMExecutionStep:self.#options.isLLMExecutionStep,structuredOutput:self.#options.structuredOutput}));}this.#baseStream=processedStream.pipeThrough(new TransformStream({transform:async(chunk,controller)=>{switch(chunk.type){case "tool-call-suspended":case "tool-call-approval":self.#status="suspended";self.#delayedPromises.suspendPayload.resolve(chunk.payload);break;case "raw":if(!self.#options.includeRawChunks){return;}break;case "object-result":self.#bufferedObject=chunk.object;if(self.#delayedPromises.object.status.type==="pending"){self.#delayedPromises.object.resolve(chunk.object);}break;case "source":self.#bufferedSources.push(chunk);self.#bufferedByStep.sources.push(chunk);break;case "text-delta":self.#bufferedText.push(chunk.payload.text);self.#bufferedByStep.text+=chunk.payload.text;if(chunk.payload.id){const ary=self.#bufferedTextChunks[chunk.payload.id]??[];ary.push(chunk.payload.text);self.#bufferedTextChunks[chunk.payload.id]=ary;}break;case "tool-call-input-streaming-start":self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId]=chunk.payload.toolName;break;case "tool-call-delta":if(!self.#toolCallArgsDeltas[chunk.payload.toolCallId]){self.#toolCallArgsDeltas[chunk.payload.toolCallId]=[];}self.#toolCallArgsDeltas?.[chunk.payload.toolCallId]?.push(chunk.payload.argsTextDelta);chunk.payload.toolName||=self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId];break;case "file":self.#bufferedFiles.push(chunk);self.#bufferedByStep.files.push(chunk);break;case "reasoning-start":self.#bufferedReasoningDetails[chunk.payload.id]={type:"reasoning",runId:chunk.runId,from:chunk.from,payload:{id:chunk.payload.id,providerMetadata:chunk.payload.providerMetadata,text:""}};break;case "reasoning-delta":{self.#bufferedReasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});self.#bufferedByStep.reasoning.push({type:"reasoning",runId:chunk.runId,from:chunk.from,payload:chunk.payload});const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(bufferedReasoning){bufferedReasoning.payload.text+=chunk.payload.text;if(chunk.payload.providerMetadata){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}}break;}case "reasoning-end":{const bufferedReasoning=self.#bufferedReasoningDetails[chunk.payload.id];if(chunk.payload.providerMetadata&&bufferedReasoning){bufferedReasoning.payload.providerMetadata=chunk.payload.providerMetadata;}break;}case "tool-call":self.#toolCalls.push(chunk);self.#bufferedByStep.toolCalls.push(chunk);const toolCallPayload=chunk.payload;if(toolCallPayload?.output?.from==="AGENT"&&toolCallPayload?.output?.type==="finish"){const finishPayload=toolCallPayload.output.payload;if(finishPayload?.usage){self.updateUsageCount(finishPayload.usage);}}break;case "tool-result":self.#toolResults.push(chunk);self.#bufferedByStep.toolResults.push(chunk);break;case "step-finish":{self.updateUsageCount(chunk.payload.output.usage);self.#warnings=chunk.payload.stepResult.warnings||[];if(chunk.payload.metadata.request){self.#request=chunk.payload.metadata.request;}const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;const stepResult={stepType:self.#bufferedSteps.length===0?"initial":"tool-result",sources:self.#bufferedByStep.sources,files:self.#bufferedByStep.files,toolCalls:self.#bufferedByStep.toolCalls,toolResults:self.#bufferedByStep.toolResults,content:messageList.get.response.aiV5.modelContent(-1),text:self.#bufferedByStep.text,reasoningText:self.#bufferedReasoning.map(reasoningPart=>reasoningPart.payload.text).join(""),reasoning:self.#bufferedByStep.reasoning,get staticToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===false);},get dynamicToolCalls(){return self.#bufferedByStep.toolCalls.filter(part=>part.type==="tool-call"&&part.payload?.dynamic===true);},get staticToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===false);},get dynamicToolResults(){return self.#bufferedByStep.toolResults.filter(part=>part.type==="tool-result"&&part.payload?.dynamic===true);},finishReason:chunk.payload.stepResult.reason,usage:chunk.payload.output.usage,warnings:self.#warnings,request:request||{},response:{id:chunk.payload.id||"",timestamp:chunk.payload.metadata?.timestamp||/* @__PURE__ */new Date(),modelId:chunk.payload.metadata?.modelId||chunk.payload.metadata?.model||"",...otherMetadata,messages:chunk.payload.messages?.nonUser||[],// We have to cast this until messageList can take generics also and type metadata, it was too
1080
1077
  // complicated to do this in this PR, it will require a much bigger change.
1081
1078
  uiMessages:messageList.get.response.aiV5.ui()},providerMetadata};await options?.onStepFinish?.({...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),...stepResult});self.#bufferedSteps.push(stepResult);self.#bufferedByStep={text:"",reasoning:[],sources:[],files:[],toolCalls:[],toolResults:[],dynamicToolCalls:[],dynamicToolResults:[],staticToolCalls:[],staticToolResults:[],content:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},warnings:[],request:{},response:{id:"",timestamp:/* @__PURE__ */new Date(),modelId:"",messages:[],uiMessages:[]},reasoningText:"",providerMetadata:void 0,finishReason:void 0};break;}case "tripwire":self.#tripwire=true;self.#tripwireReason=chunk.payload?.tripwireReason||"Content blocked";self.#finishReason="other";self.#streamFinished=true;self.#delayedPromises.text.resolve(self.#bufferedText.join(""));self.#delayedPromises.finishReason.resolve("other");self.#delayedPromises.object.resolve(void 0);self.#delayedPromises.usage.resolve(self.#usageCount);self.#delayedPromises.warnings.resolve(self.#warnings);self.#delayedPromises.providerMetadata.resolve(void 0);self.#delayedPromises.response.resolve({});self.#delayedPromises.request.resolve({});self.#delayedPromises.reasoning.resolve([]);self.#delayedPromises.reasoningText.resolve(void 0);self.#delayedPromises.sources.resolve([]);self.#delayedPromises.files.resolve([]);self.#delayedPromises.toolCalls.resolve([]);self.#delayedPromises.toolResults.resolve([]);self.#delayedPromises.steps.resolve(self.#bufferedSteps);self.#delayedPromises.totalUsage.resolve(self.#usageCount);self.#delayedPromises.content.resolve([]);self.#emitChunk(chunk);controller.enqueue(chunk);self.#emitter.emit("finish");controller.terminate();return;case "finish":self.#status="success";if(chunk.payload.stepResult.reason){self.#finishReason=chunk.payload.stepResult.reason;}if(self.#bufferedObject!==void 0){const responseMessages=messageList.get.response.v2();const lastAssistantMessage=[...responseMessages].reverse().find(m=>m.role==="assistant");if(lastAssistantMessage){if(!lastAssistantMessage.content.metadata){lastAssistantMessage.content.metadata={};}lastAssistantMessage.content.metadata.structuredOutput=self.#bufferedObject;}}let response={};if(chunk.payload.metadata){const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;response={...otherMetadata,messages:messageList.get.response.aiV5.model(),uiMessages:messageList.get.response.aiV5.ui()};}this.populateUsageCount(chunk.payload.output.usage);chunk.payload.output.usage={inputTokens:self.#usageCount.inputTokens??0,outputTokens:self.#usageCount.outputTokens??0,totalTokens:self.#usageCount.totalTokens??0,...(self.#usageCount.reasoningTokens!==void 0&&{reasoningTokens:self.#usageCount.reasoningTokens}),...(self.#usageCount.cachedInputTokens!==void 0&&{cachedInputTokens:self.#usageCount.cachedInputTokens})};try{if(self.processorRunner&&!self.#options.isLLMExecutionStep){self.messageList=await self.processorRunner.runOutputProcessors(self.messageList);const outputText=self.messageList.get.response.aiV4.core().map(m=>MessageList.coreContentToString(m.content)).join("\n");self.#delayedPromises.text.resolve(outputText);self.#delayedPromises.finishReason.resolve(self.#finishReason);if(chunk.payload.metadata){const{providerMetadata,request,...otherMetadata}=chunk.payload.metadata;response={...otherMetadata,messages:messageList.get.response.aiV5.model(),uiMessages:messageList.get.response.aiV5.ui()};}}else {const textContent=self.#bufferedText.join("");self.#delayedPromises.text.resolve(textContent);self.#delayedPromises.finishReason.resolve(self.#finishReason);}}catch(error2){if(error2 instanceof TripWire){self.#tripwire=true;self.#tripwireReason=error2.message;self.#delayedPromises.finishReason.resolve("other");self.#delayedPromises.text.resolve("");}else {self.#error=error2 instanceof Error?error2.message:String(error2);self.#delayedPromises.finishReason.resolve("error");self.#delayedPromises.text.resolve("");}if(self.#delayedPromises.object.status.type!=="resolved"){self.#delayedPromises.object.resolve(void 0);}}self.#delayedPromises.usage.resolve(self.#usageCount);self.#delayedPromises.warnings.resolve(self.#warnings);self.#delayedPromises.providerMetadata.resolve(chunk.payload.metadata?.providerMetadata);self.#delayedPromises.response.resolve(response);self.#delayedPromises.request.resolve(self.#request||{});self.#delayedPromises.text.resolve(self.#bufferedText.join(""));const reasoningText=self.#bufferedReasoning.length>0?self.#bufferedReasoning.map(reasoningPart=>reasoningPart.payload.text).join(""):void 0;self.#delayedPromises.reasoningText.resolve(reasoningText);self.#delayedPromises.reasoning.resolve(Object.values(self.#bufferedReasoningDetails||{}));self.#delayedPromises.sources.resolve(self.#bufferedSources);self.#delayedPromises.files.resolve(self.#bufferedFiles);self.#delayedPromises.toolCalls.resolve(self.#toolCalls);self.#delayedPromises.toolResults.resolve(self.#toolResults);self.#delayedPromises.steps.resolve(self.#bufferedSteps);self.#delayedPromises.totalUsage.resolve(self.#getTotalUsage());self.#delayedPromises.content.resolve(messageList.get.response.aiV5.stepContent());self.#delayedPromises.suspendPayload.resolve(void 0);const baseFinishStep=self.#bufferedSteps[self.#bufferedSteps.length-1];if(baseFinishStep){const onFinishPayload={// StepResult properties from baseFinishStep
1082
1079
  providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnings:baseFinishStep.warnings??[],finishReason:chunk.payload.stepResult.reason,content:messageList.get.response.aiV5.stepContent(),request:await self.request,error:self.error,reasoning:await self.reasoning,reasoningText:await self.reasoningText,sources:await self.sources,files:await self.files,steps:self.#bufferedSteps,response:{...(await self.response),...baseFinishStep.response,messages:messageList.get.response.aiV5.model()},usage:chunk.payload.output.usage,totalUsage:self.#getTotalUsage(),toolCalls:await self.toolCalls,toolResults:await self.toolResults,staticToolCalls:(await self.toolCalls).filter(toolCall=>toolCall?.payload?.dynamic===false),staticToolResults:(await self.toolResults).filter(toolResult=>toolResult?.payload?.dynamic===false),dynamicToolCalls:(await self.toolCalls).filter(toolCall=>toolCall?.payload?.dynamic===true),dynamicToolResults:(await self.toolResults).filter(toolResult=>toolResult?.payload?.dynamic===true),// Custom properties (not part of standard callback)
1083
- ...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),object:self.#delayedPromises.object.status.type==="rejected"?void 0:self.#delayedPromises.object.status.type==="resolved"?self.#delayedPromises.object.status.value:self.#options.output&&baseFinishStep.text?(()=>{try{return JSON.parse(baseFinishStep.text);}catch{return void 0;}})():void 0};await options?.onFinish?.(onFinishPayload);}if(options?.rootSpan){options.rootSpan.setAttributes({...(self.#model.modelId?{"aisdk.model.id":self.#model.modelId}:{}),...(self.#model.provider?{"aisdk.model.provider":self.#model.provider}:{}),...(baseFinishStep?.usage?.reasoningTokens?{"stream.usage.reasoningTokens":baseFinishStep.usage.reasoningTokens}:{}),...(baseFinishStep?.usage?.totalTokens?{"stream.usage.totalTokens":baseFinishStep.usage.totalTokens}:{}),...(baseFinishStep?.usage?.inputTokens?{"stream.usage.inputTokens":baseFinishStep.usage.inputTokens}:{}),...(baseFinishStep?.usage?.outputTokens?{"stream.usage.outputTokens":baseFinishStep.usage.outputTokens}:{}),...(baseFinishStep?.usage?.cachedInputTokens?{"stream.usage.cachedInputTokens":baseFinishStep.usage.cachedInputTokens}:{}),...(baseFinishStep?.providerMetadata?{"stream.response.providerMetadata":JSON.stringify(baseFinishStep?.providerMetadata)}:{}),...(baseFinishStep?.finishReason?{"stream.response.finishReason":baseFinishStep?.finishReason}:{}),...(options?.telemetry_settings?.recordOutputs!==false?{"stream.response.text":baseFinishStep?.text}:{}),...(baseFinishStep?.toolCalls&&options?.telemetry_settings?.recordOutputs!==false?{"stream.response.toolCalls":JSON.stringify(baseFinishStep?.toolCalls?.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.payload?.toolCallId,args:toolCall.payload?.args,toolName:toolCall.payload?.toolName};}).filter(Boolean))}:{})});options.rootSpan.end();}break;case "error":self.#error=chunk.payload.error;self.#status="failed";self.#streamFinished=true;const errorMessage=self.#error?.message||safeParseErrorObject(self.#error);const error=new Error(errorMessage);Object.values(self.#delayedPromises).forEach(promise=>{if(promise.status.type==="pending"){promise.reject(error);}});break;}self.#emitChunk(chunk);controller.enqueue(chunk);},flush:()=>{if(self.#delayedPromises.object.status.type!=="resolved"){self.#delayedPromises.object.resolve(void 0);}Object.entries(self.#delayedPromises).forEach(([key,promise])=>{if(promise.status.type==="pending"){promise.reject(new Error(`promise '${key}' was not resolved or rejected when stream finished`));}});self.#streamFinished=true;self.#emitter.emit("finish");}}));this.#aisdkv5=new AISDKV5OutputStream({modelOutput:this,messageList,options:{toolCallStreaming:options?.toolCallStreaming,output:options?.output,tracingContext:options?.tracingContext}});}#getDelayedPromise(promise){if(!this.#consumptionStarted){void this.consumeStream();}return promise.promise;}/**
1080
+ ...(self.#model.modelId&&self.#model.provider&&self.#model.version?{model:self.#model}:{}),object:self.#delayedPromises.object.status.type==="rejected"?void 0:self.#delayedPromises.object.status.type==="resolved"?self.#delayedPromises.object.status.value:self.#structuredOutputMode==="direct"&&baseFinishStep.text?(()=>{try{return JSON.parse(baseFinishStep.text);}catch{return void 0;}})():void 0};await options?.onFinish?.(onFinishPayload);}if(options?.rootSpan){options.rootSpan.setAttributes({...(self.#model.modelId?{"aisdk.model.id":self.#model.modelId}:{}),...(self.#model.provider?{"aisdk.model.provider":self.#model.provider}:{}),...(baseFinishStep?.usage?.reasoningTokens?{"stream.usage.reasoningTokens":baseFinishStep.usage.reasoningTokens}:{}),...(baseFinishStep?.usage?.totalTokens?{"stream.usage.totalTokens":baseFinishStep.usage.totalTokens}:{}),...(baseFinishStep?.usage?.inputTokens?{"stream.usage.inputTokens":baseFinishStep.usage.inputTokens}:{}),...(baseFinishStep?.usage?.outputTokens?{"stream.usage.outputTokens":baseFinishStep.usage.outputTokens}:{}),...(baseFinishStep?.usage?.cachedInputTokens?{"stream.usage.cachedInputTokens":baseFinishStep.usage.cachedInputTokens}:{}),...(baseFinishStep?.providerMetadata?{"stream.response.providerMetadata":JSON.stringify(baseFinishStep?.providerMetadata)}:{}),...(baseFinishStep?.finishReason?{"stream.response.finishReason":baseFinishStep?.finishReason}:{}),...(options?.telemetry_settings?.recordOutputs!==false?{"stream.response.text":baseFinishStep?.text}:{}),...(baseFinishStep?.toolCalls&&options?.telemetry_settings?.recordOutputs!==false?{"stream.response.toolCalls":JSON.stringify(baseFinishStep?.toolCalls?.map(toolCall=>{return {type:"tool-call",toolCallId:toolCall.payload?.toolCallId,args:toolCall.payload?.args,toolName:toolCall.payload?.toolName};}).filter(Boolean))}:{})});options.rootSpan.end();}break;case "error":self.#error=chunk.payload.error;self.#status="failed";self.#streamFinished=true;const errorMessage=self.#error?.message||safeParseErrorObject(self.#error);const error=new Error(errorMessage);Object.values(self.#delayedPromises).forEach(promise=>{if(promise.status.type==="pending"){promise.reject(error);}});break;}self.#emitChunk(chunk);controller.enqueue(chunk);},flush:()=>{if(self.#delayedPromises.object.status.type!=="resolved"){self.#delayedPromises.object.resolve(void 0);}Object.entries(self.#delayedPromises).forEach(([key,promise])=>{if(promise.status.type==="pending"){promise.reject(new Error(`promise '${key}' was not resolved or rejected when stream finished`));}});self.#streamFinished=true;self.#emitter.emit("finish");}}));this.#aisdkv5=new AISDKV5OutputStream({modelOutput:this,messageList,options:{toolCallStreaming:options?.toolCallStreaming,structuredOutput:options?.structuredOutput,tracingContext:options?.tracingContext}});}#getDelayedPromise(promise){if(!this.#consumptionStarted){void this.consumeStream();}return promise.promise;}/**
1084
1081
  * Resolves to the complete text response after streaming completes.
1085
1082
  */get text(){return this.#getDelayedPromise(this.#delayedPromises.text);}/**
1086
1083
  * Resolves to reasoning parts array for models that support reasoning.
@@ -1124,7 +1121,10 @@ providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnin
1124
1121
  * @example
1125
1122
  * ```typescript
1126
1123
  * const stream = await agent.stream("Extract data", {
1127
- * output: z.object({ name: z.string(), age: z.number() })
1124
+ * structuredOutput: {
1125
+ * schema: z.object({ name: z.string(), age: z.number() }),
1126
+ * model: 'gpt-4o-mini' // optional to use a model for structuring json output
1127
+ * }
1128
1128
  * });
1129
1129
  * // partial json chunks
1130
1130
  * for await (const data of stream.objectStream) {
@@ -1135,21 +1135,24 @@ providerMetadata:baseFinishStep.providerMetadata,text:baseFinishStep.text,warnin
1135
1135
  * Stream of individual array elements when output schema is an array type.
1136
1136
  */get elementStream(){let publishedElements=0;return this.#createEventedStream().pipeThrough(new TransformStream({transform(chunk,controller){if(chunk.type==="object"){if(Array.isArray(chunk.object)){for(;publishedElements<chunk.object.length;publishedElements++){controller.enqueue(chunk.object[publishedElements]);}}}}}));}/**
1137
1137
  * Stream of only text content, filtering out metadata and other chunk types.
1138
- */get textStream(){const outputSchema=getTransformedSchema(this.#options.output);if(outputSchema?.outputFormat==="array"){return this.#createEventedStream().pipeThrough(createJsonTextStreamTransformer(this.#options.output));}return this.#createEventedStream().pipeThrough(new TransformStream({transform(chunk,controller){if(chunk.type==="text-delta"){controller.enqueue(chunk.payload.text);}}}));}/**
1138
+ */get textStream(){if(this.#structuredOutputMode==="direct"){const outputSchema=getTransformedSchema(this.#options.structuredOutput?.schema);if(outputSchema?.outputFormat==="array"){return this.#createEventedStream().pipeThrough(createJsonTextStreamTransformer(this.#options.structuredOutput?.schema));}}return this.#createEventedStream().pipeThrough(new TransformStream({transform(chunk,controller){if(chunk.type==="text-delta"){controller.enqueue(chunk.payload.text);}}}));}/**
1139
1139
  * Resolves to the complete object response from the model. Validated against the 'output' schema when the stream ends.
1140
1140
  *
1141
1141
  * @example
1142
1142
  * ```typescript
1143
1143
  * const stream = await agent.stream("Extract data", {
1144
- * output: z.object({ name: z.string(), age: z.number() })
1144
+ * structuredOutput: {
1145
+ * schema: z.object({ name: z.string(), age: z.number() }),
1146
+ * model: 'gpt-4o-mini' // optionally use a model for structuring json output
1147
+ * }
1145
1148
  * });
1146
1149
  * // final validated json
1147
1150
  * const data = await stream.object // { name: 'John', age: 30 }
1148
1151
  * ```
1149
- */get object(){if(!this.processorRunner&&!this.#options.output&&this.#delayedPromises.object.status.type==="pending"){this.#delayedPromises.object.resolve(void 0);}return this.#getDelayedPromise(this.#delayedPromises.object);}// Internal methods for immediate values - used internally by Mastra (llm-execution.ts bailing on errors/abort signals with current state)
1152
+ */get object(){if(!this.processorRunner&&!this.#options.structuredOutput?.schema&&this.#delayedPromises.object.status.type==="pending"){this.#delayedPromises.object.resolve(void 0);}return this.#getDelayedPromise(this.#delayedPromises.object);}// Internal methods for immediate values - used internally by Mastra (llm-execution.ts bailing on errors/abort signals with current state)
1150
1153
  // These are not part of the public API
1151
1154
  /** @internal */_getImmediateToolCalls(){return this.#toolCalls;}/** @internal */_getImmediateToolResults(){return this.#toolResults;}/** @internal */_getImmediateText(){return this.#bufferedText.join("");}/** @internal */_getImmediateObject(){return this.#bufferedObject;}/** @internal */_getImmediateUsage(){return this.#usageCount;}/** @internal */_getImmediateWarnings(){return this.#warnings;}/** @internal */_getImmediateFinishReason(){return this.#finishReason;}/** @internal */_getBaseStream(){return this.#baseStream;}#getTotalUsage(){let total=this.#usageCount.totalTokens;if(total===void 0){const input=this.#usageCount.inputTokens??0;const output=this.#usageCount.outputTokens??0;const reasoning=this.#usageCount.reasoningTokens??0;total=input+output+reasoning;}return {inputTokens:this.#usageCount.inputTokens,outputTokens:this.#usageCount.outputTokens,totalTokens:total,reasoningTokens:this.#usageCount.reasoningTokens,cachedInputTokens:this.#usageCount.cachedInputTokens};}#emitChunk(chunk){this.#bufferedChunks.push(chunk);this.#emitter.emit("chunk",chunk);}#createEventedStream(){const self=this;return new ReadableStream$1({start(controller){self.#bufferedChunks.forEach(chunk=>{controller.enqueue(chunk);});if(self.#streamFinished){controller.close();return;}const chunkHandler=chunk=>{controller.enqueue(chunk);};const finishHandler=()=>{self.#emitter.off("chunk",chunkHandler);self.#emitter.off("finish",finishHandler);controller.close();};self.#emitter.on("chunk",chunkHandler);self.#emitter.on("finish",finishHandler);},pull(_controller){if(!self.#consumptionStarted){void self.consumeStream();}},cancel(){self.#emitter.removeAllListeners();}});}get status(){return this.#status;}serializeState(){return {status:this.#status,bufferedSteps:this.#bufferedSteps,bufferedReasoningDetails:this.#bufferedReasoningDetails,bufferedByStep:this.#bufferedByStep,bufferedText:this.#bufferedText,bufferedTextChunks:this.#bufferedTextChunks,bufferedSources:this.#bufferedSources,bufferedReasoning:this.#bufferedReasoning,bufferedFiles:this.#bufferedFiles,toolCallArgsDeltas:this.#toolCallArgsDeltas,toolCallDeltaIdNameMap:this.#toolCallDeltaIdNameMap,toolCalls:this.#toolCalls,toolResults:this.#toolResults,warnings:this.#warnings,finishReason:this.#finishReason,request:this.#request,usageCount:this.#usageCount,tripwire:this.#tripwire,tripwireReason:this.#tripwireReason};}deserializeState(state){this.#status=state.status;this.#bufferedSteps=state.bufferedSteps;this.#bufferedReasoningDetails=state.bufferedReasoningDetails;this.#bufferedByStep=state.bufferedByStep;this.#bufferedText=state.bufferedText;this.#bufferedTextChunks=state.bufferedTextChunks;this.#bufferedSources=state.bufferedSources;this.#bufferedReasoning=state.bufferedReasoning;this.#bufferedFiles=state.bufferedFiles;this.#toolCallArgsDeltas=state.toolCallArgsDeltas;this.#toolCallDeltaIdNameMap=state.toolCallDeltaIdNameMap;this.#toolCalls=state.toolCalls;this.#toolResults=state.toolResults;this.#warnings=state.warnings;this.#finishReason=state.finishReason;this.#request=state.request;this.#usageCount=state.usageCount;this.#tripwire=state.tripwire;this.#tripwireReason=state.tripwireReason;}};
1152
1155
 
1153
- export { AISDKV5OutputStream, Agent, BatchPartsProcessor, ChunkFrom, DefaultExecutionEngine, ExecutionEngine, LanguageDetector, LanguageDetectorInputProcessor, LegacyStep, LegacyWorkflow, MastraModelOutput, ModerationInputProcessor, ModerationProcessor, PIIDetector, PIIDetectorInputProcessor, ProcessorState, PromptInjectionDetector, PromptInjectionDetectorInputProcessor, Run, StructuredOutputProcessor, SystemPromptScrubber, TokenLimiterProcessor, TripWire, UnicodeNormalizer, UnicodeNormalizerInputProcessor, WhenConditionReturnValue, Workflow, agentToStep, cloneStep, cloneWorkflow, convertFullStreamChunkToUIMessageStream, convertMastraChunkToAISDKv5, createStep, createWorkflow, getActivePathsAndStatus, getResultActivePaths, getStepResult, getStepResult2, getSuspendedPaths, isAgent, isConditionalKey, isErrorEvent, isFinalState, isLimboState, isTransitionEvent, isVariableReference, isWorkflow, loop, mapVariable, mergeChildValue, recursivelyCheckForFinalState, resolveVariables, updateStepInHierarchy, validateStepInput, workflowToStep };
1154
- //# sourceMappingURL=chunk-EB2KTBHB.js.map
1155
- //# sourceMappingURL=chunk-EB2KTBHB.js.map
1156
+ export { AISDKV5OutputStream, Agent, BatchPartsProcessor, ChunkFrom, DefaultExecutionEngine, ExecutionEngine, LanguageDetector, LanguageDetectorInputProcessor, LegacyStep, LegacyWorkflow, MastraModelOutput, ModerationInputProcessor, ModerationProcessor, PIIDetector, PIIDetectorInputProcessor, ProcessorState, PromptInjectionDetector, PromptInjectionDetectorInputProcessor, Run, StructuredOutputProcessor, SystemPromptScrubber, TokenLimiterProcessor, TripWire, UnicodeNormalizer, UnicodeNormalizerInputProcessor, WhenConditionReturnValue, Workflow, agentToStep, cloneStep, cloneWorkflow, convertFullStreamChunkToUIMessageStream, convertMastraChunkToAISDKv5, createStep, createWorkflow, getActivePathsAndStatus, getResultActivePaths, getStepResult, getStepResult2, getSuspendedPaths, isAgent, isConditionalKey, isErrorEvent, isFinalState, isLimboState, isTransitionEvent, isVariableReference, isWorkflow, loop, mapVariable, mergeChildValue, recursivelyCheckForFinalState, resolveVariables, tryGenerateWithJsonFallback, tryStreamWithJsonFallback, updateStepInHierarchy, validateStepInput, workflowToStep };
1157
+ //# sourceMappingURL=chunk-WYJFP2MU.js.map
1158
+ //# sourceMappingURL=chunk-WYJFP2MU.js.map