@mastra/core 1.86.0 → 1.87.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (481) hide show
  1. package/dist/_types/@ai-sdk_anthropic@3.0.137/dist/index.d.ts +2 -2
  2. package/dist/_types/@ai-sdk_google@3.0.140/dist/index.d.ts +2 -2
  3. package/dist/_types/@ai-sdk_openai@3.0.135/dist/index.d.ts +2 -2
  4. package/dist/a2a/index.cjs +1 -1
  5. package/dist/a2a/index.js +1 -1
  6. package/dist/agent/durable/constants.d.ts +2 -0
  7. package/dist/agent/durable/evented-execution.d.ts +7 -0
  8. package/dist/agent/durable/execution-engine.d.ts +1 -0
  9. package/dist/agent/durable/execution-fence.d.ts +2 -0
  10. package/dist/agent/durable/index.cjs +4 -1
  11. package/dist/agent/durable/index.d.ts +2 -1
  12. package/dist/agent/durable/index.js +2 -2
  13. package/dist/agent/durable/run-registry.d.ts +13 -0
  14. package/dist/agent/durable/segment-spans.d.ts +54 -1
  15. package/dist/agent/durable/types.d.ts +12 -0
  16. package/dist/agent/durable/workflows/durable-loop-builder.d.ts +57 -2
  17. package/dist/agent/durable/workflows/finalize-run.d.ts +4 -1
  18. package/dist/agent/durable/workflows/shared/index.d.ts +1 -1
  19. package/dist/agent/durable/workflows/shared/reported-cost.d.ts +7 -0
  20. package/dist/agent/durable/workflows/shared/schemas.d.ts +16 -1
  21. package/dist/agent/durable/workflows/shared/tool-call-concurrency.d.ts +6 -0
  22. package/dist/agent/durable/workflows/steps/llm-execution.d.ts +5 -0
  23. package/dist/agent/durable/workflows/steps/llm-mapping.d.ts +6 -0
  24. package/dist/agent/durable/workflows/steps/tool-call.d.ts +20 -0
  25. package/dist/agent/index.cjs +3 -3
  26. package/dist/agent/index.js +3 -3
  27. package/dist/agent/message-list/index.cjs +1 -1
  28. package/dist/agent/message-list/index.js +1 -1
  29. package/dist/agent/request-context-snapshot.d.ts +3 -2
  30. package/dist/agent/streams/run-records.d.ts +9 -1
  31. package/dist/agent/thread-stream-runtime.d.ts +3 -1
  32. package/dist/agent-builder/ee/index.cjs +1 -1
  33. package/dist/agent-builder/ee/index.js +1 -1
  34. package/dist/agent-controller/index.cjs +1 -1
  35. package/dist/agent-controller/index.js +1 -1
  36. package/dist/agent-controller/session-run-engine.d.ts +5 -2
  37. package/dist/agent-controller/session.d.ts +2 -0
  38. package/dist/agent-controller/types.d.ts +23 -0
  39. package/dist/{agent-controller-D_5Dc8d3.cjs → agent-controller-BTIxiD1u.cjs} +44 -14
  40. package/dist/{agent-controller-D5EKeS1H.js → agent-controller-C1bK0CXm.js} +44 -14
  41. package/dist/background-tasks/index.cjs +1 -1
  42. package/dist/background-tasks/index.js +1 -1
  43. package/dist/background-tasks/manager.d.ts +4 -1
  44. package/dist/{background-tasks-idnlMbqD.js → background-tasks-BbVsBghi.js} +139 -51
  45. package/dist/{background-tasks-BVxb0VGV.cjs → background-tasks-CVl6e0Jo.cjs} +139 -51
  46. package/dist/browser/index.cjs +1 -1
  47. package/dist/browser/index.js +1 -1
  48. package/dist/{builder-CBWoYNck.cjs → builder-BRJPSTig.cjs} +2 -2
  49. package/dist/{builder-Cuq-j2w3.js → builder-C8XzrtBQ.js} +2 -2
  50. package/dist/cache/base.d.ts +40 -10
  51. package/dist/cache/index.cjs +1 -1
  52. package/dist/cache/index.js +1 -1
  53. package/dist/capabilities/302ai.json +213 -213
  54. package/dist/capabilities/abliteratedllm.json +30 -30
  55. package/dist/capabilities/abliteration-ai.json +6 -6
  56. package/dist/capabilities/above.json +19 -19
  57. package/dist/capabilities/adaption.json +16 -16
  58. package/dist/capabilities/adzuki.json +19 -19
  59. package/dist/capabilities/agentrouter.json +11 -11
  60. package/dist/capabilities/agnes.json +2 -2
  61. package/dist/capabilities/ai-router.json +6 -6
  62. package/dist/capabilities/aiand.json +20 -20
  63. package/dist/capabilities/aigrow.json +14 -14
  64. package/dist/capabilities/aimlapi.json +146 -150
  65. package/dist/capabilities/aixy.json +21 -21
  66. package/dist/capabilities/aki-io.json +14 -14
  67. package/dist/capabilities/alibaba-cn.json +96 -96
  68. package/dist/capabilities/alibaba-coding-plan-cn.json +4 -4
  69. package/dist/capabilities/alibaba-coding-plan.json +4 -4
  70. package/dist/capabilities/alibaba-token-plan-cn.json +50 -50
  71. package/dist/capabilities/alibaba-token-plan.json +49 -49
  72. package/dist/capabilities/alibaba.json +69 -69
  73. package/dist/capabilities/ambient.json +12 -12
  74. package/dist/capabilities/amd.json +8 -8
  75. package/dist/capabilities/anthropic.json +43 -43
  76. package/dist/capabilities/anyapi.json +17 -17
  77. package/dist/capabilities/apiko.json +2 -2
  78. package/dist/capabilities/arcee.json +11 -11
  79. package/dist/capabilities/augure.json +6 -6
  80. package/dist/capabilities/auriko.json +24 -24
  81. package/dist/capabilities/bailing.json +5 -5
  82. package/dist/capabilities/baseten.json +35 -35
  83. package/dist/capabilities/bee.json +5 -5
  84. package/dist/capabilities/berget.json +8 -8
  85. package/dist/capabilities/bothub.json +15 -15
  86. package/dist/capabilities/boundless.json +36 -36
  87. package/dist/capabilities/bumo.json +47 -47
  88. package/dist/capabilities/byteplus.json +30 -30
  89. package/dist/capabilities/cerebras.json +4 -4
  90. package/dist/capabilities/cheapaimodel.json +10 -10
  91. package/dist/capabilities/cheapest-token.json +32 -32
  92. package/dist/capabilities/chutes.json +11 -14
  93. package/dist/capabilities/cline-pass.json +33 -33
  94. package/dist/capabilities/cloudcode.json +9 -9
  95. package/dist/capabilities/cloudferro-sherlock.json +4 -4
  96. package/dist/capabilities/cloudflare-workers-ai.json +17 -78
  97. package/dist/capabilities/commandcode.json +155 -155
  98. package/dist/capabilities/concentrate.json +286 -277
  99. package/dist/capabilities/cortecs.json +114 -114
  100. package/dist/capabilities/crossmodel.json +189 -189
  101. package/dist/capabilities/crusoe.json +8 -8
  102. package/dist/capabilities/daoxe.json +6 -6
  103. package/dist/capabilities/databricks.json +129 -129
  104. package/dist/capabilities/deepinfra.json +132 -69
  105. package/dist/capabilities/deepseek.json +4 -4
  106. package/dist/capabilities/digitalocean.json +112 -112
  107. package/dist/capabilities/dothoosh.json +31 -31
  108. package/dist/capabilities/doubleword.json +26 -26
  109. package/dist/capabilities/edenai.json +902 -1760
  110. package/dist/capabilities/empiriolabs.json +156 -158
  111. package/dist/capabilities/engy.json +18 -18
  112. package/dist/capabilities/entrim.json +6 -6
  113. package/dist/capabilities/evroc.json +16 -16
  114. package/dist/capabilities/ezkielyna.json +7 -7
  115. package/dist/capabilities/fastrouter.json +73 -73
  116. package/dist/capabilities/fireworks-ai.json +86 -65
  117. package/dist/capabilities/freemodel.json +24 -24
  118. package/dist/capabilities/friendli.json +2 -2
  119. package/dist/capabilities/frogbot.json +96 -96
  120. package/dist/capabilities/gisoo.json +17 -17
  121. package/dist/capabilities/gmicloud.json +10 -10
  122. package/dist/capabilities/google.json +50 -50
  123. package/dist/capabilities/graphn.json +12 -12
  124. package/dist/capabilities/greenpt.json +35 -35
  125. package/dist/capabilities/groq.json +8 -8
  126. package/dist/capabilities/helicone.json +77 -77
  127. package/dist/capabilities/hostinger-router.json +11 -11
  128. package/dist/capabilities/hpc-ai.json +14 -14
  129. package/dist/capabilities/huawei-maas.json +16 -16
  130. package/dist/capabilities/hubris.json +30 -30
  131. package/dist/capabilities/huggingface.json +101 -91
  132. package/dist/capabilities/hyper.json +24 -24
  133. package/dist/capabilities/impossibl.json +135 -135
  134. package/dist/capabilities/inception.json +2 -2
  135. package/dist/capabilities/inceptron.json +8 -8
  136. package/dist/capabilities/inco.json +4 -4
  137. package/dist/capabilities/infer.json +13 -13
  138. package/dist/capabilities/inferall.json +4 -4
  139. package/dist/capabilities/inference-coop.json +9 -9
  140. package/dist/capabilities/inferenceapis.json +26 -26
  141. package/dist/capabilities/inferris.json +3 -3
  142. package/dist/capabilities/infersia.json +14 -14
  143. package/dist/capabilities/inferx.json +3 -3
  144. package/dist/capabilities/infomaniak.json +2 -2
  145. package/dist/capabilities/io-net.json +5 -5
  146. package/dist/capabilities/iteracompute.json +55 -55
  147. package/dist/capabilities/jad-ai.json +2 -2
  148. package/dist/capabilities/jalapeno.json +11 -11
  149. package/dist/capabilities/jiekou.json +64 -64
  150. package/dist/capabilities/joingonka.json +4 -4
  151. package/dist/capabilities/jzstoken.json +40 -40
  152. package/dist/capabilities/keln.json +25 -25
  153. package/dist/capabilities/kenari.json +123 -123
  154. package/dist/capabilities/kilo.json +639 -623
  155. package/dist/capabilities/kimi-code-plan-cn.json +4 -4
  156. package/dist/capabilities/kimi-code-plan-global.json +4 -4
  157. package/dist/capabilities/kitani.json +6 -6
  158. package/dist/capabilities/klavo.json +23 -23
  159. package/dist/capabilities/korouter.json +31 -31
  160. package/dist/capabilities/kunavo.json +10 -10
  161. package/dist/capabilities/liquid.json +10 -10
  162. package/dist/capabilities/lithosai.json +2 -2
  163. package/dist/capabilities/llmgateway-providers.json +895 -886
  164. package/dist/capabilities/llmgateway.json +344 -336
  165. package/dist/capabilities/llmtr.json +26 -26
  166. package/dist/capabilities/logits.json +2 -2
  167. package/dist/capabilities/longcat.json +2 -2
  168. package/dist/capabilities/lowrouter.json +49 -49
  169. package/dist/capabilities/lyceum.json +11 -11
  170. package/dist/capabilities/melious.json +12 -12
  171. package/dist/capabilities/merge-gateway.json +259 -258
  172. package/dist/capabilities/meta.json +8 -8
  173. package/dist/capabilities/minimax-cn-coding-plan.json +2 -2
  174. package/dist/capabilities/minimax-cn.json +5 -5
  175. package/dist/capabilities/minimax-coding-plan.json +2 -2
  176. package/dist/capabilities/minimax.json +5 -5
  177. package/dist/capabilities/mistral.json +18 -18
  178. package/dist/capabilities/mixlayer.json +5 -5
  179. package/dist/capabilities/modal.json +10 -10
  180. package/dist/capabilities/model-oracle-ai.json +26 -26
  181. package/dist/capabilities/modelis.json +13 -13
  182. package/dist/capabilities/modelscope.json +2 -2
  183. package/dist/capabilities/modular.json +8 -8
  184. package/dist/capabilities/moneo.json +13 -13
  185. package/dist/capabilities/moonshotai-cn.json +3 -3
  186. package/dist/capabilities/moonshotai.json +3 -3
  187. package/dist/capabilities/morph.json +11 -11
  188. package/dist/capabilities/munito-eu.json +6 -6
  189. package/dist/capabilities/munito.json +10 -10
  190. package/dist/capabilities/nan.json +24 -24
  191. package/dist/capabilities/nano-gpt.json +583 -548
  192. package/dist/capabilities/nearai.json +82 -82
  193. package/dist/capabilities/nebius.json +33 -33
  194. package/dist/capabilities/neon.json +135 -135
  195. package/dist/capabilities/neuralwatt.json +37 -37
  196. package/dist/capabilities/nokeep.json +5 -5
  197. package/dist/capabilities/novita-ai.json +153 -153
  198. package/dist/capabilities/nvidia.json +25 -57
  199. package/dist/capabilities/oathbreaker.json +2 -2
  200. package/dist/capabilities/obscurify.json +27 -27
  201. package/dist/capabilities/oci.json +16 -7
  202. package/dist/capabilities/ofox.json +358 -358
  203. package/dist/capabilities/ollama-cloud.json +50 -50
  204. package/dist/capabilities/openai.json +79 -47
  205. package/dist/capabilities/opencode-go.json +88 -88
  206. package/dist/capabilities/openreason.json +5 -5
  207. package/dist/capabilities/openrouter.json +543 -533
  208. package/dist/capabilities/opper.json +28 -28
  209. package/dist/capabilities/orcarouter.json +238 -238
  210. package/dist/capabilities/outerlabs.json +30 -30
  211. package/dist/capabilities/ovhcloud.json +61 -7
  212. package/dist/capabilities/pareto.json +4 -4
  213. package/dist/capabilities/pendra.json +4 -4
  214. package/dist/capabilities/perplexity-agent.json +59 -59
  215. package/dist/capabilities/perplexity.json +2 -2
  216. package/dist/capabilities/phala.json +34 -34
  217. package/dist/capabilities/pioneer.json +26 -26
  218. package/dist/capabilities/poe.json +99 -99
  219. package/dist/capabilities/poolside.json +2 -2
  220. package/dist/capabilities/powerspring.json +12 -12
  221. package/dist/capabilities/primalabs.json +10 -10
  222. package/dist/capabilities/prime.json +117 -101
  223. package/dist/capabilities/privatemode-ai.json +11 -11
  224. package/dist/capabilities/proxystacks.json +6 -6
  225. package/dist/capabilities/qiniu-ai.json +13 -13
  226. package/dist/capabilities/refuseless.json +8 -8
  227. package/dist/capabilities/regolo-ai.json +11 -11
  228. package/dist/capabilities/requesty.json +171 -171
  229. package/dist/capabilities/ruapi.json +19 -19
  230. package/dist/capabilities/runcrate.json +17 -17
  231. package/dist/capabilities/runinfra.json +16 -16
  232. package/dist/capabilities/sakana.json +5 -5
  233. package/dist/capabilities/sambanova.json +6 -6
  234. package/dist/capabilities/sandbase.json +22 -22
  235. package/dist/capabilities/sarvam.json +12 -12
  236. package/dist/capabilities/scaleway.json +17 -17
  237. package/dist/capabilities/scnet-token-plan.json +14 -14
  238. package/dist/capabilities/scx-ai.json +29 -29
  239. package/dist/capabilities/sensenova.json +10 -10
  240. package/dist/capabilities/siliconflow-cn.json +58 -58
  241. package/dist/capabilities/siliconflow.json +61 -61
  242. package/dist/capabilities/snowflake-cortex.json +24 -24
  243. package/dist/capabilities/sokkan.json +9 -9
  244. package/dist/capabilities/sparrowcodes.json +18 -18
  245. package/dist/capabilities/standardcompute.json +94 -94
  246. package/dist/capabilities/steadyrouter.json +42 -42
  247. package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
  248. package/dist/capabilities/stepfun-ai.json +5 -5
  249. package/dist/capabilities/stepfun-step-plan.json +5 -5
  250. package/dist/capabilities/stepfun.json +5 -5
  251. package/dist/capabilities/stepping-stone.json +20 -20
  252. package/dist/capabilities/superbot-gg.json +4 -4
  253. package/dist/capabilities/synthetic.json +12 -12
  254. package/dist/capabilities/synthorai.json +21 -21
  255. package/dist/capabilities/teamorouter.json +24 -24
  256. package/dist/capabilities/teapot-router.json +13 -13
  257. package/dist/capabilities/tencent-token-plan.json +56 -32
  258. package/dist/capabilities/tencent-tokenhub.json +43 -43
  259. package/dist/capabilities/tensorx.json +48 -48
  260. package/dist/capabilities/tenstorrent.json +2 -2
  261. package/dist/capabilities/the-grid-ai.json +33 -33
  262. package/dist/capabilities/thinkingmachines.json +78 -78
  263. package/dist/capabilities/tinfoil.json +10 -10
  264. package/dist/capabilities/toapis.json +2 -2
  265. package/dist/capabilities/togetherai.json +52 -50
  266. package/dist/capabilities/tokengo.json +19 -19
  267. package/dist/capabilities/tokenify.json +10 -10
  268. package/dist/capabilities/trustedrouter.json +5 -5
  269. package/dist/capabilities/trustedtokens.json +16 -16
  270. package/dist/capabilities/umans-ai-coding-plan.json +16 -16
  271. package/dist/capabilities/umans-ai.json +10 -10
  272. package/dist/capabilities/unrestricted.json +8 -8
  273. package/dist/capabilities/uplinkswitch.json +19 -19
  274. package/dist/capabilities/upstage.json +8 -8
  275. package/dist/capabilities/vancine.json +20 -20
  276. package/dist/capabilities/vercel.json +539 -539
  277. package/dist/capabilities/vivgrid.json +85 -85
  278. package/dist/capabilities/volcengine-coding-plan.json +36 -27
  279. package/dist/capabilities/volcengine.json +26 -26
  280. package/dist/capabilities/vultr.json +30 -30
  281. package/dist/capabilities/wafer.ai.json +19 -19
  282. package/dist/capabilities/wallaby.json +5 -5
  283. package/dist/capabilities/wally.json +8 -8
  284. package/dist/capabilities/wandb.json +19 -19
  285. package/dist/capabilities/watt.json +23 -23
  286. package/dist/capabilities/xai.json +7 -7
  287. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -2
  288. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -2
  289. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -2
  290. package/dist/capabilities/xiaomi.json +2 -2
  291. package/dist/capabilities/xpersona.json +12 -12
  292. package/dist/capabilities/xxapi.json +30 -30
  293. package/dist/capabilities/zai-coding-plan.json +17 -17
  294. package/dist/capabilities/zai.json +28 -26
  295. package/dist/capabilities/zenifra.json +27 -27
  296. package/dist/capabilities/zenmux.json +164 -164
  297. package/dist/capabilities/zerogpu.json +11 -11
  298. package/dist/capabilities/zhipuai-coding-plan.json +4 -4
  299. package/dist/capabilities/zhipuai.json +22 -22
  300. package/dist/capabilities/zro.json +3 -3
  301. package/dist/channels/agent-channels.d.ts +9 -1
  302. package/dist/channels/attach-file-tool.d.ts +22 -0
  303. package/dist/channels/formatting.d.ts +8 -0
  304. package/dist/channels/index.cjs +13 -2
  305. package/dist/channels/index.d.ts +11 -1
  306. package/dist/channels/index.js +3 -3
  307. package/dist/channels/reply-guidance-processor.d.ts +26 -0
  308. package/dist/channels/reply-mode.d.ts +66 -0
  309. package/dist/channels/reply-reminder-processor.d.ts +23 -0
  310. package/dist/channels/reply-tool.d.ts +43 -0
  311. package/dist/channels/thread-link-processor.d.ts +48 -0
  312. package/dist/channels/thread-lookup.d.ts +16 -0
  313. package/dist/channels/tool-announcement-processor.d.ts +29 -0
  314. package/dist/channels/types.d.ts +30 -3
  315. package/dist/{channels-D7bBM9xD.cjs → channels-Cl-pRrWB.cjs} +122 -1
  316. package/dist/{channels-DSOCNoab.js → channels-DegTNzaq.js} +99 -2
  317. package/dist/coding-agent/index.cjs +1 -1
  318. package/dist/coding-agent/index.js +1 -1
  319. package/dist/datasets/experiment/index.d.ts +1 -1
  320. package/dist/datasets/experiment/item.d.ts +4 -3
  321. package/dist/datasets/experiment/scorer.d.ts +34 -11
  322. package/dist/datasets/index.cjs +3 -2
  323. package/dist/datasets/index.js +3 -3
  324. package/dist/{dist-ByO0vuJJ-BjMue5_p.cjs → dist-CufwpBZM-CwERFaas.cjs} +4 -4
  325. package/dist/{dist-ByO0vuJJ-CCXLBnvJ.js → dist-CufwpBZM-DK14Qe0Z.js} +4 -4
  326. package/dist/docs/SKILL.md +2 -1
  327. package/dist/docs/assets/SOURCE_MAP.json +817 -817
  328. package/dist/docs/references/docs-agents-resumable-streams.md +15 -6
  329. package/dist/docs/references/docs-channels.md +43 -0
  330. package/dist/docs/references/docs-deployment-workers.md +3 -1
  331. package/dist/docs/references/docs-evals-experiments.md +13 -3
  332. package/dist/docs/references/docs-harness-background-tasks.md +4 -4
  333. package/dist/docs/references/docs-harness-durable-agents.md +39 -48
  334. package/dist/docs/references/docs-knowledge-importers.md +1 -1
  335. package/dist/docs/references/docs-mastra-platform-observability-overview.md +1 -1
  336. package/dist/docs/references/docs-sandbox-overview.md +1 -0
  337. package/dist/docs/references/docs-server-pubsub.md +1 -1
  338. package/dist/docs/references/docs-workflows-overview.md +67 -3
  339. package/dist/docs/references/integrations-agentic-ui-assistant-ui.md +2 -0
  340. package/dist/docs/references/integrations-frameworks-angular.md +39 -0
  341. package/dist/docs/references/integrations-frameworks-astro.md +5 -2
  342. package/dist/docs/references/integrations-frameworks-electron.md +40 -0
  343. package/dist/docs/references/integrations-frameworks-next-js.md +5 -2
  344. package/dist/docs/references/integrations-frameworks-nuxt.md +5 -2
  345. package/dist/docs/references/integrations-frameworks-sveltekit.md +5 -2
  346. package/dist/docs/references/integrations-frameworks-vite-react.md +40 -0
  347. package/dist/docs/references/integrations.md +3 -0
  348. package/dist/docs/references/reference-agent-controller-agent-controller-class.md +6 -0
  349. package/dist/docs/references/reference-agents-channels.md +1 -1
  350. package/dist/docs/references/reference-agents-durable-agent.md +5 -3
  351. package/dist/docs/references/reference-agents-generate.md +2 -0
  352. package/dist/docs/references/reference-channels-thread-link.md +67 -0
  353. package/dist/docs/references/reference-configuration.md +1 -1
  354. package/dist/docs/references/reference-core-mastra-class.md +2 -0
  355. package/dist/docs/references/reference-knowledge-knowledge-class.md +1 -1
  356. package/dist/docs/references/reference-knowledge-knowledge-tools.md +11 -5
  357. package/dist/docs/references/reference-pubsub-caching-pubsub.md +2 -2
  358. package/dist/docs/references/reference-pubsub-redis-streams.md +2 -2
  359. package/dist/docs/references/reference-pubsub-valkey-streams.md +2 -2
  360. package/dist/docs/references/reference-workers-overview.md +2 -0
  361. package/dist/docs/references/reference-workflows-workflow-methods-create-run.md +2 -0
  362. package/dist/docs/references/reference-workflows-workflow.md +2 -0
  363. package/dist/docs/references/reference-workspace-factory-sandbox.md +2 -1
  364. package/dist/docs/references/reference.md +2 -0
  365. package/dist/error/index.cjs +2 -1
  366. package/dist/error/index.d.ts +1 -1
  367. package/dist/error/index.js +2 -2
  368. package/dist/error/provider-error.d.ts +2 -1
  369. package/dist/{error-BLwEXqOK.js → error-BC9Au-22.js} +13 -1
  370. package/dist/{error-BdEvO8za.cjs → error-L1V4uUbd.cjs} +18 -0
  371. package/dist/evals/index.cjs +1 -1
  372. package/dist/evals/index.js +1 -1
  373. package/dist/evals/scoreTraces/index.cjs +1 -1
  374. package/dist/evals/scoreTraces/index.js +1 -1
  375. package/dist/events/caching-pubsub.d.ts +28 -0
  376. package/dist/events/index.cjs +4 -1
  377. package/dist/events/index.js +2 -2
  378. package/dist/events/topics.d.ts +55 -9
  379. package/dist/harness/index.cjs +1 -1
  380. package/dist/harness/index.js +1 -1
  381. package/dist/index.cjs +1 -1
  382. package/dist/index.js +1 -1
  383. package/dist/{inmemory-BDD0w8gx.js → inmemory-BK3zLwvM.js} +42 -12
  384. package/dist/{inmemory-fgR8sq-U.cjs → inmemory-Dc86VWGB.cjs} +42 -12
  385. package/dist/knowledge/changes.d.ts +17 -5
  386. package/dist/knowledge/importers/runner.d.ts +6 -0
  387. package/dist/knowledge/index.cjs +78 -16
  388. package/dist/knowledge/index.d.ts +2 -2
  389. package/dist/knowledge/index.js +78 -16
  390. package/dist/knowledge/search-snippet.d.ts +30 -0
  391. package/dist/llm/index.cjs +3 -3
  392. package/dist/llm/index.js +3 -3
  393. package/dist/llm/model/provider-types.generated.d.ts +8175 -8296
  394. package/dist/{llm-BOQR5g0t.cjs → llm-BKxlS9Kk.cjs} +3 -3
  395. package/dist/{llm-DMNEZIV9.js → llm-CMkzIFAk.js} +3 -3
  396. package/dist/loop/index.cjs +2 -2
  397. package/dist/loop/index.js +2 -2
  398. package/dist/{manager-BzNynLwT.js → manager-C-eQXmRq.js} +120 -70
  399. package/dist/{manager-CyCR9IpR.cjs → manager-CasaT35Q.cjs} +125 -69
  400. package/dist/mastra/index.cjs +1 -1
  401. package/dist/mastra/index.js +1 -1
  402. package/dist/{mastra-CqBmnzjM.js → mastra-5EEmN3Ok.js} +28 -18
  403. package/dist/{mastra-D2B01_gg.cjs → mastra-C7Tj4U8c.cjs} +28 -18
  404. package/dist/memory/index.cjs +3 -3
  405. package/dist/memory/index.js +3 -3
  406. package/dist/{message-list-Cj0Sq_JP.cjs → message-list-DfN9mWeN.cjs} +121 -121
  407. package/dist/{message-list-KRbg-TnI.js → message-list-wI71UGxk.js} +1 -1
  408. package/dist/{model-CrXDhcbw.cjs → model-9HA-W0tg.cjs} +1 -1
  409. package/dist/{model-3AeJKHLU.js → model-DCLUL-8a.js} +1 -1
  410. package/dist/{netlify-DTXLQiG1.cjs → netlify-Cq3H-A9I.cjs} +12 -12
  411. package/dist/{netlify-DUPSTzi6.js → netlify-DaWURNSU.js} +11 -11
  412. package/dist/notifications/index.cjs +1 -1
  413. package/dist/notifications/index.js +1 -1
  414. package/dist/observability/index.cjs +1 -0
  415. package/dist/observability/index.d.ts +1 -1
  416. package/dist/observability/index.js +2 -2
  417. package/dist/{output-helpers-CedRCE17.js → output-helpers-CVzhy1Y0.js} +126 -56
  418. package/dist/{output-helpers-1Zu4Vt9C.cjs → output-helpers-DgsH4aTb.cjs} +143 -55
  419. package/dist/processor-provider/index.cjs +1 -1
  420. package/dist/processor-provider/index.js +1 -1
  421. package/dist/processors/index.cjs +2 -2
  422. package/dist/processors/index.js +2 -2
  423. package/dist/processors/runner.d.ts +2 -0
  424. package/dist/{provider-registry-BeB8RQO8.js → provider-registry-DWixjFX7.js} +21915 -22166
  425. package/dist/{provider-registry-B_rC-5aL.cjs → provider-registry-a649fS5r.cjs} +21915 -22166
  426. package/dist/provider-registry.json +22772 -23030
  427. package/dist/{registry-generator-Cv6GnxLG.js → registry-generator-BYJC7p8M.js} +1 -1
  428. package/dist/{registry-generator-DbBoIOby.cjs → registry-generator-BuKC7UKd.cjs} +1 -1
  429. package/dist/{rehydrate-3f-i1Ga2.js → rehydrate-DPhmASM6.js} +2 -2
  430. package/dist/{rehydrate-BWaa2eGN.cjs → rehydrate-DR2_WAz2.cjs} +2 -2
  431. package/dist/relevance/index.cjs +2 -2
  432. package/dist/relevance/index.js +2 -2
  433. package/dist/{run-registry-Bx06ZIN_.js → run-registry-D3X7XvUL.js} +2464 -731
  434. package/dist/{run-registry-Bk6QxNE4.cjs → run-registry-oUNF6szW.cjs} +2584 -785
  435. package/dist/storage/domains/inmemory-db.d.ts +1 -0
  436. package/dist/storage/domains/knowledge/base.d.ts +5 -0
  437. package/dist/storage/domains/knowledge/inmemory.d.ts +1 -0
  438. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +10 -2
  439. package/dist/storage/domains/knowledge/pages.d.ts +30 -0
  440. package/dist/storage/index.cjs +2 -2
  441. package/dist/storage/index.js +2 -2
  442. package/dist/storage/run-fencing.d.ts +5 -0
  443. package/dist/stream/index.cjs +2 -2
  444. package/dist/stream/index.js +2 -2
  445. package/dist/{stream-BIXX67WE.cjs → stream-DQC1vpvl.cjs} +4 -4
  446. package/dist/{stream-DVy0Z-m0.js → stream-DoZ6F41o.js} +4 -4
  447. package/dist/test-utils/llm-mock.cjs +1 -1
  448. package/dist/test-utils/llm-mock.js +1 -1
  449. package/dist/tool-loop-agent/index.cjs +1 -1
  450. package/dist/tool-loop-agent/index.js +1 -1
  451. package/dist/{tool-loop-agent-PSKeNhuT.js → tool-loop-agent-C9YkvDRd.js} +4 -4
  452. package/dist/{tool-loop-agent-DDeKGwtr.cjs → tool-loop-agent-Cy4NDOMS.cjs} +4 -4
  453. package/dist/{utils-BJiQF8Pi.js → utils-9JyiKu5r.js} +1 -1
  454. package/dist/{utils-CAnUlnUm.cjs → utils-Bs2IYyOb.cjs} +1 -1
  455. package/dist/utils.cjs +1 -1
  456. package/dist/utils.js +1 -1
  457. package/dist/{validate-BAVwAgtT.js → validate-8j0phWFV.js} +1 -1
  458. package/dist/{validate-BMNxfs4Z.cjs → validate-BE3mVxVy.cjs} +1 -1
  459. package/dist/vector/index.cjs +2 -2
  460. package/dist/vector/index.js +2 -2
  461. package/dist/worker/index.cjs +1 -1
  462. package/dist/worker/index.js +1 -1
  463. package/dist/{worker-BlvJM_Hu.js → worker-BfWFqSH2.js} +2 -2
  464. package/dist/{worker-CFUKBBCF.cjs → worker-BiK1kfMa.cjs} +2 -2
  465. package/dist/{worker-CVoD3tts.js → worker-DIRdEwih.js} +2 -2
  466. package/dist/{worker-Brwa-HqM.cjs → worker-DwdgU6E9.cjs} +2 -2
  467. package/dist/{workflow-zvQGBMCM.cjs → workflow-CxQMcTbT.cjs} +4 -4
  468. package/dist/{workflow-BSLS7_vB.js → workflow-ni-keg2i.js} +4 -4
  469. package/dist/workflows/builder/index.cjs +1 -1
  470. package/dist/workflows/builder/index.js +1 -1
  471. package/dist/workflows/evented/index.cjs +1 -1
  472. package/dist/workflows/evented/index.js +1 -1
  473. package/dist/workflows/index.cjs +4 -4
  474. package/dist/workflows/index.js +4 -4
  475. package/dist/workflows/run-ownership.d.ts +74 -8
  476. package/dist/workflows/types.d.ts +16 -0
  477. package/dist/workflows/workflow.d.ts +4 -0
  478. package/package.json +5 -5
  479. package/src/llm/model/provider-types.generated.d.ts +8175 -8296
  480. /package/dist/_types/{@ai-sdk_provider-utils@4.0.66 → @ai-sdk_provider-utils@4.0.67}/dist/index.d.ts +0 -0
  481. /package/dist/_types/{@ai-sdk_provider-utils@4.0.66 → @ai-sdk_provider-utils@4.0.67}/package.json +0 -0
@@ -3,15 +3,15 @@ import { a as RegisteredLogger, t as ConsoleLogger, u as noopLogger } from "./lo
3
3
  import { t as MastraBase } from "./base-CKLWBhDo.js";
4
4
  import { A as compactStopReasonContext, D as agentLoopTermination, O as executionFailureTermination, S as resolveObservabilityContext, b as wrapMastra, i as subtractReportedUsage, k as tripwireTermination, n as extractUsageMetrics, r as isUsageIncomplete, t as calculateObservedUsage, x as createObservabilityContext, y as unwrapMastraTracingProxy } from "./observability-D7RNOAPx.js";
5
5
  import { a as MastraNonRetryableError, i as MastraError, n as ErrorDomain, o as getErrorFromUnknown, t as ErrorCategory } from "./error-oh2DLsP2.js";
6
- import { c as describeProviderError, i as classifyProviderError, l as readProviderErrorDetails, t as recordTerminalErrorMessage } from "./error-BLwEXqOK.js";
7
- import { $ as resolveProcessorSpanAttributes, $t as computeModelOutputProviderMetadata, A as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, An as safeError, B as ProviderHistoryCompat, Bt as summarizeStepResult, C as markChunkOutputProcessed, Cn as isMastraTimeoutError, Ct as resolveTemplate, D as asJsonSchema, Dn as MastraModelInput, Dt as getStepResult, E as isStructuredOutputError, Et as validateTemplate, F as findOwnModelStepSpan, Ft as materializeState, G as REPROCESS_PART_KEY, Gt as patchState, Ht as applyStatePatch, It as materializeWorkflowRun, J as summarizeActiveToolsForSpan, Jt as isObservationalMemoryEnabled$1, K as takeHeldParts, L as isTrailingAssistantGuardContinuation, Lt as pickStateKeys, M as ProcessorState, Mn as createRunScopeKey, Mt as applyStateColumnsWrite, N as endOutputStreamSpanAtStepEnd, Nt as isStateCheckpointDue, O as getResponseFormat, On as safeClose, Ot as getStepResultAsync, P as endOutputStreamSpanOutsideStep, Pt as latestStepResults, Q as summarizeToolChoiceForSpan, Qt as commitToolResult, R as needsTrailingAssistantGuard, Rt as stateBaseOf, S as stampChunkProducedAt, Sn as guardStreamWithAbort, T as escapeUnescapedControlCharsInJsonStrings, Tn as settledOrElapsed, Tt as traverseMappingPath, Vt as unusedStateEntries, W as FLUSH_HELD_PARTS_KEY, Wt as diffStateAsJson, X as summarizeProcessorResultForSpan, Xt as parseMemoryRequestContext, Y as summarizeProcessorModelForSpan, Z as summarizeProcessorToolsForSpan, _ as reconcileBufferedStepTexts, _n as DEADLINE_SAVE_WAIT_MS, _t as collectMappingStepRefs, a as convertFullStreamChunkToMastra, an as withAgentWorkflowToolMarker, at as RunJournal, b as resolveProcessorWriterMessageId, bn as getAbortReason, bt as resolveStepOutputs, c as WorkflowRunOutput, cn as isProcessorWorkflow, ct as hydrateStepResults, d as MastraModelOutput, dn as resolveThreadIdFromArgs, dt as loadStepResults, en as hasToolResultProcessor, et as resolveProcessorSpanName, f as clearStepPartIndexes, fn as supportedLanguageModelSpecifications, ft as loadedStepResults, g as persistProcessorDataChunk, gn as DEADLINE_SAVE_CLAIM_HOLD_MS, gt as stubStepResult, h as findStepPartBoundaries, hn as applyStateSignal, ht as storageV2StepResultAccessors, in as snapshotToolResult, it as PROCESSOR_ABORT_SIGNAL, j as ProcessorRunner, jn as createRunScope, k as isSignalChunkExcluded, kn as safeEnqueue, kt as getSnapshotMemoryInfo, l as TripWire, ln as isSupportedLanguageModel, lt as isStepResultStub, m as findIterationOffsetInParts, mn as tryStreamWithJsonFallback, mt as residentStepResultsLoader, nn as readModelOutput, nt as PROCESSOR_LATE_SIGNAL_SINK, on as normalizeModelOutput, ot as buildStepResultAccessors, p as createDestructurableOutput, pn as tryGenerateWithJsonFallback, pt as residentStepResults, q as withoutHeldContent, rn as resolveModelOutputAfterToolResultProcessors, rt as createProcessorSendSignal, s as MastraAgentNetworkStream, sn as validationErrorModelOutput, st as getHydratedStepResult, tn as latestProcessedModelOutput, tt as toProcessorSpanPhase, u as getModelOutputForTripwire, un as resolveSuspendedToolRunId, ut as lazyStepResults, v as resolveMessageText, vn as MastraTimeoutError, vt as collectPredicateStepRefs, w as createOutputHandler, wn as raceAgainstAbort, wt as templateReadsState, x as getChunkProducedAt, xn as guardStreamUntilMatch, xt as stepRefId, y as resolveOutputMessageSkippingCompletionChecks, yn as createTimeoutAbortSignal, yt as predicateReadsState, z as removeTrailingAssistantGuardContinuations, zt as stateColumnsWrite } from "./stream-DVy0Z-m0.js";
6
+ import { a as classifyProviderError, l as describeProviderError, t as recordTerminalErrorMessage, u as readProviderErrorDetails } from "./error-BC9Au-22.js";
7
+ import { $ as resolveProcessorSpanAttributes, $t as computeModelOutputProviderMetadata, A as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, An as safeError, B as ProviderHistoryCompat, Bt as summarizeStepResult, C as markChunkOutputProcessed, Cn as isMastraTimeoutError, Ct as resolveTemplate, D as asJsonSchema, Dn as MastraModelInput, Dt as getStepResult, E as isStructuredOutputError, Et as validateTemplate, F as findOwnModelStepSpan, Ft as materializeState, G as REPROCESS_PART_KEY, Gt as patchState, Ht as applyStatePatch, It as materializeWorkflowRun, J as summarizeActiveToolsForSpan, Jt as isObservationalMemoryEnabled$1, K as takeHeldParts, L as isTrailingAssistantGuardContinuation, Lt as pickStateKeys, M as ProcessorState, Mn as createRunScopeKey, Mt as applyStateColumnsWrite, N as endOutputStreamSpanAtStepEnd, Nt as isStateCheckpointDue, O as getResponseFormat, On as safeClose, Ot as getStepResultAsync, P as endOutputStreamSpanOutsideStep, Pt as latestStepResults, Q as summarizeToolChoiceForSpan, Qt as commitToolResult, R as needsTrailingAssistantGuard, Rt as stateBaseOf, S as stampChunkProducedAt, Sn as guardStreamWithAbort, T as escapeUnescapedControlCharsInJsonStrings, Tn as settledOrElapsed, Tt as traverseMappingPath, Vt as unusedStateEntries, W as FLUSH_HELD_PARTS_KEY, Wt as diffStateAsJson, X as summarizeProcessorResultForSpan, Xt as parseMemoryRequestContext, Y as summarizeProcessorModelForSpan, Z as summarizeProcessorToolsForSpan, _ as reconcileBufferedStepTexts, _n as DEADLINE_SAVE_WAIT_MS, _t as collectMappingStepRefs, a as convertFullStreamChunkToMastra, an as withAgentWorkflowToolMarker, at as RunJournal, b as resolveProcessorWriterMessageId, bn as getAbortReason, bt as resolveStepOutputs, c as WorkflowRunOutput, cn as isProcessorWorkflow, ct as hydrateStepResults, d as MastraModelOutput, dn as resolveThreadIdFromArgs, dt as loadStepResults, en as hasToolResultProcessor, et as resolveProcessorSpanName, f as clearStepPartIndexes, fn as supportedLanguageModelSpecifications, ft as loadedStepResults, g as persistProcessorDataChunk, gn as DEADLINE_SAVE_CLAIM_HOLD_MS, gt as stubStepResult, h as findStepPartBoundaries, hn as applyStateSignal, ht as storageV2StepResultAccessors, in as snapshotToolResult, it as PROCESSOR_ABORT_SIGNAL, j as ProcessorRunner, jn as createRunScope, k as isSignalChunkExcluded, kn as safeEnqueue, kt as getSnapshotMemoryInfo, l as TripWire, ln as isSupportedLanguageModel, lt as isStepResultStub, m as findIterationOffsetInParts, mn as tryStreamWithJsonFallback, mt as residentStepResultsLoader, nn as readModelOutput, nt as PROCESSOR_LATE_SIGNAL_SINK, on as normalizeModelOutput, ot as buildStepResultAccessors, p as createDestructurableOutput, pn as tryGenerateWithJsonFallback, pt as residentStepResults, q as withoutHeldContent, rn as resolveModelOutputAfterToolResultProcessors, rt as createProcessorSendSignal, s as MastraAgentNetworkStream, sn as validationErrorModelOutput, st as getHydratedStepResult, tn as latestProcessedModelOutput, tt as toProcessorSpanPhase, u as getModelOutputForTripwire, un as resolveSuspendedToolRunId, ut as lazyStepResults, v as resolveMessageText, vn as MastraTimeoutError, vt as collectPredicateStepRefs, w as createOutputHandler, wn as raceAgainstAbort, wt as templateReadsState, x as getChunkProducedAt, xn as guardStreamUntilMatch, xt as stepRefId, y as resolveOutputMessageSkippingCompletionChecks, yn as createTimeoutAbortSignal, yt as predicateReadsState, z as removeTrailingAssistantGuardContinuations, zt as stateColumnsWrite } from "./stream-DoZ6F41o.js";
8
8
  import { c as MASTRA_THREAD_ID_KEY, d as isReservedRequestContextKey, f as mergeVersionOverrides$1, l as MASTRA_VERSIONS_KEY, n as MASTRA_AUTH_TOKEN_KEY, o as MASTRA_RESOURCE_ID_KEY, p as withoutLiveRequestKeys, r as MASTRA_INHERITED_MEMORY_KEY, s as MASTRA_SCOPES_KEY, t as MASTRA_CONTINUATION_TOOL_CALL_IDS_KEY, u as RequestContext } from "./request-context-COnZHt2-.js";
9
- import { c as RUN_LOG_TTL_MS, f as slimNestedAgentChunks, g as NoopLeaseProvider, h as EventEmitterPubSub, m as stripModelSnapshots, n as PublisherQueueLimitError, o as serializeError$1, r as CachingPubSub, t as DefaultStepResult, u as isRunLocalTopic, v as isLeaseProvider, y as withAck } from "./output-helpers-CedRCE17.js";
10
- import { A as stableStringify$1, E as removeWorkingMemoryTags, P as embed$3, Z as preserveResponseItemIdsOnMerge, a as isTerminalToolInvocationState, c as withUnavailableAttachmentUrls, d as aiV5UIMessagesToAIV5ModelMessages, f as coreContentToString, i as isClientToolInvocationUpdate, l as isDownloadAssetsError, m as filterMessagesForPersistence, n as MessageList, ot as normalizeToolOutput, p as messagesAreEqual, r as advancesToolInvocationState, s as unavailableAttachmentPlaceholder, t as convertMessages, u as MessageMerger } from "./message-list-KRbg-TnI.js";
9
+ import { S as withAck, _ as serializeError$1, h as stripModelSnapshots, n as PublisherQueueLimitError, p as slimNestedAgentChunks, r as CachingPubSub, t as DefaultStepResult, u as isRunLocalTopic, v as EventEmitterPubSub, x as isLeaseProvider, y as NoopLeaseProvider } from "./output-helpers-CVzhy1Y0.js";
10
+ import { A as stableStringify$1, E as removeWorkingMemoryTags, P as embed$3, Z as preserveResponseItemIdsOnMerge, a as isTerminalToolInvocationState, c as withUnavailableAttachmentUrls, d as aiV5UIMessagesToAIV5ModelMessages, f as coreContentToString, i as isClientToolInvocationUpdate, l as isDownloadAssetsError, m as filterMessagesForPersistence, n as MessageList, ot as normalizeToolOutput, p as messagesAreEqual, r as advancesToolInvocationState, s as unavailableAttachmentPlaceholder, t as convertMessages, u as MessageMerger } from "./message-list-wI71UGxk.js";
11
11
  import { Bt as listScoresArgsSchema, Ft as listLogsArgsSchema, Lt as listMetricsArgsSchema, Nt as listFeedbackArgsSchema, t as EntityType } from "./storage-Cc50aQAp.js";
12
12
  import { a as getOrCreateSpan, f as resolveCurrentSpan, l as getTimeToFirstChunkMs, n as executeWithContextSync, o as getResumeTracingContext, p as resolveExportedSpanId, s as getRootExportSpan, t as executeWithContext, u as getWorkflowResumeTracingContext } from "./utils-DU_pU5SK.js";
13
13
  import { i as setSpanErrorOrigin, n as getSpanErrorOrigin } from "./error-count-BH-rJW7q.js";
14
- import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-DMNEZIV9.js";
14
+ import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-CMkzIFAk.js";
15
15
  import { a as withToolPayloadTransformMetadata, i as transformToolPayloadForTargets, n as hasTransformedToolPayload, o as withToolPayloadTransformProviderMetadata, r as normalizeToolPayloadTransformPolicy, t as getTransformedToolPayload } from "./payload-transform-Dj3HUeD4.js";
16
16
  import { boundedStringify, ensureSerializable, safeStringify } from "./utils/safe-stringify.js";
17
17
  import { d as signalSpanAttributes, h as signalToXmlMarkup, l as mastraDBMessageToSignal, n as createSignal, o as isMastraSignalMessage, s as isTransientSignalMessage, u as resolveDeliveryAttributes } from "./signals-CqR_iWkg.js";
@@ -24,13 +24,13 @@ import { _ as getRequestContextInputValues, a as getModelFacingValidationError,
24
24
  import { a as isApprovalExempt, c as isProviderDefinedTool, d as markAgentWorkflowTool, f as markApprovalExempt, l as isProviderTool, n as getNeedsApprovalFn, o as isBuiltBeforeApproval, r as getProviderToolName, s as isMastraTool, t as getBeforeApprovalFn } from "./toolchecks-DrsZdc3S.js";
25
25
  import { a as waitDelay, i as getRetryAfterMs, n as DEFAULT_MAX_RETRY_AFTER_MS, r as clampDelayMs } from "./fetchWithRetry-DFSvpYDT.js";
26
26
  import { i as hasFreeFormObject } from "./model-DS-b2R-R.js";
27
- import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-BeB8RQO8.js";
28
- import { t as InMemoryServerCache } from "./inmemory-BDD0w8gx.js";
27
+ import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-DWixjFX7.js";
28
+ import { t as InMemoryServerCache } from "./inmemory-BK3zLwvM.js";
29
29
  import { n as resolveDynamicArgument, t as getRequestUser } from "./dynamic-argument-BzPK3qPN.js";
30
- import { t as MastraLLMV1 } from "./model-3AeJKHLU.js";
31
- import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-BJiQF8Pi.js";
30
+ import { t as MastraLLMV1 } from "./model-DCLUL-8a.js";
31
+ import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-9JyiKu5r.js";
32
32
  import { h as getWorkflowFGAResourceId, i as MastraFGAPermissions, y as requireFGA } from "./ee-iTj2bRDt-By_B9ngH.js";
33
- import { a as resolveBackgroundConfig, o as createBackgroundTask, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-idnlMbqD.js";
33
+ import { a as resolveBackgroundConfig, o as createBackgroundTask, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-BbVsBghi.js";
34
34
  import { t as ToolStream } from "./stream-D9JOykz7.js";
35
35
  import { MISSING, collectInvalidPredicatePaths, createPredicateEvaluator, derivePredicateLabel, normalizePredicatePath, walk } from "./predicate/index.js";
36
36
  import { Classifier } from "./classifier/index.js";
@@ -190,6 +190,46 @@ function currentRunGeneration(runId) {
190
190
  function resolveRunFence(store, fence, runId) {
191
191
  return fence ?? getRunFenceContext()?.current()?.fenceFor(store, runId);
192
192
  }
193
+ // src/storage/workflow-step-guard.ts
194
+ var WorkflowStepConflictError = class extends Error {
195
+ reason;
196
+ storedResult;
197
+ storedRequestContext;
198
+ storedSnapshot;
199
+ code = "WORKFLOW_STEP_CONFLICT";
200
+ constructor(reason, storedResult, storedRequestContext, storedSnapshot) {
201
+ super(`Workflow step delivery rejected (${reason}).`);
202
+ this.reason = reason;
203
+ this.storedResult = storedResult;
204
+ this.storedRequestContext = storedRequestContext;
205
+ this.storedSnapshot = storedSnapshot;
206
+ }
207
+ };
208
+ function isWorkflowStepConflictError(error) {
209
+ return typeof error === "object" && error !== null && "code" in error && error.code === "WORKFLOW_STEP_CONFLICT";
210
+ }
211
+ /** Call inside the adapter's snapshot lock, before mutating results, state, or request context. */
212
+ function assertWorkflowStepGuard({ snapshot, stepId, startGuard, completionGuard }) {
213
+ if (!startGuard && !completionGuard) return;
214
+ if (!snapshot) throw new WorkflowStepConflictError("missing");
215
+ const stored = snapshot.context[stepId];
216
+ const startedBy = stored?.metadata?.startedBy;
217
+ if (stored && !startedBy) return;
218
+ if (startedBy === (startGuard ?? completionGuard).eventId) {
219
+ if (completionGuard?.pruneOnly) {
220
+ if (stored?.status === "success") return;
221
+ throw new WorkflowStepConflictError("stale", stored);
222
+ }
223
+ if (stored?.status === "running") return;
224
+ if (stored?.metadata?.__continuationStarted) throw new WorkflowStepConflictError("stale", stored);
225
+ throw new WorkflowStepConflictError("completed", stored, snapshot.requestContext, snapshot);
226
+ }
227
+ if (startGuard) {
228
+ if (!stored && startGuard.expectedStartedBy === void 0) return;
229
+ if (stored && (stored.status !== "running" || stored.metadata?.__restartPending === true) && startedBy === startGuard.expectedStartedBy) return;
230
+ }
231
+ throw new WorkflowStepConflictError("stale", stored);
232
+ }
193
233
  // src/stream/aisdk/v5/compat/prepare-tools.ts
194
234
  /**
195
235
  * Recursively fixes JSON Schema properties that lack a 'type' key.
@@ -2548,6 +2588,340 @@ function markFrameworkCondition(condition) {
2548
2588
  function isFrameworkCondition(condition) {
2549
2589
  return typeof condition === "function" && condition[FRAMEWORK_CONDITION] === true;
2550
2590
  }
2591
+ // src/agent/durable/run-fence-scope.ts
2592
+ const runFenceScope = new AsyncLocalStorage();
2593
+ const runFenceContext = setRunFenceContext({
2594
+ current: () => runFenceScope.getStore(),
2595
+ run: (scope, fn) => runFenceScope.run(scope, fn)
2596
+ });
2597
+ /**
2598
+ * Run `fn` with `scope` supplying the fence of every storage write it makes,
2599
+ * including writes from processors, tools and memory that never see the fence.
2600
+ */
2601
+ function runInRunFenceScope(scope, fn) {
2602
+ return runFenceContext.run(scope, fn);
2603
+ }
2604
+ /** The scope installed for the current async context, if any. */
2605
+ function currentRunFenceScope() {
2606
+ return runFenceContext.current();
2607
+ }
2608
+ // src/agent/run-ownership.ts
2609
+ /**
2610
+ * TTL for the cross-process leases that mark a live process driving an agent
2611
+ * thread or durable run. Kept short so a crashed owner frees the run quickly;
2612
+ * owners renew while they work. Overridable via
2613
+ * `MASTRA_AGENT_THREAD_LEASE_TTL_MS` (production keeps the 15s default).
2614
+ */
2615
+ const AGENT_LEASE_TTL_MS = readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_TTL_MS", 15e3);
2616
+ const DEFAULT_RENEW_INTERVAL_MS = Math.max(1, Math.floor(AGENT_LEASE_TTL_MS / 3));
2617
+ const configuredRenewIntervalMs = readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_RENEW_INTERVAL_MS", DEFAULT_RENEW_INTERVAL_MS);
2618
+ /**
2619
+ * Interval at which an owner renews its lease. Defaults to TTL/3, leaving room
2620
+ * for two missed renewals (network blip, GC pause) before the lease expires.
2621
+ * Overridable via `MASTRA_AGENT_THREAD_LEASE_RENEW_INTERVAL_MS`; a value not
2622
+ * shorter than the TTL would let the lease expire before its first renewal, so
2623
+ * it falls back to the default.
2624
+ */
2625
+ const AGENT_LEASE_RENEW_INTERVAL_MS = configuredRenewIntervalMs < AGENT_LEASE_TTL_MS ? configuredRenewIntervalMs : DEFAULT_RENEW_INTERVAL_MS;
2626
+ /**
2627
+ * How long a run that lost its thread lease lets a tool call that is already running go on before stopping it.
2628
+ * The thread's new owner may be working meanwhile, so a tool that never returns must not keep the old run going for
2629
+ * long. Overridable via `MASTRA_AGENT_THREAD_LEASE_LOST_TOOL_GRACE_MS`.
2630
+ */
2631
+ const AGENT_LEASE_LOST_TOOL_GRACE_MS = readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_LOST_TOOL_GRACE_MS", 3e5);
2632
+ // src/workflows/run-ownership.ts
2633
+ const WORKFLOW_RUN_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
2634
+ const WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
2635
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
2636
+ const MAX_LEASE_MS = 3 * MAX_TIMER_DELAY_MS;
2637
+ /** The longest `leaseTtlMs`, so that even after every doubling the lease stays within {@link MAX_LEASE_MS}. */
2638
+ const MAX_WORKFLOW_RUN_LEASE_TTL_MS = Math.floor(MAX_LEASE_MS / 8);
2639
+ /**
2640
+ * The shortest `leaseTtlMs`. A run renews every third of its lease with one storage write, and
2641
+ * `createRun()` options can come from a request body, so a tiny value must not set that rate.
2642
+ */
2643
+ const MIN_WORKFLOW_RUN_LEASE_TTL_MS = 1e3;
2644
+ /**
2645
+ * `leaseTtlMs` as configured, rounded up to whole milliseconds and kept between
2646
+ * {@link MIN_WORKFLOW_RUN_LEASE_TTL_MS} and {@link MAX_WORKFLOW_RUN_LEASE_TTL_MS}, or `fallback`
2647
+ * when it is not a positive finite number. `fallback` is used as is, so the default lease from
2648
+ * `MASTRA_AGENT_THREAD_LEASE_TTL_MS` can be shorter than the minimum.
2649
+ */
2650
+ function normalizeLeaseTtlMs(leaseTtlMs, fallback) {
2651
+ if (typeof leaseTtlMs !== "number" || !Number.isFinite(leaseTtlMs) || leaseTtlMs <= 0) return fallback;
2652
+ return Math.min(Math.max(Math.ceil(leaseTtlMs), MIN_WORKFLOW_RUN_LEASE_TTL_MS), MAX_WORKFLOW_RUN_LEASE_TTL_MS);
2653
+ }
2654
+ /** How often a lease of `leaseMs` is renewed: a third of it, or the configured interval for the default lease. */
2655
+ function renewIntervalFor(leaseMs) {
2656
+ if (leaseMs === WORKFLOW_RUN_LEASE_TTL_MS) return WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS;
2657
+ return Math.min(Math.max(1, Math.floor(leaseMs / 3)), MAX_TIMER_DELAY_MS);
2658
+ }
2659
+ /**
2660
+ * The lease a restart claims a run with. After a lease that lapsed without being released, its
2661
+ * last owner stopped renewing (it crashed, or blocked its event loop past the lease), so the
2662
+ * restart doubles that lease to give a step that blocks the same way room to finish. The previous
2663
+ * length is the owners row's `leaseExpiresAt - updatedAt`, which stores write in one statement.
2664
+ * Stores that read their clock twice there can come out a few milliseconds short; the result
2665
+ * never drops below `baseMs` or the previous length, so that only trims the doubling.
2666
+ */
2667
+ function leaseAfterTakeover(baseMs, previous) {
2668
+ if (!previous?.leaseExpiresAt || previous.live || !previous.updatedAt) return { leaseMs: baseMs };
2669
+ const previousLeaseMs = previous.leaseExpiresAt.getTime() - previous.updatedAt.getTime();
2670
+ if (!(previousLeaseMs > 0)) return { leaseMs: baseMs };
2671
+ const capMs = baseMs * 8;
2672
+ const leaseMs = Math.max(baseMs, previousLeaseMs, Math.min(previousLeaseMs * 2, capMs));
2673
+ return {
2674
+ leaseMs: Math.min(leaseMs, MAX_LEASE_MS),
2675
+ previousLeaseMs
2676
+ };
2677
+ }
2678
+ let lastStallWarningAt = -Infinity;
2679
+ /** The handle of a run that holds no claim: saves stay unfenced and nothing is released. */
2680
+ const UNCLAIMED_WORKFLOW_RUN = {
2681
+ release: async () => {},
2682
+ run: (_runId, fn) => fn()
2683
+ };
2684
+ /**
2685
+ * Runs `tick` `intervalMs` after it starts, then again `intervalMs` after
2686
+ * each run of it settles, until the returned function is called. A tick that
2687
+ * is running when the chain is stopped finishes, and nothing runs after it.
2688
+ * Every tick runs in the async context this function was called in, and the
2689
+ * timer is unref'd. `tick` reports its own failures and must not reject.
2690
+ *
2691
+ * `intervalMs` can be a function, read before each wait, for a delay that
2692
+ * follows what the last tick saw. With `immediately`, the first tick runs at
2693
+ * once instead of after the first wait.
2694
+ */
2695
+ function repeatAfterSettled(tick, intervalMs, { immediately = false } = {}) {
2696
+ let stopped = false;
2697
+ let timer;
2698
+ const arm = () => {
2699
+ timer = setTimeout(() => void run(), typeof intervalMs === "number" ? intervalMs : intervalMs());
2700
+ timer.unref?.();
2701
+ };
2702
+ const run = async () => {
2703
+ try {
2704
+ await tick();
2705
+ } finally {
2706
+ if (!stopped) {
2707
+ const { refresh } = timer ?? {};
2708
+ if (refresh && typeof intervalMs === "number") refresh.call(timer);
2709
+ else arm();
2710
+ }
2711
+ }
2712
+ };
2713
+ if (immediately) run();
2714
+ else arm();
2715
+ return () => {
2716
+ stopped = true;
2717
+ clearTimeout(timer);
2718
+ };
2719
+ }
2720
+ /**
2721
+ * Renews the lease `fence` holds, `leaseMs` long, every third of it (every
2722
+ * {@link WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS} for the default lease) until
2723
+ * the returned function is called, counting each interval from the end of the
2724
+ * previous renewal. Stops by itself after the first renewal that finds the
2725
+ * claim superseded, reporting it through `onLost`.
2726
+ *
2727
+ * When a renewal, or the returned function, finds that a lease length passed
2728
+ * since the last renewal (or the claim, sent at `since`) that succeeded, the
2729
+ * lease may have lapsed meanwhile: that is reported through `onStall`, once
2730
+ * per stall in this process. Gaps after a failed renewal are left to `onError`.
2731
+ */
2732
+ function renewWorkflowLease({ store, fence, leaseMs = WORKFLOW_RUN_LEASE_TTL_MS, since = Date.now(), onLost, onError, onStall }) {
2733
+ const intervalMs = renewIntervalFor(leaseMs);
2734
+ let renewedAt = since;
2735
+ let inFlightSince;
2736
+ let failing = false;
2737
+ let lost = false;
2738
+ const checkStall = (sentAt) => {
2739
+ const now = Date.now();
2740
+ if (!onStall || failing || lost || now - sentAt < leaseMs || sentAt < lastStallWarningAt) return;
2741
+ lastStallWarningAt = now;
2742
+ onStall(now - sentAt);
2743
+ };
2744
+ const stop = repeatAfterSettled(async () => {
2745
+ checkStall(renewedAt);
2746
+ const sentAt = inFlightSince = Date.now();
2747
+ try {
2748
+ const result = await store.renewRunOwnership({
2749
+ ...fence,
2750
+ leaseMs
2751
+ });
2752
+ failing = false;
2753
+ if (result.renewed) {
2754
+ renewedAt = sentAt;
2755
+ return;
2756
+ }
2757
+ lost = true;
2758
+ stop();
2759
+ onLost(result.record);
2760
+ } catch (error) {
2761
+ failing = true;
2762
+ onError(error);
2763
+ } finally {
2764
+ inFlightSince = void 0;
2765
+ }
2766
+ }, intervalMs);
2767
+ return () => {
2768
+ checkStall(inFlightSince ?? renewedAt);
2769
+ stop();
2770
+ };
2771
+ }
2772
+ /**
2773
+ * Marks this process as the live driver of a workflow run through the storage
2774
+ * run-ownership lease (the one durable agents use), renewing it while the run
2775
+ * executes. The lease tells the recovery sweep on other replicas that the run
2776
+ * is not orphaned, and saves made inside {@link WorkflowRunOwnership.run} carry
2777
+ * it, so a process that lost the run can't overwrite the new owner's saves.
2778
+ *
2779
+ * Returns the current owner record instead of a handle when `force` is off and
2780
+ * another execution holds a live lease. Stores without run fencing get a no-op
2781
+ * handle, keeping their previous behaviour.
2782
+ *
2783
+ * The lease is `leaseMs` long. With `backOff`, a claim over a lease that lapsed
2784
+ * takes a longer one (see {@link leaseAfterTakeover}).
2785
+ */
2786
+ async function claimWorkflowRunOwnership({ store, runId, force, logger, leaseMs: baseLeaseMs = WORKFLOW_RUN_LEASE_TTL_MS, backOff = false }) {
2787
+ if (!store || !await store.supportsRunFencing()) return UNCLAIMED_WORKFLOW_RUN;
2788
+ let previous = null;
2789
+ if (backOff) try {
2790
+ previous = await store.getRunOwnership({ runId });
2791
+ } catch (error) {
2792
+ logger?.debug("Failed to read the previous workflow run ownership lease", {
2793
+ runId,
2794
+ error
2795
+ });
2796
+ }
2797
+ const { leaseMs, previousLeaseMs } = leaseAfterTakeover(baseLeaseMs, previous);
2798
+ const claimedAt = Date.now();
2799
+ const claim = await store.claimRunOwnership({
2800
+ runId,
2801
+ ownerId: crypto.randomUUID(),
2802
+ leaseMs,
2803
+ force
2804
+ });
2805
+ if (!claim.acquired) return { owner: claim.record };
2806
+ if (previous?.leaseExpiresAt && !previous.live) logger?.warn("Took over a workflow run whose previous owner stopped renewing its ownership lease: it crashed or blocked its event loop for longer than the lease. If a step blocks the event loop, move that work off it or raise the workflow leaseTtlMs option.", {
2807
+ runId,
2808
+ previousLeaseMs,
2809
+ leaseMs
2810
+ });
2811
+ const fence = {
2812
+ runId,
2813
+ generation: claim.record.generation,
2814
+ ownerId: claim.record.ownerId
2815
+ };
2816
+ const stopRenewing = renewWorkflowLease({
2817
+ store,
2818
+ fence,
2819
+ leaseMs,
2820
+ since: claimedAt,
2821
+ onStall: (sinceRenewalMs) => logger?.warn(`This process went ${sinceRenewalMs} ms without renewing the ${leaseMs} ms ownership lease of a workflow run, so other processes may take over the runs it drives. Its event loop was most likely blocked: move blocking work off the event loop, or raise the workflow leaseTtlMs option.`, {
2822
+ runId,
2823
+ sinceRenewalMs,
2824
+ leaseMs
2825
+ }),
2826
+ onLost: (owner) => {
2827
+ if (matchesRunFence(owner, fence) && owner?.leaseExpiresAt === null) return;
2828
+ logger?.warn("Lost the ownership lease of a running workflow run; another process may now recover it", {
2829
+ runId,
2830
+ owner: owner?.ownerId
2831
+ });
2832
+ },
2833
+ onError: (error) => logger?.warn("Failed to renew workflow run ownership lease", {
2834
+ runId,
2835
+ error
2836
+ })
2837
+ });
2838
+ const claimState = {
2839
+ store,
2840
+ fence,
2841
+ logger,
2842
+ nestedRunIds: /* @__PURE__ */ new Set(),
2843
+ refused: false
2844
+ };
2845
+ return {
2846
+ release: async () => {
2847
+ stopRenewing();
2848
+ try {
2849
+ await store.releaseRunOwnership(fence);
2850
+ } catch (error) {
2851
+ logger?.warn("Failed to release workflow run ownership lease", {
2852
+ runId,
2853
+ error
2854
+ });
2855
+ }
2856
+ },
2857
+ run: (target, fn) => {
2858
+ if (target !== runId) claimState.nestedRunIds.add(target);
2859
+ return runInRunFenceScope(new WorkflowRunClaimScope(claimState, currentRunFenceScope()), fn);
2860
+ }
2861
+ };
2862
+ }
2863
+ /**
2864
+ * The fence scope of a workflow run claim. Saves to the claimed run and the nested runs it covers
2865
+ * carry the claim; everything else (other runs, memory) goes to the scope it was installed in,
2866
+ * such as a durable agent running the workflow or an enclosing workflow run.
2867
+ */
2868
+ var WorkflowRunClaimScope = class {
2869
+ claim;
2870
+ outer;
2871
+ constructor(claim, outer) {
2872
+ this.claim = claim;
2873
+ this.outer = outer;
2874
+ }
2875
+ covers(runId) {
2876
+ return runId === this.claim.fence.runId || this.claim.nestedRunIds.has(runId);
2877
+ }
2878
+ fenceFor(store, runId) {
2879
+ if (runId === void 0 || !this.covers(runId)) return this.outer?.fenceFor(store, runId);
2880
+ if (store !== this.claim.store) this.claim.logger?.error("A workflow run saved to a different store than the one holding its lease", { runId });
2881
+ return this.claim.fence;
2882
+ }
2883
+ onConflict(fence) {
2884
+ if (!matchesRunFence(this.claim.fence, fence)) return this.outer?.onConflict?.(fence);
2885
+ if (this.claim.refused) return;
2886
+ this.claim.refused = true;
2887
+ this.claim.logger?.warn("Stopped driving a workflow run that another process took over; its saves are refused", {
2888
+ runId: fence.runId,
2889
+ generation: fence.generation
2890
+ });
2891
+ }
2892
+ coverNestedRun(parentRunId, nestedRunId) {
2893
+ if (this.covers(parentRunId)) this.claim.nestedRunIds.add(nestedRunId);
2894
+ else this.outer?.coverNestedRun?.(parentRunId, nestedRunId);
2895
+ }
2896
+ generationFor(runId) {
2897
+ return this.covers(runId) ? this.claim.fence.generation : this.outer?.generationFor?.(runId);
2898
+ }
2899
+ };
2900
+ /** The fence of the `RunFenceConflictError` in `error` or its cause chain, if there is one. */
2901
+ function runFenceConflictOf(error) {
2902
+ let current = error;
2903
+ for (let depth = 0; depth < 8 && current && typeof current === "object"; depth++) {
2904
+ const { id, code, details } = current;
2905
+ if ((id === "STORAGE_RUN_FENCE_CONFLICT" || code === "STORAGE_RUN_FENCE_CONFLICT") && details?.runId !== void 0) return details;
2906
+ current = current.cause;
2907
+ }
2908
+ }
2909
+ /**
2910
+ * Whether storage refused `error`'s save because the claim the current fence scope holds was
2911
+ * replaced, so this execution lost its run. A conflict on another run (one a step started) is not.
2912
+ */
2913
+ function isOwnRunFenceConflict(error) {
2914
+ const fence = runFenceConflictOf(error);
2915
+ return !!fence && currentRunGeneration(fence.runId) === fence.generation;
2916
+ }
2917
+ /**
2918
+ * Makes the saves of `nestedRunId` carry the claim of the workflow run execution this runs in, when
2919
+ * that claim covers `parentRunId`. Unlike `coverNestedRun`, it leaves a durable agent's fence alone.
2920
+ */
2921
+ function coverNestedWorkflowRun(parentRunId, nestedRunId) {
2922
+ const scope = currentRunFenceScope();
2923
+ if (scope instanceof WorkflowRunClaimScope && scope.covers(parentRunId)) scope.claim.nestedRunIds.add(nestedRunId);
2924
+ }
2551
2925
  /** Every workflow run status. Internal to core: not re-exported from `@mastra/core/storage`. */
2552
2926
  const WORKFLOW_RUN_STATUSES = Object.keys({
2553
2927
  running: true,
@@ -4949,7 +5323,10 @@ async function executeForeach(engine, params) {
4949
5323
  });
4950
5324
  } catch (err) {
4951
5325
  checkpointError = err instanceof Error ? err : new Error(String(err));
4952
- engine.getLogger()?.error("Failed to checkpoint foreach progress", {
5326
+ if (isOwnRunFenceConflict(err)) {
5327
+ killQueue();
5328
+ if (inFlight === 0) resolveCompletion?.();
5329
+ } else engine.getLogger()?.error("Failed to checkpoint foreach progress", {
4953
5330
  stepId,
4954
5331
  runId,
4955
5332
  error: checkpointError
@@ -5834,6 +6211,7 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
5834
6211
  }))
5835
6212
  };
5836
6213
  } catch (e) {
6214
+ if (isOwnRunFenceConflict(e)) throw e;
5837
6215
  const isNonRetryable = e instanceof MastraNonRetryableError;
5838
6216
  if (isNonRetryable || i === params.retries) {
5839
6217
  const errorInstance = getErrorFromUnknown(e, {
@@ -6739,140 +7117,6 @@ function resolveCurrentState(params) {
6739
7117
  const { stepResult, stepResults, state } = params;
6740
7118
  return stepResult?.__state ?? stepResults?.__state ?? state ?? {};
6741
7119
  }
6742
- // src/agent/run-ownership.ts
6743
- /**
6744
- * TTL for the cross-process leases that mark a live process driving an agent
6745
- * thread or durable run. Kept short so a crashed owner frees the run quickly;
6746
- * owners renew while they work. Overridable via
6747
- * `MASTRA_AGENT_THREAD_LEASE_TTL_MS` (production keeps the 15s default).
6748
- */
6749
- const AGENT_LEASE_TTL_MS = readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_TTL_MS", 15e3);
6750
- const DEFAULT_RENEW_INTERVAL_MS = Math.max(1, Math.floor(AGENT_LEASE_TTL_MS / 3));
6751
- const configuredRenewIntervalMs = readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_RENEW_INTERVAL_MS", DEFAULT_RENEW_INTERVAL_MS);
6752
- /**
6753
- * Interval at which an owner renews its lease. Defaults to TTL/3, leaving room
6754
- * for two missed renewals (network blip, GC pause) before the lease expires.
6755
- * Overridable via `MASTRA_AGENT_THREAD_LEASE_RENEW_INTERVAL_MS`; a value not
6756
- * shorter than the TTL would let the lease expire before its first renewal, so
6757
- * it falls back to the default.
6758
- */
6759
- const AGENT_LEASE_RENEW_INTERVAL_MS = configuredRenewIntervalMs < AGENT_LEASE_TTL_MS ? configuredRenewIntervalMs : DEFAULT_RENEW_INTERVAL_MS;
6760
- /**
6761
- * How long a run that lost its thread lease lets a tool call that is already running go on before stopping it.
6762
- * The thread's new owner may be working meanwhile, so a tool that never returns must not keep the old run going for
6763
- * long. Overridable via `MASTRA_AGENT_THREAD_LEASE_LOST_TOOL_GRACE_MS`.
6764
- */
6765
- const AGENT_LEASE_LOST_TOOL_GRACE_MS = readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_LOST_TOOL_GRACE_MS", 3e5);
6766
- // src/workflows/run-ownership.ts
6767
- const WORKFLOW_RUN_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
6768
- const WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
6769
- const UNFENCED = { release: async () => {} };
6770
- /**
6771
- * Runs `tick` `intervalMs` after it starts, then again `intervalMs` after
6772
- * each run of it settles, until the returned function is called. A tick that
6773
- * is running when the chain is stopped finishes, and nothing runs after it.
6774
- * Every tick runs in the async context this function was called in, and the
6775
- * timer is unref'd. `tick` reports its own failures and must not reject.
6776
- *
6777
- * `intervalMs` can be a function, read before each wait, for a delay that
6778
- * follows what the last tick saw. With `immediately`, the first tick runs at
6779
- * once instead of after the first wait.
6780
- */
6781
- function repeatAfterSettled(tick, intervalMs, { immediately = false } = {}) {
6782
- let stopped = false;
6783
- let timer;
6784
- const arm = () => {
6785
- timer = setTimeout(() => void run(), typeof intervalMs === "number" ? intervalMs : intervalMs());
6786
- timer.unref?.();
6787
- };
6788
- const run = async () => {
6789
- try {
6790
- await tick();
6791
- } finally {
6792
- if (!stopped) {
6793
- const { refresh } = timer ?? {};
6794
- if (refresh && typeof intervalMs === "number") refresh.call(timer);
6795
- else arm();
6796
- }
6797
- }
6798
- };
6799
- if (immediately) run();
6800
- else arm();
6801
- return () => {
6802
- stopped = true;
6803
- clearTimeout(timer);
6804
- };
6805
- }
6806
- /**
6807
- * Renews the lease `fence` holds every {@link WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS}
6808
- * until the returned function is called, counting each interval from the end
6809
- * of the previous renewal. Stops by itself after the first renewal that finds
6810
- * the claim superseded, reporting it through `onLost`.
6811
- */
6812
- function renewWorkflowLease({ store, fence, onLost, onError }) {
6813
- const stop = repeatAfterSettled(async () => {
6814
- try {
6815
- const result = await store.renewRunOwnership({
6816
- ...fence,
6817
- leaseMs: WORKFLOW_RUN_LEASE_TTL_MS
6818
- });
6819
- if (result.renewed) return;
6820
- stop();
6821
- onLost(result.record);
6822
- } catch (error) {
6823
- onError(error);
6824
- }
6825
- }, WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS);
6826
- return stop;
6827
- }
6828
- /**
6829
- * Marks this process as the live driver of a workflow run through the storage
6830
- * run-ownership lease (the one durable agents use), renewing it while the run
6831
- * executes. Writes stay unfenced: the lease only tells the boot-time recovery
6832
- * sweep on other replicas that the run is not orphaned.
6833
- *
6834
- * Returns the current owner record instead of a handle when `force` is off and
6835
- * another execution holds a live lease. Stores without run fencing get a no-op
6836
- * handle, keeping their previous behaviour.
6837
- */
6838
- async function claimWorkflowRunOwnership({ store, runId, force, logger }) {
6839
- if (!store || !await store.supportsRunFencing()) return UNFENCED;
6840
- const claim = await store.claimRunOwnership({
6841
- runId,
6842
- ownerId: crypto.randomUUID(),
6843
- leaseMs: WORKFLOW_RUN_LEASE_TTL_MS,
6844
- force
6845
- });
6846
- if (!claim.acquired) return { owner: claim.record };
6847
- const fence = {
6848
- runId,
6849
- generation: claim.record.generation,
6850
- ownerId: claim.record.ownerId
6851
- };
6852
- const stopRenewing = renewWorkflowLease({
6853
- store,
6854
- fence,
6855
- onLost: (owner) => logger?.warn("Lost the ownership lease of a running workflow run; another process may now recover it", {
6856
- runId,
6857
- owner: owner?.ownerId
6858
- }),
6859
- onError: (error) => logger?.warn("Failed to renew workflow run ownership lease", {
6860
- runId,
6861
- error
6862
- })
6863
- });
6864
- return { release: async () => {
6865
- stopRenewing();
6866
- try {
6867
- await store.releaseRunOwnership(fence);
6868
- } catch (error) {
6869
- logger?.warn("Failed to release workflow run ownership lease", {
6870
- runId,
6871
- error
6872
- });
6873
- }
6874
- } };
6875
- }
6876
7120
  // src/workflows/nested-run-recovery.ts
6877
7121
  const FINISHED_STATUSES = /* @__PURE__ */ new Set([
6878
7122
  "success",
@@ -8125,7 +8369,8 @@ var Workflow = class Workflow extends MastraBase {
8125
8369
  onFinish: options.onFinish,
8126
8370
  onError: options.onError,
8127
8371
  sharePubsub: options.sharePubsub,
8128
- autoRestartActiveRuns: options.autoRestartActiveRuns
8372
+ autoRestartActiveRuns: options.autoRestartActiveRuns,
8373
+ leaseTtlMs: options.leaseTtlMs
8129
8374
  };
8130
8375
  if (!executionEngine) this.executionEngine = new DefaultExecutionEngine({
8131
8376
  mastra: this.#mastra,
@@ -8859,7 +9104,10 @@ var Workflow = class Workflow extends MastraBase {
8859
9104
  nestedRun,
8860
9105
  lookUpStoredRun
8861
9106
  });
8862
- const run = this.#runs.get(runIdToUse) ?? new Run({
9107
+ const leaseTtlMs = normalizeLeaseTtlMs(options?.leaseTtlMs, normalizeLeaseTtlMs(this.#options.leaseTtlMs, WORKFLOW_RUN_LEASE_TTL_MS));
9108
+ const reused = this.#runs.get(runIdToUse);
9109
+ if (reused && options?.leaseTtlMs !== void 0) setRunLeaseTtlMs(reused, leaseTtlMs);
9110
+ const run = reused ?? new Run({
8863
9111
  workflowId: this.id,
8864
9112
  stateSchema: this.stateSchema,
8865
9113
  inputSchema: this.inputSchema,
@@ -8884,7 +9132,8 @@ var Workflow = class Workflow extends MastraBase {
8884
9132
  workflowEngineType: this.engineType,
8885
9133
  pubsub: options?.pubsub,
8886
9134
  storageVersion,
8887
- recoverable: this.engineType === "default" && this.#options.autoRestartActiveRuns !== false && this.type !== "processor"
9135
+ recoverable: this.engineType === "default" && this.#options.autoRestartActiveRuns !== false && this.type !== "processor",
9136
+ leaseTtlMs
8888
9137
  });
8889
9138
  this.#runs.set(runIdToUse, run);
8890
9139
  if (options?.shouldPersistSnapshot) this.executionEngine.setRunPersistenceOverride(runIdToUse, options.shouldPersistSnapshot);
@@ -8978,6 +9227,8 @@ var Workflow = class Workflow extends MastraBase {
8978
9227
  if (startedFrom) startState = copyState(state);
8979
9228
  }
8980
9229
  const inheritedState = !restart && !isResume ? await parentState?.(startState) : void 0;
9230
+ const nestedRunId = isResume ? resume.runId : runId;
9231
+ if (parentWorkflow && nestedRunId) coverNestedWorkflowRun(parentWorkflow.runId, nestedRunId);
8981
9232
  this.#nestedRun = {
8982
9233
  storageVersion: parentState ? 2 : 1,
8983
9234
  start: !isResume ? {
@@ -9249,6 +9500,13 @@ var Workflow = class Workflow extends MastraBase {
9249
9500
  });
9250
9501
  return;
9251
9502
  }
9503
+ if (runFenceConflictOf(error)?.runId === runSnapshot.runId) {
9504
+ this.logger.debug("Stopped restarting workflow run another process took over", {
9505
+ workflowId: this.id,
9506
+ runId: runSnapshot.runId
9507
+ });
9508
+ return;
9509
+ }
9252
9510
  this.logger.error("Failed to restart workflow run", {
9253
9511
  workflowId: this.id,
9254
9512
  runId: runSnapshot.runId,
@@ -9456,6 +9714,7 @@ const TERMINAL_WORKFLOW_RUN_STATUSES = /* @__PURE__ */ new Set([
9456
9714
  "tripwire",
9457
9715
  "bailed"
9458
9716
  ]);
9717
+ let setRunLeaseTtlMs;
9459
9718
  /**
9460
9719
  * Represents a workflow run that can be executed
9461
9720
  */
@@ -9548,6 +9807,12 @@ var Run = class {
9548
9807
  #mastra;
9549
9808
  #observerHandlers = [];
9550
9809
  #recoverable;
9810
+ #leaseTtlMs;
9811
+ static {
9812
+ setRunLeaseTtlMs = (run, leaseTtlMs) => {
9813
+ run.#leaseTtlMs = leaseTtlMs;
9814
+ };
9815
+ }
9551
9816
  get mastra() {
9552
9817
  return this.#mastra;
9553
9818
  }
@@ -9589,6 +9854,7 @@ var Run = class {
9589
9854
  getStore: async () => (this.executionEngine.mastra ?? this.#mastra)?.getStorage()?.getStore("workflows")
9590
9855
  });
9591
9856
  this.#recoverable = params.recoverable ?? false;
9857
+ this.#leaseTtlMs = params.leaseTtlMs ?? WORKFLOW_RUN_LEASE_TTL_MS;
9592
9858
  }
9593
9859
  get abortController() {
9594
9860
  if (!this.#abortController) this.#abortController = new AbortController();
@@ -9613,6 +9879,7 @@ var Run = class {
9613
9879
  actor
9614
9880
  });
9615
9881
  })().catch((error) => {
9882
+ if (runFenceConflictOf(error)?.runId === parent.runId) return;
9616
9883
  this.#mastra?.getLogger()?.error("Failed to resume parent workflow after nested child completion.", error);
9617
9884
  });
9618
9885
  }
@@ -9799,11 +10066,12 @@ var Run = class {
9799
10066
  waitingPaths: {},
9800
10067
  timestamp: Date.now()
9801
10068
  };
10069
+ const ownership = "release" in held ? held : UNCLAIMED_WORKFLOW_RUN;
9802
10070
  try {
9803
- await this.runStorage.writeSnapshot(this.executionEngine.options.pruneSnapshot && this.storageVersion === 1 ? this.executionEngine.options.pruneSnapshot({
10071
+ await ownership.run(this.runId, () => this.runStorage.writeSnapshot(this.executionEngine.options.pruneSnapshot && this.storageVersion === 1 ? this.executionEngine.options.pruneSnapshot({
9804
10072
  snapshot: initialRunSnapshot,
9805
10073
  workflowStatus: "waiting"
9806
- }) : initialRunSnapshot, this.resourceId);
10074
+ }) : initialRunSnapshot, this.resourceId));
9807
10075
  } catch (error) {
9808
10076
  workflowSpan?.error({
9809
10077
  ...executionFailureTermination(error),
@@ -9873,6 +10141,7 @@ var Run = class {
9873
10141
  const execution = this._start(args, notifyStarted);
9874
10142
  await Promise.race([started, execution]);
9875
10143
  execution.catch((error) => {
10144
+ if (runFenceConflictOf(error)?.runId === this.runId) return;
9876
10145
  this.mastra?.getLogger()?.error(`[Workflow ${this.workflowId}] Background execution failed:`, error);
9877
10146
  });
9878
10147
  return { runId: this.runId };
@@ -10208,6 +10477,8 @@ var Run = class {
10208
10477
  */
10209
10478
  async resumeAsync(params) {
10210
10479
  this._resume(params).catch((err) => {
10480
+ const conflictRunId = runFenceConflictOf(err)?.runId;
10481
+ if (conflictRunId !== void 0 && (conflictRunId === this.runId || conflictRunId === this.parentWorkflow?.runId)) return;
10211
10482
  this.mastra?.getLogger()?.error(`[Workflow ${this.workflowId}] Background resume failed:`, err);
10212
10483
  });
10213
10484
  return { runId: this.runId };
@@ -10225,6 +10496,8 @@ var Run = class {
10225
10496
  * parent's lease unless `nested` is set. The sweep lists `running` and `waiting` runs of registered
10226
10497
  * workflows, so a run that persists neither is never swept. Internal workflows aren't registered,
10227
10498
  * so persisting `waiting` alone doesn't make their runs claim.
10499
+ *
10500
+ * A claim without `force` is a restart's, which backs off from a lease that lapsed.
10228
10501
  */
10229
10502
  async #claimOwnership(force, { nested = false } = {}) {
10230
10503
  const shouldPersistSnapshot = this.executionEngine.getRunPersistenceOverride(this.runId) ?? this.executionEngine.options.shouldPersistSnapshot;
@@ -10235,20 +10508,41 @@ var Run = class {
10235
10508
  workflowStatus: "waiting",
10236
10509
  stepResults: {}
10237
10510
  });
10238
- if (!this.#recoverable || this.parentWorkflow && !nested || !swept) return { release: async () => {} };
10511
+ if (!this.#recoverable || this.parentWorkflow && !nested || !swept) return UNCLAIMED_WORKFLOW_RUN;
10239
10512
  return claimWorkflowRunOwnership({
10240
- store: await this.#mastra?.getStorage()?.getStore("workflows"),
10513
+ store: await (this.executionEngine.mastra ?? this.#mastra)?.getStorage()?.getStore("workflows"),
10241
10514
  runId: this.runId,
10242
10515
  force,
10243
- logger: this.#mastra?.getLogger()
10516
+ logger: this.#mastra?.getLogger(),
10517
+ leaseMs: this.#leaseTtlMs,
10518
+ backOff: !force
10244
10519
  });
10245
10520
  }
10246
- /** Runs `execute` under the run's lease: `held`, when the caller hands one over, or a new claim. */
10247
- async #executeOwned(execute, held) {
10248
- const ownership = held ?? await this.#claimOwnership(true);
10249
- if (!("release" in ownership)) return execute();
10521
+ /**
10522
+ * Runs `execute` under the run's lease: `held`, when the caller hands one over, or a new claim.
10523
+ * Its saves carry that claim, or `fencedBy` when the run executes under another run's lease (a
10524
+ * nested run resumed while it holds its parent's). `onFailure` undoes the caller's own claim when
10525
+ * `execute` rejects, still under the lease, since a rejection can mean another process owns the run.
10526
+ */
10527
+ async #executeOwned(execute, held, { fencedBy, onFailure } = {}) {
10528
+ const executeOrUndo = async () => {
10529
+ try {
10530
+ return await execute();
10531
+ } catch (error) {
10532
+ await onFailure?.();
10533
+ throw error;
10534
+ }
10535
+ };
10536
+ let ownership;
10250
10537
  try {
10251
- return await execute();
10538
+ ownership = held ?? await this.#claimOwnership(true);
10539
+ } catch (error) {
10540
+ await onFailure?.();
10541
+ throw error;
10542
+ }
10543
+ if (!("release" in ownership)) return executeOrUndo();
10544
+ try {
10545
+ return await (fencedBy ?? ownership).run(this.runId, executeOrUndo);
10252
10546
  } finally {
10253
10547
  await ownership.release();
10254
10548
  }
@@ -10429,6 +10723,7 @@ var Run = class {
10429
10723
  expectedStatus: "running"
10430
10724
  });
10431
10725
  } catch (releaseError) {
10726
+ if (isOwnRunFenceConflict(releaseError)) return;
10432
10727
  this.#mastra?.getLogger()?.warn(`[Workflow ${this.workflowId}] Failed to release resume claim for run ${this.runId}`, releaseError);
10433
10728
  }
10434
10729
  };
@@ -10493,6 +10788,7 @@ var Run = class {
10493
10788
  claimedParent = {
10494
10789
  run: parentRun,
10495
10790
  snapshot: parentSnapshot,
10791
+ lease: parentLease,
10496
10792
  takeLease: () => {
10497
10793
  if (leaseHandedOver) return;
10498
10794
  leaseHandedOver = true;
@@ -10511,13 +10807,14 @@ var Run = class {
10511
10807
  }
10512
10808
  const releaseParentClaim = async () => {
10513
10809
  if (!claimedParent) return;
10810
+ const { run: parentRun, lease } = claimedParent;
10514
10811
  try {
10515
- await claimedParent.run.runStorage.updateHeader({
10812
+ await (lease ?? UNCLAIMED_WORKFLOW_RUN).run(parentRun.runId, () => parentRun.runStorage.updateHeader({
10516
10813
  status: "suspended",
10517
10814
  expectedStatus: "running"
10518
- });
10815
+ }));
10519
10816
  } catch (releaseError) {
10520
- this.#mastra?.getLogger()?.warn(`[Workflow ${this.workflowId}] Failed to release parent resume claim for run ${claimedParent.run.runId}`, releaseError);
10817
+ if (runFenceConflictOf(releaseError)?.runId !== parentRun.runId) this.#mastra?.getLogger()?.warn(`[Workflow ${this.workflowId}] Failed to release parent resume claim for run ${claimedParent.run.runId}`, releaseError);
10521
10818
  }
10522
10819
  await claimedParent.releaseLease();
10523
10820
  };
@@ -10552,13 +10849,20 @@ var Run = class {
10552
10849
  perStep: params.perStep,
10553
10850
  storageVersion: this.storageVersion,
10554
10851
  storedState: this.runStorage.storedState(snapshot)
10555
- }), params.takeHeldOwnership?.() ?? ownLease).then(async (result) => {
10852
+ }), params.takeHeldOwnership?.() ?? ownLease, {
10853
+ fencedBy: claimedParent?.lease,
10854
+ onFailure: async () => {
10855
+ await releaseParentClaim();
10856
+ await releaseClaimIfUnused();
10857
+ }
10858
+ }).then(async (result) => {
10556
10859
  if (!params.isVNext && result.status !== "suspended") this.closeStreamAction?.().catch(() => {});
10557
10860
  this.workflowRunStatus = result.status;
10558
10861
  if (result.status !== "suspended") this.cleanup?.();
10559
10862
  if (result.status === "success") {
10560
10863
  if (claimedParent && this.parentWorkflow) {
10561
10864
  let parentExecutionStarted = false;
10865
+ const parentRunId = claimedParent.run.runId;
10562
10866
  claimedParent.run._resume({
10563
10867
  step: this.parentWorkflow.stepId,
10564
10868
  forEachIndex: this.parentWorkflow.foreachIndex,
@@ -10571,6 +10875,7 @@ var Run = class {
10571
10875
  }
10572
10876
  }).catch(async (error) => {
10573
10877
  if (!parentExecutionStarted) await releaseParentClaim();
10878
+ if (runFenceConflictOf(error)?.runId === parentRunId) return;
10574
10879
  this.#mastra?.getLogger()?.error("Failed to resume parent workflow after nested child completion.", error);
10575
10880
  });
10576
10881
  } else if (!params.skipParentWorkflowClaim) this.#wakeParentWorkflow({
@@ -10581,10 +10886,6 @@ var Run = class {
10581
10886
  result.traceId = traceId;
10582
10887
  result.spanId = spanId;
10583
10888
  return result;
10584
- }).catch(async (error) => {
10585
- await releaseParentClaim();
10586
- await releaseClaimIfUnused();
10587
- throw error;
10588
10889
  });
10589
10890
  this.executionResults = executionResultPromise;
10590
10891
  return executionResultPromise.then((result) => {
@@ -10709,7 +11010,7 @@ var Run = class {
10709
11010
  const spanId = workflowSpan?.id;
10710
11011
  let result;
10711
11012
  try {
10712
- result = await this.executionEngine.execute({
11013
+ result = await ownership.run(this.runId, () => this.executionEngine.execute({
10713
11014
  workflowId: this.workflowId,
10714
11015
  runId: this.runId,
10715
11016
  parentWorkflow: this.parentWorkflow,
@@ -10728,7 +11029,7 @@ var Run = class {
10728
11029
  workflowSpan,
10729
11030
  storageVersion: this.storageVersion,
10730
11031
  storedState: this.runStorage.storedState(snapshot)
10731
- });
11032
+ }));
10732
11033
  } finally {
10733
11034
  await ownership.release();
10734
11035
  }
@@ -10821,36 +11122,31 @@ var Run = class {
10821
11122
  expectedStatus: "running"
10822
11123
  });
10823
11124
  } catch (releaseError) {
11125
+ if (isOwnRunFenceConflict(releaseError)) return;
10824
11126
  this.#mastra?.getLogger()?.warn(`[Workflow ${this.workflowId}] Failed to release time travel claim for run ${this.runId}`, releaseError);
10825
11127
  }
10826
11128
  };
10827
- let result;
10828
- try {
10829
- result = await this.#executeOwned(() => this.executionEngine.execute({
10830
- workflowId: this.workflowId,
10831
- runId: this.runId,
10832
- parentWorkflow: this.parentWorkflow,
10833
- resourceId: this.resourceId,
10834
- disableScorers: this.disableScorers,
10835
- graph: this.executionGraph,
10836
- timeTravel: timeTravelData,
10837
- serializedStepGraph: this.serializedStepGraph,
10838
- pubsub: this.pubsub,
10839
- retryConfig: this.retryConfig,
10840
- requestContext: requestContextToUse,
10841
- actor,
10842
- abortController: this.abortController,
10843
- outputWriter,
10844
- workflowSpan,
10845
- outputOptions,
10846
- perStep,
10847
- storageVersion: this.storageVersion,
10848
- inheritedState
10849
- }));
10850
- } catch (error) {
10851
- await releaseClaimIfUnused();
10852
- throw error;
10853
- }
11129
+ const result = await this.#executeOwned(() => this.executionEngine.execute({
11130
+ workflowId: this.workflowId,
11131
+ runId: this.runId,
11132
+ parentWorkflow: this.parentWorkflow,
11133
+ resourceId: this.resourceId,
11134
+ disableScorers: this.disableScorers,
11135
+ graph: this.executionGraph,
11136
+ timeTravel: timeTravelData,
11137
+ serializedStepGraph: this.serializedStepGraph,
11138
+ pubsub: this.pubsub,
11139
+ retryConfig: this.retryConfig,
11140
+ requestContext: requestContextToUse,
11141
+ actor,
11142
+ abortController: this.abortController,
11143
+ outputWriter,
11144
+ workflowSpan,
11145
+ outputOptions,
11146
+ perStep,
11147
+ storageVersion: this.storageVersion,
11148
+ inheritedState
11149
+ }), void 0, { onFailure: releaseClaimIfUnused });
10854
11150
  this.workflowRunStatus = result.status;
10855
11151
  if (result.status !== "suspended") this.cleanup?.();
10856
11152
  result.traceId = traceId;
@@ -11719,9 +12015,11 @@ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
11719
12015
  * already rebuilt in the step's scope — falling back to it is what keeps
11720
12016
  * request-scoped resolution (tenant/user, workspace, dynamic model/memory)
11721
12017
  * working for tools rebuilt on a cross-process worker, including a delegated
11722
- * subagent's.
12018
+ * subagent's. Pass `liveRunContext` only for the same run's original context,
12019
+ * not an engine-rebuilt context or another caller's context.
11723
12020
  */
11724
- function restoreRequestContext$1(entries, runLevel) {
12021
+ function restoreRequestContext(entries, runLevel, liveRunContext) {
12022
+ if (liveRunContext) return liveRunContext;
11725
12023
  if (entries) {
11726
12024
  const restored = new RequestContext([...Object.entries(withoutLiveRequestKeys(entries)), ...liveRequestEntries(runLevel)]);
11727
12025
  restoreRunAgentScopes(restored);
@@ -11736,6 +12034,118 @@ function liveRequestEntries(runLevel) {
11736
12034
  const kept = withoutLiveRequestKeys(live);
11737
12035
  return Object.entries(live).filter(([key]) => !(key in kept));
11738
12036
  }
12037
+ // src/agent/streams/constants.ts
12038
+ /**
12039
+ * Topics and event types of an agent's resumable run stream.
12040
+ */
12041
+ /**
12042
+ * Generate the pubsub topic name for agent streaming events
12043
+ * @param runId - The unique run identifier
12044
+ * @returns The topic name for subscribing/publishing agent stream events
12045
+ */
12046
+ const AGENT_STREAM_TOPIC = (runId) => `agent.stream.${runId}`;
12047
+ /**
12048
+ * Generate the pubsub topic name for agent control messages.
12049
+ *
12050
+ * Separate from {@link AGENT_STREAM_TOPIC} because control messages travel the
12051
+ * opposite direction: stream events flow worker -> consumer, control messages
12052
+ * flow caller -> worker. Keeping them apart means stream consumers never see
12053
+ * control traffic and vice versa.
12054
+ *
12055
+ * @param runId - The unique run identifier
12056
+ * @returns The topic name for publishing/subscribing agent control events
12057
+ */
12058
+ const AGENT_CONTROL_TOPIC = (runId) => `agent.control.${runId}`;
12059
+ /**
12060
+ * Event type constants for agent control events
12061
+ */
12062
+ const AgentControlEventTypes = {
12063
+ /**
12064
+ * Request that a run abort itself. Published by `abort()` in whichever
12065
+ * process the caller lives in; handled by whichever process is actually
12066
+ * executing the run's steps.
12067
+ */
12068
+ ABORT_REQUEST: "abort-request" };
12069
+ /**
12070
+ * Event type constants for agent stream events
12071
+ */
12072
+ const AgentStreamEventTypes = {
12073
+ /** Chunk of streaming data (text, tool call, etc.) */
12074
+ CHUNK: "chunk",
12075
+ /** Internal boundary preceding all output from an LLM execution step. */
12076
+ ITERATION_START: "iteration-start",
12077
+ /** Start of a new step in the agentic loop */
12078
+ STEP_START: "step-start",
12079
+ /** End of a step in the agentic loop */
12080
+ STEP_FINISH: "step-finish",
12081
+ /** Agent execution completed successfully */
12082
+ FINISH: "finish",
12083
+ /** Error occurred during execution */
12084
+ ERROR: "error",
12085
+ /** Workflow suspended (e.g., for tool approval) */
12086
+ SUSPENDED: "suspended",
12087
+ /** Execution aborted by abortSignal */
12088
+ ABORT: "abort",
12089
+ /** Single agentic-loop iteration completed (observability hook) */
12090
+ ITERATION_COMPLETE: "iteration-complete",
12091
+ /**
12092
+ * A new execution claimed the run. Carries no chunk: consumers only raise
12093
+ * their generation so events the superseded execution still publishes are
12094
+ * dropped.
12095
+ */
12096
+ OWNERSHIP_CLAIMED: "ownership-claimed"
12097
+ };
12098
+ // src/agent/durable/constants.ts
12099
+ const DURABLE_STOP_WHEN_ERROR_ID = "DURABLE_AGENT_STOP_WHEN_FAILED";
12100
+ const REJECT_STREAM_ERROR = Symbol("mastra.durable.rejectStreamError");
12101
+ function markErrorForStreamRejection(error) {
12102
+ error[REJECT_STREAM_ERROR] = true;
12103
+ return error;
12104
+ }
12105
+ function shouldRejectStream(error) {
12106
+ return error[REJECT_STREAM_ERROR] === true;
12107
+ }
12108
+ /**
12109
+ * Default values for durable agent execution
12110
+ */
12111
+ const DurableAgentDefaults = {
12112
+ /** Default maximum number of agentic loop iterations */
12113
+ MAX_STEPS: 5,
12114
+ /**
12115
+ * Default tool call concurrency.
12116
+ * Applied by `resolveDurableToolCallConcurrency` when a run doesn't
12117
+ * configure `toolCallConcurrency`. Approval / suspend-capable tool sets
12118
+ * always run sequentially (concurrency: 1) regardless of this value.
12119
+ */
12120
+ TOOL_CALL_CONCURRENCY: 10
12121
+ };
12122
+ /**
12123
+ * Step IDs used in the durable agentic workflow
12124
+ */
12125
+ const DurableStepIds = {
12126
+ /** LLM execution step */
12127
+ LLM_EXECUTION: "durable-llm-execution",
12128
+ /** Tool call step */
12129
+ TOOL_CALL: "durable-tool-call",
12130
+ /** LLM mapping step (combines results) */
12131
+ LLM_MAPPING: "durable-llm-mapping",
12132
+ /** Agentic execution workflow (one iteration) */
12133
+ AGENTIC_EXECUTION: "durable-agentic-execution",
12134
+ /** Full agentic loop workflow */
12135
+ AGENTIC_LOOP: "durable-agentic-loop",
12136
+ /** Scorer execution step */
12137
+ SCORER_EXECUTION: "durable-scorer-execution",
12138
+ /** isTaskComplete evaluation step */
12139
+ IS_TASK_COMPLETE: "durable-is-task-complete"
12140
+ };
12141
+ /** The loop's last step, which ends the run's spans when it succeeds. */
12142
+ const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
12143
+ const RECOVER_ALREADY_IN_PROGRESS_ERROR_ID = "DURABLE_AGENT_RECOVER_ALREADY_IN_PROGRESS";
12144
+ const RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID = "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND";
12145
+ const RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID = "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE";
12146
+ const RECOVER_RUN_SUSPENDED_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_SUSPENDED";
12147
+ const RECOVER_RUN_NOT_ACTIVE_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_NOT_ACTIVE";
12148
+ const RECOVER_SHUTDOWN_ERROR_ID = "DURABLE_AGENT_RECOVER_SHUTDOWN";
11739
12149
  // src/agent/durable/execution-ownership-guard.ts
11740
12150
  /** One step's observation of its immutable driver's claim. Never renews it. */
11741
12151
  var ExecutionOwnershipGuard = class {
@@ -11853,70 +12263,17 @@ var ExecutionOwnershipGuard = class {
11853
12263
  this.#unsubscribe?.();
11854
12264
  }
11855
12265
  };
11856
- // src/agent/streams/constants.ts
11857
- /**
11858
- * Topics and event types of an agent's resumable run stream.
11859
- */
11860
- /**
11861
- * Generate the pubsub topic name for agent streaming events
11862
- * @param runId - The unique run identifier
11863
- * @returns The topic name for subscribing/publishing agent stream events
11864
- */
11865
- const AGENT_STREAM_TOPIC = (runId) => `agent.stream.${runId}`;
11866
- /**
11867
- * Generate the pubsub topic name for agent control messages.
11868
- *
11869
- * Separate from {@link AGENT_STREAM_TOPIC} because control messages travel the
11870
- * opposite direction: stream events flow worker -> consumer, control messages
11871
- * flow caller -> worker. Keeping them apart means stream consumers never see
11872
- * control traffic and vice versa.
11873
- *
11874
- * @param runId - The unique run identifier
11875
- * @returns The topic name for publishing/subscribing agent control events
11876
- */
11877
- const AGENT_CONTROL_TOPIC = (runId) => `agent.control.${runId}`;
11878
- /**
11879
- * Event type constants for agent control events
11880
- */
11881
- const AgentControlEventTypes = {
11882
- /**
11883
- * Request that a run abort itself. Published by `abort()` in whichever
11884
- * process the caller lives in; handled by whichever process is actually
11885
- * executing the run's steps.
11886
- */
11887
- ABORT_REQUEST: "abort-request" };
12266
+ // src/agent/streams/run-records.ts
11888
12267
  /**
11889
- * Event type constants for agent stream events
12268
+ * Lifetime of a running or suspended run's record. Deliberately much longer
12269
+ * than the stream log's retention: the record is a single small key, and it is
12270
+ * what lets any replica authorize `observe()`/abort/resume on a run parked
12271
+ * overnight on a tool approval — long after its replay log expired (the log
12272
+ * is recreated with later indices and observers resync; see
12273
+ * `MastraServerCache.listPushIndexed`). A finished run's record is deleted by
12274
+ * run cleanup; this lifetime bounds it when cleanup never runs.
11890
12275
  */
11891
- const AgentStreamEventTypes = {
11892
- /** Chunk of streaming data (text, tool call, etc.) */
11893
- CHUNK: "chunk",
11894
- /** Internal boundary preceding all output from an LLM execution step. */
11895
- ITERATION_START: "iteration-start",
11896
- /** Start of a new step in the agentic loop */
11897
- STEP_START: "step-start",
11898
- /** End of a step in the agentic loop */
11899
- STEP_FINISH: "step-finish",
11900
- /** Agent execution completed successfully */
11901
- FINISH: "finish",
11902
- /** Error occurred during execution */
11903
- ERROR: "error",
11904
- /** Workflow suspended (e.g., for tool approval) */
11905
- SUSPENDED: "suspended",
11906
- /** Execution aborted by abortSignal */
11907
- ABORT: "abort",
11908
- /** Single agentic-loop iteration completed (observability hook) */
11909
- ITERATION_COMPLETE: "iteration-complete",
11910
- /**
11911
- * A new execution claimed the run. Carries no chunk: consumers only raise
11912
- * their generation so events the superseded execution still publishes are
11913
- * dropped.
11914
- */
11915
- OWNERSHIP_CLAIMED: "ownership-claimed"
11916
- };
11917
- // src/agent/streams/run-records.ts
11918
- /** Lifetime of a record. Matches the stream log so ownership never outlives the history it guards by more than one write. */
11919
- const AGENT_RUN_RECORD_TTL_MS = RUN_LOG_TTL_MS;
12276
+ const AGENT_RUN_RECORD_TTL_MS = 864e5;
11920
12277
  const agentRunRecordKey = (agentId, runId) => `agent.run.${agentId}.${runId}`;
11921
12278
  async function writeAgentRunRecord(cache, record, key = agentRunRecordKey(record.agentId, record.runId)) {
11922
12279
  await cache.set(key, record, AGENT_RUN_RECORD_TTL_MS);
@@ -12895,10 +13252,14 @@ function createOwnerHandle({ pubsub, runId, cleanupTimeoutMs, logger, abortSigna
12895
13252
  await assertCleanupOwnership?.();
12896
13253
  if (record) {
12897
13254
  const current = await readAgentRunRecord(record.cache, record.agentId, runId, record.key);
12898
- if (current && current.publisherId !== publisherId) return false;
13255
+ if (current && current.publisherId !== publisherId) {
13256
+ logger?.info?.(`[AgentStream:${runId}] skipping stream cleanup: the run record belongs to publisher ${current.publisherId}, not ${publisherId}`);
13257
+ return false;
13258
+ }
12899
13259
  }
12900
13260
  return true;
12901
- } catch {
13261
+ } catch (error) {
13262
+ logger?.warn?.(`[AgentStream:${runId}] skipping stream cleanup: ownership could not be verified; the run's stream state is left to expire with its retention TTL`, { error });
12902
13263
  return false;
12903
13264
  }
12904
13265
  };
@@ -12916,8 +13277,12 @@ function createOwnerHandle({ pubsub, runId, cleanupTimeoutMs, logger, abortSigna
12916
13277
  AGENT_STREAM_TOPIC(runId),
12917
13278
  AGENT_CONTROL_TOPIC(runId),
12918
13279
  abortAckTopic(runId)
12919
- ]) pubsub.clearTopic(topic).catch(() => {});
12920
- if (record) deleteAgentRunRecord(record.cache, record.agentId, runId, record.key).catch(() => {});
13280
+ ]) pubsub.clearTopic(topic).catch((error) => {
13281
+ logger?.warn?.(`[AgentStream:${runId}] failed to clear stream topic ${topic}`, { error });
13282
+ });
13283
+ if (record) deleteAgentRunRecord(record.cache, record.agentId, runId, record.key).catch((error) => {
13284
+ logger?.warn?.(`[AgentStream:${runId}] failed to delete the run record`, { error });
13285
+ });
12921
13286
  };
12922
13287
  const scheduleCleanup = () => {
12923
13288
  scheduleStreamCleanup(cleanupTimeoutMs, () => void cleanup())?.unref?.();
@@ -13102,9 +13467,11 @@ const streamOwnerKey = createRunScopeKey("execution-stream-owner");
13102
13467
  const executionTransport = Symbol("execution-stream-publisher-transport");
13103
13468
  function resolveExecutionPublisher({ runId, mastra, agentId, agent, claim, entry = getRunRegistryEntry(runId, mastra) }) {
13104
13469
  if (!entry && !claim) return;
13470
+ let createdPlaceholder = false;
13105
13471
  if (!entry) {
13106
13472
  entry = { isPlaceholder: true };
13107
13473
  if (!setRunRegistryEntry(runId, entry, mastra)) return;
13474
+ createdPlaceholder = true;
13108
13475
  }
13109
13476
  const scope = entry.runScope ??= createRunScope();
13110
13477
  if (agent) scope.set(streamOwnerKey, agent);
@@ -13128,16 +13495,17 @@ function resolveExecutionPublisher({ runId, mastra, agentId, agent, claim, entry
13128
13495
  executionClaim,
13129
13496
  requestContext,
13130
13497
  memoryInfo,
13131
- entry
13498
+ entry,
13499
+ createdPlaceholder
13132
13500
  };
13133
13501
  }
13134
13502
  /** Worker output keeps its captured execution authority and cannot settle or clean up the run. */
13135
13503
  function getExecutionStreamProducer(options) {
13136
13504
  const context = resolveExecutionPublisher(options);
13137
13505
  if (!context) return;
13138
- const { publisher, publisherId, runBus, requestContext } = context;
13506
+ const { publisher, publisherId, runBus, requestContext, entry, createdPlaceholder } = context;
13139
13507
  const { runId, agentId, mastra } = options;
13140
- return publisher.attachEventProducer({
13508
+ const producer = publisher.attachEventProducer({
13141
13509
  publisherId,
13142
13510
  pubsub: runBus.pubsub,
13143
13511
  assertOwnership: () => assertExecutionNotSuperseded({
@@ -13147,6 +13515,19 @@ function getExecutionStreamProducer(options) {
13147
13515
  requestContext
13148
13516
  })
13149
13517
  });
13518
+ if (!createdPlaceholder) return producer;
13519
+ return {
13520
+ async publishEvent(event, transport, publishOptions) {
13521
+ try {
13522
+ return await producer.publishEvent(event, transport, publishOptions);
13523
+ } catch (error) {
13524
+ const current = getRunRegistryEntry(runId, mastra);
13525
+ if (isExecutionFenceError(error) && current === entry && entry.isPlaceholder === true) deleteRunRegistryEntry(runId, mastra);
13526
+ throw error;
13527
+ }
13528
+ },
13529
+ detach: () => producer.detach()
13530
+ };
13150
13531
  }
13151
13532
  /** Owning readers settle and clean up using the authority of their captured execution. */
13152
13533
  function getExecutionStreamOwner(options) {
@@ -13235,23 +13616,6 @@ function withExecutionStreamProducer(pubsub, options) {
13235
13616
  return typeof value === "function" ? value.bind(target) : value;
13236
13617
  } });
13237
13618
  }
13238
- // src/agent/durable/run-fence-scope.ts
13239
- const runFenceScope = new AsyncLocalStorage();
13240
- const runFenceContext = setRunFenceContext({
13241
- current: () => runFenceScope.getStore(),
13242
- run: (scope, fn) => runFenceScope.run(scope, fn)
13243
- });
13244
- /**
13245
- * Run `fn` with `scope` supplying the fence of every storage write it makes,
13246
- * including writes from processors, tools and memory that never see the fence.
13247
- */
13248
- function runInRunFenceScope(scope, fn) {
13249
- return runFenceContext.run(scope, fn);
13250
- }
13251
- /** The scope installed for the current async context, if any. */
13252
- function currentRunFenceScope() {
13253
- return runFenceContext.current();
13254
- }
13255
13619
  // src/agent/durable/execution-fence.ts
13256
13620
  /**
13257
13621
  * Execution fence for DurableAgent runs (#23734).
@@ -13280,10 +13644,12 @@ function currentRunFenceScope() {
13280
13644
  const EXECUTION_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
13281
13645
  const EXECUTION_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
13282
13646
  /**
13283
- * How long past its local lease deadline a storage-backed execution waits for a renewal still in flight. A renewal
13284
- * queued behind other writes can still extend the lease; one that never returns must not keep the execution going.
13647
+ * Heartbeat ticks a storage-backed execution goes without a confirmed renewal before it gives up the run: a TTL's
13648
+ * worth while renewals fail, and one more TTL while a renewal is still in flight, since one queued behind other writes
13649
+ * can still extend the lease. Ticks, not elapsed time, because a stalled process misses ticks without failing any.
13285
13650
  */
13286
- const STORAGE_RENEWAL_GRACE_MS = EXECUTION_LEASE_TTL_MS;
13651
+ const STORAGE_FAILED_RENEWAL_TICKS = Math.ceil(EXECUTION_LEASE_TTL_MS / EXECUTION_LEASE_RENEW_INTERVAL_MS);
13652
+ const STORAGE_PENDING_RENEWAL_TICKS = 2 * STORAGE_FAILED_RENEWAL_TICKS;
13287
13653
  /** Allowance for the store's clock running ahead of this process when reading a renewed lease's expiry. */
13288
13654
  const STORE_CLOCK_SKEW_MS = EXECUTION_LEASE_RENEW_INTERVAL_MS;
13289
13655
  const VERIFY_RETRY_DELAY_MS = 250;
@@ -13782,6 +14148,7 @@ var ExecutionFence = class ExecutionFence {
13782
14148
  /** The grace for a release of this claim is spent: a renewal already found it released before this fence settled. */
13783
14149
  #releaseSeen = false;
13784
14150
  #settlement;
14151
+ #detached = false;
13785
14152
  #settledAs;
13786
14153
  #resolveSettled;
13787
14154
  /** Resolves once {@link settle} has finished and the claim is released or left to its new holder. */
@@ -13907,26 +14274,97 @@ var ExecutionFence = class ExecutionFence {
13907
14274
  if (!claim.agentId) return void 0;
13908
14275
  const executionBackend = await resolveRemoteBackend(mastra, claim.agentId, runId, claim);
13909
14276
  if (!executionBackend) return void 0;
13910
- const holdsThreadLease = async (threadId) => {
13911
- const lease = [
13912
- mastra.pubsub,
13913
- runId,
13914
- threadId,
13915
- claim.resourceId,
13916
- claim.generation,
13917
- claim.executionId
13918
- ];
13919
- if (claim.generation === void 0) return agentThreadStreamRuntime.renewDurableThreadLease(...lease);
14277
+ const details = {
14278
+ agentId: claim.agentId,
14279
+ runId,
14280
+ executionId: claim.executionId
14281
+ };
14282
+ const threadId = claim.threadId;
14283
+ const lease = threadId ? [
14284
+ mastra.pubsub,
14285
+ runId,
14286
+ threadId,
14287
+ claim.resourceId,
14288
+ claim.generation,
14289
+ claim.executionId
14290
+ ] : void 0;
14291
+ let heartbeatRenewal;
14292
+ let participant;
14293
+ const verifyCurrent = async () => {
14294
+ await executionBackend.verify(claim, details);
14295
+ if (participant?.isLost()) throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details);
14296
+ };
14297
+ const checkThread = async (threadLease, heartbeatWorker) => {
14298
+ const stopped = () => heartbeatWorker && (!heartbeatWorker.#heartbeat || heartbeatWorker.isLost());
14299
+ let timedOut = false;
14300
+ let timer;
14301
+ const check = async () => {
14302
+ let renewed;
14303
+ try {
14304
+ renewed = await agentThreadStreamRuntime.renewDurableThreadLease(...threadLease);
14305
+ } catch (error) {
14306
+ if (agentThreadStreamRuntime.isThreadLeaseBackendUnavailableToAll(mastra.pubsub, error)) return true;
14307
+ throw error;
14308
+ }
14309
+ if (renewed) return true;
14310
+ if (timedOut || stopped()) return void 0;
14311
+ await verifyCurrent();
14312
+ if (timedOut || stopped()) return void 0;
14313
+ let acquired;
14314
+ try {
14315
+ acquired = await agentThreadStreamRuntime.reclaimDurableThreadLease(...threadLease);
14316
+ } catch (error) {
14317
+ if (agentThreadStreamRuntime.isThreadLeaseBackendUnavailableToAll(mastra.pubsub, error)) return true;
14318
+ throw error;
14319
+ }
14320
+ if (acquired) try {
14321
+ await verifyCurrent();
14322
+ } catch (error) {
14323
+ if (error instanceof DurableExecutionFenceError && error.id === "DURABLE_AGENT_EXECUTION_SUPERSEDED") (async () => {
14324
+ const snapshot = await (await mastra.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
14325
+ workflowName: DurableStepIds.AGENTIC_LOOP,
14326
+ runId
14327
+ });
14328
+ if (!(snapshot?.status === "suspended" || snapshot?.status === "waiting") || await executionBackend.isSuperseded(claim)) await agentThreadStreamRuntime.releaseDurableThreadLease(...threadLease);
14329
+ })().catch(() => {});
14330
+ throw error;
14331
+ }
14332
+ else if (heartbeatWorker) {
14333
+ if (timedOut || stopped()) return void 0;
14334
+ const [pubsub, , threadId, resourceId] = threadLease;
14335
+ if (!await agentThreadStreamRuntime.isDurableThreadLeaseHeldByAnotherRun(pubsub, runId, threadId, resourceId)) return;
14336
+ }
14337
+ return acquired;
14338
+ };
13920
14339
  try {
13921
- return await agentThreadStreamRuntime.renewDurableThreadLease(...lease) || await agentThreadStreamRuntime.reclaimDurableThreadLease(...lease);
13922
- } catch (error) {
13923
- if (!agentThreadStreamRuntime.isThreadLeaseBackendUnavailableToAll(mastra.pubsub, error)) throw error;
13924
- mastra.getLogger()?.warn(`[DurableAgent] run ${runId}: thread lease backend unavailable, relying on run ownership`, { error });
13925
- return true;
14340
+ return await Promise.race([check(), new Promise((resolve) => {
14341
+ timer = setTimeout(() => {
14342
+ timedOut = true;
14343
+ resolve(void 0);
14344
+ }, EXECUTION_LEASE_RENEW_INTERVAL_MS);
14345
+ timer.unref?.();
14346
+ })]);
14347
+ } finally {
14348
+ clearTimeout(timer);
13926
14349
  }
13927
14350
  };
13928
14351
  const backend = {
13929
14352
  ...executionBackend,
14353
+ verify: async () => {
14354
+ await verifyCurrent();
14355
+ if (!lease || claim.generation === void 0) return;
14356
+ for (;;) {
14357
+ const held = await checkThread(lease);
14358
+ await verifyCurrent();
14359
+ if (held === true) return;
14360
+ if (held === false) {
14361
+ ExecutionFence.releaseSharedClaim(mastra, runId, claim, "abandoned").catch(() => {});
14362
+ throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details);
14363
+ }
14364
+ await sleep(VERIFY_RETRY_DELAY_MS);
14365
+ await verifyCurrent();
14366
+ }
14367
+ },
13930
14368
  renew: async (current) => {
13931
14369
  const result = await executionBackend.renew(current);
13932
14370
  if (!result.renewed) {
@@ -13937,20 +14375,22 @@ var ExecutionFence = class ExecutionFence {
13937
14375
  });
13938
14376
  return result;
13939
14377
  }
13940
- if (claim.threadId && !await holdsThreadLease(claim.threadId)) throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, {
13941
- agentId: claim.agentId,
13942
- runId,
13943
- executionId: claim.executionId
13944
- });
14378
+ if (lease) {
14379
+ if (claim.generation === void 0) {
14380
+ if (!await agentThreadStreamRuntime.renewDurableThreadLease(...lease)) throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details);
14381
+ } else if (participant && !heartbeatRenewal) {
14382
+ const worker = participant;
14383
+ heartbeatRenewal = checkThread(lease, worker).then(async (held) => {
14384
+ if (held !== false || !worker.#heartbeat || worker.isLost()) return;
14385
+ worker.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details));
14386
+ await ExecutionFence.releaseSharedClaim(mastra, runId, claim, "abandoned");
14387
+ }).catch(() => {}).finally(() => heartbeatRenewal = void 0);
14388
+ }
14389
+ }
13945
14390
  return result;
13946
14391
  }
13947
14392
  };
13948
14393
  const startedAt = Date.now();
13949
- const details = {
13950
- agentId: claim.agentId,
13951
- runId,
13952
- executionId: claim.executionId
13953
- };
13954
14394
  let deadline;
13955
14395
  try {
13956
14396
  await Promise.race([(async () => {
@@ -13968,7 +14408,7 @@ var ExecutionFence = class ExecutionFence {
13968
14408
  } finally {
13969
14409
  if (deadline) clearTimeout(deadline);
13970
14410
  }
13971
- const fence = new ExecutionFence({
14411
+ const fence = participant = new ExecutionFence({
13972
14412
  ...details,
13973
14413
  backend,
13974
14414
  generation: claim.generation,
@@ -14001,6 +14441,10 @@ var ExecutionFence = class ExecutionFence {
14001
14441
  get settlement() {
14002
14442
  return this.#settledAs;
14003
14443
  }
14444
+ /** This process stopped coordinating the run and left its settlement to the workers. */
14445
+ get detached() {
14446
+ return this.#detached;
14447
+ }
14004
14448
  /** An owned deadline settlement revokes writes without handing its topics to another execution. */
14005
14449
  ownsRunTopics() {
14006
14450
  return this.#settledAs === "owned" || !this.#lossError;
@@ -14193,6 +14637,7 @@ var ExecutionFence = class ExecutionFence {
14193
14637
  /** Detach a coordinator without changing the claim shared with remote workers. */
14194
14638
  detach() {
14195
14639
  if (this.#settlement) return;
14640
+ this.#detached = true;
14196
14641
  this.stopHeartbeat();
14197
14642
  this.#settledAs = "superseded";
14198
14643
  this.#settlement = Promise.resolve("superseded");
@@ -14326,8 +14771,16 @@ var ExecutionFence = class ExecutionFence {
14326
14771
  }
14327
14772
  /**
14328
14773
  * Keep the claim alive between write checks. A `false` renewal marks the
14329
- * fence lost, which notifies {@link onLost} listeners. Backend errors are
14330
- * tolerated until the local lease deadline. A failed renewal can be caused
14774
+ * fence lost, which notifies {@link onLost} listeners.
14775
+ *
14776
+ * A storage claim is judged by the store's conditional renewal, not the
14777
+ * local clock: a blocked event loop moves the clock without letting this
14778
+ * process renew, so a stall alone must not lose the run (#30669). The
14779
+ * heartbeat counts its ticks since the last confirmed renewal instead:
14780
+ * failed renewals are tolerated for a TTL's worth of ticks, and one still
14781
+ * in flight for one more TTL. A pubsub lease has no generation to tell a
14782
+ * late renewal from a later holder's, so it keeps the local deadline, and
14783
+ * its backend errors are tolerated until then. A failed renewal can be caused
14331
14784
  * by this execution's own release: in this process, when the backend
14332
14785
  * confirmed the claim still held the run as it was released (without that
14333
14786
  * confirmation another execution claimed the run first); in another process,
@@ -14347,11 +14800,19 @@ var ExecutionFence = class ExecutionFence {
14347
14800
  let fences = renewingFencesByClaim.get(key);
14348
14801
  if (!fences) renewingFencesByClaim.set(key, fences = /* @__PURE__ */ new Set());
14349
14802
  fences.add(this);
14803
+ const storage = this.generation !== void 0;
14804
+ let unconfirmedTicks = 0;
14805
+ let lastFailure;
14350
14806
  this.#heartbeat = setInterval(() => {
14351
14807
  if (this.#settlement || this.#lossError) return;
14352
- const now = Date.now();
14353
- if (this.#renewalInFlight && this.generation !== void 0 && now < this.#leaseExpiresAt + STORAGE_RENEWAL_GRACE_MS) return;
14354
- if (now >= this.#leaseExpiresAt) {
14808
+ if (storage) {
14809
+ unconfirmedTicks++;
14810
+ const limit = this.#renewalInFlight ? STORAGE_PENDING_RENEWAL_TICKS : STORAGE_FAILED_RENEWAL_TICKS;
14811
+ if (unconfirmedTicks >= limit) {
14812
+ this.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, this.#details(), lastFailure));
14813
+ return;
14814
+ }
14815
+ } else if (Date.now() >= this.#leaseExpiresAt) {
14355
14816
  this.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, this.#details()));
14356
14817
  return;
14357
14818
  }
@@ -14363,6 +14824,8 @@ var ExecutionFence = class ExecutionFence {
14363
14824
  const { leaseExpiresAt } = result;
14364
14825
  const reported = leaseExpiresAt ? Math.min(leaseExpiresAt.getTime() - STORE_CLOCK_SKEW_MS, Date.now() + EXECUTION_LEASE_TTL_MS) : 0;
14365
14826
  this.#leaseExpiresAt = Math.max(startedAt + EXECUTION_LEASE_TTL_MS, reported);
14827
+ unconfirmedTicks = 0;
14828
+ lastFailure = void 0;
14366
14829
  return;
14367
14830
  }
14368
14831
  if (await this.#releaseExplainsFailedRenewal(result.released)) return;
@@ -14370,7 +14833,8 @@ var ExecutionFence = class ExecutionFence {
14370
14833
  return this.#noteTakeover();
14371
14834
  }).catch(async (cause) => {
14372
14835
  if (this.#settlement && await releaseAnswer(this.#ownRelease.awaitAnswer())) return;
14373
- if (Date.now() >= this.#leaseExpiresAt) {
14836
+ if (storage && !this.#settlement) lastFailure = cause;
14837
+ else if (Date.now() >= this.#leaseExpiresAt) {
14374
14838
  this.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, this.#details(), cause));
14375
14839
  return;
14376
14840
  }
@@ -14683,46 +15147,6 @@ var EventProcessor = class {
14683
15147
  this.mastra = mastra;
14684
15148
  }
14685
15149
  };
14686
- // src/storage/workflow-step-guard.ts
14687
- var WorkflowStepConflictError = class extends Error {
14688
- reason;
14689
- storedResult;
14690
- storedRequestContext;
14691
- storedSnapshot;
14692
- code = "WORKFLOW_STEP_CONFLICT";
14693
- constructor(reason, storedResult, storedRequestContext, storedSnapshot) {
14694
- super(`Workflow step delivery rejected (${reason}).`);
14695
- this.reason = reason;
14696
- this.storedResult = storedResult;
14697
- this.storedRequestContext = storedRequestContext;
14698
- this.storedSnapshot = storedSnapshot;
14699
- }
14700
- };
14701
- function isWorkflowStepConflictError(error) {
14702
- return typeof error === "object" && error !== null && "code" in error && error.code === "WORKFLOW_STEP_CONFLICT";
14703
- }
14704
- /** Call inside the adapter's snapshot lock, before mutating results, state, or request context. */
14705
- function assertWorkflowStepGuard({ snapshot, stepId, startGuard, completionGuard }) {
14706
- if (!startGuard && !completionGuard) return;
14707
- if (!snapshot) throw new WorkflowStepConflictError("missing");
14708
- const stored = snapshot.context[stepId];
14709
- const startedBy = stored?.metadata?.startedBy;
14710
- if (stored && !startedBy) return;
14711
- if (startedBy === (startGuard ?? completionGuard).eventId) {
14712
- if (completionGuard?.pruneOnly) {
14713
- if (stored?.status === "success") return;
14714
- throw new WorkflowStepConflictError("stale", stored);
14715
- }
14716
- if (stored?.status === "running") return;
14717
- if (stored?.metadata?.__continuationStarted) throw new WorkflowStepConflictError("stale", stored);
14718
- throw new WorkflowStepConflictError("completed", stored, snapshot.requestContext, snapshot);
14719
- }
14720
- if (startGuard) {
14721
- if (!stored && startGuard.expectedStartedBy === void 0) return;
14722
- if (stored && (stored.status !== "running" || stored.metadata?.__restartPending === true) && startedBy === startGuard.expectedStartedBy) return;
14723
- }
14724
- throw new WorkflowStepConflictError("stale", stored);
14725
- }
14726
15150
  // src/workflows/scheduler/definition-hash.ts
14727
15151
  /**
14728
15152
  * Computes a stable content hash of a workflow's serialized step graph.
@@ -20456,13 +20880,20 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
20456
20880
  */
20457
20881
  async handle(event) {
20458
20882
  if (!reachesOtherProcesses(this.mastra.pubsub)) return this.#handleDelivery(event);
20459
- if (!isStorageFencedExecution(new RequestContext(Object.entries(event.data?.requestContext ?? {})), event.runId, event.data?.parentWorkflow)) return this.#handleDelivery(event);
20883
+ if (!isStorageFencedExecution(new RequestContext(Object.entries(event.data?.requestContext ?? {})), event.runId, event.data?.parentWorkflow)) {
20884
+ await carryEndedSegment(this.mastra, event);
20885
+ const result = await this.#handleDelivery(event);
20886
+ if (result.ok) endFailedIteration(this.mastra, event);
20887
+ return result;
20888
+ }
20460
20889
  try {
20461
20890
  if (await retrySettledDurableExecution(this.mastra, event)) return { ok: true };
20462
20891
  const execute = async () => {
20463
20892
  const result = await this.#handleDelivery(event);
20464
- if (result.ok) await settleEventedDurableExecution(this.mastra, event);
20465
- else if (!result.retry) await stopAbandonedDurableExecution(this.mastra, event, !this.#abandonedUnpublished.has(this.#deliveryKey(event)));
20893
+ if (result.ok) {
20894
+ endFailedIteration(this.mastra, event);
20895
+ await settleEventedDurableExecution(this.mastra, event);
20896
+ } else if (!result.retry) await stopAbandonedDurableExecution(this.mastra, event, !this.#abandonedUnpublished.has(this.#deliveryKey(event)));
20466
20897
  return result;
20467
20898
  };
20468
20899
  return await participateInDurableExecution(this.mastra, event, execute);
@@ -39635,6 +40066,13 @@ const compareCodeUnits$1 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
39635
40066
  const byPosition = (a, b) => a.position < b.position ? -1 : a.position > b.position ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
39636
40067
  const byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
39637
40068
  const newestFirst = (a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
40069
+ /** An oldest-first position: the event's insertion counter as plain decimal text. */
40070
+ function activityPosition(value) {
40071
+ if (value === void 0) return void 0;
40072
+ const n = /^(0|[1-9]\d*)$/.test(value) ? Number(value) : NaN;
40073
+ if (!Number.isSafeInteger(n)) throw new RangeError(`Knowledge activity position is not one this store issued: ${value}`);
40074
+ return n;
40075
+ }
39638
40076
  const oldestFirst = (a, b) => newestFirst(b, a);
39639
40077
  const clone$1 = (value) => structuredClone(value);
39640
40078
  const PIN_KINDS = ["page", "list"];
@@ -39646,6 +40084,8 @@ var InMemoryKnowledgePageStore = class {
39646
40084
  #activity = [];
39647
40085
  #bodyLinks = /* @__PURE__ */ new Map();
39648
40086
  #clock = 0;
40087
+ /** Insertion counter behind each event's `position`; never reset, so a held position can't be reused. */
40088
+ #activitySeq = 0;
39649
40089
  /** A deep copy of every page, note, pin, body link and event, for {@link restore}. */
39650
40090
  snapshot() {
39651
40091
  return structuredClone({
@@ -39664,6 +40104,9 @@ var InMemoryKnowledgePageStore = class {
39664
40104
  this.#pins = copy.pins;
39665
40105
  this.#activity = copy.activity;
39666
40106
  this.#bodyLinks = copy.bodyLinks;
40107
+ const positioned = (event) => Number.isSafeInteger(event.position === void 0 ? NaN : Number(event.position));
40108
+ for (const event of this.#activity) if (positioned(event)) this.#activitySeq = Math.max(this.#activitySeq, Number(event.position));
40109
+ if (!this.#activity.every(positioned)) for (const event of this.#activity) event.position = String(++this.#activitySeq);
39667
40110
  }
39668
40111
  /** Drops every page, note, pin, body link and event. */
39669
40112
  clear() {
@@ -39686,7 +40129,8 @@ var InMemoryKnowledgePageStore = class {
39686
40129
  pageId: page.id,
39687
40130
  ...noteId ? { noteId } : {},
39688
40131
  provenance: clone$1(provenance),
39689
- createdAt: this.#now()
40132
+ createdAt: this.#now(),
40133
+ position: String(++this.#activitySeq)
39690
40134
  });
39691
40135
  }
39692
40136
  #page(id) {
@@ -40274,25 +40718,40 @@ var InMemoryKnowledgePageStore = class {
40274
40718
  }
40275
40719
  async listPageActivity(input) {
40276
40720
  if (input.before !== void 0 && input.cursor !== void 0) throw new RangeError("Knowledge activity takes either a cursor or a before position, not both");
40277
- const { items, nextCursor } = paginate(this.#activity.filter((event) => {
40278
- const page = this.#pages.get(event.pageId);
40279
- if (!page || !this.#pageReadable(page, input.read)) return false;
40280
- if (input.pageId !== void 0 && event.pageId !== input.pageId) return false;
40281
- if (input.scopeId !== void 0 && page.scopeId !== input.scopeId) return false;
40282
- if (event.noteId !== void 0) {
40283
- const note = this.#notes.get(event.noteId);
40284
- if (!note || !this.#noteVisible(note, input.read)) return false;
40285
- }
40286
- if (input.since !== void 0 && event.createdAt.getTime() < input.since.getTime()) return false;
40287
- if (input.until !== void 0 && event.createdAt.getTime() >= input.until.getTime()) return false;
40288
- if (input.before !== void 0 && newestFirst(event, input.before) <= 0) return false;
40289
- return true;
40290
- }).sort(newestFirst), input.cursor, input.limit);
40721
+ if (input.after !== void 0 && input.order !== "asc") throw new RangeError("Knowledge activity takes an after position only with order asc");
40722
+ if (input.after !== void 0 && input.cursor !== void 0) throw new RangeError("Knowledge activity takes either a cursor or an after position, not both");
40723
+ if (input.before !== void 0 && input.order === "asc") throw new RangeError("Knowledge activity takes a before position only newest first; use after with order asc");
40724
+ if (input.order === "asc") {
40725
+ const after = activityPosition(input.after ?? input.cursor);
40726
+ if (after !== void 0 && after > this.#activitySeq) throw new RangeError(`Knowledge activity position is ahead of this feed: ${after}`);
40727
+ const size = pageSize(input.limit);
40728
+ const matched = this.#activity.filter((event) => this.#activityMatches(event, input) && (after === void 0 || Number(event.position) > after));
40729
+ const items = matched.slice(0, size);
40730
+ const last = items[items.length - 1];
40731
+ return {
40732
+ events: items.map(clone$1),
40733
+ ...matched.length > size && last ? { nextCursor: last.position } : {}
40734
+ };
40735
+ }
40736
+ const { items, nextCursor } = paginate(this.#activity.filter((event) => this.#activityMatches(event, input) && (input.before === void 0 || newestFirst(event, input.before) > 0)).sort(newestFirst), input.cursor, input.limit);
40291
40737
  return {
40292
- events: items.map(clone$1),
40738
+ events: items.map(({ position: _position, ...event }) => clone$1(event)),
40293
40739
  ...nextCursor ? { nextCursor } : {}
40294
40740
  };
40295
40741
  }
40742
+ #activityMatches(event, input) {
40743
+ const page = this.#pages.get(event.pageId);
40744
+ if (!page || !this.#pageReadable(page, input.read)) return false;
40745
+ if (input.pageId !== void 0 && event.pageId !== input.pageId) return false;
40746
+ if (input.scopeId !== void 0 && page.scopeId !== input.scopeId) return false;
40747
+ if (event.noteId !== void 0) {
40748
+ const note = this.#notes.get(event.noteId);
40749
+ if (!note || !this.#noteVisible(note, input.read)) return false;
40750
+ }
40751
+ if (input.since !== void 0 && event.createdAt.getTime() < input.since.getTime()) return false;
40752
+ if (input.until !== void 0 && event.createdAt.getTime() >= input.until.getTime()) return false;
40753
+ return true;
40754
+ }
40296
40755
  async addPinAudience(input) {
40297
40756
  const page = this.#livePage(input.pageId);
40298
40757
  if (!input.audience.length) throw new Error("A Knowledge pin needs at least one audience scope");
@@ -40517,7 +40976,8 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40517
40976
  supportsExplicitReset: true,
40518
40977
  supportsPinKinds: true,
40519
40978
  supportsTransactions: true,
40520
- supportsActivityDateRange: true
40979
+ supportsActivityDateRange: true,
40980
+ supportsActivityAscending: true
40521
40981
  };
40522
40982
  }
40523
40983
  async inspectSchema() {
@@ -43876,7 +44336,8 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43876
44336
  generation: owner.generation,
43877
44337
  ownerId: owner.ownerId,
43878
44338
  leaseExpiresAt: owner.leaseExpiresAt ? new Date(owner.leaseExpiresAt) : null,
43879
- live: !!owner.leaseExpiresAt && owner.leaseExpiresAt.getTime() > Date.now()
44339
+ live: !!owner.leaseExpiresAt && owner.leaseExpiresAt.getTime() > Date.now(),
44340
+ updatedAt: new Date(owner.updatedAt)
43880
44341
  };
43881
44342
  }
43882
44343
  assertFence(explicit, runId, operation) {
@@ -43893,10 +44354,12 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43893
44354
  acquired: false,
43894
44355
  record: current
43895
44356
  };
44357
+ const now = Date.now();
43896
44358
  this.db.runOwners.set(runId, {
43897
- generation: current ? current.generation + 1 : Math.max(1, Date.now()),
44359
+ generation: current ? current.generation + 1 : Math.max(1, now),
43898
44360
  ownerId,
43899
- leaseExpiresAt: new Date(Date.now() + leaseMs)
44361
+ leaseExpiresAt: new Date(now + leaseMs),
44362
+ updatedAt: new Date(now)
43900
44363
  });
43901
44364
  return {
43902
44365
  acquired: true,
@@ -43909,7 +44372,9 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43909
44372
  renewed: false,
43910
44373
  record: this.ownershipRecord(fence.runId)
43911
44374
  };
43912
- owner.leaseExpiresAt = new Date(Date.now() + leaseMs);
44375
+ const now = Date.now();
44376
+ owner.leaseExpiresAt = new Date(now + leaseMs);
44377
+ owner.updatedAt = new Date(now);
43913
44378
  return {
43914
44379
  renewed: true,
43915
44380
  record: this.ownershipRecord(fence.runId)
@@ -43919,6 +44384,7 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43919
44384
  const owner = this.db.runOwners.get(fence.runId);
43920
44385
  if (!owner || !matchesRunFence(owner, fence)) return false;
43921
44386
  owner.leaseExpiresAt = null;
44387
+ owner.updatedAt = /* @__PURE__ */ new Date();
43922
44388
  return true;
43923
44389
  }
43924
44390
  async getRunOwnership({ runId }) {
@@ -47110,6 +47576,14 @@ function formatToolResult(toolName, argsSummary, resultText, isError, durationMs
47110
47576
  }
47111
47577
  return `${header} \u00B7 ${status}\n${isError && !resultText.startsWith("Error: ") ? `Error: ${resultText}` : resultText}`;
47112
47578
  }
47579
+ /**
47580
+ * Action id of a button that continues a stopped run. Put it on an error card
47581
+ * (see `formatError`); a click sends {@link CONTINUE_RUN_MESSAGE} to the agent
47582
+ * from the clicker, through the same handler as a reply in the thread.
47583
+ */
47584
+ const CONTINUE_RUN_ACTION_ID = "run_continue";
47585
+ /** What a click on a {@link CONTINUE_RUN_ACTION_ID} button says to the agent. */
47586
+ const CONTINUE_RUN_MESSAGE = "Continue.";
47113
47587
  /** Format a tool approval request message */
47114
47588
  function formatToolApproval(toolName, argsSummary, toolCallId, useCards) {
47115
47589
  const header = formatToolHeader(toolName, argsSummary);
@@ -47485,10 +47959,6 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47485
47959
  if (piece) textBuffer += piece;
47486
47960
  continue;
47487
47961
  }
47488
- if (chunk.type === "text-end") {
47489
- await flushText();
47490
- continue;
47491
- }
47492
47962
  if (chunk.type === "step-finish") {
47493
47963
  await flushText();
47494
47964
  continue;
@@ -47525,7 +47995,10 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47525
47995
  continue;
47526
47996
  }
47527
47997
  if (chunk.type === "tool-call") {
47528
- if (channelToolNames.has(chunk.payload.toolName)) continue;
47998
+ if (channelToolNames.has(chunk.payload.toolName)) {
47999
+ await flushText();
48000
+ continue;
48001
+ }
47529
48002
  const enr = tracker.trackStart({
47530
48003
  toolCallId: chunk.payload.toolCallId,
47531
48004
  toolName: chunk.payload.toolName,
@@ -47988,10 +48461,6 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
47988
48461
  pushToSession(piece);
47989
48462
  continue;
47990
48463
  }
47991
- if (chunk.type === "text-end") {
47992
- if (toolDisplay === "hidden") await closeSession();
47993
- continue;
47994
- }
47995
48464
  if (chunk.type === "step-finish") {
47996
48465
  if (toolDisplay !== "grouped") await closeSession();
47997
48466
  continue;
@@ -48027,7 +48496,10 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
48027
48496
  continue;
48028
48497
  }
48029
48498
  if (chunk.type === "tool-call") {
48030
- if (channelToolNames.has(chunk.payload.toolName)) continue;
48499
+ if (channelToolNames.has(chunk.payload.toolName)) {
48500
+ if (toolDisplay === "hidden") await closeSession();
48501
+ continue;
48502
+ }
48031
48503
  const enr = tracker.trackStart({
48032
48504
  toolCallId: chunk.payload.toolCallId,
48033
48505
  toolName: chunk.payload.toolName,
@@ -48807,6 +49279,488 @@ function channelLines(ctx, textHidden, tools) {
48807
49279
  if (tools && "add_reaction" in tools) lines.push(`If you want to acknowledge a message without ${textHidden ? "posting" : "speaking"}, use the \`add_reaction\` tool to react with an emoji instead of replying with text.`);
48808
49280
  return lines;
48809
49281
  }
49282
+ // src/channels/thread-link-processor.ts
49283
+ /**
49284
+ * Request-context marker for a run that opened a new channel thread. `AgentChannels` sets it when
49285
+ * it creates the thread; a host that decides "new" itself can call {@link markNewChannelThread}.
49286
+ */
49287
+ const NEW_CHANNEL_THREAD_KEY = "__mastra_new_channel_thread";
49288
+ function markNewChannelThread(requestContext) {
49289
+ requestContext.set(NEW_CHANNEL_THREAD_KEY, true);
49290
+ }
49291
+ /** Text-part id of the link delta; never collides with a model block id. */
49292
+ const LINK_PART_ID = "mastra-channel-thread-link";
49293
+ const EMITTED_SUFFIX_KEY = "mastra__channelThreadLinkSuffix";
49294
+ /**
49295
+ * Posts a link to the thread in the host's web UI right after the first reply of a new channel
49296
+ * thread, so the link closes the reply rather than leading it. The channel driver ends a post at
49297
+ * `text-end`, so the link shows as its own short message after the reply.
49298
+ *
49299
+ * "End of the reply" is not `text-end`: a reply with citations is several text blocks, each with
49300
+ * its own `text-end`. The reply ends at the first `tool-call` (an opener before tools run) or at
49301
+ * `step-finish` (a reply with no tools), whichever comes first after some text. A processor
49302
+ * returns one part, so on that chunk this returns a `text-delta` carrying the link and stashes the
49303
+ * chunk under `REPROCESS_PART_KEY`, which the runner re-drives through the chain right after.
49304
+ *
49305
+ * The link is a channel display detail. Saved to memory it would show the model its own link on
49306
+ * later turns (inviting it to fabricate links) and render a self-link in the web transcript, so
49307
+ * `processOutputStep` drops the link's text part before the message is saved.
49308
+ *
49309
+ * No-op unless the run opened a new thread, the reply text is shown, and `link` returns a URL.
49310
+ */
49311
+ var ChannelThreadLinkProcessor = class {
49312
+ id = "channel-thread-link";
49313
+ #options;
49314
+ /** Pass options, or a function picking them per run (e.g. by the run's platform). */
49315
+ constructor(options) {
49316
+ this.#options = typeof options === "function" ? options : () => options;
49317
+ }
49318
+ async processOutputStream({ part, state, requestContext }) {
49319
+ if (state.linked || !linksThisRun(requestContext)) return part;
49320
+ if (part.type === "text-delta") {
49321
+ if (part.payload.text.trim()) state.textStarted = true;
49322
+ return part;
49323
+ }
49324
+ if (part.type !== "tool-call" && part.type !== "step-finish" || !state.textStarted) return part;
49325
+ state.linked = true;
49326
+ const suffix = this.#suffix(requestContext);
49327
+ if (!suffix) return part;
49328
+ requestContext.set(EMITTED_SUFFIX_KEY, suffix);
49329
+ state[REPROCESS_PART_KEY] = part;
49330
+ return {
49331
+ type: "text-delta",
49332
+ runId: part.runId,
49333
+ from: part.from,
49334
+ payload: {
49335
+ id: LINK_PART_ID,
49336
+ text: suffix
49337
+ }
49338
+ };
49339
+ }
49340
+ processOutputStep({ messageList, requestContext }) {
49341
+ const suffix = requestContext?.get(EMITTED_SUFFIX_KEY);
49342
+ if (!suffix) return messageList;
49343
+ for (const message of messageList.get.response.db()) {
49344
+ if (message.role !== "assistant") continue;
49345
+ const index = message.content.parts.findIndex((part) => part.type === "text" && part.text === suffix);
49346
+ if (index === -1) continue;
49347
+ message.content.parts.splice(index, 1);
49348
+ if (typeof message.content.content === "string" && message.content.content.endsWith(suffix)) message.content.content = message.content.content.slice(0, -suffix.length);
49349
+ return messageList;
49350
+ }
49351
+ return messageList;
49352
+ }
49353
+ #suffix(requestContext) {
49354
+ const options = this.#options(requestContext);
49355
+ if (!options) return void 0;
49356
+ const memory = parseMemoryRequestContext(requestContext);
49357
+ const link = options.link({
49358
+ requestContext,
49359
+ threadId: memory?.thread?.id,
49360
+ resourceId: memory?.resourceId
49361
+ });
49362
+ return link && `\n\n[${options.label ?? "Open thread \u2197"}](${link})`;
49363
+ }
49364
+ };
49365
+ function linksThisRun(requestContext) {
49366
+ if (!requestContext?.get("__mastra_new_channel_thread")) return false;
49367
+ return requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY)?.textDisplay !== "hidden";
49368
+ }
49369
+ // src/channels/reply-tool.ts
49370
+ const REPLY_TOOL_NAME = "reply_in_thread";
49371
+ /**
49372
+ * Which reply carries the session link: `claimed` while that reply is posting,
49373
+ * `posted` once it landed. Claimed before any await, so overlapping replies
49374
+ * can't both take it; a failed post hands it back to the next reply.
49375
+ */
49376
+ const LINKED_KEY = "mastra__channelReplyLinked";
49377
+ const replyInput = z$1.object({ text: z$1.string().trim().min(1).max(12e3).describe("The message to post, in markdown.") }).strict();
49378
+ /** @internal */
49379
+ function createChannelReplyTool(requestContext, options) {
49380
+ const { resolveRender } = options;
49381
+ return { [REPLY_TOOL_NAME]: createTool({
49382
+ id: REPLY_TOOL_NAME,
49383
+ description: "Post a message in this chat thread. Nothing you write outside this tool reaches the thread, so use it for anything the people there should see: a short note that you are starting a longer job, a question you need answered, and the outcome when you finish. Post when you have something new; do not repeat yourself or post that nothing changed. To stay quiet, do not call it.",
49384
+ inputSchema: replyInput,
49385
+ execute: async (input, context) => {
49386
+ const link = claimFirstReplyLink(requestContext, options.link);
49387
+ const suffix = link ? `\n\n[${options.link?.label ?? "Open thread \u2197"}](${link})` : "";
49388
+ const toolCallId = context?.agent?.toolCallId;
49389
+ const streamed = toolCallId ? replyStreams(requestContext).get(toolCallId) : void 0;
49390
+ if (toolCallId) replyStreams(requestContext).delete(toolCallId);
49391
+ try {
49392
+ if (!streamed || !await streamed.finish(input.text, suffix)) {
49393
+ const render = await resolveRender(requestContext);
49394
+ if (!render) throw new Error("This session is no longer linked to a chat thread.");
49395
+ await render.chatThread.post({ markdown: `${input.text}${suffix}` });
49396
+ }
49397
+ } catch (error) {
49398
+ if (link) requestContext.set(LINKED_KEY, void 0);
49399
+ throw error;
49400
+ }
49401
+ if (link) requestContext.set(LINKED_KEY, "posted");
49402
+ return { posted: true };
49403
+ }
49404
+ }) };
49405
+ }
49406
+ /**
49407
+ * The session link the first reply of a new session ends with, claimed for
49408
+ * this reply. With reply text hidden, the session-link processor's text delta
49409
+ * never reaches the thread, so the tool carries the link instead.
49410
+ */
49411
+ function claimFirstReplyLink(requestContext, link) {
49412
+ if (!link || !requestContext.get("__mastra_new_channel_thread") || requestContext.get(LINKED_KEY)) return;
49413
+ const memory = parseMemoryRequestContext(requestContext);
49414
+ const url = link.link({
49415
+ requestContext,
49416
+ threadId: memory?.thread?.id,
49417
+ resourceId: memory?.resourceId
49418
+ });
49419
+ if (url) requestContext.set(LINKED_KEY, "claimed");
49420
+ return url;
49421
+ }
49422
+ /** Live posts of `reply_in_thread` calls whose text is still streaming in, by tool call id. */
49423
+ const STREAMS_KEY = "mastra__channelReplyStreams";
49424
+ function replyStreams(requestContext) {
49425
+ let streams = requestContext.get(STREAMS_KEY);
49426
+ if (!streams) {
49427
+ streams = /* @__PURE__ */ new Map();
49428
+ requestContext.set(STREAMS_KEY, streams);
49429
+ }
49430
+ return streams;
49431
+ }
49432
+ /**
49433
+ * One streamed post, opened on the first visible text so an abandoned
49434
+ * call never leaves an empty message behind.
49435
+ */
49436
+ function openReplyStream({ chatThread, logger }) {
49437
+ const queue = [];
49438
+ let sent = "";
49439
+ let closed = false;
49440
+ let wake;
49441
+ let done;
49442
+ async function* chunks() {
49443
+ while (true) {
49444
+ while (queue.length > 0) yield queue.shift();
49445
+ if (closed) return;
49446
+ await new Promise((resolve) => wake = resolve);
49447
+ }
49448
+ }
49449
+ const push = (text) => {
49450
+ if (!text) return;
49451
+ queue.push(text);
49452
+ done ??= chatThread.post(chunks()).then(() => true, (error) => {
49453
+ logger?.warn("[channels] streamed reply failed; posting it whole", { error });
49454
+ return false;
49455
+ });
49456
+ wake?.();
49457
+ };
49458
+ return {
49459
+ update(text) {
49460
+ const visible = text.trimStart();
49461
+ if (!visible.startsWith(sent)) return;
49462
+ push(visible.slice(sent.length));
49463
+ sent = visible;
49464
+ },
49465
+ async finish(text, suffix) {
49466
+ if (text.startsWith(sent)) push(text.slice(sent.length));
49467
+ if (!done) return false;
49468
+ push(suffix);
49469
+ closed = true;
49470
+ wake?.();
49471
+ return done;
49472
+ },
49473
+ async close() {
49474
+ closed = true;
49475
+ wake?.();
49476
+ return done ?? false;
49477
+ }
49478
+ };
49479
+ }
49480
+ /**
49481
+ * Streams a `reply_in_thread` call's `text` into the thread while the model is
49482
+ * still writing it, so a long reply appears as it is written instead of all at
49483
+ * once when the call completes. The tool finishes the post with the validated
49484
+ * text. Runs whose adapter doesn't stream, or that show reply text, are left
49485
+ * alone.
49486
+ */
49487
+ var ChannelReplyStreamProcessor = class {
49488
+ id = "channel-reply-stream";
49489
+ #resolveRender;
49490
+ constructor(resolveRender) {
49491
+ this.#resolveRender = resolveRender;
49492
+ }
49493
+ async processOutputStream({ part, state, requestContext }) {
49494
+ if (!requestContext) return part;
49495
+ const args = state.args ??= {};
49496
+ if (part.type === "tool-call-input-streaming-start" && part.payload.toolName === "reply_in_thread") {
49497
+ const render = await this.#resolveRender(requestContext);
49498
+ if (render?.textDisplay !== "hidden" || !render.streaming?.enabled) return part;
49499
+ args[part.payload.toolCallId] = "";
49500
+ replyStreams(requestContext).set(part.payload.toolCallId, openReplyStream(render));
49501
+ } else if (part.type === "tool-call-delta" && part.payload.toolCallId in args) {
49502
+ const text = partialStringField(args[part.payload.toolCallId] += part.payload.argsTextDelta, "text");
49503
+ if (text !== void 0) replyStreams(requestContext).get(part.payload.toolCallId)?.update(text);
49504
+ } else if ((part.type === "tool-error" || part.type === "tool-result") && part.payload.toolCallId in args) {
49505
+ delete args[part.payload.toolCallId];
49506
+ await closeStream(requestContext, part.payload.toolCallId);
49507
+ } else if (RUN_END.has(part.type)) {
49508
+ for (const toolCallId of Object.keys(args)) await closeStream(requestContext, toolCallId);
49509
+ state.args = {};
49510
+ }
49511
+ return part;
49512
+ }
49513
+ };
49514
+ /** Chunks after which no `reply_in_thread` call of this run will still execute. */
49515
+ const RUN_END = /* @__PURE__ */ new Set([
49516
+ "finish",
49517
+ "abort",
49518
+ "error",
49519
+ "tripwire"
49520
+ ]);
49521
+ /**
49522
+ * Ends a streamed post whose call will never reach `execute`, keeping the text
49523
+ * shown so far, so the platform isn't left with a message that never finishes.
49524
+ */
49525
+ async function closeStream(requestContext, toolCallId) {
49526
+ const streams = replyStreams(requestContext);
49527
+ const stream = streams.get(toolCallId);
49528
+ if (!stream) return;
49529
+ streams.delete(toolCallId);
49530
+ await stream.close();
49531
+ }
49532
+ const ESCAPES = {
49533
+ "\"": "\"",
49534
+ "\\": "\\",
49535
+ "/": "/",
49536
+ b: "\b",
49537
+ f: "\f",
49538
+ n: "\n",
49539
+ r: "\r",
49540
+ t: " "
49541
+ };
49542
+ /** The decoded value of a top-level string field in JSON that may still be cut off mid-string. */
49543
+ function partialStringField(json, field) {
49544
+ const start = new RegExp(`"${field}"\\s*:\\s*"`).exec(json);
49545
+ if (!start) return void 0;
49546
+ let out = "";
49547
+ for (let i = start.index + start[0].length; i < json.length; i++) {
49548
+ const ch = json[i];
49549
+ if (ch === "\"") return out;
49550
+ if (ch !== "\\") {
49551
+ out += ch;
49552
+ continue;
49553
+ }
49554
+ const next = json[i + 1];
49555
+ if (next === void 0) return out;
49556
+ if (next === "u") {
49557
+ const hex = json.slice(i + 2, i + 6);
49558
+ if (hex.length < 4) return out;
49559
+ out += String.fromCharCode(parseInt(hex, 16));
49560
+ i += 5;
49561
+ } else {
49562
+ out += ESCAPES[next] ?? next;
49563
+ i += 1;
49564
+ }
49565
+ }
49566
+ return out;
49567
+ }
49568
+ // src/channels/reply-guidance-processor.ts
49569
+ const ID$1 = "channel-reply-guidance";
49570
+ /** Chat surfaces show what the agent writes as-is, so a bare id is a dead end for the reader. */
49571
+ const LINK_REFERENCES = "Write every pull request, issue, commit, ticket or other reference you mention in the thread as a markdown link to its page, with the id as plain link text, e.g. [#28467](https://github.com/<owner>/<repo>/pull/28467). Never leave one as a bare id or wrap it in code formatting. Build links from URLs your tools returned; don't guess a URL, and leave a reference unlinked only when you can't work out its URL.";
49572
+ /** Agents tend to write the way they report to other agents: names, ids and shorthand only they follow. */
49573
+ const WRITE_FOR_PEOPLE = [
49574
+ "Write for the people in the thread, not for another agent. A teammate who knows the product and programming, but has not read this code or this conversation, should follow your message on first read.",
49575
+ "Lead with the answer or the outcome and anything you need from them, in plain sentences. Keep it short: a few sentences answer most questions, and when there is more, offer it rather than writing it all out. Say what code does rather than naming the function, file, field, error class or tool that does it; name one only when they need it to find the code. Use the project\u2019s real terms, not invented analogies.",
49576
+ "Leave out tool names and run ids unless someone asks for them, and always leave out agent shorthand. When you pass on what another agent reported, say what it means for the people here in your own words; never paste its report."
49577
+ ].join(" ");
49578
+ /**
49579
+ * Tells the agent how to speak in a chat channel: open a long job with one line that names it,
49580
+ * finish with the outcome, write for people, and link references. With `reply_in_thread` on the
49581
+ * run, that advice becomes advice on when to call it. A run outside the channel that can still
49582
+ * post there (a web prompt on a linked thread) gets a short note on when to. Runs with neither
49583
+ * get nothing.
49584
+ */
49585
+ var ChannelReplyGuidanceProcessor = class {
49586
+ id = ID$1;
49587
+ #instructions;
49588
+ constructor(options = {}) {
49589
+ this.#instructions = options.instructions;
49590
+ }
49591
+ processInputStep({ messageList, requestContext, tools }) {
49592
+ const canReply = !!tools && "reply_in_thread" in tools;
49593
+ let content;
49594
+ if (!requestContext?.get("channel")) {
49595
+ if (!canReply) return void 0;
49596
+ content = [`Post to that thread with \`${REPLY_TOOL_NAME}\`. This request came from outside it, so don't post an opener or progress there; post the outcome when the people in the thread asked for this work or are waiting on it, or when you're asked to. Don't write a note about what you posted.`];
49597
+ } else if (canReply) content = [
49598
+ `Only messages you send with \`${REPLY_TOOL_NAME}\` reach this thread; your other text stays out of it. Don't write a note about what you posted. After a reply, either keep working or end your turn with an empty message; any text you write after posting is wasted.`,
49599
+ "When a request will take tools or more than a moment, post one short line first that says what you are about to do, then do the work and post the outcome when you finish \u2014 not a replay of the steps.",
49600
+ "Post again in between only when you need an answer or have news the people in the thread would want. When a message that doesn't mention you needs nothing from you, don't call it."
49601
+ ];
49602
+ else content = ["When a request will take tools or more than a moment to answer, reply first with one short line that says what you are about to do \u2014 \"On it \u2014 <the task in a few words>.\" \u2014 then do the work; the opener posts as its own message before any progress is shown. Give direct answers and trivial replies without an opener.", "Finish with the outcome, not a replay of the steps."];
49603
+ const extra = typeof this.#instructions === "function" ? this.#instructions({ canReply }) : this.#instructions ?? [];
49604
+ messageList.addSystem({
49605
+ role: "system",
49606
+ content: [
49607
+ ...content,
49608
+ ...extra,
49609
+ LINK_REFERENCES,
49610
+ WRITE_FOR_PEOPLE
49611
+ ].join("\n")
49612
+ }, ID$1);
49613
+ return { messageList };
49614
+ }
49615
+ };
49616
+ // src/channels/reply-reminder-processor.ts
49617
+ const ID = "channel-reply-reminder";
49618
+ /** How long a run may work without posting before it is nudged. */
49619
+ const REPLY_REMINDER_AFTER_MS = 3e5;
49620
+ /**
49621
+ * With reply text hidden, a long job can run silently for an hour while the
49622
+ * person who asked has no idea whether anything is happening. Once a run has
49623
+ * gone `afterMs` without calling `reply_in_thread`, this sends the agent one
49624
+ * signal suggesting a status update, then restarts the clock. Ignoring it is
49625
+ * how the agent stays quiet. A signal joins the end of the transcript, so the
49626
+ * cached prompt prefix is untouched. Only runs that have the reply tool are
49627
+ * touched.
49628
+ */
49629
+ var ChannelReplyReminderProcessor = class {
49630
+ id = ID;
49631
+ #afterMs;
49632
+ #now;
49633
+ constructor({ afterMs = REPLY_REMINDER_AFTER_MS, now = Date.now } = {}) {
49634
+ this.#afterMs = afterMs;
49635
+ this.#now = now;
49636
+ }
49637
+ async processInputStep({ messageList, tools, state, sendSignal }) {
49638
+ if (!tools || !("reply_in_thread" in tools) || !sendSignal) return void 0;
49639
+ const reminder = state;
49640
+ const now = this.#now();
49641
+ reminder.quietSince ??= now;
49642
+ const seen = new Set(reminder.seenCalls ?? []);
49643
+ const calls = replyCalls(messageList.get.response.db());
49644
+ if (calls.some((id) => !seen.has(id))) reminder.quietSince = now;
49645
+ reminder.seenCalls = calls;
49646
+ const silentFor = now - reminder.quietSince;
49647
+ if (silentFor < this.#afterMs) return void 0;
49648
+ const minutes = Math.floor(silentFor / 6e4);
49649
+ await sendSignal({
49650
+ type: "reactive",
49651
+ contents: `It has been ${minutes} minute${minutes === 1 ? "" : "s"} since you last posted in this thread. If the people there would want to know where things stand, post a short status with \`${REPLY_TOOL_NAME}\`. Otherwise keep working.`
49652
+ });
49653
+ reminder.quietSince = now;
49654
+ }
49655
+ };
49656
+ /** Ids of the `reply_in_thread` calls this run has finished. */
49657
+ function replyCalls(messages) {
49658
+ const ids = [];
49659
+ for (const message of messages) {
49660
+ if (message.role !== "assistant") continue;
49661
+ for (const part of message.content.parts ?? []) {
49662
+ if (part.type !== "tool-invocation") continue;
49663
+ const { toolName, toolCallId, state } = part.toolInvocation;
49664
+ if (toolName === "reply_in_thread" && state === "result") ids.push(toolCallId);
49665
+ }
49666
+ }
49667
+ return ids;
49668
+ }
49669
+ // src/channels/reply-mode.ts
49670
+ /**
49671
+ * Slack renders the status inline next to the app name, and rejects a status
49672
+ * (sent as its loading message) of 51 characters or more. Other platforms get
49673
+ * the same cap; reply mode has only been tested on Slack.
49674
+ */
49675
+ const MAX_STATUS_LENGTH = 50;
49676
+ /**
49677
+ * Turns a tool's `description` arg ("Listing the repo root") into a status
49678
+ * line that reads after the app name ("<App> is listing the repo root…").
49679
+ * Only the first line counts: issue/PR creators carry whole bodies there.
49680
+ */
49681
+ function describeToolCall(args) {
49682
+ if (!args || typeof args !== "object") return void 0;
49683
+ const { description } = args;
49684
+ if (typeof description !== "string") return void 0;
49685
+ const line = description.split("\n").map((part) => part.replace(/\s+/g, " ").trim()).find(Boolean);
49686
+ if (!line) return void 0;
49687
+ const status = `is ${/^[A-Z][a-z]/.test(line) ? line.charAt(0).toLowerCase() + line.slice(1) : line}`;
49688
+ return status.length > MAX_STATUS_LENGTH ? `${status.slice(0, 49)}\u2026` : status;
49689
+ }
49690
+ /**
49691
+ * Progress as a status line rather than posts: "is thinking...", the current
49692
+ * tool's `description`, "is typing..." while a reply is written. With reply
49693
+ * text hidden, streamed text never reaches the thread, so it gets no status:
49694
+ * an "is typing..." set after the reply tool's post would sit on the thread
49695
+ * with nothing coming, and race the clear at the end of the run.
49696
+ *
49697
+ * @internal
49698
+ */
49699
+ function channelReplyTypingStatus(textDisplay = "hidden") {
49700
+ return (chunk) => {
49701
+ switch (chunk.type) {
49702
+ case "reasoning-delta": return "is thinking...";
49703
+ case "text-delta": return textDisplay === "show" ? "is typing..." : void 0;
49704
+ case "tool-call-input-streaming-start": return chunk.payload.toolName === "reply_in_thread" ? "is typing..." : void 0;
49705
+ case "tool-call":
49706
+ if (chunk.payload.toolName === "reply_in_thread") return "is typing...";
49707
+ return describeToolCall(chunk.payload.args) ?? "is working...";
49708
+ default: return;
49709
+ }
49710
+ };
49711
+ }
49712
+ function threadLinkOptions(link) {
49713
+ if (!link) return void 0;
49714
+ return typeof link === "function" ? { link } : link;
49715
+ }
49716
+ /**
49717
+ * Installed by `AgentChannels` when an adapter sets `replyMode`. On runs whose chat
49718
+ * thread is on that adapter (including runs started elsewhere whose thread is linked
49719
+ * to it) it adds the `reply_in_thread` tool, the reply guidance prompt, and the
49720
+ * nudge after a quiet stretch. Other runs are untouched.
49721
+ *
49722
+ * @internal
49723
+ */
49724
+ var ChannelReplyModeProcessor = class {
49725
+ id = "channel-reply-mode";
49726
+ #deps;
49727
+ constructor(deps) {
49728
+ this.#deps = deps;
49729
+ }
49730
+ async processInputStep(args) {
49731
+ const { requestContext, state } = args;
49732
+ const render = await this.#deps.resolveRender(requestContext, state);
49733
+ const adapter = render && this.#deps.adapter(render.platform);
49734
+ if (!requestContext || !render || !adapter?.replyMode) return void 0;
49735
+ const config = adapter.replyMode === "tool" ? {} : adapter.replyMode;
49736
+ if (render.textDisplay !== "hidden") {
49737
+ new ChannelReplyGuidanceProcessor({ instructions: config.instructions }).processInputStep(args);
49738
+ return { messageList: args.messageList };
49739
+ }
49740
+ const tools = {
49741
+ ...args.tools,
49742
+ ...createChannelReplyTool(requestContext, {
49743
+ resolveRender: async () => render,
49744
+ link: threadLinkOptions(adapter.threadLink)
49745
+ })
49746
+ };
49747
+ const withTools = {
49748
+ ...args,
49749
+ tools
49750
+ };
49751
+ new ChannelReplyGuidanceProcessor({ instructions: config.instructions }).processInputStep(withTools);
49752
+ await new ChannelReplyReminderProcessor({
49753
+ afterMs: config.reminderAfterMs,
49754
+ now: this.#deps.now
49755
+ }).processInputStep(withTools);
49756
+ const activeTools = args.activeTools && !args.activeTools.includes("reply_in_thread") ? [...args.activeTools, REPLY_TOOL_NAME] : void 0;
49757
+ return {
49758
+ tools,
49759
+ messageList: args.messageList,
49760
+ ...activeTools ? { activeTools } : {}
49761
+ };
49762
+ }
49763
+ };
48810
49764
  // src/channels/state-adapter.ts
48811
49765
  /**
48812
49766
  * Chat SDK StateAdapter backed by Mastra storage.
@@ -49226,6 +50180,24 @@ function formatLegacyHistoryBlock(history, chatThread, platform) {
49226
50180
  for (const msg of history.recent) lines.push(line(msg));
49227
50181
  return lines.join("\n");
49228
50182
  }
50183
+ // src/channels/thread-lookup.ts
50184
+ /**
50185
+ * The chat thread this run posts into, if any.
50186
+ *
50187
+ * A run started by a platform message has the render context on `requestContext`. A run
50188
+ * started elsewhere (web UI, schedule, signal wake) on a thread linked to a chat thread does
50189
+ * not, so rebuild it from the thread's persisted channel coordinates. The thread id comes from
50190
+ * the agent controller when there is one, else from the run's memory context. A forked
50191
+ * subagent's thread carries no channel metadata, so forks resolve nothing.
50192
+ */
50193
+ async function resolveChannelRenderContext(requestContext, channels) {
50194
+ if (!requestContext) return void 0;
50195
+ const stashed = requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
50196
+ if (stashed) return stashed;
50197
+ const threadId = requestContext.get("controller")?.threadId ?? parseMemoryRequestContext(requestContext)?.thread?.id;
50198
+ if (!threadId) return void 0;
50199
+ return await channels?.()?.buildRenderContextForThread(threadId) ?? void 0;
50200
+ }
49229
50201
  // src/channels/typing-status.ts
49230
50202
  /**
49231
50203
  * Built-in typing-status resolver. Used when `typingStatus: true` (the default)
@@ -49471,7 +50443,7 @@ var AgentChannels = class {
49471
50443
  for (const [name, value] of Object.entries(config.adapters)) if (value && typeof value === "object" && "adapter" in value) {
49472
50444
  const cfg = value;
49473
50445
  adapters[name] = cfg.adapter;
49474
- adapterConfigs[name] = cfg;
50446
+ adapterConfigs[name] = cfg.replyMode ? withReplyModeDefaults(cfg) : cfg;
49475
50447
  } else {
49476
50448
  adapters[name] = value;
49477
50449
  adapterConfigs[name] = { adapter: value };
@@ -49492,6 +50464,7 @@ var AgentChannels = class {
49492
50464
  this.channelConfig = config;
49493
50465
  this.channelToolNames = new Set(Object.keys(this.getTools()));
49494
50466
  if (this.generativeUIEnabled) this.channelToolNames.add(RENDER_CARD_TOOL_NAME);
50467
+ if (this.replyModeEnabled) this.channelToolNames.add(REPLY_TOOL_NAME);
49495
50468
  }
49496
50469
  /**
49497
50470
  * Bind the owning agent used for webhook paths and stored-thread ownership.
@@ -49784,9 +50757,53 @@ var AgentChannels = class {
49784
50757
  return defaultHandler();
49785
50758
  });
49786
50759
  if (onAction !== false) chat.onAction((event) => {
49787
- const { handlerContext } = beginMessage();
50760
+ const { defaultHandler: handleMessage, handlerContext } = beginMessage();
49788
50761
  const defaultHandler = async () => {
49789
50762
  const { actionId } = event;
50763
+ if (actionId === "run_continue") {
50764
+ const clickedThread = event.thread;
50765
+ if (!clickedThread || onSubscribedMessage === false) return;
50766
+ const threadId = this.resolveExternalThreadId({
50767
+ platform: event.adapter.name,
50768
+ chatThread: clickedThread,
50769
+ messageId: event.messageId
50770
+ });
50771
+ const text = CONTINUE_RUN_MESSAGE;
50772
+ const message = new ChatMessage({
50773
+ attachments: [],
50774
+ author: event.user,
50775
+ formatted: {
50776
+ type: "root",
50777
+ children: [{
50778
+ type: "paragraph",
50779
+ children: [{
50780
+ type: "text",
50781
+ value: text
50782
+ }]
50783
+ }]
50784
+ },
50785
+ id: event.triggerId ?? crypto.randomUUID(),
50786
+ isMention: true,
50787
+ metadata: {
50788
+ dateSent: /* @__PURE__ */ new Date(),
50789
+ edited: false
50790
+ },
50791
+ raw: event.raw,
50792
+ text,
50793
+ threadId
50794
+ });
50795
+ const chatThread = threadId === clickedThread.id ? clickedThread : new ThreadImpl({
50796
+ adapter: event.adapter,
50797
+ channelId: clickedThread.channelId,
50798
+ channelVisibility: clickedThread.channelVisibility,
50799
+ currentMessage: message,
50800
+ id: threadId,
50801
+ isDM: clickedThread.isDM,
50802
+ stateAdapter: this.stateAdapter
50803
+ });
50804
+ if (typeof onSubscribedMessage === "function") return onSubscribedMessage(chatThread, message, handleMessage, handlerContext);
50805
+ return handleMessage(chatThread, message);
50806
+ }
49790
50807
  if (!actionId.startsWith("tool_approve:") && !actionId.startsWith("tool_deny:")) return;
49791
50808
  const platform = event.adapter.name;
49792
50809
  const messageId = event.messageId;
@@ -50155,8 +51172,28 @@ var AgentChannels = class {
50155
51172
  const processors = [];
50156
51173
  if (this.channelConfig.threadContext?.addSystemMessage !== false && !has("chat-channel-context")) processors.push(new ChatChannelProcessor(this));
50157
51174
  if (this.generativeUIEnabled && !has("chat-channel-generative-ui")) processors.push(new ChatChannelGenerativeUIProcessor(this));
51175
+ if (this.replyModeEnabled && !has(REPLY_MODE_PROCESSOR_ID)) processors.push(new ChannelReplyModeProcessor({
51176
+ resolveRender: (requestContext, state) => this.resolveRunRender(requestContext, state),
51177
+ adapter: (platform) => this.adapterConfigs[platform]
51178
+ }));
50158
51179
  return processors;
50159
51180
  }
51181
+ get replyModeEnabled() {
51182
+ return Object.values(this.adapterConfigs).some((cfg) => cfg.replyMode);
51183
+ }
51184
+ /**
51185
+ * The chat thread a run posts to: the one it came in on, else the one its
51186
+ * thread (the controller's, or memory's) is linked to. Cached on `state`
51187
+ * when given; `null` remembers a thread that isn't channel-backed.
51188
+ */
51189
+ async resolveRunRender(requestContext, state) {
51190
+ const inbound = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
51191
+ if (inbound) return inbound;
51192
+ if (state && "render" in state) return state.render ?? void 0;
51193
+ const render = await resolveChannelRenderContext(requestContext, () => this);
51194
+ if (state) state.render = render ?? null;
51195
+ return render;
51196
+ }
50160
51197
  /** Whether the Slack adapter opted into `generativeUI` (the only platform it supports). */
50161
51198
  get generativeUIEnabled() {
50162
51199
  return this.adapterConfigs.slack?.generativeUI === true;
@@ -50177,8 +51214,15 @@ var AgentChannels = class {
50177
51214
  */
50178
51215
  close() {}
50179
51216
  getOutputProcessors(configuredProcessors = []) {
50180
- if (configuredProcessors.some((p) => !isProcessorWorkflow(p) && p.id === "chat-channel-render")) return [];
50181
- return [new ChatChannelOutputProcessor(this)];
51217
+ const has = (id) => configuredProcessors.some((p) => !isProcessorWorkflow(p) && p.id === id);
51218
+ const processors = [];
51219
+ if (Object.values(this.adapterConfigs).some((cfg) => cfg.threadLink) && !has(THREAD_LINK_PROCESSOR_ID)) processors.push(new ChannelThreadLinkProcessor((requestContext) => {
51220
+ const render = requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
51221
+ return render && threadLinkOptions(this.adapterConfigs[render.platform]?.threadLink);
51222
+ }));
51223
+ if (!has("chat-channel-render")) processors.push(new ChatChannelOutputProcessor(this));
51224
+ if (this.replyModeEnabled && !has(REPLY_STREAM_PROCESSOR_ID)) processors.push(new ChannelReplyStreamProcessor((requestContext) => this.resolveRunRender(requestContext)));
51225
+ return processors;
50182
51226
  }
50183
51227
  /**
50184
51228
  * Returns generic channel tools (add_reaction, remove_reaction) that resolve
@@ -50453,6 +51497,7 @@ var AgentChannels = class {
50453
51497
  defaultThreadId,
50454
51498
  requestContext
50455
51499
  }) : void 0,
51500
+ onCreate: () => markNewChannelThread(requestContext),
50456
51501
  mastra
50457
51502
  });
50458
51503
  const threadResourceId = mastraThread.resourceId;
@@ -51100,7 +52145,8 @@ var AgentChannels = class {
51100
52145
  * normally in cards/hidden modes.
51101
52146
  *
51102
52147
  * When the run's stream ends, an empty status is sent to clear any status
51103
- * this run set, so runs that end without posting a message (e.g. terminated
52148
+ * left on the thread — set by this run or by a channel handler before it
52149
+ * dispatched — so runs that end without posting a message (e.g. terminated
51104
52150
  * by `stopWhen` on a tool call, or aborted) don't leave a stale status
51105
52151
  * pinned to the thread.
51106
52152
  */
@@ -51108,7 +52154,6 @@ var AgentChannels = class {
51108
52154
  const typingStatusOption = adapterConfig?.typingStatus;
51109
52155
  const typingStatusFn = typingStatusOption === false ? null : typeof typingStatusOption === "function" ? typingStatusOption : defaultTypingStatus;
51110
52156
  let currentTypingStatus;
51111
- let statusSent = false;
51112
52157
  try {
51113
52158
  for await (const chunk of stream) {
51114
52159
  if (typingStatusFn && !typingGate.active) {
@@ -51130,7 +52175,6 @@ var AgentChannels = class {
51130
52175
  }
51131
52176
  if (typeof result === "string" && result.length > 0 && result !== currentTypingStatus) {
51132
52177
  currentTypingStatus = result;
51133
- statusSent = true;
51134
52178
  chatThread.startTyping(result).catch((e) => {
51135
52179
  this.log("debug", "Typing indicator failed (best-effort)", {
51136
52180
  platform,
@@ -51144,7 +52188,7 @@ var AgentChannels = class {
51144
52188
  yield chunk;
51145
52189
  }
51146
52190
  } finally {
51147
- if (statusSent && !typingGate.active) chatThread.startTyping("").catch((e) => {
52191
+ if (typingStatusFn && !typingGate.active) chatThread.startTyping("").catch((e) => {
51148
52192
  this.log("debug", "Typing clear failed (best-effort)", {
51149
52193
  platform,
51150
52194
  threadId: chatThread.id,
@@ -51358,7 +52402,7 @@ var AgentChannels = class {
51358
52402
  /**
51359
52403
  * Resolves an existing Mastra thread for the given external IDs, or creates one.
51360
52404
  */
51361
- async getOrCreateThread({ externalThreadId, channelId, platform, resourceId, threadId, mastra }) {
52405
+ async getOrCreateThread({ externalThreadId, channelId, platform, resourceId, threadId, onCreate, mastra }) {
51362
52406
  const { thread: existingThread, memoryStore, metadata } = await this.findThreadMapping({
51363
52407
  externalThreadId,
51364
52408
  channelId,
@@ -51366,6 +52410,7 @@ var AgentChannels = class {
51366
52410
  mastra
51367
52411
  });
51368
52412
  if (existingThread) return existingThread;
52413
+ onCreate?.();
51369
52414
  const resolvedResourceId = typeof resourceId === "function" ? await resourceId() : resourceId;
51370
52415
  const defaultThreadId = crypto.randomUUID();
51371
52416
  let resolvedThreadId = threadId ? await threadId(resolvedResourceId, defaultThreadId) : defaultThreadId;
@@ -51567,6 +52612,21 @@ async function storedAttachmentBytes(fs, dir, root = true) {
51567
52612
  }
51568
52613
  return total;
51569
52614
  }
52615
+ const REPLY_MODE_PROCESSOR_ID = "channel-reply-mode";
52616
+ const REPLY_STREAM_PROCESSOR_ID = "channel-reply-stream";
52617
+ const THREAD_LINK_PROCESSOR_ID = "channel-thread-link";
52618
+ /** Reply mode keeps reply text and tool calls out of the thread and shows progress in the status, unless set. */
52619
+ function withReplyModeDefaults(cfg) {
52620
+ const legacyCards = "cards" in cfg && cfg.cards !== void 0;
52621
+ const set = Object.fromEntries(Object.entries(cfg).filter(([, value]) => value !== void 0));
52622
+ const textDisplay = cfg.textDisplay ?? "hidden";
52623
+ return {
52624
+ textDisplay,
52625
+ ...legacyCards ? {} : { toolDisplay: "hidden" },
52626
+ typingStatus: channelReplyTypingStatus(textDisplay),
52627
+ ...set
52628
+ };
52629
+ }
51570
52630
  // src/knowledge/instructions.ts
51571
52631
  function readInstructions(canEdit) {
51572
52632
  return `Use the Knowledge tools for durable, shared knowledge. Pinned knowledge pages may already be in your context if <pinned-knowledge> tags are present in the visible conversation history: answer from their bodies without searching for or reading them again${canEdit ? ", and edit one straight from its body and the version shown, unless its body was cut off: then read it first, since a write replaces the whole body" : ""}. Read a pinned page with knowledge_read only when the answer depends on what its notes say, or on its child pages; a note count alone is no reason to read it. For anything else, search with knowledge_search before answering from Knowledge, and read a page with knowledge_read before relying on it. To see how a scope or section is organized, list it with knowledge_list and read pages by the refs it gives. Read a page whole first; when its body is too long, it comes back as its headings with line numbers and the first lines under each: read the section you need, or match the terms you are looking for. A result's more says what it left out: follow it only when what you need is not already in what you have read, and answer as soon as you have it. Cite the page or note you used. When nothing is found, say so plainly instead of guessing. When notes disagree, show both with their dates.`;
@@ -61086,8 +62146,8 @@ function knowledgeBodyGrep(lines, terms, context, from = 0) {
61086
62146
  const half = 200;
61087
62147
  let cutStart = start + Math.max(0, at - half);
61088
62148
  let cutEnd = Math.min(end, start + at + half);
61089
- if (isLowSurrogate(lines.body.charCodeAt(cutStart))) cutStart--;
61090
- if (isLowSurrogate(lines.body.charCodeAt(cutEnd))) cutEnd++;
62149
+ if (isLowSurrogate$1(lines.body.charCodeAt(cutStart))) cutStart--;
62150
+ if (isLowSurrogate$1(lines.body.charCodeAt(cutEnd))) cutEnd++;
61091
62151
  parts.push({
61092
62152
  start: cutStart,
61093
62153
  end: cutEnd
@@ -61097,7 +62157,7 @@ function knowledgeBodyGrep(lines, terms, context, from = 0) {
61097
62157
  }
61098
62158
  return parts;
61099
62159
  }
61100
- function isLowSurrogate(code) {
62160
+ function isLowSurrogate$1(code) {
61101
62161
  return code >= 56320 && code <= 57343;
61102
62162
  }
61103
62163
  /**
@@ -61991,6 +63051,248 @@ function knowledgeRunPrincipals(runtime, context) {
61991
63051
  for (const address of memory) if (!runtime.compiled.match(address)) throw new KnowledgeDeclarationError(`Knowledge run scope "${address}" does not match a declared scope type. Declare it in Knowledge \`scopes\` (for Memory's resource:/thread: scopes, spread \`...knowledgeMemoryScopes()\`).`);
61992
63052
  return [.../* @__PURE__ */ new Set([...knowledgeRunScopes(runtime.compiled, raw), ...memory])];
61993
63053
  }
63054
+ /** Longest heading line a hit shows ahead of its excerpt; a longer one is cut with `…`. */
63055
+ const HEADING_CHARS = 120;
63056
+ /** Characters of body looked at past a window's start when fitting it to the token budget. */
63057
+ const WINDOW_SCAN_CHARS = 720;
63058
+ /** Occurrences of each query word sampled as window anchors. */
63059
+ const OCCURRENCES_PER_WORD = 32;
63060
+ /** How far a window edge may move to land on whitespace. */
63061
+ const SNAP_CHARS = 20;
63062
+ /**
63063
+ * The words `knowledge_search` searches for: keyword search has no quoting, so quote marks become
63064
+ * spaces (`"refund" policy` searches `refund policy`).
63065
+ */
63066
+ function knowledgeSearchQuery(query) {
63067
+ return query.replace(/["`\u201C\u201D]/g, " ").trim();
63068
+ }
63069
+ /** Source code units per chunk when lowercasing the body and mapping offsets back. */
63070
+ const MAP_CHUNK = 4096;
63071
+ /**
63072
+ * Exact `toLowerCase()` substring matches of each word, as `[start, end)` offsets into `body`, the
63073
+ * way keyword search matches. The body is lowercased chunk by chunk, so each chunk's lowercased
63074
+ * length is known: lowercasing keeps the length for nearly all text, and where it doesn't (`İ` →
63075
+ * `i̇`) only the chunks a match lands in are walked code point by code point to map offsets back. A
63076
+ * body with no match returns before any mapping.
63077
+ */
63078
+ function lowercaseHits(body, words) {
63079
+ const sourceStarts = [];
63080
+ const loweredStarts = [];
63081
+ const pieces = [];
63082
+ let loweredLength = 0;
63083
+ for (let s = 0; s < body.length;) {
63084
+ let e = Math.min(body.length, s + MAP_CHUNK);
63085
+ if (e < body.length && isHighSurrogate(body.charCodeAt(e - 1))) e++;
63086
+ const piece = body.slice(s, e).toLowerCase();
63087
+ sourceStarts.push(s);
63088
+ loweredStarts.push(loweredLength);
63089
+ pieces.push(piece);
63090
+ loweredLength += piece.length;
63091
+ s = e;
63092
+ }
63093
+ sourceStarts.push(body.length);
63094
+ loweredStarts.push(loweredLength);
63095
+ const text = body.includes("\u03A3") ? body.toLowerCase() : pieces.join("");
63096
+ const found = [];
63097
+ words.forEach((word, w) => {
63098
+ let from = 0;
63099
+ for (let n = 0; n < OCCURRENCES_PER_WORD; n++) {
63100
+ const at = text.indexOf(word, from);
63101
+ if (at < 0) break;
63102
+ found.push({
63103
+ word: w,
63104
+ at,
63105
+ length: word.length
63106
+ });
63107
+ from = at + word.length;
63108
+ }
63109
+ });
63110
+ if (!found.length || loweredLength === body.length) return {
63111
+ hits: found.map(({ word, at, length }) => ({
63112
+ word,
63113
+ start: at,
63114
+ end: at + length
63115
+ })),
63116
+ text
63117
+ };
63118
+ const walked = /* @__PURE__ */ new Map();
63119
+ const widths = /* @__PURE__ */ new Map();
63120
+ const source = (index, edge) => {
63121
+ let chunk = 0;
63122
+ for (let lo = 0, hi = sourceStarts.length - 2; lo <= hi;) {
63123
+ const mid = lo + hi >> 1;
63124
+ if (loweredStarts[mid] <= index) {
63125
+ chunk = mid;
63126
+ lo = mid + 1;
63127
+ } else hi = mid - 1;
63128
+ }
63129
+ const sourceStart = sourceStarts[chunk];
63130
+ const loweredStart = loweredStarts[chunk];
63131
+ const sourceEnd = sourceStarts[chunk + 1];
63132
+ if (loweredStarts[chunk + 1] - loweredStart === sourceEnd - sourceStart) return Math.min(body.length, sourceStart + (index - loweredStart));
63133
+ let changes = walked.get(chunk);
63134
+ if (!changes) {
63135
+ changes = [];
63136
+ for (let i = sourceStart, l = loweredStart; i < sourceEnd;) {
63137
+ const point = body.codePointAt(i);
63138
+ const width = point > 65535 ? 2 : 1;
63139
+ let lowerWidth = point < 128 ? 1 : widths.get(point);
63140
+ if (lowerWidth === void 0) {
63141
+ lowerWidth = String.fromCodePoint(point).toLowerCase().length;
63142
+ widths.set(point, lowerWidth);
63143
+ }
63144
+ if (lowerWidth !== width) changes.push({
63145
+ lowered: l,
63146
+ source: i,
63147
+ width,
63148
+ lowerWidth
63149
+ });
63150
+ i += width;
63151
+ l += lowerWidth;
63152
+ }
63153
+ walked.set(chunk, changes);
63154
+ }
63155
+ let last = -1;
63156
+ for (let lo = 0, hi = changes.length - 1; lo <= hi;) {
63157
+ const mid = lo + hi >> 1;
63158
+ if (changes[mid].lowered <= index) {
63159
+ last = mid;
63160
+ lo = mid + 1;
63161
+ } else hi = mid - 1;
63162
+ }
63163
+ if (last < 0) return sourceStart + (index - loweredStart);
63164
+ const change = changes[last];
63165
+ const into = index - change.lowered;
63166
+ if (into === 0) return change.source;
63167
+ if (into < change.lowerWidth) return edge === "start" ? change.source : change.source + change.width;
63168
+ return Math.min(body.length, change.source + change.width + (into - change.lowerWidth));
63169
+ };
63170
+ return {
63171
+ hits: found.map(({ word, at, length }) => ({
63172
+ word,
63173
+ start: source(at, "start"),
63174
+ end: source(at + length, "end")
63175
+ })),
63176
+ text
63177
+ };
63178
+ }
63179
+ /**
63180
+ * The same matches as {@link lowercaseHits} without lowercasing the body, when that is provably
63181
+ * equivalent: every word is ASCII and the body has neither `İ` (lowercases to `i̇`, does not case-fold
63182
+ * to `i`) nor `ſ` (case-folds to `s`, does not lowercase to it). For ASCII words those are the only
63183
+ * characters where Unicode case folding and lowercasing disagree. `undefined` when not equivalent.
63184
+ */
63185
+ function foldedAsciiHits(body, words) {
63186
+ if (words.some((word) => /[^\x00-\x7f]/.test(word)) || /[\u0130\u017f]/.test(body)) return void 0;
63187
+ const hits = [];
63188
+ words.forEach((word, w) => {
63189
+ const pattern = new RegExp(word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "giu");
63190
+ for (let n = 0; n < OCCURRENCES_PER_WORD; n++) {
63191
+ const match = pattern.exec(body);
63192
+ if (!match) break;
63193
+ hits.push({
63194
+ word: w,
63195
+ start: match.index,
63196
+ end: match.index + match[0].length
63197
+ });
63198
+ }
63199
+ });
63200
+ return hits;
63201
+ }
63202
+ const isLowSurrogate = (code) => code >= 56320 && code <= 57343;
63203
+ const isHighSurrogate = (code) => code >= 55296 && code <= 56319;
63204
+ const isSpace = (char) => char !== void 0 && /\s/.test(char);
63205
+ /** How many lines of a search hit's body have a matched word. */
63206
+ function matchingLines(body, words, lowered) {
63207
+ const pattern = lowered ? void 0 : new RegExp(words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), "iu");
63208
+ let count = 0;
63209
+ (lowered ?? body).split("\n").forEach((line, i) => {
63210
+ if (!(pattern ? pattern.test(line) : words.some((word) => line.includes(word)))) return;
63211
+ count++;
63212
+ });
63213
+ return count;
63214
+ }
63215
+ /**
63216
+ * The nearest markdown heading above body offset `at`, as `12│## Heading` with its `knowledge_read`
63217
+ * line number, unless the heading starts inside the excerpt that begins at `windowStart`.
63218
+ */
63219
+ function headingAbove(body, at, windowStart, width) {
63220
+ let nearest;
63221
+ for (const section of knowledgeBodySections(body)) {
63222
+ if (section.start > at) break;
63223
+ nearest = section;
63224
+ }
63225
+ if (!nearest || nearest.start >= windowStart) return void 0;
63226
+ const lines = new KnowledgeBodyLines(body);
63227
+ const line = lines.lineAt(nearest.start);
63228
+ const text = body.slice(nearest.start, lines.lineEnd(line));
63229
+ return `${String(line).padStart(width)}\u2502${text.length > HEADING_CHARS ? `${Array.from(text).slice(0, 119).join("")}\u2026` : text}`;
63230
+ }
63231
+ /**
63232
+ * Where `body` matches the query words, or `undefined` when it contains none of them. Uses the same
63233
+ * words and the same rule as keyword search (case-insensitive substrings: a body matches exactly
63234
+ * when `body.toLowerCase()` contains the word). Each word's first {@link OCCURRENCES_PER_WORD}
63235
+ * occurrences anchor candidate windows of {@link KNOWLEDGE_SNIPPET_TOKENS} tokens; the window
63236
+ * holding the most distinct words wins, earliest on ties. Lines are counted over the whole body.
63237
+ * Cost: a scan per word and one lowercase copy of the body, except for ASCII words in a body with
63238
+ * no `İ` or `ſ`, which are matched without lowercasing; offsets are mapped only for actual matches.
63239
+ */
63240
+ function knowledgeBodyHit(body, query) {
63241
+ if (!body) return void 0;
63242
+ const words = knowledgeSearchWords(knowledgeSearchQuery(query));
63243
+ if (!words.length) return void 0;
63244
+ const folded = foldedAsciiHits(body, words);
63245
+ const lowercase = folded ? void 0 : lowercaseHits(body, words);
63246
+ const hits = folded ?? lowercase.hits;
63247
+ if (!hits.length) return void 0;
63248
+ const windowEnd = (start) => {
63249
+ const rest = body.slice(start, start + WINDOW_SCAN_CHARS);
63250
+ return start + (estimateTokenCount(rest) <= 60 ? rest.length : sliceByTokens(rest, 0, 60).length);
63251
+ };
63252
+ let best;
63253
+ for (const hit of hits) {
63254
+ const before = body.slice(Math.max(0, hit.start - 180), hit.start);
63255
+ const start = hit.start - sliceByTokens(before, -15).length;
63256
+ const end = Math.max(windowEnd(start), hit.end);
63257
+ const seen = /* @__PURE__ */ new Set();
63258
+ for (const other of hits) if (other.start >= start && other.end <= end) seen.add(other.word);
63259
+ const score = seen.size;
63260
+ if (!best || score > best.score || score === best.score && start < best.start) best = {
63261
+ start,
63262
+ end,
63263
+ anchor: hit.start,
63264
+ score
63265
+ };
63266
+ }
63267
+ let { start, end } = best;
63268
+ const { anchor } = best;
63269
+ if (start > 0) {
63270
+ for (let i = start; i < Math.min(anchor, start + SNAP_CHARS); i++) if (isSpace(body[i])) {
63271
+ start = i + 1;
63272
+ break;
63273
+ }
63274
+ }
63275
+ if (end < body.length) {
63276
+ for (let i = end; i > Math.max(anchor, end - SNAP_CHARS); i--) if (isSpace(body[i - 1])) {
63277
+ end = i - 1;
63278
+ break;
63279
+ }
63280
+ }
63281
+ if (start < body.length && isLowSurrogate(body.charCodeAt(start))) start++;
63282
+ if (end > start && isHighSurrogate(body.charCodeAt(end - 1))) end--;
63283
+ const lines = new KnowledgeBodyLines(body);
63284
+ const rows = lines.numbered(start, end > start && body[end - 1] === "\n" ? end - 1 : end).split("\n");
63285
+ const width = rows[0].indexOf("\u2502");
63286
+ if (start > 0) rows[0] = `${rows[0].slice(0, width + 1)}\u2026${rows[0].slice(width + 1)}`;
63287
+ if (end < body.length) rows[rows.length - 1] += "\u2026";
63288
+ const heading = headingAbove(body, anchor, start, width);
63289
+ const matches = matchingLines(body, words, lowercase?.text);
63290
+ return {
63291
+ snippet: heading ? `${heading}\n${rows.join("\n")}` : rows.join("\n"),
63292
+ line: lines.lineAt(anchor),
63293
+ matchingLines: matches
63294
+ };
63295
+ }
61994
63296
  // src/knowledge/page-tools.ts
61995
63297
  function maxTokensOf(host) {
61996
63298
  return host.maxTokens ?? 1e3;
@@ -62017,6 +63319,8 @@ function pageEmbedFailed(storage, page) {
62017
63319
  const RRF_K = 60;
62018
63320
  const DEFAULT_LIMIT = 10;
62019
63321
  const MAX_LIMIT = 50;
63322
+ /** The most words knowledge_read's `match` accepts; a search hint never emits a longer array. */
63323
+ const READ_MATCH_MAX_WORDS = 10;
62020
63324
  const MENTION = /\[\[([^\]]+)\]\]/g;
62021
63325
  /** Misses a note's mention linking may spend beyond its stored mentions (renamed or ambiguous refs). */
62022
63326
  const MENTION_LOOKUP_SLACK = 2;
@@ -62059,6 +63363,17 @@ function pageSummary(page, { refs, scopes }) {
62059
63363
  ...page.description ? { description: page.description } : {}
62060
63364
  };
62061
63365
  }
63366
+ /**
63367
+ * A page search hit: its summary, plus, when the body contains a matched word, a short excerpt around
63368
+ * it with every line numbered, the line it is centred on, and how many lines have a match.
63369
+ */
63370
+ function searchPageSummary(page, refs, words) {
63371
+ const hit = knowledgeBodyHit(page.body, words);
63372
+ return {
63373
+ ...pageSummary(page, refs),
63374
+ ...hit ?? {}
63375
+ };
63376
+ }
62062
63377
  function noteSummary(note, mentions) {
62063
63378
  return {
62064
63379
  id: note.id,
@@ -62156,7 +63471,7 @@ async function requireAudienceAuthority(run, audience) {
62156
63471
  function searchTool(host) {
62157
63472
  return createTool({
62158
63473
  id: "knowledge_search",
62159
- description: "Search the knowledge this run can read: page names, descriptions, bodies and notes. Optional `scope` narrows to pages in those scopes.",
63474
+ description: "Search the knowledge this run can read: page names, descriptions, bodies and notes. A page hit whose body contains a matched word carries a short `snippet` around it, numbered line by line like knowledge_read (with the heading it sits under when that is out of view), the `line` the snippet is centred on and `matchingLines`, how many lines match; read from that line, or with `match`, before relying on a snippet. Optional `scope` narrows to pages in those scopes.",
62160
63475
  inputSchema: {
62161
63476
  type: "object",
62162
63477
  properties: {
@@ -62182,7 +63497,7 @@ function searchTool(host) {
62182
63497
  const run = await start(host, context);
62183
63498
  const scopeIds = scope ? (await readableScopes(run, scope)).map((page) => page.id) : void 0;
62184
63499
  const max = limitOf(limit);
62185
- const words = query.replace(/["`\u201C\u201D]/g, " ").trim();
63500
+ const words = knowledgeSearchQuery(query);
62186
63501
  const lexical = words ? await run.storage.searchPages({
62187
63502
  query: words,
62188
63503
  read: run.read,
@@ -62235,16 +63550,22 @@ function searchTool(host) {
62235
63550
  }
62236
63551
  const addresses = await pageRefs(run, hits.map((hit) => hit.page));
62237
63552
  const mentionCache = /* @__PURE__ */ new Map();
63553
+ const results = await Promise.all(hits.map(async (hit) => hit.type === "page" ? {
63554
+ type: "page",
63555
+ page: searchPageSummary(hit.page, addresses, words)
63556
+ } : {
63557
+ type: "note",
63558
+ page: pageSummary(hit.page, addresses),
63559
+ note: noteSummary(hit.note, await noteMentions(run, hit.note, mentionCache))
63560
+ }));
63561
+ const matched = results.some((result) => result.type === "page" && "line" in result.page);
63562
+ const readWords = knowledgeSearchWords(words);
63563
+ const readMatch = readWords.length <= READ_MATCH_MAX_WORDS ? JSON.stringify(readWords) : `${JSON.stringify(readWords.slice(0, READ_MATCH_MAX_WORDS))} (the first ${READ_MATCH_MAX_WORDS} of your ${readWords.length} search words; search again with fewer words to see the rest)`;
63564
+ const readOn = matched ? [`snippet: each page hit's \`line\` is the line its snippet is centred on (numbered as in the snippet), and \`matchingLines\` how many lines have a matched word. Pass the hit's ref as page to read on from that line with knowledge_read { page, from: { line } }, or to see every match with knowledge_read { page, match: ${readMatch} }.`] : [];
63565
+ const more = [...hits.length === 0 ? [`results: no page or note contains any word of ${JSON.stringify(words || query)}. Search again with different key words, or browse with knowledge_list.`] : hits.length === max ? [max < MAX_LIMIT ? `results: showing the top ${max}. If none of these is what you need, narrow the query, raise the limit (up to ${MAX_LIMIT}), or browse with knowledge_list.` : `results: showing the top ${max}, the most one search returns. Narrow the query or scope, or browse with knowledge_list.`] : [], ...readOn];
62238
63566
  return {
62239
- results: await Promise.all(hits.map(async (hit) => hit.type === "page" ? {
62240
- type: "page",
62241
- page: pageSummary(hit.page, addresses)
62242
- } : {
62243
- type: "note",
62244
- page: pageSummary(hit.page, addresses),
62245
- note: noteSummary(hit.note, await noteMentions(run, hit.note, mentionCache))
62246
- })),
62247
- ...hits.length === 0 ? { more: [`results: no page or note contains any word of ${JSON.stringify(words || query)}. Search again with different key words, or browse with knowledge_list.`] } : hits.length === max ? { more: [max < MAX_LIMIT ? `results: showing the top ${max}. If none of these is what you need, narrow the query, raise the limit (up to ${MAX_LIMIT}), or browse with knowledge_list.` : `results: showing the top ${max}, the most one search returns. Narrow the query or scope, or browse with knowledge_list.`] } : {}
63567
+ results,
63568
+ ...more.length ? { more } : {}
62248
63569
  };
62249
63570
  }
62250
63571
  });
@@ -62429,7 +63750,7 @@ function readTool(host, canEdit) {
62429
63750
  minLength: 1
62430
63751
  },
62431
63752
  minItems: 1,
62432
- maxItems: 10
63753
+ maxItems: READ_MATCH_MAX_WORDS
62433
63754
  }],
62434
63755
  description: "Like grep: return only the lines that contain this term, or any of these terms (case-insensitive), as numbered lines with the range each covers."
62435
63756
  },
@@ -63306,6 +64627,7 @@ function decodeActivityCursor(value) {
63306
64627
  try {
63307
64628
  const cursor = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
63308
64629
  if (cursor?.v === 1 && Array.isArray(cursor.before) && typeof cursor.before[0] === "string" && typeof cursor.before[1] === "string" && !Number.isNaN(new Date(cursor.before[0]).getTime()) && typeof cursor.bind === "string") return cursor;
64630
+ if (cursor?.v === 2 && (cursor.after === null || typeof cursor.after === "string" && cursor.after.length > 0) && typeof cursor.bind === "string") return cursor;
63309
64631
  } catch {}
63310
64632
  throw new Error("knowledge_activity: that cursor did not come from knowledge_activity.");
63311
64633
  }
@@ -63313,7 +64635,7 @@ function activityTool(host) {
63313
64635
  const maxTokens = maxTokensOf(host);
63314
64636
  return createTool({
63315
64637
  id: "knowledge_activity",
63316
- description: `What changed in Knowledge over a period: page creates, edits, moves, merges and deletes, and notes added, restamped, removed or restored, newest first, with who made each change. Give \`since\` and/or \`until\` (a date like 2026-07-01, or a date-time with a zone like 2026-07-01T09:30:00Z; at least one); \`from\` narrows it to one page or scope. A note entry shows the note's current text (marked \`current\`), not its text when the change happened; a removed note shows no text. One result holds at most \`limit\` changes and about ${maxTokens.toLocaleString("en-US")} tokens of them; when it stops early, \`more\` is true and \`cursor\` continues (pass the same since, until and from).`,
64638
+ description: `What changed in Knowledge over a period: page creates, edits, moves, merges and deletes, and notes added, restamped, removed or restored, newest first (or oldest first with \`order: "oldest"\`), with who made each change. Give \`since\` and/or \`until\` (a date like 2026-07-01, or a date-time with a zone like 2026-07-01T09:30:00Z; at least one); \`from\` narrows it to one page or scope. A note entry shows the note's current text (marked \`current\`), not its text when the change happened; a removed note shows no text. One result holds at most \`limit\` changes and about ${maxTokens.toLocaleString("en-US")} tokens of them; when it stops early, \`more\` is true and \`cursor\` continues (pass the same since, until, from and order). Oldest first always returns a \`cursor\`, also when it has caught up or found nothing yet: keep it, and a later call with it returns only the changes it has not listed, none missed or repeated. The exception: a page or note that becomes readable later (moved into view, or a note restamped or restored) keeps its earlier changes behind that cursor, and they are not returned. The move, restamp or restore itself comes through as a change of the page it changed: without \`from\`, or with \`from\` on that page or the scope it is in now, but not with \`from\` on another page (such as one under a moved folder). To see what came before it, read that page newest first with \`from\`.`,
63317
64639
  inputSchema: {
63318
64640
  type: "object",
63319
64641
  properties: {
@@ -63332,6 +64654,11 @@ function activityTool(host) {
63332
64654
  minLength: 1,
63333
64655
  description: `Only changes to this page or scope. ${pageRefDescription}`
63334
64656
  },
64657
+ order: {
64658
+ type: "string",
64659
+ enum: ["newest", "oldest"],
64660
+ description: "newest (default) lists the latest changes first; oldest lists them roughly in the order they happened, in an order where a change still being saved shows up on a later call instead of being skipped."
64661
+ },
63335
64662
  limit: {
63336
64663
  type: "integer",
63337
64664
  minimum: 1,
@@ -63341,20 +64668,24 @@ function activityTool(host) {
63341
64668
  cursor: {
63342
64669
  type: "string",
63343
64670
  minLength: 1,
63344
- description: "The previous result's cursor, for the changes after it (pass the same since, until and from)."
64671
+ description: "The previous result's cursor, for the changes after it (pass the same since, until, from and order)."
63345
64672
  }
63346
64673
  },
63347
64674
  additionalProperties: false
63348
64675
  },
63349
64676
  execute: async (input, context) => {
63350
64677
  const args = input;
64678
+ const oldest = args.order === "oldest";
63351
64679
  if (args.since === void 0 && args.until === void 0) throw new Error("knowledge_activity needs since or until, e.g. since: \"2026-07-01\".");
63352
64680
  const since = args.since === void 0 ? void 0 : activityDate("since", args.since);
63353
64681
  const until = args.until === void 0 ? void 0 : activityDate("until", args.until);
63354
64682
  if (since && until && since.getTime() >= until.getTime()) throw new Error("knowledge_activity: since must be earlier than until.");
63355
64683
  const limit = Math.min(Math.max(args.limit ?? ACTIVITY_DEFAULT_LIMIT, 1), ACTIVITY_MAX_LIMIT);
63356
- if (!(await host.getStorage()).getCapabilities().supportsActivityDateRange) throw new KnowledgeUnsupportedCapabilityError("listPageActivity date range");
64684
+ const capabilities = (await host.getStorage()).getCapabilities();
64685
+ if (!capabilities.supportsActivityDateRange) throw new KnowledgeUnsupportedCapabilityError("listPageActivity date range");
64686
+ if (oldest && !capabilities.supportsActivityAscending) throw new KnowledgeUnsupportedCapabilityError("listPageActivity oldest first");
63357
64687
  const cursor = args.cursor === void 0 ? void 0 : decodeActivityCursor(args.cursor);
64688
+ if (cursor && cursor.v === 2 !== oldest) throw new Error("knowledge_activity: this cursor came from a call with different since, until, from or order. Pass the same ones as the call that returned it.");
63358
64689
  const run = await start(host, context);
63359
64690
  const origin = args.from ? await run.pageOrCloseMatches(args.from) : void 0;
63360
64691
  const filter = origin ? origin.isScope ? { scopeId: origin.id } : { pageId: origin.id } : {};
@@ -63362,15 +64693,24 @@ function activityTool(host) {
63362
64693
  since?.toISOString(),
63363
64694
  until?.toISOString(),
63364
64695
  "scopeId" in filter ? filter.scopeId : void 0,
63365
- "pageId" in filter ? filter.pageId : void 0
64696
+ "pageId" in filter ? filter.pageId : void 0,
64697
+ ...oldest ? ["oldest"] : []
63366
64698
  ]);
63367
- if (cursor && cursor.bind !== bind) throw new Error("knowledge_activity: this cursor came from a call with different since, until or from. Pass the same ones as the call that returned it.");
64699
+ if (cursor && cursor.bind !== bind) throw new Error("knowledge_activity: this cursor came from a call with different since, until, from or order. Pass the same ones as the call that returned it.");
63368
64700
  const entries = [];
63369
64701
  let used = 0;
63370
- let position = cursor ? {
64702
+ let position = !cursor ? void 0 : cursor.v === 2 ? cursor.after ?? void 0 : {
63371
64703
  createdAt: new Date(cursor.before[0]),
63372
64704
  id: cursor.before[1]
63373
- } : void 0;
64705
+ };
64706
+ const passed = (event) => {
64707
+ if (!oldest) return {
64708
+ createdAt: event.createdAt,
64709
+ id: event.id
64710
+ };
64711
+ if (!event.position) throw new Error("knowledge_activity: the store returned an oldest-first change without a position.");
64712
+ return event.position;
64713
+ };
63374
64714
  let more = false;
63375
64715
  let stopped = false;
63376
64716
  let batches = 0;
@@ -63382,7 +64722,12 @@ function activityTool(host) {
63382
64722
  ...filter,
63383
64723
  ...since ? { since } : {},
63384
64724
  ...until ? { until } : {},
63385
- ...position ? { before: position } : {},
64725
+ ...typeof position === "string" ? {
64726
+ order: "asc",
64727
+ after: position
64728
+ } : {},
64729
+ ...position && typeof position !== "string" ? { before: position } : {},
64730
+ ...oldest && !position ? { order: "asc" } : {},
63386
64731
  limit: limit - entries.length
63387
64732
  });
63388
64733
  more = batch.nextCursor !== void 0;
@@ -63410,10 +64755,7 @@ function activityTool(host) {
63410
64755
  const page = pages.get(event.pageId);
63411
64756
  const note = event.noteId ? notes.get(event.noteId) : void 0;
63412
64757
  if (!page || event.noteId && !note) {
63413
- position = {
63414
- createdAt: event.createdAt,
63415
- id: event.id
63416
- };
64758
+ position = passed(event);
63417
64759
  continue;
63418
64760
  }
63419
64761
  const entry = {
@@ -63455,10 +64797,7 @@ function activityTool(host) {
63455
64797
  }
63456
64798
  entries.push(entry);
63457
64799
  used += size;
63458
- position = {
63459
- createdAt: event.createdAt,
63460
- id: event.id
63461
- };
64800
+ position = passed(event);
63462
64801
  if (entries.length >= limit) break;
63463
64802
  }
63464
64803
  if (!more) break;
@@ -63472,7 +64811,14 @@ function activityTool(host) {
63472
64811
  name: origin.name
63473
64812
  } } : {},
63474
64813
  changes: entries,
63475
- ...hasMore && position ? {
64814
+ ...oldest ? {
64815
+ ...hasMore ? { more: true } : {},
64816
+ cursor: encodeActivityCursor({
64817
+ v: 2,
64818
+ after: typeof position === "string" ? position : null,
64819
+ bind
64820
+ })
64821
+ } : hasMore && position && typeof position !== "string" ? {
63476
64822
  more: true,
63477
64823
  cursor: encodeActivityCursor({
63478
64824
  v: 1,
@@ -70676,55 +72022,6 @@ function armRunDeadline(controller, deadline) {
70676
72022
  timer.unref?.();
70677
72023
  return timer;
70678
72024
  }
70679
- // src/agent/durable/constants.ts
70680
- const DURABLE_STOP_WHEN_ERROR_ID = "DURABLE_AGENT_STOP_WHEN_FAILED";
70681
- const REJECT_STREAM_ERROR = Symbol("mastra.durable.rejectStreamError");
70682
- function markErrorForStreamRejection(error) {
70683
- error[REJECT_STREAM_ERROR] = true;
70684
- return error;
70685
- }
70686
- function shouldRejectStream(error) {
70687
- return error[REJECT_STREAM_ERROR] === true;
70688
- }
70689
- /**
70690
- * Default values for durable agent execution
70691
- */
70692
- const DurableAgentDefaults = {
70693
- /** Default maximum number of agentic loop iterations */
70694
- MAX_STEPS: 5,
70695
- /**
70696
- * Default tool call concurrency.
70697
- * Applied by `resolveDurableToolCallConcurrency` when a run doesn't
70698
- * configure `toolCallConcurrency`. Approval / suspend-capable tool sets
70699
- * always run sequentially (concurrency: 1) regardless of this value.
70700
- */
70701
- TOOL_CALL_CONCURRENCY: 10
70702
- };
70703
- /**
70704
- * Step IDs used in the durable agentic workflow
70705
- */
70706
- const DurableStepIds = {
70707
- /** LLM execution step */
70708
- LLM_EXECUTION: "durable-llm-execution",
70709
- /** Tool call step */
70710
- TOOL_CALL: "durable-tool-call",
70711
- /** LLM mapping step (combines results) */
70712
- LLM_MAPPING: "durable-llm-mapping",
70713
- /** Agentic execution workflow (one iteration) */
70714
- AGENTIC_EXECUTION: "durable-agentic-execution",
70715
- /** Full agentic loop workflow */
70716
- AGENTIC_LOOP: "durable-agentic-loop",
70717
- /** Scorer execution step */
70718
- SCORER_EXECUTION: "durable-scorer-execution",
70719
- /** isTaskComplete evaluation step */
70720
- IS_TASK_COMPLETE: "durable-is-task-complete"
70721
- };
70722
- const RECOVER_ALREADY_IN_PROGRESS_ERROR_ID = "DURABLE_AGENT_RECOVER_ALREADY_IN_PROGRESS";
70723
- const RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID = "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND";
70724
- const RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID = "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE";
70725
- const RECOVER_RUN_SUSPENDED_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_SUSPENDED";
70726
- const RECOVER_RUN_NOT_ACTIVE_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_NOT_ACTIVE";
70727
- const RECOVER_SHUTDOWN_ERROR_ID = "DURABLE_AGENT_RECOVER_SHUTDOWN";
70728
72025
  // src/agent/durable/durable-stream-until-idle.ts
70729
72026
  /**
70730
72027
  * Run `DurableAgent.streamUntilIdle` (or `DurableAgent.stream({ untilIdle })`).
@@ -70841,6 +72138,165 @@ async function runResumeDurableStreamUntilIdle(agent, runId, resumeData, streamO
70841
72138
  }
70842
72139
  });
70843
72140
  }
72141
+ // src/agent/durable/segment-spans.ts
72142
+ /**
72143
+ * Which AGENT_RUN + MODEL_GENERATION pair a durable execution reports under.
72144
+ *
72145
+ * A segment is one execution of the durable loop: the run's start, or a resume or a recovery, up
72146
+ * to its suspension or its end. Each segment has its own span pair and ends its own spans once.
72147
+ * The run's first pair travels in the workflow input. A resume or recovery opens the next pair and
72148
+ * carries it on the request context, which every engine hands to every step and persists with the
72149
+ * run, so the worker that finishes a segment ends that segment's spans wherever it runs.
72150
+ */
72151
+ /** The wire form of the pair a resume or recovery opened. */
72152
+ function openedSegment(agentSpan, modelSpan) {
72153
+ return {
72154
+ agentSpanData: agentSpan.snapshot?.() ?? agentSpan.exportSpan(),
72155
+ modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),
72156
+ stepParentId: resolveExportedSpanId(modelSpan ?? agentSpan)
72157
+ };
72158
+ }
72159
+ function hasRawAccess(target) {
72160
+ return typeof target.setRaw === "function";
72161
+ }
72162
+ function readCarrier(requestContext, runId) {
72163
+ const all = requestContext?.getRaw?.(MASTRA_DURABLE_SEGMENTS_KEY);
72164
+ if (!all || typeof all !== "object") return void 0;
72165
+ const segment = all[runId];
72166
+ if (segment === null) return null;
72167
+ return typeof segment?.agentSpanData?.id === "string" ? segment : void 0;
72168
+ }
72169
+ /**
72170
+ * Record the pair a resume or recovery opened for `runId`, or `null` when it opened none, on the
72171
+ * request context it hands the engine. Keyed by runId so a delegated durable sub-agent sharing the
72172
+ * caller's context cannot overwrite the parent's segment.
72173
+ */
72174
+ function carrySegmentSpans(target, runId, segment) {
72175
+ const current = hasRawAccess(target) ? target.getRaw(MASTRA_DURABLE_SEGMENTS_KEY) : target[MASTRA_DURABLE_SEGMENTS_KEY];
72176
+ const next = {
72177
+ ...current && typeof current === "object" ? current : {},
72178
+ [runId]: segment
72179
+ };
72180
+ if (hasRawAccess(target)) target.setRaw(MASTRA_DURABLE_SEGMENTS_KEY, next);
72181
+ else target[MASTRA_DURABLE_SEGMENTS_KEY] = next;
72182
+ }
72183
+ /**
72184
+ * The pair the current execution reports under: the one a resume or recovery carried for `runId`,
72185
+ * else the run's first pair from `state` (the workflow input or the loop state). A carried `null`
72186
+ * means the execution opened no spans, so its steps end none. `carried` tells the two apart.
72187
+ * `live` is this process's registry entry, the fallback when the context lost the carried pair.
72188
+ */
72189
+ function segmentSpanData(requestContext, runId, state, live) {
72190
+ const carried = readCarrier(requestContext, runId);
72191
+ if (carried === null) return { carried: true };
72192
+ if (carried) return {
72193
+ ...carried,
72194
+ carried: true
72195
+ };
72196
+ if (live?.resumeAgentSpan) return {
72197
+ ...openedSegment(live.resumeAgentSpan, live.resumeModelSpan),
72198
+ carried: true
72199
+ };
72200
+ return {
72201
+ agentSpanData: state.agentSpanData,
72202
+ modelSpanData: state.modelSpanData,
72203
+ carried: false
72204
+ };
72205
+ }
72206
+ /**
72207
+ * The generations whose MODEL_STEP the execution that persisted `requestContext` left open: its own
72208
+ * pair's, plus those it was itself finishing after an earlier crash. Every other step was ended by
72209
+ * the suspension before a resume. Undefined when that execution carried no pair.
72210
+ */
72211
+ function openStepsOfCrashedSegment(requestContext, runId) {
72212
+ const crashed = (requestContext?.[MASTRA_DURABLE_SEGMENTS_KEY])?.[runId];
72213
+ if (!crashed?.stepParentId || crashed.adoptsOpenSteps && !crashed.openStepsOf) return void 0;
72214
+ return [crashed.stepParentId, ...crashed.openStepsOf ?? []];
72215
+ }
72216
+ /** The live span behind `data` when this process holds it, so it is ended in place; otherwise undefined. */
72217
+ function liveSegmentSpan(data, ...candidates) {
72218
+ return data ? candidates.find((span) => span?.id === data.id) : void 0;
72219
+ }
72220
+ /**
72221
+ * Whether `segment` may end the MODEL_STEP `stepSpanData`. The run's first execution opened every
72222
+ * step it sees. A resumed one ends only the steps opened under its own pair: the step that
72223
+ * suspended was ended by that suspension. A recovered one also finishes the step its crashed
72224
+ * execution left open.
72225
+ */
72226
+ function segmentOwnsStep(segment, stepSpanData) {
72227
+ if (!segment.carried) return true;
72228
+ const parent = stepSpanData?.parentSpanId ?? void 0;
72229
+ if (segment.openStepsOf) return parent !== void 0 && [segment.stepParentId, ...segment.openStepsOf].includes(parent);
72230
+ if (segment.adoptsOpenSteps) return segment.endedStepsOf === void 0 || parent !== segment.endedStepsOf;
72231
+ return parent === segment.stepParentId;
72232
+ }
72233
+ /** Longer than any pause between the calls of one step; a key is only written when they run side by side. */
72234
+ const SEGMENT_END_TTL_MS = 864e5;
72235
+ /**
72236
+ * Whether `outcome` ends the spans of the run's first segment. Behind a broker, a tool call that suspends and one
72237
+ * beside it that fails the run are in different processes, and both end the same spans, so the first one to claim
72238
+ * them does. Undefined when no claim can be made, and in one process only the suspension asks.
72239
+ */
72240
+ async function claimSegmentEnd({ mastra, requestContext, runId, iterationCount, outcome }) {
72241
+ try {
72242
+ if (!mastra || !reachesOtherProcesses(mastra.pubsub)) return true;
72243
+ const claim = getExecutionClaim(requestContext, runId);
72244
+ const leases = resolveLeaseProvider(mastra.pubsub);
72245
+ if (claim?.generation === void 0 || leases === NoopLeaseProvider) return void 0;
72246
+ const key = `mastra:durable-segment-end:v1:${JSON.stringify([
72247
+ runId,
72248
+ claim.executionId,
72249
+ iterationCount
72250
+ ])}`;
72251
+ const { acquired, owner } = await leases.acquireLease(key, outcome, SEGMENT_END_TTL_MS);
72252
+ return acquired || (owner ? false : void 0);
72253
+ } catch {
72254
+ return;
72255
+ }
72256
+ }
72257
+ /** A MODEL_STEP the run's deadline stopped is interrupted, as on the regular agent; the run itself hit a limit. */
72258
+ function stepFailure(failure) {
72259
+ return isMastraTimeoutError(failure.error) ? {
72260
+ ...failure,
72261
+ outcome: "interrupted"
72262
+ } : failure;
72263
+ }
72264
+ /**
72265
+ * Whether a tool call that suspended beside the failed one already ended the spans of the segment. Only the failed
72266
+ * iteration's steps show it, so the settling engine takes it to the run's own failure as a carried `null` segment.
72267
+ */
72268
+ function segmentEndedBySuspension(segment, steps) {
72269
+ const { output, suspendPayload } = steps[DurableStepIds.TOOL_CALL] ?? {};
72270
+ return [suspendPayload?.__workflow_meta?.foreachOutput, output].flat().some((call) => call?.status === "suspended") && segmentOwnsStep(segment, steps[DurableStepIds.LLM_EXECUTION]?.output?.stepSpanData);
72271
+ }
72272
+ /**
72273
+ * End what a failed execution left open, from the facts the run carries, where the process that settles the
72274
+ * failure may hold none of the run's live spans. An iteration's failure ends its MODEL_STEP; the run's failure
72275
+ * ends the MODEL_GENERATION and AGENT_RUN its segment reports under. Never throws.
72276
+ */
72277
+ function endFailedSegmentSpans({ mastra, requestContext, runId, state, steps, error, live, firstPairOnly }) {
72278
+ try {
72279
+ const observability = mastra?.observability?.getSelectedInstance({ requestContext });
72280
+ if (!observability || !("input" in steps) || steps["map-final-output"]?.status === "success") return;
72281
+ const segment = segmentSpanData(requestContext, runId, state, live);
72282
+ const failure = {
72283
+ error,
72284
+ ...executionFailureTermination(error),
72285
+ endSpan: true
72286
+ };
72287
+ if (state.iterationCount !== void 0) {
72288
+ const stepSpanData = steps[DurableStepIds.LLM_EXECUTION]?.output?.stepSpanData;
72289
+ if (!stepSpanData || steps[DurableStepIds.LLM_MAPPING]?.status === "success") return;
72290
+ if (!segmentOwnsStep(segment, stepSpanData) || segmentEndedBySuspension(segment, steps)) return;
72291
+ (liveSegmentSpan(stepSpanData, live?.openStepSpan) ?? observability.rebuildSpan(stepSpanData)).error(stepFailure(failure));
72292
+ return;
72293
+ }
72294
+ if (firstPairOnly && segment.carried) return;
72295
+ const { modelSpanData, agentSpanData } = segment;
72296
+ if (modelSpanData) (liveSegmentSpan(modelSpanData, live?.resumeModelSpan, live?.modelSpan) ?? observability.rebuildSpan(modelSpanData)).error(failure);
72297
+ if (agentSpanData) (liveSegmentSpan(agentSpanData, live?.resumeAgentSpan, live?.agentSpan) ?? observability.rebuildSpan(agentSpanData)).error(failure);
72298
+ } catch {}
72299
+ }
70844
72300
  // ../_internal-core/dist/durable/index.js
70845
72301
  function toolModelOutput(result) {
70846
72302
  return typeof result === "string" ? {
@@ -71800,87 +73256,6 @@ function createDurableAgentStream(options) {
71800
73256
  ready
71801
73257
  };
71802
73258
  }
71803
- // src/agent/durable/segment-spans.ts
71804
- /**
71805
- * Which AGENT_RUN + MODEL_GENERATION pair a durable execution reports under.
71806
- *
71807
- * A segment is one execution of the durable loop: the run's start, or a resume or a recovery, up
71808
- * to its suspension or its end. Each segment has its own span pair and ends its own spans once.
71809
- * The run's first pair travels in the workflow input. A resume or recovery opens the next pair and
71810
- * carries it on the request context, which every engine hands to every step and persists with the
71811
- * run, so the worker that finishes a segment ends that segment's spans wherever it runs.
71812
- */
71813
- /** The wire form of the pair a resume or recovery opened. */
71814
- function openedSegment(agentSpan, modelSpan) {
71815
- return {
71816
- agentSpanData: agentSpan.snapshot?.() ?? agentSpan.exportSpan(),
71817
- modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),
71818
- stepParentId: resolveExportedSpanId(modelSpan ?? agentSpan)
71819
- };
71820
- }
71821
- function hasRawAccess(target) {
71822
- return typeof target.setRaw === "function";
71823
- }
71824
- function readCarrier(requestContext, runId) {
71825
- const all = requestContext?.getRaw?.(MASTRA_DURABLE_SEGMENTS_KEY);
71826
- if (!all || typeof all !== "object") return void 0;
71827
- const segment = all[runId];
71828
- if (segment === null) return null;
71829
- return typeof segment?.agentSpanData?.id === "string" ? segment : void 0;
71830
- }
71831
- /**
71832
- * Record the pair a resume or recovery opened for `runId`, or `null` when it opened none, on the
71833
- * request context it hands the engine. Keyed by runId so a delegated durable sub-agent sharing the
71834
- * caller's context cannot overwrite the parent's segment.
71835
- */
71836
- function carrySegmentSpans(target, runId, segment) {
71837
- const current = hasRawAccess(target) ? target.getRaw(MASTRA_DURABLE_SEGMENTS_KEY) : target[MASTRA_DURABLE_SEGMENTS_KEY];
71838
- const next = {
71839
- ...current && typeof current === "object" ? current : {},
71840
- [runId]: segment
71841
- };
71842
- if (hasRawAccess(target)) target.setRaw(MASTRA_DURABLE_SEGMENTS_KEY, next);
71843
- else target[MASTRA_DURABLE_SEGMENTS_KEY] = next;
71844
- }
71845
- /**
71846
- * The pair the current execution reports under: the one a resume or recovery carried for `runId`,
71847
- * else the run's first pair from `state` (the workflow input or the loop state). A carried `null`
71848
- * means the execution opened no spans, so its steps end none. `carried` tells the two apart.
71849
- * `live` is this process's registry entry, the fallback when the context lost the carried pair.
71850
- */
71851
- function segmentSpanData(requestContext, runId, state, live) {
71852
- const carried = readCarrier(requestContext, runId);
71853
- if (carried === null) return { carried: true };
71854
- if (carried) return {
71855
- ...carried,
71856
- carried: true
71857
- };
71858
- if (live?.resumeAgentSpan) return {
71859
- ...openedSegment(live.resumeAgentSpan, live.resumeModelSpan),
71860
- carried: true
71861
- };
71862
- return {
71863
- agentSpanData: state.agentSpanData,
71864
- modelSpanData: state.modelSpanData,
71865
- carried: false
71866
- };
71867
- }
71868
- /** The live span behind `data` when this process holds it, so it is ended in place; otherwise undefined. */
71869
- function liveSegmentSpan(data, ...candidates) {
71870
- return data ? candidates.find((span) => span?.id === data.id) : void 0;
71871
- }
71872
- /**
71873
- * Whether `segment` may end the MODEL_STEP `stepSpanData`. The run's first execution opened every
71874
- * step it sees. A resumed one ends only the steps opened under its own pair: the step that
71875
- * suspended was ended by that suspension. A recovered one also finishes the step its crashed
71876
- * execution left open.
71877
- */
71878
- function segmentOwnsStep(segment, stepSpanData) {
71879
- if (!segment.carried) return true;
71880
- const parent = stepSpanData?.parentSpanId ?? void 0;
71881
- if (segment.adoptsOpenSteps) return segment.endedStepsOf === void 0 || parent !== segment.endedStepsOf;
71882
- return parent === segment.stepParentId;
71883
- }
71884
73259
  // src/agent/durable/utils/run-message-list.ts
71885
73260
  /** The id generator does not survive the serialize/deserialize round-trip a durable run makes on every step. */
71886
73261
  function createRunMessageList({ mastra, threadId, resourceId }) {
@@ -72371,7 +73746,7 @@ async function resolveRuntimeDependencies(options) {
72371
73746
  else if (mastra) try {
72372
73747
  const agent = await resolveRunAgent(mastra, agentId, runId, input.agentVersionId);
72373
73748
  rebuiltAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
72374
- const resolveRequestContext = restoreRequestContext$1(input.requestContextEntries, options.requestContext);
73749
+ const resolveRequestContext = restoreRequestContext(input.requestContextEntries, options.requestContext);
72375
73750
  backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
72376
73751
  tools = await agent.getToolsForExecution({
72377
73752
  runId,
@@ -72492,7 +73867,7 @@ async function rebuildRunToolsFromMastra(options) {
72492
73867
  const agent = await resolveRunAgent(mastra, agentId, runId, options.agentVersionId);
72493
73868
  agentResolved = true;
72494
73869
  const processorAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
72495
- const resolveRequestContext = restoreRequestContext$1(requestContextEntries, requestContext);
73870
+ const resolveRequestContext = restoreRequestContext(requestContextEntries, requestContext);
72496
73871
  const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
72497
73872
  const tools = await agent.getToolsForExecution({
72498
73873
  runId,
@@ -72532,12 +73907,17 @@ async function rebuildRunToolsFromMastra(options) {
72532
73907
  agent: processorAgent,
72533
73908
  ...backgroundTasks,
72534
73909
  ...rebuiltProcessors,
72535
- ...options.rehydrateProcessors ? { requestContext: resolveRequestContext } : {}
73910
+ ...options.rehydrateProcessors ? {
73911
+ requestContext: resolveRequestContext,
73912
+ requestContextRebuilt: true
73913
+ } : {}
72536
73914
  };
72537
73915
  existing = getRunRegistryEntry(runId, mastra);
72538
73916
  if (existing) {
72539
- const needsProcessorPipeline = !existing.outputProcessors || !existing.processorStates;
72540
- if (options.rehydrateProcessors && (existing.isPlaceholder && needsProcessorPipeline || !existing.requestContext)) existing.requestContext = resolveRequestContext;
73917
+ if (options.rehydrateProcessors && !existing.requestContext) {
73918
+ existing.requestContext = resolveRequestContext;
73919
+ existing.requestContextRebuilt = true;
73920
+ }
72541
73921
  const registryModel = existing.model;
72542
73922
  if (!(existing.isPlaceholder !== true && !!registryModel && registryModel.__metadataOnly !== true && (existing.baseTools !== void 0 || existing.tools !== void 0)) && Object.keys(existing.tools ?? {}).length === 0) existing.tools = tools;
72543
73923
  existing.workspace ??= workspace;
@@ -72935,9 +74315,9 @@ function runTranscriptRefs(params) {
72935
74315
  }
72936
74316
  /** The run's memory: the live instance in this process, else re-resolved from the agent. */
72937
74317
  async function runMemory(params, run) {
72938
- const memory = run.runId ? getRunRegistryEntry(run.runId, params.mastra)?.memory : void 0;
72939
- if (memory || !params.mastra || !run.agentId) return memory;
72940
- return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: restoreRequestContext$1(run.requestContextEntries, params.requestContext) });
74318
+ const entry = run.runId ? getRunRegistryEntry(run.runId, params.mastra) : void 0;
74319
+ if (entry?.memory || !params.mastra || !run.agentId) return entry?.memory;
74320
+ return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: restoreRequestContext(run.requestContextEntries, params.requestContext, getLiveRunRequestContext(entry, run.runId, params.requestContext)) });
72941
74321
  }
72942
74322
  /** The most recent transcript in a snapshot: workflow state, else the last step output carrying one. */
72943
74323
  function latestMessageListState(snapshot) {
@@ -72956,7 +74336,8 @@ function latestMessageListState(snapshot) {
72956
74336
  return latest?.value;
72957
74337
  }
72958
74338
  // src/agent/durable/workflows/finalize-run.ts
72959
- function restoreRequestContext(entries, fallback) {
74339
+ function mergeRequestContextForFinalization(entries, fallback, liveRunContext) {
74340
+ if (liveRunContext) return liveRunContext;
72960
74341
  if (!entries) return fallback ?? new RequestContext();
72961
74342
  const restored = new RequestContext(fallback?.entries());
72962
74343
  for (const [key, value] of Object.entries(withoutLiveRequestKeys(entries))) restored.set(key, value);
@@ -73012,7 +74393,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73012
74393
  error
73013
74394
  });
73014
74395
  }
73015
- const effectiveRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext);
74396
+ const effectiveRequestContext = mergeRequestContextForFinalization(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext));
73016
74397
  if (!effectiveRequestContext.has("MastraMemory") && durableState?.threadId) effectiveRequestContext.set("MastraMemory", {
73017
74398
  thread: { id: durableState.threadId },
73018
74399
  resourceId: durableState.resourceId,
@@ -73029,16 +74410,18 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73029
74410
  const liveStructuredOutput = registryEntry?.structuredOutput;
73030
74411
  const structuredOutputSchema = liveStructuredOutput?.schema ?? (structuredOutput?.schema ? toLiveStructuredOutputSchema(structuredOutput.schema, structuredOutput.nullToUndefined) : void 0);
73031
74412
  let structuredOutputChunks;
74413
+ let object;
73032
74414
  const structuringParts = structuredOutput?.hasStructuringModel ? responseStreamParts(messageList) : void 0;
73033
74415
  if (structuredOutputSchema && (structuredOutputText.trim() || structuringParts?.length)) {
73034
74416
  const finishReason = outputResult?.finishReason;
73035
74417
  const truncated = finishReason === "length" || finishReason === "content-filter";
74418
+ const failed = finishReason === "abort" || finishReason === "error";
73036
74419
  const errorStrategy = liveStructuredOutput ? liveStructuredOutput.errorStrategy : structuredOutput?.errorStrategy;
73037
74420
  const fallbackValue = liveStructuredOutput ? liveStructuredOutput.fallbackValue : structuredOutput?.fallbackValue;
73038
74421
  let value;
73039
74422
  if (structuredOutput?.hasStructuringModel) {
73040
74423
  const structuringModel = liveStructuredOutput?.model ?? structuredOutput.structuringModelConfig?.originalConfig;
73041
- if (structuringModel && !truncated && !(finishReason === "abort" || finishReason === "error")) {
74424
+ if (structuringModel && !truncated && !failed) {
73042
74425
  structuredOutputChunks = await runStructuringPass({
73043
74426
  options: {
73044
74427
  ...liveStructuredOutput ?? {},
@@ -73064,6 +74447,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73064
74447
  value = result?.success ? result.value : errorStrategy === "fallback" ? fallbackValue : void 0;
73065
74448
  }
73066
74449
  const lastAssistantMessage = messageList.get.response.db().findLast((message) => message.role === "assistant" && !message.content?.metadata?.completionResult);
74450
+ object = failed ? void 0 : value;
73067
74451
  if (value !== void 0 && lastAssistantMessage) lastAssistantMessage.content.metadata = {
73068
74452
  ...lastAssistantMessage.content.metadata,
73069
74453
  structuredOutput: value
@@ -73256,6 +74640,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73256
74640
  titleGeneration,
73257
74641
  titleForStream,
73258
74642
  structuredOutputChunks,
74643
+ object,
73259
74644
  outputResultChunks
73260
74645
  };
73261
74646
  }
@@ -73305,9 +74690,9 @@ function deadlineMessageListState(entry, fallback) {
73305
74690
  * durable run. The run never reaches its finish step, so this runs over what the deadline saves
73306
74691
  * (see `deadlineMessageListState`), as the default loop's deadline pass does.
73307
74692
  */
73308
- async function runDurableDeadlineOutputPass({ runId, initData, messageListState, cutOffText, entry, mastra, tracingContext, logger }) {
74693
+ async function runDurableDeadlineOutputPass({ runId, initData, messageListState, cutOffText, entry, executionId, mastra, tracingContext, logger }) {
73309
74694
  const durableState = initData.state;
73310
- const requestContext = restoreRequestContext(initData.requestContextEntries, entry.requestContext);
74695
+ const requestContext = mergeRequestContextForFinalization(initData.requestContextEntries, void 0, getLiveRunRequestContext(entry, runId, void 0, executionId));
73311
74696
  if (!requestContext.has("MastraMemory") && durableState?.threadId) requestContext.set("MastraMemory", {
73312
74697
  thread: { id: durableState.threadId },
73313
74698
  resourceId: durableState.resourceId,
@@ -73750,11 +75135,17 @@ const accumulatedUsageSchema = z$1.object({
73750
75135
  reasoningTokens: z$1.number().optional()
73751
75136
  });
73752
75137
  /**
73753
- * Provider id and serving model of one response.
75138
+ * One response: the provider's id and model for it, the configured model that
75139
+ * answered, and the cost the provider reported for it.
73754
75140
  */
73755
75141
  const responseRecordSchema = z$1.object({
73756
75142
  id: z$1.string().optional(),
73757
- modelId: z$1.string().optional()
75143
+ modelId: z$1.string().optional(),
75144
+ servedBy: z$1.object({
75145
+ provider: z$1.string(),
75146
+ modelId: z$1.string()
75147
+ }).optional(),
75148
+ reportedCost: z$1.custom().optional()
73758
75149
  });
73759
75150
  /**
73760
75151
  * Schema for output from the durable agentic workflow
@@ -73814,6 +75205,8 @@ const baseIterationStateSchema = z$1.object({
73814
75205
  accumulatedSteps: z$1.array(z$1.any()).optional(),
73815
75206
  accumulatedUsage: accumulatedUsageSchema,
73816
75207
  usageAggregationVersion: z$1.literal(1).optional(),
75208
+ generationReportedUsage: accumulatedUsageSchema.optional(),
75209
+ generationReportedSteps: z$1.number().optional(),
73817
75210
  lastStepResult: z$1.any().optional(),
73818
75211
  deferredStepFinishChunk: z$1.any().optional(),
73819
75212
  backgroundTaskPending: z$1.boolean().optional(),
@@ -73836,6 +75229,7 @@ const baseIterationStateSchema = z$1.object({
73836
75229
  completionStartTime: z$1.coerce.date().optional(),
73837
75230
  timeToFirstTokenMs: z$1.number().optional(),
73838
75231
  lastResponse: responseRecordSchema.optional(),
75232
+ reportedCosts: z$1.array(z$1.custom().nullable()).optional(),
73839
75233
  tracingStopCause: z$1.enum(CONTINUATION_STOP_CAUSES).optional(),
73840
75234
  tracingTermination: z$1.custom().optional(),
73841
75235
  tracingDelegationFailure: z$1.custom().optional()
@@ -73888,7 +75282,7 @@ function buildStepRecord(executionOutput) {
73888
75282
  text: executionOutput.output.text,
73889
75283
  content: executionOutput.output.content,
73890
75284
  toolCalls: executionOutput.output.toolCalls,
73891
- toolResults: executionOutput.toolResults?.map(({ stepSpanData: _stepSpanData, tracingDelegationFailure: _tracingDelegationFailure, ...result }) => result),
75285
+ toolResults: executionOutput.toolResults?.map(({ stepSpanData: _stepSpanData, tracingDelegationFailure: _tracingDelegationFailure, response: _response, sideBySide: _sideBySide, ...result }) => result),
73892
75286
  usage: executionOutput.output.usage,
73893
75287
  finishReason: executionOutput.stepResult.reason,
73894
75288
  tripwire: executionOutput.stepResult.tripwire
@@ -73973,6 +75367,13 @@ function createBaseIterationStateUpdate(input) {
73973
75367
  accumulatedSteps: signalPreempted ? previousSteps : [...withReleasedToolResults(previousSteps, executionOutput.releasedToolResultIds), buildStepRecord(executionOutput)],
73974
75368
  accumulatedUsage: newUsage,
73975
75369
  usageAggregationVersion: signalPreempted ? currentState.usageAggregationVersion : 1,
75370
+ ...currentState.generationReportedUsage && executionOutput.suspensionReportedUsage && !isUsageIncomplete(newUsage) ? {
75371
+ generationReportedUsage: newUsage,
75372
+ generationReportedSteps: previousSteps.length + 1
75373
+ } : {
75374
+ generationReportedUsage: currentState.generationReportedUsage,
75375
+ generationReportedSteps: currentState.generationReportedSteps
75376
+ },
73976
75377
  lastStepResult,
73977
75378
  deferredStepFinishChunk: executionOutput.deferredStepFinishChunk,
73978
75379
  backgroundTaskPending: executionOutput.backgroundTaskPending,
@@ -73991,6 +75392,7 @@ function createBaseIterationStateUpdate(input) {
73991
75392
  timeToFirstTokenMs: executionOutput.timeToFirstTokenMs
73992
75393
  },
73993
75394
  lastResponse: signalPreempted ? currentState.lastResponse : executionOutput.response,
75395
+ reportedCosts: signalPreempted ? currentState.reportedCosts : [...previousSteps.map((_, index) => currentState.reportedCosts?.[index] ?? null), executionOutput.response?.reportedCost ?? null],
73994
75396
  tracingTermination: executionOutput.tracingTermination,
73995
75397
  tracingDelegationFailure: executionOutput.tracingDelegationFailure
73996
75398
  };
@@ -74068,6 +75470,14 @@ function resolveDurableToolCallConcurrency({ options, toolsMetadata, toolCalls }
74068
75470
  if (consideredTools.some((tool) => tool.hasSuspendSchema || tool.requireApproval)) return 1;
74069
75471
  return limit > 0 ? limit : DurableAgentDefaults.TOOL_CALL_CONCURRENCY;
74070
75472
  }
75473
+ /**
75474
+ * Whether the step's tool calls run at the same time. Then more than one can suspend in the same
75475
+ * execution, on workers that share no memory, so none of them can report the step's model usage
75476
+ * exactly once. The run's last execution reports it instead.
75477
+ */
75478
+ function toolCallsRunSideBySide(args) {
75479
+ return (args.toolCalls?.length ?? 0) > 1 && resolveDurableToolCallConcurrency(args) > 1;
75480
+ }
74071
75481
  // src/agent/durable/workflows/steps/background-task-check.ts
74072
75482
  const BG_CHECK_STEP_ID = `${DurableStepIds.AGENTIC_EXECUTION}-bg-task-check`;
74073
75483
  /**
@@ -75026,6 +76436,9 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
75026
76436
  }
75027
76437
  }
75028
76438
  spans.flushSpansLeftOpen(parts);
76439
+ if (!chunks.some((chunk) => chunk.type === "finish" || chunk.type === "step-finish")) {
76440
+ for (const part of parts) if (part.type === "text" || part.type === "reasoning") dropResponseItemIds(part);
76441
+ }
75029
76442
  const nonEmptyParts = parts.filter((p) => !(p.type === "text" && p.text === "" && p.providerMetadata == null));
75030
76443
  const finalParts = [];
75031
76444
  for (let i = 0; i < nonEmptyParts.length; i++) {
@@ -75046,6 +76459,16 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
75046
76459
  }
75047
76460
  }];
75048
76461
  }
76462
+ function dropResponseItemIds(part) {
76463
+ if (!part.providerMetadata) return;
76464
+ const providerMetadata = Object.fromEntries(Object.entries(part.providerMetadata).map(([provider, value]) => {
76465
+ if (!value || typeof value !== "object" || !("itemId" in value)) return [provider, value];
76466
+ const { itemId: _itemId, ...rest } = value;
76467
+ return [provider, rest];
76468
+ }).filter(([, value]) => !(value && typeof value === "object" && Object.keys(value).length === 0)));
76469
+ if (Object.keys(providerMetadata).length > 0) part.providerMetadata = providerMetadata;
76470
+ else delete part.providerMetadata;
76471
+ }
75049
76472
  // src/loop/workflows/agentic-execution/provider-tool-spans.ts
75050
76473
  function endPendingProviderToolSpan({ toolCallId, pending, parentSpan, result, logger }) {
75051
76474
  let span;
@@ -75116,6 +76539,20 @@ function resolveMaxProcessorRetries({ maxProcessorRetries, hasErrorProcessors, h
75116
76539
  }
75117
76540
  return 3;
75118
76541
  }
76542
+ // src/agent/durable/workflows/shared/reported-cost.ts
76543
+ /**
76544
+ * The part of a step's provider metadata that says what the call cost. The rest, such as search
76545
+ * grounding, can be large, and the loop state that carries this is saved with the run.
76546
+ */
76547
+ function reportedCost(metadata) {
76548
+ const cost = metadata?.gateway?.cost;
76549
+ const usage = metadata?.openrouter?.usage;
76550
+ if (cost === void 0 && usage === void 0) return void 0;
76551
+ return {
76552
+ ...cost === void 0 ? {} : { gateway: { cost } },
76553
+ ...usage === void 0 ? {} : { openrouter: { usage } }
76554
+ };
76555
+ }
75119
76556
  // src/agent/durable/workflows/steps/llm-execution.ts
75120
76557
  /**
75121
76558
  * Detect a run-level budget expiry (`modelSettings.timeout.totalMs`, #21724
@@ -75267,12 +76704,13 @@ function createDurableLLMExecutionStep(_options) {
75267
76704
  inputSchema: durableLLMInputSchema,
75268
76705
  outputSchema: durableLLMOutputSchema,
75269
76706
  execute: withStepLifetime(async (params, stepLifetime) => {
75270
- const { inputData, mastra, tracingContext, requestContext, abortSignal } = params;
76707
+ const { inputData, mastra, tracingContext, abortSignal } = params;
75271
76708
  const ownership = getExecutionOwnershipGuard(params);
75272
76709
  const pubsub = params[PUBSUB_SYMBOL];
75273
76710
  const typedInput = inputData;
75274
76711
  const { agentId, messageId, options: execOptions } = typedInput;
75275
76712
  const runId = typedInput.runId;
76713
+ const requestContext = getLiveRunRequestContext(getRunRegistryEntry(runId, mastra), runId, params.requestContext) ?? params.requestContext;
75276
76714
  const logger = mastra?.getLogger?.();
75277
76715
  if (pubsub) await emitIterationStartEvent(pubsub, runId, inputData.stepIndex ?? 0);
75278
76716
  const { messageList, tools, model: resolvedModel, modelList: resolvedModelList, inputProcessors: resolvedInputProcessors, llmRequestInputProcessors: resolvedLlmRequestInputProcessors, outputProcessors: resolvedOutputProcessors } = await resolveRuntimeDependencies({
@@ -75303,7 +76741,7 @@ function createDurableLLMExecutionStep(_options) {
75303
76741
  }
75304
76742
  } : void 0;
75305
76743
  if (pubsub) try {
75306
- await ensureRemoteAbortListener(pubsub, runId, mastra, readRunDeadline(requestContext));
76744
+ await ensureRemoteAbortListener(pubsub, runId, mastra, readRunDeadline(params.requestContext));
75307
76745
  } catch (error) {
75308
76746
  ownership?.throwIfLost();
75309
76747
  logger?.warn?.("Failed to subscribe to cross-process abort requests", {
@@ -75311,6 +76749,8 @@ function createDurableLLMExecutionStep(_options) {
75311
76749
  error: error instanceof Error ? error.message : String(error)
75312
76750
  });
75313
76751
  }
76752
+ const runEntry = getRunRegistryEntry(runId, mastra);
76753
+ if (runEntry) runEntry.openStepSpan = void 0;
75314
76754
  let request = {};
75315
76755
  let terminateAttemptSpans;
75316
76756
  let tracingTermination;
@@ -76966,6 +78406,7 @@ function createDurableLLMExecutionStep(_options) {
76966
78406
  tripwire: stepTripwire
76967
78407
  });
76968
78408
  const stepSpanData = hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.exportCurrentStep() : void 0;
78409
+ if (registryEntry && stepSpanData) registryEntry.openStepSpan = observability?.rebuildSpan(stepSpanData);
76969
78410
  const stepFinishPayload = hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.getPendingStepFinishPayload() : void 0;
76970
78411
  const output = {
76971
78412
  ...await storeStepTranscript(),
@@ -76989,7 +78430,12 @@ function createDurableLLMExecutionStep(_options) {
76989
78430
  },
76990
78431
  response: deferredStepFinishChunk ? {
76991
78432
  id: deferredStepFinishChunk.payload?.metadata?.id,
76992
- modelId: resolveResponseModelId(deferredStepFinishChunk.payload?.metadata?.providerMetadata, deferredStepFinishChunk.payload?.metadata?.modelId)
78433
+ modelId: resolveResponseModelId(deferredStepFinishChunk.payload?.metadata?.providerMetadata, deferredStepFinishChunk.payload?.metadata?.modelId),
78434
+ ...cachedResponse ? {} : { servedBy: {
78435
+ provider: currentModel.provider,
78436
+ modelId: currentModel.modelId
78437
+ } },
78438
+ reportedCost: reportedCost(deferredStepFinishChunk.payload?.metadata?.providerMetadata)
76993
78439
  } : void 0,
76994
78440
  state: typedInput.state,
76995
78441
  modelSpanData: hasToolCalls && !processOutputStepTripwire ? modelSpan?.snapshot?.() ?? modelSpan?.exportSpan() : void 0,
@@ -77000,6 +78446,7 @@ function createDurableLLMExecutionStep(_options) {
77000
78446
  ...releasedToolResultIds.length ? { releasedToolResultIds } : {},
77001
78447
  tracingTermination
77002
78448
  };
78449
+ if (effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) getToolResultRunner().endStreamProcessorSpans(registryEntry.processorStates, { stepScopedOnly: true });
77003
78450
  if (!hasToolCalls || processOutputStepTripwire) {
77004
78451
  const pendingPayload = modelSpanTracker?.getPendingStepFinishPayload();
77005
78452
  if (pendingPayload) {
@@ -78055,7 +79502,9 @@ const durableToolCallInputSchema = z$1.object({
78055
79502
  stepSpanData: z$1.any().optional(),
78056
79503
  completionStartTime: z$1.coerce.date().optional(),
78057
79504
  timeToFirstTokenMs: z$1.number().optional(),
78058
- stepUsage: z$1.any().optional()
79505
+ stepUsage: z$1.any().optional(),
79506
+ sideBySide: z$1.boolean().optional(),
79507
+ response: responseRecordSchema.optional()
78059
79508
  });
78060
79509
  /**
78061
79510
  * Output schema for the durable tool call step.
@@ -78158,6 +79607,15 @@ async function flushMessagesBeforeSuspension({ saveQueueManager, messageList, me
78158
79607
  return false;
78159
79608
  }
78160
79609
  }
79610
+ /**
79611
+ * Context for output processors on a tool result. A live context is reused only for the execution that
79612
+ * owns it. A context rebuilt from the run snapshot is returned as before; whether a rebuilt entry can
79613
+ * outlive a resume by another caller is tracked in COR-1660.
79614
+ */
79615
+ function toolResultRequestContext(registryEntry, runId, stepRequestContext) {
79616
+ if (registryEntry?.requestContextRebuilt) return registryEntry.requestContext;
79617
+ return getLiveRunRequestContext(registryEntry, runId, stepRequestContext) ?? stepRequestContext;
79618
+ }
78161
79619
  var DurableOutputProcessorError = class extends Error {
78162
79620
  constructor(error) {
78163
79621
  super(error instanceof Error ? error.message : String(error), { cause: error });
@@ -78179,7 +79637,7 @@ var DurableChunkPublishError = class extends Error {
78179
79637
  * Thin glue over the shared per-chunk pipeline core; mirrors the regular
78180
79638
  * agent's `processAndEnqueueChunk` in llm-mapping-step.ts.
78181
79639
  */
78182
- async function processChunkThroughOutputProcessors(chunk, registryEntry, pubsub, runId, agentName, logger, messageList, observabilityContext, collectDataPart, onEmit) {
79640
+ async function processChunkThroughOutputProcessors(chunk, registryEntry, stepRequestContext, pubsub, runId, agentName, logger, messageList, observabilityContext, collectDataPart, onEmit) {
78183
79641
  const runner = registryEntry?.outputProcessors?.length && registryEntry.processorStates ? new ProcessorRunner({
78184
79642
  inputProcessors: [],
78185
79643
  outputProcessors: registryEntry.outputProcessors,
@@ -78192,7 +79650,7 @@ async function processChunkThroughOutputProcessors(chunk, registryEntry, pubsub,
78192
79650
  runner,
78193
79651
  processorStates: registryEntry?.processorStates,
78194
79652
  observabilityContext,
78195
- requestContext: registryEntry?.requestContext,
79653
+ requestContext: toolResultRequestContext(registryEntry, runId, stepRequestContext),
78196
79654
  messageList,
78197
79655
  streamWriter: pubsub ? { custom: async (data, writerOptions) => {
78198
79656
  if (data.type.startsWith("data-") && !data.transient) collectDataPart?.({
@@ -78273,7 +79731,7 @@ function createDurableToolCallStep() {
78273
79731
  const initData = getInitData();
78274
79732
  const { runId, options: agentOptions, state } = initData;
78275
79733
  const logger = mastra?.getLogger?.();
78276
- const endSpansAsSuspended = (info) => {
79734
+ const endSpansAsSuspended = async (info) => {
78277
79735
  try {
78278
79736
  const obs = mastra?.observability?.getSelectedInstance({ requestContext });
78279
79737
  if (!obs) return;
@@ -78285,6 +79743,15 @@ function createDurableToolCallStep() {
78285
79743
  };
78286
79744
  const reg = getRunRegistryEntry(runId, mastra);
78287
79745
  const segment = segmentSpanData(requestContext, runId, initData, reg);
79746
+ if (typedInput.sideBySide && !segment.carried) {
79747
+ if (!(await claimSegmentEnd({
79748
+ mastra,
79749
+ requestContext,
79750
+ runId,
79751
+ iterationCount: initData.iterationCount,
79752
+ outcome: "suspend"
79753
+ }) ?? await assertOwned().then(() => true, (error) => !isExecutionFenceError(error)))) return;
79754
+ }
78288
79755
  const { agentSpanData, modelSpanData } = segment;
78289
79756
  const attributes = carriedSpanClocks(reg, initData.completionStartTime ? {
78290
79757
  completionStartTime: initData.completionStartTime,
@@ -78293,26 +79760,57 @@ function createDurableToolCallStep() {
78293
79760
  completionStartTime: typedInput.completionStartTime,
78294
79761
  timeToFirstTokenMs: typedInput.timeToFirstTokenMs
78295
79762
  }, segment.carried);
78296
- if (typedInput.stepSpanData && segmentOwnsStep(segment, typedInput.stepSpanData)) obs.rebuildSpan(typedInput.stepSpanData)?.end({
78297
- output,
78298
- outcome: "suspend",
78299
- stopReason: info.reason === "approval" ? "approval_required" : null,
78300
- stopReasonContext: info.reason === "approval" ? compactStopReasonContext("approval_required", {
78301
- toolCallId: info.toolCallId,
78302
- toolName: info.toolName
78303
- }) : null
78304
- });
78305
- if (modelSpanData) obs.rebuildSpan(modelSpanData)?.end({
78306
- output,
78307
- attributes,
78308
- outcome: "suspend",
78309
- stopReason: info.reason === "approval" ? "approval_required" : null,
78310
- stopReasonContext: info.reason === "approval" ? compactStopReasonContext("approval_required", {
78311
- toolCallId: info.toolCallId,
78312
- toolName: info.toolName
78313
- }) : null
78314
- });
78315
- if (agentSpanData) obs.rebuildSpan(agentSpanData)?.end({
79763
+ const ownsStep = !!typedInput.stepSpanData && segmentOwnsStep(segment, typedInput.stepSpanData);
79764
+ const reported = initData.generationReportedUsage;
79765
+ const total = calculateAccumulatedUsage(initData.accumulatedUsage, typedInput.stepUsage);
79766
+ const usage = reported && ownsStep && !typedInput.sideBySide && !isUsageIncomplete(total) ? subtractReportedUsage(total, reported) : void 0;
79767
+ if (ownsStep) {
79768
+ const stepSpanData = typedInput.stepSpanData;
79769
+ (liveSegmentSpan(stepSpanData, reg?.openStepSpan) ?? obs.rebuildSpan(stepSpanData))?.end({
79770
+ output,
79771
+ ...reported ? { attributes: { usage: extractUsageMetrics(typedInput.stepUsage) } } : {},
79772
+ outcome: "suspend",
79773
+ stopReason: info.reason === "approval" ? "approval_required" : null,
79774
+ stopReasonContext: info.reason === "approval" ? compactStopReasonContext("approval_required", {
79775
+ toolCallId: info.toolCallId,
79776
+ toolName: info.toolName
79777
+ }) : null
79778
+ });
79779
+ }
79780
+ const agentSpan = agentSpanData && obs.rebuildSpan(agentSpanData);
79781
+ if (modelSpanData) {
79782
+ const end = {
79783
+ output,
79784
+ attributes,
79785
+ outcome: "suspend",
79786
+ stopReason: info.reason === "approval" ? "approval_required" : null,
79787
+ stopReasonContext: info.reason === "approval" ? compactStopReasonContext("approval_required", {
79788
+ toolCallId: info.toolCallId,
79789
+ toolName: info.toolName
79790
+ }) : null
79791
+ };
79792
+ const modelSpan = obs.rebuildSpan(modelSpanData);
79793
+ if (modelSpan?.isInternal) modelSpan.parent ??= agentSpan;
79794
+ if (usage) {
79795
+ const servedBy = typedInput.response?.servedBy;
79796
+ const servedName = servedBy && `llm: '${servedBy.modelId}'`;
79797
+ if (servedName && modelSpan && modelSpan.name !== servedName) modelSpan.update({ name: servedName });
79798
+ const costs = initData.reportedCosts?.slice(initData.generationReportedSteps ?? 0) ?? [];
79799
+ modelSpan?.createTracker()?.endGeneration({
79800
+ ...end,
79801
+ attributes: {
79802
+ ...attributes,
79803
+ ...servedBy ? {
79804
+ model: servedBy.modelId,
79805
+ provider: servedBy.provider
79806
+ } : {}
79807
+ },
79808
+ usage,
79809
+ stepProviderMetadata: [...costs, typedInput.response?.reportedCost].map((cost) => cost ?? void 0)
79810
+ });
79811
+ } else modelSpan?.end(end);
79812
+ }
79813
+ agentSpan?.end({
78316
79814
  output,
78317
79815
  attributes,
78318
79816
  outcome: "suspend",
@@ -78503,7 +80001,7 @@ function createDurableToolCallStep() {
78503
80001
  }).add(invocation, "memory");
78504
80002
  }
78505
80003
  if (saveQueueManager && messagesToFlush && memory && state?.threadId && state.resourceId && !state.memoryConfig?.readOnly) {
78506
- const authorizationRequestContext = registryEntry?.requestContext ?? restoreRequestContext$1(initData.requestContextEntries, requestContext);
80004
+ const authorizationRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext));
78507
80005
  const authorizeMemory = (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
78508
80006
  mastra,
78509
80007
  user: authorizationRequestContext.get("user"),
@@ -78547,10 +80045,10 @@ function createDurableToolCallStep() {
78547
80045
  };
78548
80046
  const registryRequireToolApproval = registryEntry?.requireToolApproval;
78549
80047
  const effectiveRequireToolApproval = registryRequireToolApproval !== void 0 ? registryRequireToolApproval : agentOptions.requireToolApproval;
78550
- const approvalRequestContext = registryEntry?.requestContext ?? restoreRequestContext$1(initData.requestContextEntries, requestContext);
80048
+ const approvalRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext));
78551
80049
  const requiresApproval = await toolRequiresApproval(tool, effectiveRequireToolApproval, args, {
78552
80050
  toolName,
78553
- requestContext: Object.fromEntries([...approvalRequestContext.entries()].filter(([key]) => !INTERNAL_APPROVAL_KEYS.has(key))),
80051
+ requestContext: Object.fromEntries([...approvalRequestContext.entries()].filter(([key]) => key !== "__mastra_durableContextSegment" && !INTERNAL_APPROVAL_KEYS.has(key))),
78554
80052
  workspace
78555
80053
  });
78556
80054
  const addToolMetadata = (opts) => {
@@ -78730,7 +80228,7 @@ function createDurableToolCallStep() {
78730
80228
  toolTransform: tool?.transform,
78731
80229
  tools: toolsForTransform,
78732
80230
  logger
78733
- }), registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
80231
+ }), registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
78734
80232
  } catch (emitError) {
78735
80233
  if (emitError instanceof DurableOutputProcessorError) throw emitError;
78736
80234
  logger?.warn?.(`[DurableAgent] Failed to emit tool-result chunk for ${toolName}: ${emitError}`);
@@ -78780,7 +80278,7 @@ function createDurableToolCallStep() {
78780
80278
  type: "approval",
78781
80279
  resumeSchema: approvalResumeSchema
78782
80280
  }));
78783
- endSpansAsSuspended({
80281
+ await endSpansAsSuspended({
78784
80282
  toolCallId,
78785
80283
  toolName,
78786
80284
  reason: "approval"
@@ -78832,7 +80330,7 @@ function createDurableToolCallStep() {
78832
80330
  policy: toolPayloadTransform,
78833
80331
  tools: toolsForTransform,
78834
80332
  logger
78835
- }), registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
80333
+ }), registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
78836
80334
  } catch (emitError) {
78837
80335
  if (emitError instanceof DurableOutputProcessorError) throw emitError;
78838
80336
  logger?.warn?.(`[DurableAgent] Failed to emit tool-output-denied chunk for ${toolName}: ${emitError}`);
@@ -79002,7 +80500,7 @@ function createDurableToolCallStep() {
79002
80500
  type: "approval",
79003
80501
  resumeSchema: approvalResumeSchema
79004
80502
  }));
79005
- endSpansAsSuspended({
80503
+ await endSpansAsSuspended({
79006
80504
  toolCallId,
79007
80505
  toolName: approvalToolName,
79008
80506
  reason: "approval"
@@ -79057,7 +80555,7 @@ function createDurableToolCallStep() {
79057
80555
  await publishAfterPersist(() => emitChunkEvent(pubsub, runId, suspensionChunk));
79058
80556
  await publishAfterPersist(() => emitSuspendedEvent(pubsub, runId, suspendedEventData));
79059
80557
  }
79060
- endSpansAsSuspended({
80558
+ await endSpansAsSuspended({
79061
80559
  toolCallId,
79062
80560
  toolName,
79063
80561
  reason: "suspension"
@@ -79272,7 +80770,7 @@ function createDurableToolCallStep() {
79272
80770
  toolCallId: params.toolCallId,
79273
80771
  toolName: params.toolName,
79274
80772
  status: params.status === "failed" ? "failed" : "completed",
79275
- requestContext: registryEntry?.requestContext ?? restoreRequestContext$1(initData.requestContextEntries, requestContext)
80773
+ requestContext: restoreRequestContext(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext))
79276
80774
  });
79277
80775
  } catch (error) {
79278
80776
  resolveReconciliation({ error });
@@ -79571,7 +81069,7 @@ function createDurableToolCallStep() {
79571
81069
  result,
79572
81070
  modelOutput: readModelOutput(providerMetadata),
79573
81071
  ...processorObservabilityContext ?? {},
79574
- requestContext: registryEntry.requestContext,
81072
+ requestContext: toolResultRequestContext(registryEntry, runId, requestContext),
79575
81073
  retryCount: 0,
79576
81074
  writer: pubsub ? { custom: async (data, writerOptions) => {
79577
81075
  if (data.type.startsWith("data-") && !data.transient) collectProcessorDataPart({
@@ -79676,7 +81174,7 @@ function createDurableToolCallStep() {
79676
81174
  logger
79677
81175
  });
79678
81176
  transformMetadata = resultChunk.metadata;
79679
- await processChunkThroughOutputProcessors(resultChunk, registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart, (chunk) => {
81177
+ await processChunkThroughOutputProcessors(resultChunk, registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart, (chunk) => {
79680
81178
  if (chunk.type === "tool-result" && chunk.payload.toolCallId === toolCallId) resultEmitted = true;
79681
81179
  });
79682
81180
  } catch (emitError) {
@@ -79748,7 +81246,7 @@ function createDurableToolCallStep() {
79748
81246
  logger
79749
81247
  });
79750
81248
  errorTransformMetadata = errorChunk.metadata;
79751
- await processChunkThroughOutputProcessors(errorChunk, registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
81249
+ await processChunkThroughOutputProcessors(errorChunk, registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
79752
81250
  } catch (emitError) {
79753
81251
  ownership?.throwIfLost();
79754
81252
  if (emitError instanceof DurableOutputProcessorError) throw emitError;
@@ -79813,7 +81311,8 @@ const durableLLMMappingOutputSchema = z$1.object({
79813
81311
  deferredStepFinishChunk: z$1.any().optional(),
79814
81312
  completionStartTime: z$1.coerce.date().optional(),
79815
81313
  timeToFirstTokenMs: z$1.number().optional(),
79816
- response: responseRecordSchema.optional()
81314
+ response: responseRecordSchema.optional(),
81315
+ suspensionReportedUsage: z$1.boolean().optional()
79817
81316
  });
79818
81317
  /**
79819
81318
  * Create a durable LLM mapping step.
@@ -79884,8 +81383,19 @@ function createDurableLLMMappingStep() {
79884
81383
  const isPendingClientCall = (toolResult) => toolResult.result === void 0 && !toolResult.error && !toolResult.aborted && !toolResult.resultBlocked && !toolResult.providerExecuted && !isDeniedApproval(toolResult);
79885
81384
  const registryTools = registryEntry?.tools;
79886
81385
  let stepSpan;
81386
+ let suspensionReportedUsage = false;
79887
81387
  if (llmOutput.stepSpanData) try {
79888
- if (segmentOwnsStep(segmentSpanData(requestContext, _runId, getInitData(), getRunRegistryEntry(_runId, mastra)), llmOutput.stepSpanData)) stepSpan = (mastra?.observability?.getSelectedInstance({ requestContext }))?.rebuildSpan(llmOutput.stepSpanData);
81388
+ const initData = getInitData();
81389
+ const reg = getRunRegistryEntry(_runId, mastra);
81390
+ if (segmentOwnsStep(segmentSpanData(requestContext, _runId, initData, reg), llmOutput.stepSpanData)) {
81391
+ const observability = mastra?.observability?.getSelectedInstance({ requestContext });
81392
+ const stepSpanData = llmOutput.stepSpanData;
81393
+ stepSpan = liveSegmentSpan(stepSpanData, reg?.openStepSpan) ?? observability?.rebuildSpan(stepSpanData);
81394
+ } else suspensionReportedUsage = !toolCallsRunSideBySide({
81395
+ options: initData.options,
81396
+ toolsMetadata: initData.toolsMetadata,
81397
+ toolCalls: llmOutput.toolCalls
81398
+ });
79889
81399
  } catch {}
79890
81400
  if (toolResults.length > 0) {
79891
81401
  const runStopped = toolResults.some((result) => result.deadlineTimeout || result.runAborted);
@@ -80020,6 +81530,7 @@ function createDurableLLMMappingStep() {
80020
81530
  delegationBailed,
80021
81531
  tracingDelegationFailure,
80022
81532
  tracingTermination: llmOutput.tracingTermination,
81533
+ ...suspensionReportedUsage ? { suspensionReportedUsage } : {},
80023
81534
  ...deadlineTimeout ? { deadlineTimeout } : {},
80024
81535
  ...runAborted ? { runAborted } : {},
80025
81536
  deferredStepFinishChunk,
@@ -80323,7 +81834,7 @@ function createDurableIsTaskCompleteStep(defaultMaxSteps = DurableAgentDefaults.
80323
81834
  const restored = await restoreCompletionPolicy({
80324
81835
  agent,
80325
81836
  persisted: initData.options.isTaskComplete,
80326
- requestContext: restoreRequestContext$1(initData.requestContextEntries, registryEntry?.requestContext),
81837
+ requestContext: restoreRequestContext(initData.requestContextEntries, params.requestContext, getLiveRunRequestContext(registryEntry, state.runId, params.requestContext)),
80327
81838
  runId: state.runId,
80328
81839
  logger: mastra?.getLogger?.()
80329
81840
  });
@@ -80359,7 +81870,7 @@ function createDurableIsTaskCompleteStep(defaultMaxSteps = DurableAgentDefaults.
80359
81870
  agentName: initData.agentName,
80360
81871
  threadId: initData.state?.threadId,
80361
81872
  resourceId: initData.state?.resourceId,
80362
- customContext: restoreCustomContext(initData.requestContextEntries, registryEntry?.requestContext ?? params.requestContext),
81873
+ customContext: restoreCustomContext(initData.requestContextEntries, getLiveRunRequestContext(registryEntry, state.runId, params.requestContext) ?? params.requestContext),
80363
81874
  generateId: () => mastra?.generateId?.(),
80364
81875
  emitChunk: (chunk) => {
80365
81876
  if (!pubsub) return;
@@ -80407,9 +81918,10 @@ function createDurableGoalStep() {
80407
81918
  const registryEntry = getRunRegistryEntry(state.runId, mastra);
80408
81919
  let goalConfig = registryEntry?.goal;
80409
81920
  if (!goalConfig && initData.agentId) goalConfig = mastra?.getAgentById?.(initData.agentId)?.__getGoalConfig?.();
80410
- const liveRequestContext = registryEntry?.requestContext ?? params.requestContext;
80411
- const requestContext = restoreRequestContext$1(initData.requestContextEntries, liveRequestContext);
80412
- const customContext = restoreCustomContext(initData.requestContextEntries, liveRequestContext);
81921
+ const liveRunContext = getLiveRunRequestContext(registryEntry, state.runId, params.requestContext);
81922
+ const currentRequestContext = liveRunContext ?? params.requestContext;
81923
+ const requestContext = restoreRequestContext(initData.requestContextEntries, params.requestContext, liveRunContext);
81924
+ const customContext = restoreCustomContext(initData.requestContextEntries, currentRequestContext);
80413
81925
  if (!goalConfig) return state;
80414
81926
  const messageListState = await readMessageListState(params, state);
80415
81927
  let messageList;
@@ -80480,7 +81992,6 @@ function withParams(params, overrides) {
80480
81992
  };
80481
81993
  return Object.defineProperties({}, descriptors);
80482
81994
  }
80483
- const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
80484
81995
  /**
80485
81996
  * Historical default persistence policy for durable agent workflows.
80486
81997
  *
@@ -80832,14 +82343,22 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80832
82343
  completionStartTime: state.completionStartTime,
80833
82344
  timeToFirstTokenMs: state.timeToFirstTokenMs
80834
82345
  };
80835
- }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData }) => {
82346
+ }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData, getInitData }) => {
80836
82347
  const llmOutput = inputData;
82348
+ const state = getInitData();
82349
+ const sideBySide = toolCallsRunSideBySide({
82350
+ options: state?.options,
82351
+ toolsMetadata: state?.toolsMetadata,
82352
+ toolCalls: llmOutput.toolCalls
82353
+ });
80837
82354
  return (llmOutput.toolCalls ?? []).map((toolCall) => ({
80838
82355
  ...toolCall,
80839
82356
  stepSpanData: llmOutput.stepSpanData,
80840
82357
  completionStartTime: llmOutput.completionStartTime,
80841
82358
  timeToFirstTokenMs: llmOutput.timeToFirstTokenMs,
80842
- stepUsage: llmOutput.stepResult?.totalUsage
82359
+ stepUsage: llmOutput.stepResult?.totalUsage,
82360
+ response: llmOutput.response,
82361
+ ...sideBySide ? { sideBySide } : {}
80843
82362
  }));
80844
82363
  }, { id: "extract-tool-calls" }).foreach(toolCallStep, { concurrency: ({ inputData, getInitData }) => {
80845
82364
  const state = getInitData();
@@ -81125,6 +82644,11 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81125
82644
  totalTokens: 0
81126
82645
  },
81127
82646
  usageAggregationVersion: 1,
82647
+ generationReportedUsage: {
82648
+ inputTokens: 0,
82649
+ outputTokens: 0,
82650
+ totalTokens: 0
82651
+ },
81128
82652
  lastStepResult: void 0
81129
82653
  };
81130
82654
  }, { id: "init-iteration-state" }).dowhile(this.buildIterationWorkflow(), markFrameworkCondition(this.buildContinuationPredicate())).map(async (params) => {
@@ -81150,13 +82674,24 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81150
82674
  user: finalMessageList.get.input.aiV5.model(),
81151
82675
  nonUser: finalMessageList.get.response.aiV5.model()
81152
82676
  };
82677
+ const reg = getRunRegistryEntry(initData.runId, mastra);
82678
+ let observability;
82679
+ let segment;
82680
+ let agentSpan;
82681
+ try {
82682
+ observability = mastra?.observability?.getSelectedInstance({ requestContext });
82683
+ segment = segmentSpanData(requestContext, initData.runId, initData, reg);
82684
+ agentSpan = liveOrRebuiltAgentSpan(segment.agentSpanData, reg, observability);
82685
+ } catch (error) {
82686
+ logger?.warn?.(`[DurableAgent] Error resolving the run span: ${error}`);
82687
+ }
81153
82688
  const finishResult = await runDurableFinishSideEffects({
81154
82689
  runId: state.runId,
81155
82690
  initData,
81156
82691
  messageListState,
81157
82692
  mastra,
81158
82693
  requestContext,
81159
- tracingContext,
82694
+ tracingContext: agentSpan ? { currentSpan: agentSpan } : tracingContext,
81160
82695
  logger,
81161
82696
  messageId: state.messageId,
81162
82697
  outputResult: {
@@ -81230,7 +82765,6 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81230
82765
  },
81231
82766
  state: state.state
81232
82767
  };
81233
- const reg = getRunRegistryEntry(initData.runId, mastra);
81234
82768
  const stopCause = state.tracingStopCause ?? reg?.tracingStopCause;
81235
82769
  if (pubsub) await emitFinishEvent(pubsub, state.runId, {
81236
82770
  output: finalOutput.output,
@@ -81243,30 +82777,35 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81243
82777
  const finishReason = finalOutput.stepResult?.reason;
81244
82778
  const recordedTermination = state.tracingTermination ?? reg?.tracingTermination;
81245
82779
  if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) logger?.warn?.(`[DurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
82780
+ const runTripwire = tripwire ?? state.lastStepResult?.tripwire ?? initData.inputTripwire;
81246
82781
  const termination = ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
81247
82782
  stopCause,
81248
82783
  delegationFailure: state.tracingDelegationFailure ?? reg?.tracingDelegationFailure,
81249
82784
  finishReason,
81250
- tripwire: tripwire ?? state.lastStepResult?.tripwire,
82785
+ tripwire: runTripwire,
81251
82786
  maxSteps: initData.options?.maxSteps
81252
82787
  });
81253
82788
  try {
81254
- const observability = mastra?.observability?.getSelectedInstance({ requestContext });
81255
- const { agentSpanData, modelSpanData, carried } = segmentSpanData(requestContext, initData.runId, initData, reg);
81256
- const clocks = carriedSpanClocks(reg, state, carried);
82789
+ const clocks = carriedSpanClocks(reg, state, segment?.carried);
81257
82790
  if (observability) {
82791
+ const modelSpanData = segment?.modelSpanData;
81258
82792
  if (modelSpanData) {
81259
82793
  const modelSpan = liveSegmentSpan(modelSpanData, reg?.resumeModelSpan, reg?.modelSpan) ?? observability.rebuildSpan(modelSpanData);
82794
+ if (modelSpan?.isInternal) modelSpan.parent ??= agentSpan;
81260
82795
  const toolCalls = steps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
81261
82796
  toolCallId: tc.toolCallId,
81262
82797
  toolName: tc.toolName,
81263
82798
  args: tc.args
81264
82799
  })));
81265
82800
  const usageIncomplete = isUsageIncomplete(state.accumulatedUsage);
82801
+ const servedBy = state.lastResponse?.servedBy;
82802
+ const servedName = servedBy && `llm: '${servedBy.modelId}'`;
82803
+ if (servedName && modelSpan && modelSpan.name !== servedName) modelSpan.update({ name: servedName });
81266
82804
  modelSpan?.createTracker()?.endGeneration({
81267
82805
  ...termination,
81268
82806
  output: {
81269
82807
  text: finalText,
82808
+ object: finishResult.object,
81270
82809
  toolCalls: toolCalls.length ? toolCalls : void 0
81271
82810
  },
81272
82811
  attributes: {
@@ -81274,15 +82813,32 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81274
82813
  ...usageIncomplete ? { usageIncomplete: true } : {},
81275
82814
  ...clocks,
81276
82815
  responseId: state.lastResponse?.id,
81277
- responseModel: state.lastResponse?.modelId
82816
+ responseModel: state.lastResponse?.modelId,
82817
+ ...servedBy ? {
82818
+ model: servedBy.modelId,
82819
+ provider: servedBy.provider
82820
+ } : {}
81278
82821
  },
81279
- usage: usageIncomplete ? calculateObservedUsage(steps) : state.accumulatedUsage
82822
+ usage: subtractReportedUsage(usageIncomplete ? calculateObservedUsage(steps) : state.accumulatedUsage, state.generationReportedUsage),
82823
+ stepProviderMetadata: state.reportedCosts?.slice(state.generationReportedSteps ?? 0).map((cost) => cost ?? void 0)
81280
82824
  });
81281
82825
  }
81282
- liveOrRebuiltAgentSpan(agentSpanData, reg, observability)?.end({
82826
+ agentSpan?.end({
81283
82827
  ...termination,
81284
- output: { text: finalText },
81285
- ...clocks ? { attributes: clocks } : {}
82828
+ output: {
82829
+ text: finalText,
82830
+ object: finishResult.object,
82831
+ ...runTripwire ? { tripwire: runTripwire } : {}
82832
+ },
82833
+ attributes: {
82834
+ ...clocks,
82835
+ ...runTripwire ? { tripwireAbort: {
82836
+ reason: runTripwire.reason,
82837
+ processorId: runTripwire.processorId,
82838
+ retry: runTripwire.retry,
82839
+ metadata: runTripwire.metadata
82840
+ } } : {}
82841
+ }
81286
82842
  });
81287
82843
  }
81288
82844
  } catch (error) {
@@ -81381,19 +82937,20 @@ var DefaultAgentExecutionEngine = class {
81381
82937
  keepReplayEvent,
81382
82938
  attachedAtLogIndex
81383
82939
  };
81384
- const skipped = history.slice(0, offset);
81385
- if (skipped.length === offset) {
81386
- let floor;
81387
- for (const event of skipped) {
81388
- const generation = event.generation;
81389
- if (typeof generation === "number" && (floor === void 0 || generation > floor)) floor = generation;
81390
- }
81391
- return {
81392
- minGeneration: floor,
81393
- keepReplayEvent,
81394
- attachedAtLogIndex
81395
- };
81396
- }
82940
+ let first;
82941
+ let floor;
82942
+ for (const event of history) {
82943
+ const index = event.index;
82944
+ if (typeof index !== "number" || index >= offset) continue;
82945
+ if (first === void 0 || index < first) first = index;
82946
+ const generation = event.generation;
82947
+ if (typeof generation === "number" && (floor === void 0 || generation > floor)) floor = generation;
82948
+ }
82949
+ if (first !== void 0) return {
82950
+ minGeneration: floor,
82951
+ keepReplayEvent,
82952
+ attachedAtLogIndex
82953
+ };
81397
82954
  return {
81398
82955
  minGeneration: await readRunGeneration(this.mastra, runId),
81399
82956
  keepReplayEvent,
@@ -81432,7 +82989,13 @@ var DefaultAgentExecutionEngine = class {
81432
82989
  if (typeof historyPubsub.getHistory !== "function") return "latest";
81433
82990
  try {
81434
82991
  const history = await historyPubsub.getHistory(AGENT_STREAM_TOPIC(runId));
81435
- return Array.isArray(history) && history.length > 0 ? history.length : "latest";
82992
+ if (!Array.isArray(history) || history.length === 0) return "latest";
82993
+ let newest = -1;
82994
+ for (const event of history) {
82995
+ const index = event?.index;
82996
+ if (typeof index === "number" && index > newest) newest = index;
82997
+ }
82998
+ return newest >= 0 ? newest + 1 : "latest";
81436
82999
  } catch {
81437
83000
  return "latest";
81438
83001
  }
@@ -81958,12 +83521,15 @@ var DefaultAgentExecutionEngine = class {
81958
83521
  }
81959
83522
  });
81960
83523
  const finishPublishedBeforeCrash = snapshot.context?.[MAP_FINAL_OUTPUT_STEP_ID]?.status === "success";
81961
- const resumed = Object.values(snapshot.context ?? {}).some((result) => result && typeof result === "object" && "resumedAt" in result && result.resumedAt != null);
83524
+ const results = Object.values(snapshot.context ?? {});
83525
+ const stepSuspended = results.some((result) => result?.status === "suspended");
83526
+ const resumed = stepSuspended || results.some((result) => result?.resumedAt != null);
81962
83527
  return {
81963
83528
  snapshot,
81964
83529
  workflowInput,
81965
83530
  finishPublishedBeforeCrash,
81966
- originalSpansEnded: finishPublishedBeforeCrash || resumed
83531
+ originalSpansEnded: finishPublishedBeforeCrash || resumed,
83532
+ openStepsOf: stepSuspended ? [] : openStepsOfCrashedSegment(snapshot.requestContext, runId)
81967
83533
  };
81968
83534
  }
81969
83535
  async loadSuspendedRequestContextValue(workflowsStore, runId, agent, key) {
@@ -82488,7 +84054,7 @@ async function prepareForDurableExecution(options) {
82488
84054
  });
82489
84055
  let tripwireData;
82490
84056
  if (inputProcessors.length > 0) try {
82491
- const { ProcessorRunner } = await import("./stream-DVy0Z-m0.js").then((n) => n.I);
84057
+ const { ProcessorRunner } = await import("./stream-DoZ6F41o.js").then((n) => n.I);
82492
84058
  await new ProcessorRunner({
82493
84059
  inputProcessors,
82494
84060
  outputProcessors,
@@ -82563,6 +84129,8 @@ async function prepareForDurableExecution(options) {
82563
84129
  } catch (error) {
82564
84130
  logger?.warn?.(`[DurableAgent] Error converting tools: ${error}`);
82565
84131
  }
84132
+ const toolNames = Object.keys(tools);
84133
+ if (!resumedSpans && toolNames.length > 0) agentSpan?.update({ attributes: { availableTools: toolNames } });
82566
84134
  if (!tripwireData) {
82567
84135
  await fireClientToolOutputHooks({
82568
84136
  messages,
@@ -82623,18 +84191,36 @@ async function prepareForDurableExecution(options) {
82623
84191
  type: "model_generation",
82624
84192
  outcome: null,
82625
84193
  name: `llm: '${model.modelId}'`,
84194
+ input: { messages: [...messageList.getAllSystemMessages(), ...messageList.get.all.aiV5.model()] },
82626
84195
  attributes: {
82627
84196
  model: model.modelId,
82628
84197
  provider: model.provider,
82629
- streaming: true
84198
+ streaming: true,
84199
+ parameters: serializeModelSettings(execOptions?.modelSettings),
84200
+ tools: agentSpan?.isValid ? getToolDefinitionsForTracing({
84201
+ tools,
84202
+ toolChoice: execOptions?.toolChoice,
84203
+ activeTools: execOptions?.activeTools,
84204
+ stripToolsWhenNone: sendsNativeResponseFormat(execOptions?.structuredOutput, model)
84205
+ }) : void 0
82630
84206
  },
82631
84207
  metadata: {
82632
84208
  runId,
82633
84209
  threadId,
82634
84210
  resourceId
82635
84211
  },
84212
+ tracingPolicy: agentTracingPolicy,
82636
84213
  requestContext
82637
84214
  });
84215
+ const modelSnapshot = modelSpan?.snapshot?.() ?? modelSpan?.exportSpan();
84216
+ const modelSnapshotWithoutPromptOrTools = modelSnapshot && {
84217
+ ...modelSnapshot,
84218
+ input: void 0,
84219
+ attributes: {
84220
+ ...modelSnapshot.attributes,
84221
+ tools: void 0
84222
+ }
84223
+ };
82638
84224
  return {
82639
84225
  runId,
82640
84226
  messageId,
@@ -82700,7 +84286,7 @@ async function prepareForDurableExecution(options) {
82700
84286
  },
82701
84287
  messageId,
82702
84288
  agentSpanData: agentSpan?.snapshot?.() ?? agentSpan?.exportSpan(),
82703
- modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),
84289
+ modelSpanData: modelSnapshotWithoutPromptOrTools,
82704
84290
  requestContextEntries: requestContextEntriesSnapshot,
82705
84291
  inputTripwire: tripwireData
82706
84292
  }),
@@ -92036,11 +93622,14 @@ var Agent = class Agent extends MastraBase {
92036
93622
  if (generation !== executionFence.generation || !executionFence.ownsRunTopics()) return;
92037
93623
  const currentFence = getRunRegistryEntry(runId, this.#mastra)?.executionFence;
92038
93624
  if (currentFence && currentFence !== executionFence) return;
93625
+ if (executionFence.detached) return;
92039
93626
  try {
92040
93627
  await publisher?.settle(status);
92041
93628
  } catch (error) {
92042
- if (!(error instanceof DurableExecutionFenceError) || error.id !== "DURABLE_AGENT_EXECUTION_UNVERIFIED") throw error;
92043
- this.#unverifiedReaderFences.add(executionFence);
93629
+ const unverified = error instanceof DurableExecutionFenceError && error.id === "DURABLE_AGENT_EXECUTION_UNVERIFIED";
93630
+ if (unverified) this.#unverifiedReaderFences.add(executionFence);
93631
+ if (executionFence.detached) return;
93632
+ if (!unverified) throw error;
92044
93633
  this.logger.warn(`[DurableAgent:${this.id}] run ${runId}: terminal ownership could not be verified`, { error });
92045
93634
  }
92046
93635
  };
@@ -92231,7 +93820,7 @@ var Agent = class Agent extends MastraBase {
92231
93820
  }
92232
93821
  }
92233
93822
  /** Rebuilds process-local recovery state from the persisted durable workflow input. */
92234
- async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, latestMessageListState }) {
93823
+ async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, openStepsOf, latestMessageListState }) {
92235
93824
  const requestContext = workflowInput.requestContextEntries ? new RequestContext(Object.entries(workflowInput.requestContextEntries)) : new RequestContext();
92236
93825
  restoreRunAgentScopes(requestContext);
92237
93826
  const messageListMemoryInfo = workflowInput.messageListState?.memoryInfo;
@@ -92385,6 +93974,7 @@ var Agent = class Agent extends MastraBase {
92385
93974
  provider: model?.provider,
92386
93975
  streaming: true
92387
93976
  },
93977
+ tracingPolicy: agentTracingPolicy,
92388
93978
  metadata: {
92389
93979
  runId,
92390
93980
  recovered: true
@@ -92398,7 +93988,7 @@ var Agent = class Agent extends MastraBase {
92398
93988
  carrySegmentSpans(requestContext, runId, recoverAgentSpan ? {
92399
93989
  ...openedSegment(recoverAgentSpan, recoverModelSpan),
92400
93990
  adoptsOpenSteps: true,
92401
- ...originalSpansEnded && origModelSpanData?.id ? { endedStepsOf: origModelSpanData.id } : {}
93991
+ ...openStepsOf ? { openStepsOf } : originalSpansEnded && origModelSpanData?.id ? { endedStepsOf: origModelSpanData.id } : {}
92402
93992
  } : null);
92403
93993
  executionFence.throwIfLost();
92404
93994
  const registryEntry = {
@@ -92468,7 +94058,9 @@ var Agent = class Agent extends MastraBase {
92468
94058
  * @internal
92469
94059
  */
92470
94060
  async emitError(runId, error, generation) {
92471
- endRunSpansWithError(runId, error);
94061
+ const evented = this.executionEngine.resolveWorkflowEngine(this.workflowEngine, this.logger) === "evented";
94062
+ const bus = this.#mastra?.pubsub ?? this.getPubSub();
94063
+ endRunSpansWithError(runId, error, { endStep: !evented || !bus || !reachesOtherProcesses(bus) });
92472
94064
  await runOutsideRunFenceScope(() => emitErrorEvent(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId, error, generation, shouldRejectStream(error) ? "reject" : void 0));
92473
94065
  }
92474
94066
  /**
@@ -92565,6 +94157,7 @@ var Agent = class Agent extends MastraBase {
92565
94157
  initData: runInput,
92566
94158
  ...deadlineMessageListState(runInputEntry, runInput.messageListState),
92567
94159
  entry: runInputEntry,
94160
+ executionId: fence.executionId,
92568
94161
  mastra: this.#mastra,
92569
94162
  tracingContext: deadlineSpan ? { currentSpan: deadlineSpan } : void 0,
92570
94163
  logger: this.logger
@@ -92745,6 +94338,7 @@ var Agent = class Agent extends MastraBase {
92745
94338
  abortController,
92746
94339
  executionFence,
92747
94340
  originalSpansEnded: loaded.originalSpansEnded,
94341
+ openStepsOf: loaded.openStepsOf,
92748
94342
  latestMessageListState: await this.loadLatestMessageListState(workflowsStore, runId, loaded.snapshot)
92749
94343
  });
92750
94344
  await this.coverMemory(executionFence, recoveryState.requestContext, true);
@@ -93097,7 +94691,16 @@ var Agent = class Agent extends MastraBase {
93097
94691
  const threadId = workflowInput.state?.threadId ?? memoryInfo?.threadId;
93098
94692
  const resourceId = workflowInput.state?.resourceId ?? memoryInfo?.resourceId;
93099
94693
  if (sharedExecution && pubsub && entry?.requestContext && executionFence && threadId) {
93100
- await agentThreadStreamRuntime.claimDurableThreadLease(pubsub, runId, threadId, resourceId, executionFence.generation, executionFence.executionId);
94694
+ await agentThreadStreamRuntime.claimDurableThreadLease(pubsub, runId, threadId, resourceId, executionFence.generation, executionFence.executionId, true);
94695
+ try {
94696
+ await executionFence.verify();
94697
+ } catch (error) {
94698
+ await agentThreadStreamRuntime.abandonDurableThreadLease(pubsub, runId, threadId, resourceId, executionFence.generation, executionFence.executionId).catch((releaseError) => this.logger.warn("Failed to release thread lease after losing execution ownership", {
94699
+ runId,
94700
+ error: releaseError
94701
+ }));
94702
+ throw error;
94703
+ }
93101
94704
  setExecutionClaim(entry.requestContext, runId, {
93102
94705
  ...executionFence.claim,
93103
94706
  threadId,
@@ -93362,7 +94965,13 @@ var Agent = class Agent extends MastraBase {
93362
94965
  messageListFollowsStream: () => !this.executionEngine.executesStepsLocally
93363
94966
  });
93364
94967
  streamCleanup = createdStreamCleanup;
93365
- const workflowExecution = executionFence.run(() => ready.then(async () => {
94968
+ const threadRegistration = agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
94969
+ continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
94970
+ generation: executionFence.generation,
94971
+ ownershipLost: () => executionFence.isLost(),
94972
+ stepOwner: () => getRunRegistryEntry(runId, this.#mastra)
94973
+ });
94974
+ const workflowExecution = executionFence.run(() => Promise.all([ready, threadRegistration]).then(async () => {
93366
94975
  if (await this.redeliverDeadlineError(registryEntry, executionFence)) return;
93367
94976
  await emitChunkEvent(fencePubSub(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, executionFence), runId, {
93368
94977
  type: "start",
@@ -93403,12 +95012,7 @@ var Agent = class Agent extends MastraBase {
93403
95012
  }).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })));
93404
95013
  const trackedEntry = getRunRegistryEntry(runId, this.#mastra);
93405
95014
  if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
93406
- await agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
93407
- continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
93408
- generation: executionFence.generation,
93409
- ownershipLost: () => executionFence.isLost(),
93410
- stepOwner: () => getRunRegistryEntry(runId, this.#mastra)
93411
- });
95015
+ await threadRegistration;
93412
95016
  const cleanup = () => {
93413
95017
  if (methodType === "generate" || runCleanup.done || output.status !== "running") return performCleanup();
93414
95018
  Promise.race([workflowExecution, executionFence.whenSettled]).then(() => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush()).then(() => waitForEventDelivery()).catch(() => {}).finally(performCleanup);
@@ -93701,9 +95305,6 @@ var Agent = class Agent extends MastraBase {
93701
95305
  requestContextKeys
93702
95306
  };
93703
95307
  resumeRequestContext = resolvedOptions.requestContext ?? resumeRequestContext;
93704
- entry.requestContext = resumeRequestContext;
93705
- const globalEntryForContext = getRunRegistryEntry(runId, this.#mastra);
93706
- if (globalEntryForContext) globalEntryForContext.requestContext = resumeRequestContext;
93707
95308
  if (resolvedOptions.untilIdle) {
93708
95309
  const { untilIdle, ...rest } = resolvedOptions;
93709
95310
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
@@ -93734,41 +95335,6 @@ var Agent = class Agent extends MastraBase {
93734
95335
  });
93735
95336
  const priorExecution = getRunRegistryEntry(runId, this.#mastra)?.workflowExecution;
93736
95337
  await priorExecution?.catch(() => {});
93737
- if (!coldSnapshot && (options?.requestContext || options?.delegation || options?.hooks || droppedStartingUser)) try {
93738
- const requestTools = await this.agentForExecution.getToolsForExecution({
93739
- toolsets: resolvedOptions.toolsets,
93740
- clientTools: resolvedOptions.clientTools,
93741
- threadId: memoryInfo?.threadId,
93742
- resourceId: memoryInfo?.resourceId,
93743
- runId,
93744
- requestContext: resumeRequestContext,
93745
- memoryConfig: resolvedOptions.memory?.options,
93746
- autoResumeSuspendedTools: resolvedOptions.autoResumeSuspendedTools,
93747
- delegation: options?.delegation ? resolvedOptions.delegation : entry.delegation ?? resolvedOptions.delegation,
93748
- hooks: resolvedOptions.hooks,
93749
- methodType: entry.methodType ?? "stream",
93750
- backgroundTaskEnabled: Boolean(entry.backgroundTaskManager),
93751
- backgroundTaskPolicy: resolvedOptions.backgroundTaskPolicy,
93752
- model: entry.model
93753
- });
93754
- const refresh = (current, previous) => {
93755
- const next = { ...current };
93756
- for (const [name, tool] of Object.entries(requestTools)) if (name in current ? current[name] === previous?.[name] : !previous || !(name in previous)) next[name] = tool;
93757
- return next;
93758
- };
93759
- for (const reg of /* @__PURE__ */ new Set([entry, getRunRegistryEntry(runId, this.#mastra)])) {
93760
- if (!reg) continue;
93761
- reg.tools = rebindProcessorTools(refresh(reg.tools ?? {}, reg.requestTools), resumeRequestContext);
93762
- if (reg.baseTools) reg.baseTools = rebindProcessorTools(refresh(reg.baseTools, reg.requestTools), resumeRequestContext);
93763
- reg.requestTools = {
93764
- ...reg.requestTools,
93765
- ...requestTools
93766
- };
93767
- if (options?.delegation) reg.delegation = resolvedOptions.delegation;
93768
- }
93769
- } catch (error) {
93770
- this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] resume(${runId}) tool resolution failed: ${error}`);
93771
- }
93772
95338
  const executionFence = await this.#claimExecution(runId, "acquire");
93773
95339
  let initialToolCalls;
93774
95340
  let resumedText;
@@ -93807,16 +95373,58 @@ var Agent = class Agent extends MastraBase {
93807
95373
  }
93808
95374
  });
93809
95375
  if (resumeRequestContext) await this.coverMemory(executionFence, resumeRequestContext);
93810
- await this.loadRecalledMessages(runId, coldSnapshot, resumeRequestContext);
93811
95376
  ({toolCalls: initialToolCalls, resumedText} = await this.#loadSuspendedIteration(runId));
93812
95377
  resumeOffset = await this.executionEngine.getPubsubOffset(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId);
93813
95378
  persistedInput = current?.context?.input;
93814
95379
  suspendedToolCallIds = Object.keys(current?.resumeLabels ?? {});
93815
95380
  await agentThreadStreamRuntime.reacquireParkedRunLease(runId, this.getPubSub());
95381
+ entry.requestContext = resumeRequestContext;
95382
+ entry.requestContextRebuilt = false;
95383
+ const globalEntryForContext = getRunRegistryEntry(runId, this.#mastra);
95384
+ if (globalEntryForContext) {
95385
+ globalEntryForContext.requestContext = resumeRequestContext;
95386
+ globalEntryForContext.requestContextRebuilt = false;
95387
+ }
95388
+ await this.loadRecalledMessages(runId, coldSnapshot, resumeRequestContext);
93816
95389
  } catch (error) {
93817
95390
  await executionFence.settle(async () => {});
93818
95391
  throw error;
93819
95392
  }
95393
+ if (!coldSnapshot && (options?.requestContext || options?.delegation || options?.hooks || droppedStartingUser)) try {
95394
+ const requestTools = await this.agentForExecution.getToolsForExecution({
95395
+ toolsets: resolvedOptions.toolsets,
95396
+ clientTools: resolvedOptions.clientTools,
95397
+ threadId: memoryInfo?.threadId,
95398
+ resourceId: memoryInfo?.resourceId,
95399
+ runId,
95400
+ requestContext: resumeRequestContext,
95401
+ memoryConfig: resolvedOptions.memory?.options,
95402
+ autoResumeSuspendedTools: resolvedOptions.autoResumeSuspendedTools,
95403
+ delegation: options?.delegation ? resolvedOptions.delegation : entry.delegation ?? resolvedOptions.delegation,
95404
+ hooks: resolvedOptions.hooks,
95405
+ methodType: entry.methodType ?? "stream",
95406
+ backgroundTaskEnabled: Boolean(entry.backgroundTaskManager),
95407
+ backgroundTaskPolicy: resolvedOptions.backgroundTaskPolicy,
95408
+ model: entry.model
95409
+ });
95410
+ const refresh = (current, previous) => {
95411
+ const next = { ...current };
95412
+ for (const [name, tool] of Object.entries(requestTools)) if (name in current ? current[name] === previous?.[name] : !previous || !(name in previous)) next[name] = tool;
95413
+ return next;
95414
+ };
95415
+ for (const reg of /* @__PURE__ */ new Set([entry, getRunRegistryEntry(runId, this.#mastra)])) {
95416
+ if (!reg) continue;
95417
+ reg.tools = rebindProcessorTools(refresh(reg.tools ?? {}, reg.requestTools), resumeRequestContext);
95418
+ if (reg.baseTools) reg.baseTools = rebindProcessorTools(refresh(reg.baseTools, reg.requestTools), resumeRequestContext);
95419
+ reg.requestTools = {
95420
+ ...reg.requestTools,
95421
+ ...requestTools
95422
+ };
95423
+ if (options?.delegation) reg.delegation = resolvedOptions.delegation;
95424
+ }
95425
+ } catch (error) {
95426
+ this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] resume(${runId}) tool resolution failed: ${error}`);
95427
+ }
93820
95428
  setExecutionClaim(resumeRequestContext, runId, executionFence.claim);
93821
95429
  for (const reg of [entry, getRunRegistryEntry(runId, this.#mastra)]) {
93822
95430
  if (!reg) continue;
@@ -93905,6 +95513,7 @@ var Agent = class Agent extends MastraBase {
93905
95513
  provider: resumeModel?.provider,
93906
95514
  streaming: true
93907
95515
  },
95516
+ tracingPolicy: agentTracingPolicy,
93908
95517
  metadata: {
93909
95518
  runId,
93910
95519
  resumed: true
@@ -99190,6 +100799,21 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
99190
100799
  let currentIteration = 0;
99191
100800
  let eagerAbortListenerRegistered = false;
99192
100801
  const transcriptSteps = [];
100802
+ const apiErrorRows = [];
100803
+ const restoreApiErrorRows = (messageId) => {
100804
+ const parts = messageList.get.all.db().find((message) => message.id === messageId)?.content.parts ?? [];
100805
+ const missing = apiErrorRows.filter((row) => row.messageId === messageId).filter((row) => !parts.some((part) => part.type === row.part.type && deepEqual$3(part.data, row.part.data))).map((row) => row.part);
100806
+ if (missing.length === 0) return;
100807
+ messageList.add({
100808
+ id: messageId,
100809
+ role: "assistant",
100810
+ content: {
100811
+ format: 2,
100812
+ parts: missing
100813
+ },
100814
+ createdAt: /* @__PURE__ */ new Date()
100815
+ }, "response");
100816
+ };
99193
100817
  const pendingProviderToolCallsByToolCallId = /* @__PURE__ */ new Map();
99194
100818
  const cleanupProviderToolSpans = (terminal) => {
99195
100819
  if (!terminal) return;
@@ -99408,6 +101032,19 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
99408
101032
  start: messageList.get.response.aiV5.ui().find((message) => message.id === currentMessageId)?.parts.length ?? 0,
99409
101033
  end: 0
99410
101034
  };
101035
+ const apiErrorWriter = outputWriter ? { custom: async (data, options) => {
101036
+ if (isDataChunk(data) && !data.transient) apiErrorRows.push({
101037
+ messageId: currentMessageId,
101038
+ part: {
101039
+ type: data.type,
101040
+ data: data.data
101041
+ }
101042
+ });
101043
+ return outputWriter(data, {
101044
+ ...options,
101045
+ messageId: currentMessageId
101046
+ });
101047
+ } } : void 0;
99411
101048
  modelSpanTracker?.startStep();
99412
101049
  let modelResult;
99413
101050
  let warnings;
@@ -100135,10 +101772,6 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100135
101772
  });
100136
101773
  const currentRetryCount = inputData.processorRetryCount || 0;
100137
101774
  const canRetryError = maxErrorProcessorRetries !== void 0 && currentRetryCount < maxErrorProcessorRetries;
100138
- const apiErrorWriter = outputWriter ? { custom: async (data, options) => outputWriter(data, {
100139
- ...options,
100140
- messageId: currentMessageId
100141
- }) } : void 0;
100142
101775
  const errorResult = await processorRunner.runProcessAPIError({
100143
101776
  error,
100144
101777
  messages: messageList.get.all.db(),
@@ -100383,7 +102016,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100383
102016
  }
100384
102017
  const currentRetryCount = inputData.processorRetryCount || 0;
100385
102018
  const canRetryError = maxErrorProcessorRetries !== void 0 && currentRetryCount < maxErrorProcessorRetries && !eagerCoordinator?.hasSuspendedHandback;
100386
- const processorRunner = new ProcessorRunner({
102019
+ const errorResult = await new ProcessorRunner({
100387
102020
  inputProcessors: inputProcessors || [],
100388
102021
  outputProcessors: outputProcessors || [],
100389
102022
  errorProcessors: errorProcessors || [],
@@ -100391,12 +102024,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100391
102024
  agentName: agentId || "unknown",
100392
102025
  agent,
100393
102026
  processorStates
100394
- });
100395
- const apiErrorWriter2 = outputWriter ? { custom: async (data, options) => outputWriter(data, {
100396
- ...options,
100397
- messageId: currentMessageId
100398
- }) } : void 0;
100399
- const errorResult = await processorRunner.runProcessAPIError({
102027
+ }).runProcessAPIError({
100400
102028
  error: runState.state.apiError,
100401
102029
  messages: messageList.get.all.db(),
100402
102030
  messageList,
@@ -100405,7 +102033,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100405
102033
  retryCount: currentRetryCount,
100406
102034
  requestContext,
100407
102035
  tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,
100408
- writer: apiErrorWriter2,
102036
+ writer: apiErrorWriter,
100409
102037
  abortSignal: options?.abortSignal,
100410
102038
  messageId: currentMessageId,
100411
102039
  rotateResponseMessageId: () => {
@@ -100475,6 +102103,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100475
102103
  cleanupProviderToolSpans(true);
100476
102104
  eagerCoordinator?.recarryCommittedWork(transcriptStep.messageId);
100477
102105
  messageList.rollbackToStepBoundary(transcriptStep.messageId, iterationBoundary);
102106
+ restoreApiErrorRows(transcriptStep.messageId);
100478
102107
  await discardAttemptEagerWork();
100479
102108
  if (runAbortSignal?.aborted) {
100480
102109
  await options?.onAbort?.({
@@ -102880,6 +104509,8 @@ function isStaleRequest(expiresAt) {
102880
104509
  /** Thread lease TTL and renew interval; shared with the durable execution lease. */
102881
104510
  const AGENT_THREAD_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
102882
104511
  const AGENT_THREAD_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
104512
+ const DURABLE_THREAD_CLAIM_WAIT_MS = 5e3;
104513
+ const DURABLE_THREAD_CLAIM_POLL_MS = 100;
102883
104514
  /**
102884
104515
  * TTL for a suspended run's warm in-memory state — the parked thread-run record
102885
104516
  * (swept by #sweepStaleSuspendedRecords). The Mastra internal-workflow registry
@@ -103238,12 +104869,25 @@ var AgentThreadStreamRuntime = class {
103238
104869
  return state.leaseOwners.get(runId) ?? threadLeaseOwner(runId, state.threadRunsById.get(runId)?.generation);
103239
104870
  }
103240
104871
  /** @internal Qualify a shared thread lease before dispatching this execution. */
103241
- async claimDurableThreadLease(pubsub, runId, threadId, resourceId, generation, executionId) {
103242
- const lease = await this.#acquireThreadLease(pubsub, this.#threadKey(resourceId, threadId), runId, threadLeaseOwner(runId, generation, executionId));
104872
+ async claimDurableThreadLease(pubsub, runId, threadId, resourceId, generation, executionId, workerFenced = false) {
104873
+ const key = this.#threadKey(resourceId, threadId);
104874
+ const owner = threadLeaseOwner(runId, generation, executionId);
104875
+ let lease = await this.#acquireThreadLease(pubsub, key, runId, owner);
104876
+ const previousOwner = parseThreadLeaseOwner(lease.owner);
104877
+ if (!lease.acquired && (lease.owner === void 0 || previousOwner && previousOwner[0] !== runId && (previousOwner[1] === "generation" || previousOwner[1] === "execution"))) {
104878
+ const blockingOwner = lease.owner;
104879
+ const deadline = Date.now() + DURABLE_THREAD_CLAIM_WAIT_MS;
104880
+ while (!lease.acquired && (lease.owner === void 0 || lease.owner === blockingOwner)) {
104881
+ const remaining = deadline - Date.now();
104882
+ if (remaining <= 0) break;
104883
+ await new Promise((resolve) => setTimeout(resolve, Math.min(remaining, DURABLE_THREAD_CLAIM_POLL_MS)));
104884
+ lease = await this.#acquireThreadLease(pubsub, key, runId, owner);
104885
+ }
104886
+ }
103243
104887
  if (!lease.acquired) throw new AgentThreadLeaseConflictError(runId, lease.owner ?? "another owner");
103244
104888
  if (this.#getState(pubsub).leaseRenewalTimers.has(runId)) {
103245
104889
  this.#stopLeaseRenewal(pubsub, runId);
103246
- this.#startLeaseRenewal(pubsub, this.#threadKey(resourceId, threadId), runId, threadLeaseOwner(runId, generation, executionId));
104890
+ this.#startLeaseRenewal(pubsub, key, runId, owner, workerFenced);
103247
104891
  }
103248
104892
  }
103249
104893
  /** @internal Renew only the captured execution's thread lease; never acquire or transfer it. */
@@ -103259,6 +104903,11 @@ var AgentThreadStreamRuntime = class {
103259
104903
  const { acquired } = await this.#getLeaseProvider(pubsub).acquireLease(this.#threadKey(resourceId, threadId), threadLeaseOwner(runId, generation, executionId), AGENT_THREAD_LEASE_TTL_MS);
103260
104904
  return acquired;
103261
104905
  }
104906
+ /** @internal Missing ownership is not evidence that another run took the thread. */
104907
+ async isDurableThreadLeaseHeldByAnotherRun(pubsub, runId, threadId, resourceId) {
104908
+ const owner = await this.#getLeaseProvider(pubsub).getLeaseOwner(this.#threadKey(resourceId, threadId));
104909
+ return owner !== void 0 && threadLeaseRunId(owner) !== runId;
104910
+ }
103262
104911
  /** @internal Whether `error` from the thread lease backend means it is refusing every client, not just this one. */
103263
104912
  isThreadLeaseBackendUnavailableToAll(pubsub, error) {
103264
104913
  return this.#getLeaseProvider(pubsub).isUnavailableToAll?.(error) === true;
@@ -103472,7 +105121,7 @@ var AgentThreadStreamRuntime = class {
103472
105121
  * that point, so once it passes a successor may own the thread and the
103473
105122
  * run is aborted, even if the backend never answers.
103474
105123
  */
103475
- #startLeaseRenewal(pubsub, key, runId, owner = this.#threadLeaseOwner(pubsub, runId)) {
105124
+ #startLeaseRenewal(pubsub, key, runId, owner = this.#threadLeaseOwner(pubsub, runId), workerFenced = false, confirmedSentAt = Date.now()) {
103476
105125
  const state = this.#getState(pubsub);
103477
105126
  if (state.leaseRenewalTimers.has(runId)) {
103478
105127
  if (state.leaseOwners.get(runId) === owner) return;
@@ -103480,10 +105129,12 @@ var AgentThreadStreamRuntime = class {
103480
105129
  }
103481
105130
  const leaseProvider = this.#getLeaseProvider(pubsub);
103482
105131
  const timer = setInterval(() => {
105132
+ if (workerFenced && state.pendingLeaseRenewals.has(runId)) return;
103483
105133
  const sentAt = Date.now();
103484
105134
  state.pendingLeaseRenewals.set(runId, (state.pendingLeaseRenewals.get(runId) ?? 0) + 1);
103485
105135
  leaseProvider.renewLease(key, owner, AGENT_THREAD_LEASE_TTL_MS).then((renewed) => {
103486
105136
  if (!renewed) {
105137
+ if (workerFenced) return;
103487
105138
  if (state.leaseRenewalTimers.get(runId) !== timer) return;
103488
105139
  const confirmed = state.leaseDeadlines.get(runId)?.confirmedSentAt;
103489
105140
  (confirmed === void 0 || Date.now() >= confirmed + AGENT_THREAD_LEASE_TTL_MS ? this.#retakeLease(pubsub, key, runId, timer) : Promise.resolve(false)).then((kept) => {
@@ -103492,7 +105143,7 @@ var AgentThreadStreamRuntime = class {
103492
105143
  this.#abortLeaseLostRun(state, runId);
103493
105144
  });
103494
105145
  } else {
103495
- if (state.leaseRenewalTimers.get(runId) === timer) this.#armLeaseDeadline(pubsub, key, runId, sentAt);
105146
+ if (!workerFenced && state.leaseRenewalTimers.get(runId) === timer) this.#armLeaseDeadline(pubsub, key, runId, sentAt);
103496
105147
  if (state.sweptLeasedRunIds.has(runId)) state.sweptLeasedRunIds.set(runId, Date.now());
103497
105148
  }
103498
105149
  }).catch(() => {}).finally(() => {
@@ -103504,7 +105155,8 @@ var AgentThreadStreamRuntime = class {
103504
105155
  if (typeof timer === "object" && timer && typeof timer.unref === "function") timer.unref();
103505
105156
  state.leaseRenewalTimers.set(runId, timer);
103506
105157
  state.leaseOwners.set(runId, owner);
103507
- this.#armLeaseDeadline(pubsub, key, runId, Date.now());
105158
+ if (workerFenced) return;
105159
+ this.#armLeaseDeadline(pubsub, key, runId, confirmedSentAt);
103508
105160
  if (!this.#resolveLeaseProvider(pubsub).isFallback) {
103509
105161
  const fence = this.#leaseFence(pubsub, key, runId, timer, owner);
103510
105162
  state.leaseFences.set(runId, fence);
@@ -103547,6 +105199,7 @@ var AgentThreadStreamRuntime = class {
103547
105199
  this.#stopLeaseRenewal(pubsub, runId, timer);
103548
105200
  this.#abortLeaseLostRun(state, runId);
103549
105201
  }
105202
+ if (state.threadRunsById.get(runId)?.lifecycle === "suspended" && typeof owner === "string" && threadLeaseRunId(owner) === runId) return;
103550
105203
  throw new AgentThreadLeaseLostError(runId);
103551
105204
  };
103552
105205
  }
@@ -104599,7 +106252,7 @@ var AgentThreadStreamRuntime = class {
104599
106252
  releaseMessageIdentity(getErrorFromUnknown(error));
104600
106253
  throw error;
104601
106254
  }
104602
- const callerRequestContext = remoteRequestContextEntries ? restoreRequestContext$1(remoteRequestContextEntries, ownerStreamOptions?.requestContext) : incomingStreamOptions?.requestContext;
106255
+ const callerRequestContext = remoteRequestContextEntries ? restoreRequestContext(remoteRequestContextEntries, ownerStreamOptions?.requestContext) : incomingStreamOptions?.requestContext;
104603
106256
  const incomingRequestContext = callerRequestContext && claimedOwnerRequestContext(callerRequestContext, ownerStreamOptions?.requestContext);
104604
106257
  streamOptions = incomingRequestContext === void 0 ? ownerStreamOptions : {
104605
106258
  ...ownerStreamOptions,
@@ -106223,7 +107876,14 @@ var AgentThreadStreamRuntime = class {
106223
107876
  async #publishRunSuspended(pubsub, key, record) {
106224
107877
  record.lifecycle = "suspended";
106225
107878
  record.suspendedAt = Date.now();
106226
- if (this.#getState(pubsub).shutdownStreams.has(record.streamId)) return;
107879
+ const state = this.#getState(pubsub);
107880
+ const owner = state.leaseOwners.get(record.runId);
107881
+ if (owner && state.threadRunsById.get(record.runId) === record && !state.leaseDeadlines.has(record.runId)) {
107882
+ const resolvedPubSub = this.#getPubSub(pubsub);
107883
+ this.#stopLeaseRenewal(resolvedPubSub, record.runId);
107884
+ this.#startLeaseRenewal(resolvedPubSub, key, record.runId, owner, false, record.suspendedAt - AGENT_THREAD_LEASE_TTL_MS);
107885
+ }
107886
+ if (state.shutdownStreams.has(record.streamId)) return;
106227
107887
  await this.#publishAndWait(pubsub, key, {
106228
107888
  type: "run-suspended",
106229
107889
  runId: record.runId,
@@ -108517,6 +110177,7 @@ async function participateInDurableExecution(mastra, event, execute) {
108517
110177
  const fence = await participant.fence;
108518
110178
  if (!fence) return await execute();
108519
110179
  await fence.verify();
110180
+ await carryEndedSegment(mastra, event);
108520
110181
  let parentRunId = runId;
108521
110182
  for (const nestedRunId of nestedRunIds) {
108522
110183
  fence.coverNestedRun(parentRunId, nestedRunId);
@@ -108555,6 +110216,51 @@ async function retrySettledDurableExecution(mastra, event) {
108555
110216
  await settleEventedDurableExecution(mastra, event);
108556
110217
  return true;
108557
110218
  }
110219
+ /**
110220
+ * When a suspension beside the failed tool call ends the segment's spans, tell this failure and the run's own, through
110221
+ * the request context they inherit. Called before the delivery passes that context on.
110222
+ */
110223
+ async function carryEndedSegment(mastra, event) {
110224
+ const { workflowId, stepResults, requestContext } = event.data ?? {};
110225
+ const state = stepResults?.input;
110226
+ const calls = stepResults?.[DurableStepIds.TOOL_CALL];
110227
+ if (event.type !== "workflow.fail" || workflowId !== DurableStepIds.AGENTIC_EXECUTION || !state?.runId) return;
110228
+ if (calls?.status !== "failed" || Array.isArray(calls.payload) && !calls.payload[0]?.sideBySide) return;
110229
+ const context = new RequestContext(Object.entries(requestContext ?? {}));
110230
+ const segment = segmentSpanData(context, state.runId, state);
110231
+ if (segment.carried) return;
110232
+ const { runId, iterationCount } = state;
110233
+ if (await claimSegmentEnd({
110234
+ mastra,
110235
+ requestContext: context,
110236
+ runId,
110237
+ iterationCount,
110238
+ outcome: "fail"
110239
+ }) ?? !segmentEndedBySuspension(segment, stepResults)) return;
110240
+ event.data.requestContext = { ...requestContext };
110241
+ carrySegmentSpans(event.data.requestContext, runId, null);
110242
+ }
110243
+ function endFailedSpans(mastra, event) {
110244
+ const { stepResults, prevResult, requestContext } = event.data ?? {};
110245
+ const runId = stepResults?.input?.runId;
110246
+ if (!runId || isExecutionFenceError(prevResult?.error)) return;
110247
+ endFailedSegmentSpans({
110248
+ mastra,
110249
+ requestContext: new RequestContext(Object.entries(requestContext ?? {})),
110250
+ runId,
110251
+ state: stepResults.input,
110252
+ steps: stepResults,
110253
+ error: getErrorFromUnknown(prevResult?.error ?? "Workflow execution failed"),
110254
+ live: getRunRegistryEntry(runId, mastra),
110255
+ firstPairOnly: true
110256
+ });
110257
+ }
110258
+ /** End the MODEL_STEP of a failed iteration. Only the iteration's own event still carries it. */
110259
+ function endFailedIteration(mastra, event) {
110260
+ if (event.type !== "workflow.fail" || event.data?.workflowId !== DurableStepIds.AGENTIC_EXECUTION) return;
110261
+ if (isWorkflowStepConflictError(event.data.prevResult?.error)) return;
110262
+ endFailedSpans(mastra, event);
110263
+ }
108558
110264
  /** Called only after the root terminal handler has persisted and published its outcome. */
108559
110265
  async function settleEventedDurableExecution(mastra, event) {
108560
110266
  if (!isRootTerminal(event)) return;
@@ -108591,6 +110297,7 @@ async function settleEventedDurableExecution(mastra, event) {
108591
110297
  fence
108592
110298
  });
108593
110299
  await ExecutionFence.releaseSharedClaim(mastra, event.runId, claim, "settled");
110300
+ if (event.type === "workflow.fail" && !released) endFailedSpans(mastra, event);
108594
110301
  if (claim.threadId && event.type !== "workflow.suspend") await agentThreadStreamRuntime.releaseDurableThreadLease(mastra.pubsub, event.runId, claim.threadId, claim.resourceId, claim.generation, claim.executionId);
108595
110302
  if (claim.memoryFenced && fence) await (await mastra.getStorage()?.getStore("memory"))?.retireRunFence(fence);
108596
110303
  await mastra.__getRunScope(event.runId)?.get(PARTICIPANTS)?.get(claim.executionId)?.stop();
@@ -108649,6 +110356,27 @@ function getRunRegistryEntry(runId, mastra) {
108649
110356
  return unwrapMastraTracingProxy(entry.mastra) === unwrapMastraTracingProxy(mastra) ? entry : void 0;
108650
110357
  }
108651
110358
  /**
110359
+ * Request-context key that identifies a run segment on engines whose steps carry no Core execution
110360
+ * claim (Inngest). The engine stores the same value on the registry entry it seeds for the segment.
110361
+ */
110362
+ const DURABLE_CONTEXT_SEGMENT_KEY = "__mastra_durableContextSegment";
110363
+ /**
110364
+ * The registry's live request context, when it belongs to the execution running this step. Once
110365
+ * another process claims the run (for example an approval from another host), the context cached
110366
+ * here still belongs to the previous caller and must not be reused for the new execution.
110367
+ */
110368
+ function getLiveRunRequestContext(entry, runId, stepContext, executionId) {
110369
+ const live = entry?.requestContext;
110370
+ if (!live || entry.requestContextRebuilt) return void 0;
110371
+ const expectedExecutionId = executionId ?? (runId ? getExecutionClaim(stepContext, runId)?.executionId : void 0);
110372
+ if (!expectedExecutionId) {
110373
+ const stepSegment = stepContext?.get(DURABLE_CONTEXT_SEGMENT_KEY);
110374
+ if (stepSegment === void 0) return live;
110375
+ return stepSegment === entry.requestContextSegment ? live : void 0;
110376
+ }
110377
+ return runId && getExecutionClaim(live, runId)?.executionId === expectedExecutionId ? live : void 0;
110378
+ }
110379
+ /**
108652
110380
  * Publish an entry for `runId`, owned by `mastra`, unless the slot holds
108653
110381
  * another Mastra instance's live run. Returns whether the entry was stored.
108654
110382
  */
@@ -108805,6 +110533,11 @@ async function abandonDurableAgentExecutions(mastra) {
108805
110533
  function endRunSpansWithError(runId, error, options = {}) {
108806
110534
  try {
108807
110535
  const entry = globalRunRegistry.has(runId) ? globalRunRegistry.get(runId) : void 0;
110536
+ if (options.endStep ?? options.endSpan ?? true) entry?.openStepSpan?.error(stepFailure({
110537
+ error,
110538
+ ...executionFailureTermination(error),
110539
+ endSpan: true
110540
+ }));
108808
110541
  (entry?.resumeModelSpan ?? entry?.modelSpan)?.error({
108809
110542
  error,
108810
110543
  ...executionFailureTermination(error),
@@ -108953,4 +110686,4 @@ var ExtendedRunRegistry = class extends RunRegistry {
108953
110686
  this.#memoryInfo.clear();
108954
110687
  }
108955
110688
  };
108956
- export { resolveDurableToolCallConcurrency as $, spanQueryIdentitySchema as $a, hydrateSerializedStepErrors as $c, SchemaValidationError as $i, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH as $n, TokenCostControl as $o, InMemoryMemory as $r, publishAbortRequest as $s, knowledgeDeliveredPins as $t, assembleAgentFromFsEntry as A, tracePageRequestSchema as Aa, ExecutionEngine as Ac, assertKnowledgeNoteTextWithinBound as Ai, ProcessorOutputStepPhaseSchema as Al, resolveWaitUntil as An, upsertMessageVectors as Ao, WorkflowDefinitionsStorage as Ar, createWorkflow as As, readRunDeadline as At, createDurableGoalStep as B, SPAN_QUERY_MAX_COST_METRICS as Ba, abortableSleep as Bc, InMemoryHarness as Bi, isAgentCompatible as Bl, createChannelToolScope as Bn, DEFAULT_RESPONSE_CACHE_TTL_SECONDS as Bo, dispatchDueNotifications as Br, WorkflowStepConflictError as Bs, formatCompletionFeedback as Bt, ScorerRunError as C, transformRow as Ca, WORKFLOW_RUN_LEASE_TTL_MS as Cc, MAX_KNOWLEDGE_PAGE_BODY_LINKS as Ci, MessageContentSchema as Cl, knowledgeRunScopes as Cn, DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS as Co, WorkflowsInMemory as Cr, StreamErrorRetryProcessor as Cs, runDurableStreamUntilIdle as Ct, notScorable as D, readTracePage as Da, SCORING_PREDICATE_ROOTS as Dc, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH as Di, ProcessorMessageContentSchema as Dl, encodeKnowledgeScopeId as Dn, extractMessageEmbeddingText as Do, mergeStepResult as Dr, getGoalActivityDurationMs as Ds, DurableStepIds as Dt, isNotScorable as E, TracePageError as Ea, DefaultExecutionEngine as Ec, MAX_KNOWLEDGE_PAGE_LINKS as Ei, ProcessorInputStepPhaseSchema as El, decodeKnowledgeScopeId as En, chunkMessageText as Eo, createEmptyWorkflowSnapshot as Er, PrefillErrorHandler as Es, DurableAgentDefaults as Et, prepareForDurableExecution as F, planThreadRowsQuery as Fa, createStepFromAgent$1 as Fc, knowledgePinDepth as Fi, ReasoningPartSchema as Fl, renderBuiltInToolEvent as Fn, isSystemReminderMessage as Fo, InMemorySchedulesStorage as Fr, createStep as Fs, pruneAgentLoopSnapshot as Ft, serializeDurableOptions as G, buildSpanQueryResponse as Ga, createRestartExecutionParams as Gc, DatasetsStorage as Gi, currentRunGeneration as Gl, MemoryInputFilter as Gn, SkillSearchProcessor as Go, notificationSummaryContents as Gr, emitAbortEvent as Gs, runChecks as Gt, createDurableLLMMappingStep as H, SPAN_QUERY_MAX_LIMIT as Ha, assertTimeTravelGraphMatchesSnapshot as Hc, ExperimentsInMemory as Hi, RUN_FENCING_NOT_SUPPORTED_ERROR_ID as Hl, resolveChannelToolsSettings as Hn, ResponseCache as Ho, createNotificationSummarySignal as Hr, isWorkflowStepConflictError as Hs, formatValidationFeedback as Ht, applyReservedMemoryContextKeys as I, threadQueryIdentitySchema as Ia, createStepFromClassifier as Ic, knowledgePositionBetween as Ii, SourcePartSchema as Il, formatToolApproval as In, augmentWithInit as Io, SchedulesStorage as Ir, createWorkflow$1 as Is, DEFAULT_TOOL_DECLINE_REASON as It, serializeToolsMetadata as J, parseSpanQueryRequest as Ja, defineStateAccessors as Jc, assertSupportedPatterns as Ji, resolveRunFence as Jl, WorkingMemory as Jn, ToolSearchProcessor as Jo, readNotificationRoutingRequirement as Jr, emitFinishEvent as Js, runStreamCompletionScorers as Jt, serializeDurableState as K, createSpanQueryPreview as Ka, createTimeTravelExecutionParams as Kc, DatasetItemIdentityConflictError as Ki, isRunFenceConflictError as Kl, SemanticRecall as Kn, SkillsProcessor as Ko, notificationSummarySignalMetadata as Kr, emitChunkEvent as Ks, runCompletionScorers as Kt, persistDurableRunInput as L, threadQueryRequestSchema as La, createStepFromTool as Lc, knowledgeScopeReadable as Li, StepStartPartSchema as Ll, ChannelSessionRejectedError as Ln, getStorageSource as Lo, normalizeScheduleTarget as Lr, WorkflowEventProcessor as Ls, resolveDeclineReason as Lt, AGENT_RESUME_CLAIM_STALE_MS as M, THREAD_QUERY_DEFAULT_LIMIT as Ma, normalizeConcurrency as Mc, canonicalKnowledgeName as Mi, ProcessorStepInputSchema as Ml, MastraStateAdapter as Mn, MemoryProcessor as Mo, ToolProviderConnectionsStorage as Mr, EventedWorkflow as Ms, getRunStreamSlot as Mt, Agent as N, THREAD_QUERY_MAX_LIMIT as Na, runWithConcurrency as Nc, knowledgeLinkRefKey as Ni, ProcessorStepOutputSchema as Nl, ChatChannelProcessor as Nn, memoryDefaultOptions as No, ScoresInMemory as Nr, cloneStep as Ns, getScopeStreamSlot as Nt, agentConfig as O, tracePageIdSchema as Oa, evaluateScoringPredicate as Oc, MAX_KNOWLEDGE_PAGE_LIST_LIMIT as Oi, ProcessorMessageSchema as Ol, buildKnowledgeInstructions as On, messageVectorId as Oo, mergeWorkflowStepResult as Or, cloneWorkflow as Os, RUN_DEADLINE_KEY as Ot, normalizeResumeGenerateArgs as P, encodeThreadQueryCursor as Pa, createMappingStep as Pc, knowledgePagePath as Pi, ProcessorStepSchema as Pl, CHAT_CHANNEL_RENDER_CONTEXT_KEY as Pn, filterSystemReminderMessages as Po, ScoresStorage as Pr, cloneWorkflow$1 as Ps, untilIdleHandlesBackgroundTask as Pt, createDurableBackgroundTaskCheckStep as Q, spanQueryIdentityKey as Qa, getStepIds as Qc, SchemaUpdateValidationError as Qi, MockMemory as Qn, CostGuardProcessor as Qo, resolveNotificationDeliveryDecision as Qr, AgentStreamBus as Qs, PINNED_READ_MEMO_KEY as Qt, detachFullStreamOnEnd as R, threadQueryResponseSchema as Ra, RESUME_SNAPSHOT_POLL_INTERVAL_MS as Rc, parseKnowledgePageRef as Ri, TextPartSchema as Rl, DEFAULT_CHANNEL_TOOLS_SETTINGS as Rn, createBackgroundWorkSignalProcessor as Ro, InMemoryNotificationsStorage as Rr, StepExecutor as Rs, getServerSideFallbackInfo as Rt, MastraScorer as S, storageMessageMatchesMetadataFilter as Sa, nestedRunStatusOf as Sc, MAX_KNOWLEDGE_NOTE_TOKENS as Si, ImagePartSchema as Sl, knowledgeMemoryScopes as Sn, UniqueViolationError as So, MockStore as Sr, FILE_UPLOAD_ERROR_CODES as Ss, createDurableAgentStream as St, filterRun as T, validateStorageMetadataFilter as Ta, repeatAfterSettled as Tc, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS as Ti, ProcessorInputPhaseSchema as Tl, strongerKnowledgeRole as Tn, buildMessageEmbeddingRows as To, WorkflowsStorage as Tr, isRetryableOpenAIResponsesStreamError as Ts, DURABLE_STOP_WHEN_ERROR_ID as Tt, createDurableToolCallStep as U, SPAN_QUERY_MAX_PREVIEW_CHARACTERS as Ua, cleanStepResult as Uc, ExperimentsStorage as Ui, RunFenceConflictError as Ul, toChatLogger as Un, buildResponseCacheKey as Uo, notificationSignalAttributes as Ur, __resetExecutionFencesForTests as Us, generateFinalResult as Ut, createDurableIsTaskCompleteStep as V, SPAN_QUERY_MAX_CURSOR_BYTES as Va, applyStateDelta as Vc, HarnessStorage as Vi, RUN_FENCE_CONFLICT_ERROR_ID as Vl, createChannelTools as Vn, RESPONSE_CACHE_CONTEXT_KEY as Vo, createNotificationSignal as Vr, assertWorkflowStepGuard as Vs, formatStreamCompletionFeedback as Vt, createWorkflowInput as W, SPAN_QUERY_ORDER_FIELDS as Wa, createDeprecationProxy as Wc, DatasetsInMemory as Wi, coverNestedRun as Wl, BaseProcessor as Wn, WorkspaceInstructionsProcessor as Wo, notificationSignalMetadata as Wr, diffResponseMessages as Ws, generateStructuredFinalResult as Wt, MessagePartSpans as X, resolveSpanQueryCost as Xa, getResumeLabelsByStepId as Xc, getSchemaValidator as Xi, runOutsideRunFenceScope as Xl, MemoryRunState as Xn, ToolCallFilter as Xo, defaultNotificationDeliveryDecision as Xr, emitStepStartEvent as Xs, loop as Xt, createDurableLLMExecutionStep as Y, planSpanQuery as Ya, getRestartStartIndex as Yc, createValidator as Yi, runFencingNotSupportedError as Yl, MessageHistory as Yn, AgentsMDInjector as Yo, MAX_NOTIFICATION_DELIVERY_ATTEMPTS as Yr, emitStepFinishEvent as Ys, runValidation as Yt, isSpanChunk as Z, spanQueryCostSchema as Za, getSingleStepEntryId as Zc, UnsupportedSchemaPatternError as Zi, setRunFenceContext as Zl, getMemoryRunState as Zn, RegexFilterProcessor as Zo, resolveDeliveryFailureUpdate as Zr, emitSuspendedEvent as Zs, validateModelTimeoutSettings as Zt, runEvals as _, hasErrorCode as _a, evaluatePredicate as _c, KnowledgeMoveTooLargeError as _i, workflowTermination as _l, knowledgeAccessGrants as _n, toEntityType as _o, GitHubSourceControlProvider as _r, STABILITY_ERROR_PROCESSOR_IDS as _s, toolRequiresApproval as _t, endRunSpansWithError as a, BackgroundTasksStorage as aa, AgentControlEventTypes as ac, KNOWLEDGE_STORAGE_CONTRACT_VERSION as ai, runCountDeprecationMessage as al, removeKnowledgeNote as an, getTraceQueryDeltaWatermark as ao, assertKnowledgeScopeWithinCeiling as ar, getMemoryTokenBoundary as as, baseIterationStateSchema as at, validateAndSaveScore as b, safelyParseJSON as ba, nestedRunParentOf as bc, KnowledgePageKeyConflictError as bi, isDurableAgentLike as bl, KnowledgeDeclarationError as bn, FactoryStorage as bo, FilesystemDB as br, UnsupportedFileHandler as bs, liveSegmentSpan as bt, globalRunRegistry as c, retentionCutoffMs as ca, getNestedWorkflow as cc, KnowledgeNotFoundError$1 as ci, validateStepRequestContext as cl, upsertKnowledgePage as cn, buildCreateSpanRecord as co, expandKnowledgeScope as cr, BatchPartsProcessor as cs, modelListEntrySchema as ct, takeRunScorerInstances as d, createStoreErrorId as da, Workflow as dc, KnowledgeTransactionDeadlineError as di, validateStepSuspendData as dl, KnowledgeLinkRefreshIncompleteError as dn, buildMetricRecord as do, knowledgeSemanticDocumentId as dr, StructuredOutputProcessor as ds, loadRunStoredMessages as dt, InMemoryChannelsStorage as ea, requestAcknowledgedAbort as ec, MemoryStorage as ei, isEntryFinished as el, buildKnowledgePageTools as en, spanQueryRequestSchema as eo, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH as er, SystemPromptScrubber as es, buildStepRecord as et, AgentThreadLeaseLostError as f, createVectorErrorId as fa, cloneStep$1 as fc, KnowledgeUnsupportedCapabilityError as fi, waitForSuspendedSnapshot as fl, knowledgeSubtree as fn, buildScoreRecord as fo, knowledgeSemanticIdempotencyKey as fr, LanguageDetector as fs, rebuildRunToolsFromMastra as ft, describeNonSuccessFinishReason as g, getSqlType as ga, predicateToCondition as gc, parseKnowledgeWikilinks as gi, waitMs as gl, updateKnowledgeLinks as gn, serializeSpanAttributes as go, StoreOperations as gr, UnicodeNormalizer as gs, resolveTool$1 as gt, AGENTIC_LOOP_WORKFLOW_ID as h, getDefaultValue as ha, mapVariable as hc, inspectKnowledgeSchema as hi, assertDrainTimeout as hl, syncKnowledgePageBodyLinks as hn, getStringOrNull as ho, StoreOperationsInMemory as hr, ModerationProcessor as hs, resolveRuntimeDependencies as ht, deleteRunRegistryEntry as i, BackgroundTasksInMemory as ia, AGENT_STREAM_TOPIC as ic, KnowledgeImportersStorage as ii, resolveForeachConcurrency as il, moveKnowledgePage as in, encodeTraceQueryDeltaCursor as io, assertKnowledgeRecordTextWithinBound as ir, advanceMemoryTokenBoundary as is, baseDurableAgenticInputSchema as it, MAX_FS_SUBAGENT_DEPTH as j, tracePageResponseSchema as ja, createConcurrencyLimiter as jc, assertKnowledgePageDescriptionWithinBound as ji, ProcessorOutputStreamPhaseSchema as jl, defaultTypingStatus as jn, MastraMemory as jo, InMemoryToolProviderConnectionsStorage as jr, EventedRun as js, __registerMastraCtor as jt, agentInstructions as k, tracePageNodeSchema as ka, validateScoringPredicate as kc, MAX_KNOWLEDGE_PIN_LIST_DEPTH as ki, ProcessorOutputResultPhaseSchema as kl, AgentChannels as kn, resolveMaxChunkChars as ko, InMemoryWorkflowDefinitionsStorage as kr, createEventedWorkflow as ks, ensureRemoteAbortListener as kt, isDurableAgentExecutionDetached as l, runRetentionBatches as la, getStepEntry as lc, KnowledgeSchemaResetRequiredError as li, validateStepResumeData as ll, KnowledgeSemanticIndex as ln, buildFeedbackRecord as lo, isKnowledgeScopeVisible as lr, ModelSelectionProcessor as ls, executeDurableAgentScorers as lt, AGENTIC_EXECUTION_WORKFLOW_ID as m, filterByDateRange as ma, isProcessor$1 as mc, createKnowledgeUlid as mi, getEntryWorkflow as ml, reindexKnowledgeLinks as mn, getObjectOrNull as mo, parseKnowledgeNodeCursor as mr, PromptInjectionDetector as ms, resolveModel as mt, RunRegistry as n, InMemoryBlobStore as na, createRunAbortController as nc, KnowledgeImporterBindingConflictError as ni, omitPriorCompletionFields as nl, knowledgeRunPrincipals as nn, spanQueryRowSchema as no, assertKnowledgeCeilingRaised as nr, groupLinkedToolMessages as ns, createBaseIterationStateUpdate as nt, getActiveDurableAgentWorkflowExecutions as o, executeRetentionPrune as oa, AgentStreamEventTypes as oc, KNOWLEDGE_STORAGE_SCHEMA_VERSION as oi, setLongTimeout as ol, removeKnowledgePage as on, planThreadQuery as oo, canonicalizeKnowledgeScope as or, isAfterMemoryTokenBoundary as os, durableAgenticOutputSchema as ot, agentThreadStreamRuntime as p, ensureDate as pa, createStep$1 as pc, assertKnowledgeSchemaCompatible as pi, getEntryId as pl, refreshKnowledgeLinksTo as pn, buildUpdateSpanRecord as po, knowledgeVisibleScopeKeys as pr, PIIDetector as ps, resolveInternalState as pt, serializeModelConfig as q, encodeSpanQueryCursor as qa, defineLazyWriter as qc, SchemaValidator as qi, matchesRunFence as ql, globalEmbeddingCache as qn, formatSkillsCatalog as qo, summarizeNotifications as qr, emitErrorEvent as qs, runDefaultCompletionCheck as qt, abandonDurableAgentExecutions as r, BlobStore as ra, AGENT_CONTROL_TOPIC as rc, KnowledgeImporterRunStateError as ri, omitPriorSuspensionFields as rl, addKnowledgeNote as rn, encodeTraceQueryCursor as ro, assertKnowledgeDescriptionWithinBound as rr, loadMessageHistory as rs, accumulatedUsageSchema as rt, getRunRegistryEntry as s, resolveRetentionTargets as sa, EventedExecutionEngine as sc, KnowledgeConflictError as si, validateStepInput as sl, updateKnowledgeNote as sn, planTraceQuery as so, createKnowledgeNodeCursor as sr, normalizeMessageHistoryConfig as ss, modelConfigSchema as st, ExtendedRunRegistry as t, ChannelsStorage as ta, subscribeToAbortRequests as tc, InMemoryKnowledgeStorage as ti, isSingleStepEntry as tl, KnowledgeRun as tn, spanQueryResponseSchema as to, MAX_KNOWLEDGE_SCOPE_TAGS as tr, TokenLimiterProcessor as ts, calculateAccumulatedUsage as tt, setRunRegistryEntry as u, createStorageErrorId as ua, Run as uc, KnowledgeStorage as ui, validateStepStateData as ul, embed$2 as un, buildLogRecord as uo, knowledgeScopeKey as ur, ClassifierProcessor as us, runDurableFinishSideEffects as ut, flushBeforeTraceRead as v, jsonValueEquals as va, cancelNestedRun as vc, KnowledgePageDepthError as vi, hasDurableExecution as vl, knowledgeReadScopeFor as vn, ObservabilityInMemory as vo, createGitHubSourceControlProviderFromEnv as vr, defaultStabilityErrorProcessors as vs, resolveAgentById as vt, createScorer as w, transformScoreRow as wa, renewWorkflowLease as wc, MAX_KNOWLEDGE_PAGE_DEPTH as wi, MessagePartSchema as wl, knowledgeScopeAddress as wn, MESSAGE_EMBEDDING_CHARS_PER_TOKEN as wo, cloneRunData as wr, isBadRequestError as ws, runResumeDurableStreamUntilIdle as wt, createClassifierScorer as x, serializeDate as xa, nestedRunRecoveryAction as xc, MAX_KNOWLEDGE_MOVE_PAGES as xi, FilePartSchema as xl, compileKnowledgeScopes as xn, FactoryStorageDomain as xo, InMemoryStore as xr, FileUploadProcessor as xs, segmentSpanData as xt, createOnScorerHook as y, parseDuration as ya, createNestedRunParentStatusLookup as yc, KnowledgePageHasChildrenError as yi, hasResumableStreams as yl, knowledgeRoleOn as yn, ObservabilityStorage as yo, FilesystemStore as yr, isMalformedFunctionCallError as ys, carrySegmentSpans as yt, createDurableAgenticWorkflow as z, threadQueryRowSchema as za, RESUME_SNAPSHOT_WAIT_STATUSES as zc, KnowledgeInvalidCursorError as zi, ToolInvocationPartSchema as zl, channelToolScopeResolver as zn, CyberRefusalHandler as zo, NotificationsStorage as zr, computeScheduleDefinitionHash as zs, formatCheckFeedback as zt };
110689
+ export { createDurableBackgroundTaskCheckStep as $, createSpanQueryPreview as $a, createRestartExecutionParams as $c, DatasetItemIdentityConflictError as $i, RUN_FENCING_NOT_SUPPORTED_ERROR_ID as $l, SemanticRecall as $n, SkillsProcessor as $o, notificationSummarySignalMetadata as $r, emitStepFinishEvent as $s, knowledgeDeliveredPins as $t, agentInstructions as A, transformRow as Aa, DefaultExecutionEngine as Ac, MAX_KNOWLEDGE_PAGE_BODY_LINKS as Ai, ImagePartSchema as Al, resolveWaitUntil as An, DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS as Ao, WorkflowsInMemory as Ar, StreamErrorRetryProcessor as As, readRunDeadline as At, createDurableAgenticWorkflow as B, THREAD_QUERY_MAX_LIMIT as Ba, normalizeConcurrency as Bc, knowledgeLinkRefKey as Bi, ProcessorStepInputSchema as Bl, renderBuiltInToolEvent as Bn, memoryDefaultOptions as Bo, ScoresInMemory as Br, cloneStep as Bs, formatCompletionFeedback as Bt, MastraScorer as C, getSqlType as Ca, predicateToCondition as Cc, parseKnowledgeWikilinks as Ci, assertDrainTimeout as Cl, knowledgeRunScopes as Cn, serializeSpanAttributes as Co, StoreOperations as Cr, UnicodeNormalizer as Cs, liveSegmentSpan as Ct, isNotScorable as D, safelyParseJSON as Da, nestedRunParentOf as Dc, KnowledgePageKeyConflictError as Di, hasResumableStreams as Dl, encodeKnowledgeScopeId as Dn, FactoryStorage as Do, FilesystemDB as Dr, UnsupportedFileHandler as Ds, runResumeDurableStreamUntilIdle as Dt, filterRun as E, parseDuration as Ea, createNestedRunParentStatusLookup as Ec, KnowledgePageHasChildrenError as Ei, hasDurableExecution as El, decodeKnowledgeScopeId as En, ObservabilityStorage as Eo, FilesystemStore as Er, isMalformedFunctionCallError as Es, runDurableStreamUntilIdle as Et, normalizeResumeGenerateArgs as F, tracePageIdSchema as Fa, renewWorkflowLease as Fc, MAX_KNOWLEDGE_PAGE_LIST_LIMIT as Fi, ProcessorMessageContentSchema as Fl, ChannelThreadLinkProcessor as Fn, messageVectorId as Fo, mergeWorkflowStepResult as Fr, cloneWorkflow as Fs, pruneAgentLoopSnapshot as Ft, createWorkflowInput as G, threadQueryResponseSchema as Ga, createStepFromTool as Gc, parseKnowledgePageRef as Gi, StepStartPartSchema as Gl, DEFAULT_CHANNEL_TOOLS_SETTINGS as Gn, createBackgroundWorkSignalProcessor as Go, InMemoryNotificationsStorage as Gr, StepExecutor as Gs, runChecks as Gt, createDurableIsTaskCompleteStep as H, planThreadRowsQuery as Ha, createMappingStep as Hc, knowledgePinDepth as Hi, ProcessorStepSchema as Hl, CONTINUE_RUN_MESSAGE as Hn, isSystemReminderMessage as Ho, InMemorySchedulesStorage as Hr, createStep as Hs, formatValidationFeedback as Ht, prepareForDurableExecution as I, tracePageNodeSchema as Ia, repeatAfterSettled as Ic, MAX_KNOWLEDGE_PIN_LIST_DEPTH as Ii, ProcessorMessageSchema as Il, NEW_CHANNEL_THREAD_KEY as In, resolveMaxChunkChars as Io, InMemoryWorkflowDefinitionsStorage as Ir, createEventedWorkflow as Is, DEFAULT_TOOL_DECLINE_REASON as It, serializeModelConfig as J, SPAN_QUERY_MAX_CURSOR_BYTES as Ja, abortableSleep as Jc, HarnessStorage as Ji, isAgentCompatible as Jl, createChannelTools as Jn, RESPONSE_CACHE_CONTEXT_KEY as Jo, createNotificationSignal as Jr, diffResponseMessages as Js, runStreamCompletionScorers as Jt, serializeDurableOptions as K, threadQueryRowSchema as Ka, RESUME_SNAPSHOT_POLL_INTERVAL_MS as Kc, KnowledgeInvalidCursorError as Ki, TextPartSchema as Kl, channelToolScopeResolver as Kn, CyberRefusalHandler as Ko, NotificationsStorage as Kr, computeScheduleDefinitionHash as Ks, runCompletionScorers as Kt, applyReservedMemoryContextKeys as L, tracePageRequestSchema as La, runFenceConflictOf as Lc, assertKnowledgeNoteTextWithinBound as Li, ProcessorOutputResultPhaseSchema as Ll, markNewChannelThread as Ln, upsertMessageVectors as Lo, WorkflowDefinitionsStorage as Lr, createWorkflow as Ls, resolveDeclineReason as Lt, MAX_FS_SUBAGENT_DEPTH as M, validateStorageMetadataFilter as Ma, evaluateScoringPredicate as Mc, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS as Mi, MessagePartSchema as Ml, resolveChannelRenderContext as Mn, buildMessageEmbeddingRows as Mo, WorkflowsStorage as Mr, isRetryableOpenAIResponsesStreamError as Ms, getRunStreamSlot as Mt, AGENT_RESUME_CLAIM_STALE_MS as N, TracePageError as Na, validateScoringPredicate as Nc, MAX_KNOWLEDGE_PAGE_LINKS as Ni, ProcessorInputPhaseSchema as Nl, MastraStateAdapter as Nn, chunkMessageText as No, createEmptyWorkflowSnapshot as Nr, PrefillErrorHandler as Ns, getScopeStreamSlot as Nt, notScorable as O, serializeDate as Oa, nestedRunRecoveryAction as Oc, MAX_KNOWLEDGE_MOVE_PAGES as Oi, isDurableAgentLike as Ol, buildKnowledgeInstructions as On, FactoryStorageDomain as Oo, InMemoryStore as Or, FileUploadProcessor as Os, RUN_DEADLINE_KEY as Ot, Agent as P, readTracePage as Pa, WORKFLOW_RUN_LEASE_TTL_MS as Pc, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH as Pi, ProcessorInputStepPhaseSchema as Pl, REPLY_TOOL_NAME as Pn, extractMessageEmbeddingText as Po, mergeStepResult as Pr, getGoalActivityDurationMs as Ps, untilIdleHandlesBackgroundTask as Pt, isSpanChunk as Q, buildSpanQueryResponse as Qa, createDeprecationProxy as Qc, DatasetsStorage as Qi, RUN_FENCE_CONFLICT_ERROR_ID as Ql, MemoryInputFilter as Qn, SkillSearchProcessor as Qo, notificationSummaryContents as Qr, emitFinishEvent as Qs, PINNED_READ_MEMO_KEY as Qt, persistDurableRunInput as R, tracePageResponseSchema as Ra, ExecutionEngine as Rc, assertKnowledgePageDescriptionWithinBound as Ri, ProcessorOutputStepPhaseSchema as Rl, ChatChannelProcessor as Rn, MastraMemory as Ro, InMemoryToolProviderConnectionsStorage as Rr, EventedRun as Rs, getServerSideFallbackInfo as Rt, createClassifierScorer as S, getDefaultValue as Sa, mapVariable as Sc, inspectKnowledgeSchema as Si, getEntryWorkflow as Sl, knowledgeMemoryScopes as Sn, getStringOrNull as So, StoreOperationsInMemory as Sr, ModerationProcessor as Ss, endFailedSegmentSpans as St, createScorer as T, jsonValueEquals as Ta, cancelNestedRun as Tc, KnowledgePageDepthError as Ti, workflowTermination as Tl, strongerKnowledgeRole as Tn, ObservabilityInMemory as To, createGitHubSourceControlProviderFromEnv as Tr, defaultStabilityErrorProcessors as Ts, segmentSpanData as Tt, createDurableLLMMappingStep as U, threadQueryIdentitySchema as Ua, createStepFromAgent$1 as Uc, knowledgePositionBetween as Ui, ReasoningPartSchema as Ul, formatToolApproval as Un, augmentWithInit as Uo, SchedulesStorage as Ur, createWorkflow$1 as Us, generateFinalResult as Ut, createDurableGoalStep as V, encodeThreadQueryCursor as Va, runWithConcurrency as Vc, knowledgePagePath as Vi, ProcessorStepOutputSchema as Vl, CONTINUE_RUN_ACTION_ID as Vn, filterSystemReminderMessages as Vo, ScoresStorage as Vr, cloneWorkflow$1 as Vs, formatStreamCompletionFeedback as Vt, createDurableToolCallStep as W, threadQueryRequestSchema as Wa, createStepFromClassifier as Wc, knowledgeScopeReadable as Wi, SourcePartSchema as Wl, ChannelSessionRejectedError as Wn, getStorageSource as Wo, normalizeScheduleTarget as Wr, WorkflowEventProcessor as Ws, generateStructuredFinalResult as Wt, createDurableLLMExecutionStep as X, SPAN_QUERY_MAX_PREVIEW_CHARACTERS as Xa, assertTimeTravelGraphMatchesSnapshot as Xc, ExperimentsStorage as Xi, assertWorkflowStepGuard as Xl, toChatLogger as Xn, buildResponseCacheKey as Xo, notificationSignalAttributes as Xr, emitChunkEvent as Xs, loop as Xt, serializeToolsMetadata as Y, SPAN_QUERY_MAX_LIMIT as Ya, applyStateDelta as Yc, ExperimentsInMemory as Yi, WorkflowStepConflictError as Yl, resolveChannelToolsSettings as Yn, ResponseCache as Yo, createNotificationSummarySignal as Yr, emitAbortEvent as Ys, runValidation as Yt, MessagePartSpans as Z, SPAN_QUERY_ORDER_FIELDS as Za, cleanStepResult as Zc, DatasetsInMemory as Zi, isWorkflowStepConflictError as Zl, BaseProcessor as Zn, WorkspaceInstructionsProcessor as Zo, notificationSignalMetadata as Zr, emitErrorEvent as Zs, validateModelTimeoutSettings as Zt, describeNonSuccessFinishReason as _, createStorageErrorId as _a, Run as _c, KnowledgeStorage as _i, validateStepResumeData as _l, knowledgeAccessGrants as _n, buildLogRecord as _o, knowledgeScopeKey as _r, ClassifierProcessor as _s, resolveTool$1 as _t, deleteRunRegistryEntry as a, SchemaUpdateValidationError as aa, subscribeToAbortRequests as ac, resolveNotificationDeliveryDecision as ai, getSingleStepEntryId as al, removeKnowledgeNote as an, spanQueryIdentityKey as ao, MockMemory as ar, CostGuardProcessor as as, baseDurableAgenticInputSchema as at, resolveRunFence as au, createOnScorerHook as b, ensureDate as ba, createStep$1 as bc, assertKnowledgeSchemaCompatible as bi, waitForSuspendedSnapshot as bl, KnowledgeDeclarationError as bn, buildUpdateSpanRecord as bo, knowledgeVisibleScopeKeys as br, PIIDetector as bs, createDurableAgentStream as bt, getRunRegistryEntry as c, ChannelsStorage as ca, DurableAgentDefaults as cc, InMemoryKnowledgeStorage as ci, isEntryFinished as cl, upsertKnowledgePage as cn, spanQueryResponseSchema as co, MAX_KNOWLEDGE_SCOPE_TAGS as cr, TokenLimiterProcessor as cs, modelConfigSchema as ct, setRunFenceContext as cu, setRunRegistryEntry as d, BackgroundTasksInMemory as da, AGENT_STREAM_TOPIC as dc, KnowledgeImportersStorage as di, omitPriorSuspensionFields as dl, KnowledgeLinkRefreshIncompleteError as dn, encodeTraceQueryDeltaCursor as do, assertKnowledgeRecordTextWithinBound as dr, advanceMemoryTokenBoundary as ds, runDurableFinishSideEffects as dt, SchemaValidator as ea, emitStepStartEvent as ec, summarizeNotifications as ei, createTimeTravelExecutionParams as el, buildKnowledgePageTools as en, encodeSpanQueryCursor as eo, globalEmbeddingCache as er, formatSkillsCatalog as es, resolveDurableToolCallConcurrency as et, RunFenceConflictError as eu, takeRunScorerInstances as f, BackgroundTasksStorage as fa, AgentControlEventTypes as fc, KNOWLEDGE_STORAGE_CONTRACT_VERSION as fi, resolveForeachConcurrency as fl, knowledgeSubtree as fn, getTraceQueryDeltaWatermark as fo, assertKnowledgeScopeWithinCeiling as fr, getMemoryTokenBoundary as fs, loadRunStoredMessages as ft, AGENTIC_LOOP_WORKFLOW_ID as g, runRetentionBatches as ga, getStepEntry as gc, KnowledgeSchemaResetRequiredError as gi, validateStepRequestContext as gl, updateKnowledgeLinks as gn, buildFeedbackRecord as go, isKnowledgeScopeVisible as gr, ModelSelectionProcessor as gs, resolveRuntimeDependencies as gt, AGENTIC_EXECUTION_WORKFLOW_ID as h, retentionCutoffMs as ha, getNestedWorkflow as hc, KnowledgeNotFoundError$1 as hi, validateStepInput as hl, syncKnowledgePageBodyLinks as hn, buildCreateSpanRecord as ho, expandKnowledgeScope as hr, BatchPartsProcessor as hs, resolveModel as ht, abandonDurableAgentExecutions as i, UnsupportedSchemaPatternError as ia, requestAcknowledgedAbort as ic, resolveDeliveryFailureUpdate as ii, getResumeLabelsByStepId as il, moveKnowledgePage as in, spanQueryCostSchema as io, getMemoryRunState as ir, RegexFilterProcessor as is, accumulatedUsageSchema as it, matchesRunFence as iu, assembleAgentFromFsEntry as j, transformScoreRow as ja, SCORING_PREDICATE_ROOTS as jc, MAX_KNOWLEDGE_PAGE_DEPTH as ji, MessageContentSchema as jl, defaultTypingStatus as jn, MESSAGE_EMBEDDING_CHARS_PER_TOKEN as jo, cloneRunData as jr, isBadRequestError as js, __registerMastraCtor as jt, agentConfig as k, storageMessageMatchesMetadataFilter as ka, nestedRunStatusOf as kc, MAX_KNOWLEDGE_NOTE_TOKENS as ki, FilePartSchema as kl, AgentChannels as kn, UniqueViolationError as ko, MockStore as kr, FILE_UPLOAD_ERROR_CODES as ks, ensureRemoteAbortListener as kt, globalRunRegistry as l, InMemoryBlobStore as la, DurableStepIds as lc, KnowledgeImporterBindingConflictError as li, isSingleStepEntry as ll, KnowledgeSemanticIndex as ln, spanQueryRowSchema as lo, assertKnowledgeCeilingRaised as lr, groupLinkedToolMessages as ls, modelListEntrySchema as lt, agentThreadStreamRuntime as m, resolveRetentionTargets as ma, EventedExecutionEngine as mc, KnowledgeConflictError as mi, setLongTimeout as ml, reindexKnowledgeLinks as mn, planTraceQuery as mo, createKnowledgeNodeCursor as mr, normalizeMessageHistoryConfig as ms, resolveInternalState as mt, ExtendedRunRegistry as n, createValidator as na, AgentStreamBus as nc, MAX_NOTIFICATION_DELIVERY_ATTEMPTS as ni, defineStateAccessors as nl, knowledgeRunPrincipals as nn, planSpanQuery as no, MessageHistory as nr, AgentsMDInjector as ns, calculateAccumulatedUsage as nt, currentRunGeneration as nu, endRunSpansWithError as o, SchemaValidationError as oa, createRunAbortController as oc, InMemoryMemory as oi, getStepIds as ol, removeKnowledgePage as on, spanQueryIdentitySchema as oo, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH as or, TokenCostControl as os, baseIterationStateSchema as ot, runFencingNotSupportedError as ou, AgentThreadLeaseLostError as p, executeRetentionPrune as pa, AgentStreamEventTypes as pc, KNOWLEDGE_STORAGE_SCHEMA_VERSION as pi, runCountDeprecationMessage as pl, refreshKnowledgeLinksTo as pn, planThreadQuery as po, canonicalizeKnowledgeScope as pr, isAfterMemoryTokenBoundary as ps, rebuildRunToolsFromMastra as pt, serializeDurableState as q, SPAN_QUERY_MAX_COST_METRICS as qa, RESUME_SNAPSHOT_WAIT_STATUSES as qc, InMemoryHarness as qi, ToolInvocationPartSchema as ql, createChannelToolScope as qn, DEFAULT_RESPONSE_CACHE_TTL_SECONDS as qo, dispatchDueNotifications as qr, __resetExecutionFencesForTests as qs, runDefaultCompletionCheck as qt, RunRegistry as r, getSchemaValidator as ra, publishAbortRequest as rc, defaultNotificationDeliveryDecision as ri, getRestartStartIndex as rl, addKnowledgeNote as rn, resolveSpanQueryCost as ro, MemoryRunState as rr, ToolCallFilter as rs, createBaseIterationStateUpdate as rt, isRunFenceConflictError as ru, getActiveDurableAgentWorkflowExecutions as s, InMemoryChannelsStorage as sa, DURABLE_STOP_WHEN_ERROR_ID as sc, MemoryStorage as si, hydrateSerializedStepErrors as sl, updateKnowledgeNote as sn, spanQueryRequestSchema as so, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH as sr, SystemPromptScrubber as ss, durableAgenticOutputSchema as st, runOutsideRunFenceScope as su, DURABLE_CONTEXT_SEGMENT_KEY as t, assertSupportedPatterns as ta, emitSuspendedEvent as tc, readNotificationRoutingRequirement as ti, defineLazyWriter as tl, KnowledgeRun as tn, parseSpanQueryRequest as to, WorkingMemory as tr, ToolSearchProcessor as ts, buildStepRecord as tt, coverNestedRun as tu, isDurableAgentExecutionDetached as u, BlobStore as ua, AGENT_CONTROL_TOPIC as uc, KnowledgeImporterRunStateError as ui, omitPriorCompletionFields as ul, embed$2 as un, encodeTraceQueryCursor as uo, assertKnowledgeDescriptionWithinBound as ur, loadMessageHistory as us, executeDurableAgentScorers as ut, runEvals as v, createStoreErrorId as va, Workflow as vc, KnowledgeTransactionDeadlineError as vi, validateStepStateData as vl, knowledgeReadScopeFor as vn, buildMetricRecord as vo, knowledgeSemanticDocumentId as vr, StructuredOutputProcessor as vs, toolRequiresApproval as vt, ScorerRunError as w, hasErrorCode as wa, evaluatePredicate as wc, KnowledgeMoveTooLargeError as wi, waitMs as wl, knowledgeScopeAddress as wn, toEntityType as wo, GitHubSourceControlProvider as wr, STABILITY_ERROR_PROCESSOR_IDS as ws, segmentEndedBySuspension as wt, validateAndSaveScore as x, filterByDateRange as xa, isProcessor$1 as xc, createKnowledgeUlid as xi, getEntryId as xl, compileKnowledgeScopes as xn, getObjectOrNull as xo, parseKnowledgeNodeCursor as xr, PromptInjectionDetector as xs, carrySegmentSpans as xt, flushBeforeTraceRead as y, createVectorErrorId as ya, cloneStep$1 as yc, KnowledgeUnsupportedCapabilityError as yi, validateStepSuspendData as yl, knowledgeRoleOn as yn, buildScoreRecord as yo, knowledgeSemanticIdempotencyKey as yr, LanguageDetector as ys, resolveAgentById as yt, detachFullStreamOnEnd as z, THREAD_QUERY_DEFAULT_LIMIT as za, createConcurrencyLimiter as zc, canonicalKnowledgeName as zi, ProcessorOutputStreamPhaseSchema as zl, CHAT_CHANNEL_RENDER_CONTEXT_KEY as zn, MemoryProcessor as zo, ToolProviderConnectionsStorage as zr, EventedWorkflow as zs, formatCheckFeedback as zt };