@mastra/core 1.86.0-alpha.9 → 1.87.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (726) hide show
  1. package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/voice/aisdk/speech.d.ts +1 -1
  2. package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/voice/aisdk/transcription.d.ts +1 -1
  3. package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/voice/composite-voice.d.ts +1 -1
  4. package/dist/agent/agent-legacy.d.ts +1 -1
  5. package/dist/agent/agent.d.ts +3 -3
  6. package/dist/agent/agent.types.d.ts +1 -1
  7. package/dist/agent/durable/constants.d.ts +2 -0
  8. package/dist/agent/durable/durable-agent.d.ts +3 -3
  9. package/dist/agent/durable/evented-execution.d.ts +7 -0
  10. package/dist/agent/durable/execution-engine.d.ts +1 -0
  11. package/dist/agent/durable/execution-fence.d.ts +2 -0
  12. package/dist/agent/durable/index.cjs +3 -1
  13. package/dist/agent/durable/index.d.ts +1 -1
  14. package/dist/agent/durable/index.js +2 -2
  15. package/dist/agent/durable/run-registry.d.ts +2 -0
  16. package/dist/agent/durable/segment-spans.d.ts +54 -1
  17. package/dist/agent/durable/stream-adapter.d.ts +1 -1
  18. package/dist/agent/durable/types.d.ts +12 -2
  19. package/dist/agent/durable/workflows/durable-loop-builder.d.ts +57 -2
  20. package/dist/agent/durable/workflows/finalize-run.d.ts +2 -0
  21. package/dist/agent/durable/workflows/shared/index.d.ts +1 -1
  22. package/dist/agent/durable/workflows/shared/reported-cost.d.ts +7 -0
  23. package/dist/agent/durable/workflows/shared/schemas.d.ts +16 -1
  24. package/dist/agent/durable/workflows/shared/tool-call-concurrency.d.ts +6 -0
  25. package/dist/agent/durable/workflows/steps/llm-execution.d.ts +5 -0
  26. package/dist/agent/durable/workflows/steps/llm-mapping.d.ts +6 -0
  27. package/dist/agent/durable/workflows/steps/tool-call.d.ts +20 -0
  28. package/dist/agent/index.cjs +2 -2
  29. package/dist/agent/index.js +2 -2
  30. package/dist/agent/message-list/adapters/AIV4Adapter.d.ts +1 -1
  31. package/dist/agent/message-list/adapters/types.d.ts +1 -1
  32. package/dist/agent/message-list/cache/CacheKeyGenerator.d.ts +1 -1
  33. package/dist/agent/message-list/conversion/output-converter.d.ts +1 -1
  34. package/dist/agent/message-list/conversion/to-prompt.d.ts +1 -1
  35. package/dist/agent/message-list/conversion/utils.d.ts +1 -1
  36. package/dist/agent/message-list/detection/TypeDetector.d.ts +1 -1
  37. package/dist/agent/message-list/message-list.d.ts +2 -2
  38. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts +1 -1
  39. package/dist/agent/message-list/prompt/convert-file.d.ts +1 -1
  40. package/dist/agent/message-list/prompt/data-content.d.ts +1 -1
  41. package/dist/agent/message-list/state/MessageStateManager.d.ts +1 -1
  42. package/dist/agent/message-list/state/types.d.ts +2 -2
  43. package/dist/agent/message-list/types.d.ts +9 -9
  44. package/dist/agent/message-list/utils/convert-messages.d.ts +3 -3
  45. package/dist/agent/message-list/utils/provider-compat.d.ts +1 -1
  46. package/dist/agent/request-context-snapshot.d.ts +3 -2
  47. package/dist/agent/signals.d.ts +1 -1
  48. package/dist/agent/streams/run-records.d.ts +9 -1
  49. package/dist/agent/types.d.ts +3 -3
  50. package/dist/agent/workflows/prepare-stream/run-scope-keys.d.ts +1 -1
  51. package/dist/agent-builder/ee/index.cjs +1 -1
  52. package/dist/agent-builder/ee/index.js +1 -1
  53. package/dist/agent-controller/index.cjs +1 -1
  54. package/dist/agent-controller/index.js +1 -1
  55. package/dist/agent-controller/session-run-engine.d.ts +5 -2
  56. package/dist/agent-controller/session.d.ts +2 -0
  57. package/dist/agent-controller/types.d.ts +23 -0
  58. package/dist/{agent-controller-SSlKzE6A.js → agent-controller-B8LoFdtu.js} +43 -13
  59. package/dist/{agent-controller-CrQ9OF80.cjs → agent-controller-DSnFynpa.cjs} +43 -13
  60. package/dist/auth/defaults/index.d.ts +2 -2
  61. package/dist/auth/defaults/session/cookie.d.ts +2 -2
  62. package/dist/auth/defaults/session/index.d.ts +2 -2
  63. package/dist/auth/defaults/session/memory.d.ts +2 -2
  64. package/dist/auth/ee/capabilities.d.ts +1 -1
  65. package/dist/auth/ee/defaults/index.d.ts +1 -1
  66. package/dist/auth/ee/defaults/rbac/index.d.ts +1 -1
  67. package/dist/auth/ee/defaults/rbac/static.d.ts +1 -1
  68. package/dist/auth/ee/defaults/roles.d.ts +1 -1
  69. package/dist/auth/ee/fga-check.d.ts +1 -1
  70. package/dist/auth/ee/index.d.ts +1 -1
  71. package/dist/auth/ee/interfaces/acl.d.ts +1 -1
  72. package/dist/auth/ee/interfaces/fga.d.ts +1 -1
  73. package/dist/auth/ee/interfaces/index.d.ts +1 -1
  74. package/dist/auth/ee/interfaces/permissions.generated.d.ts +1 -1
  75. package/dist/auth/ee/interfaces/rbac.d.ts +1 -1
  76. package/dist/auth/ee/interfaces/user.d.ts +1 -1
  77. package/dist/auth/ee/license.d.ts +1 -1
  78. package/dist/auth/index.d.ts +2 -2
  79. package/dist/auth/interfaces/credentials.d.ts +1 -1
  80. package/dist/auth/interfaces/index.d.ts +2 -2
  81. package/dist/auth/interfaces/session.d.ts +1 -1
  82. package/dist/auth/interfaces/sso.d.ts +1 -1
  83. package/dist/auth/interfaces/user.d.ts +1 -1
  84. package/dist/background-tasks/index.cjs +1 -1
  85. package/dist/background-tasks/index.js +1 -1
  86. package/dist/background-tasks/manager.d.ts +4 -1
  87. package/dist/{background-tasks-BDrYBis-.cjs → background-tasks-Ci5h0dhj.cjs} +139 -51
  88. package/dist/{background-tasks-BnJfNLFo.js → background-tasks-IW7M4iD2.js} +139 -51
  89. package/dist/browser/index.cjs +1 -1
  90. package/dist/browser/index.js +1 -1
  91. package/dist/{builder-Cw8u3pPl.cjs → builder-14Uptu8y.cjs} +2 -2
  92. package/dist/{builder-Cl-0BWkh.js → builder-DI2c2xjy.js} +2 -2
  93. package/dist/bundler/index.d.ts +2 -2
  94. package/dist/cache/base.d.ts +40 -10
  95. package/dist/cache/index.cjs +1 -1
  96. package/dist/cache/index.js +1 -1
  97. package/dist/capabilities/302ai.json +196 -196
  98. package/dist/capabilities/abliteratedllm.json +36 -36
  99. package/dist/capabilities/abliteration-ai.json +11 -11
  100. package/dist/capabilities/above.json +22 -22
  101. package/dist/capabilities/adaption.json +13 -13
  102. package/dist/capabilities/adzuki.json +28 -28
  103. package/dist/capabilities/agentrouter.json +9 -9
  104. package/dist/capabilities/agnes.json +4 -4
  105. package/dist/capabilities/ai-router.json +5 -5
  106. package/dist/capabilities/aiand.json +16 -16
  107. package/dist/capabilities/aigrow.json +14 -14
  108. package/dist/capabilities/aimlapi.json +146 -150
  109. package/dist/capabilities/aipg.json +2 -2
  110. package/dist/capabilities/aixy.json +9 -9
  111. package/dist/capabilities/aki-io.json +10 -10
  112. package/dist/capabilities/alibaba-cn.json +97 -97
  113. package/dist/capabilities/alibaba-coding-plan-cn.json +5 -5
  114. package/dist/capabilities/alibaba-coding-plan.json +5 -5
  115. package/dist/capabilities/alibaba-token-plan-cn.json +51 -51
  116. package/dist/capabilities/alibaba-token-plan.json +52 -52
  117. package/dist/capabilities/alibaba.json +69 -69
  118. package/dist/capabilities/ambient.json +15 -15
  119. package/dist/capabilities/amd.json +8 -8
  120. package/dist/capabilities/anthropic.json +49 -49
  121. package/dist/capabilities/anyapi.json +19 -19
  122. package/dist/capabilities/arcee.json +9 -9
  123. package/dist/capabilities/augure.json +4 -4
  124. package/dist/capabilities/auriko.json +21 -21
  125. package/dist/capabilities/bailing.json +4 -4
  126. package/dist/capabilities/baseten.json +28 -28
  127. package/dist/capabilities/bee.json +5 -5
  128. package/dist/capabilities/berget.json +4 -4
  129. package/dist/capabilities/bothub.json +14 -14
  130. package/dist/capabilities/boundless.json +39 -39
  131. package/dist/capabilities/bumo.json +42 -42
  132. package/dist/capabilities/byteplus.json +24 -24
  133. package/dist/capabilities/cheapaimodel.json +10 -10
  134. package/dist/capabilities/cheapest-token.json +29 -29
  135. package/dist/capabilities/chutes.json +10 -13
  136. package/dist/capabilities/cline-pass.json +37 -37
  137. package/dist/capabilities/cloudcode.json +10 -10
  138. package/dist/capabilities/cloudflare-workers-ai.json +12 -73
  139. package/dist/capabilities/commandcode.json +131 -131
  140. package/dist/capabilities/concentrate.json +272 -263
  141. package/dist/capabilities/cortecs.json +113 -113
  142. package/dist/capabilities/crossmodel.json +169 -169
  143. package/dist/capabilities/crusoe.json +10 -10
  144. package/dist/capabilities/daoxe.json +9 -9
  145. package/dist/capabilities/databricks.json +128 -128
  146. package/dist/capabilities/deepinfra.json +130 -67
  147. package/dist/capabilities/deepseek.json +4 -4
  148. package/dist/capabilities/digitalocean.json +112 -112
  149. package/dist/capabilities/dothoosh.json +29 -29
  150. package/dist/capabilities/doubleword.json +29 -29
  151. package/dist/capabilities/edenai.json +446 -453
  152. package/dist/capabilities/empiriolabs.json +164 -166
  153. package/dist/capabilities/engy.json +22 -22
  154. package/dist/capabilities/entrim.json +4 -4
  155. package/dist/capabilities/evroc.json +14 -14
  156. package/dist/capabilities/ezkielyna.json +10 -10
  157. package/dist/capabilities/fastrouter.json +79 -79
  158. package/dist/capabilities/fireworks-ai.json +92 -71
  159. package/dist/capabilities/freemodel.json +21 -21
  160. package/dist/capabilities/friendli.json +10 -10
  161. package/dist/capabilities/frogbot.json +87 -87
  162. package/dist/capabilities/gisoo.json +19 -19
  163. package/dist/capabilities/gmicloud.json +21 -21
  164. package/dist/capabilities/google.json +52 -52
  165. package/dist/capabilities/graphn.json +11 -11
  166. package/dist/capabilities/greenpt.json +35 -35
  167. package/dist/capabilities/groq.json +3 -3
  168. package/dist/capabilities/helicone.json +78 -78
  169. package/dist/capabilities/hostinger-router.json +13 -13
  170. package/dist/capabilities/hpc-ai.json +10 -10
  171. package/dist/capabilities/huawei-maas.json +17 -17
  172. package/dist/capabilities/hubris.json +25 -25
  173. package/dist/capabilities/huggingface.json +94 -84
  174. package/dist/capabilities/hyper.json +29 -29
  175. package/dist/capabilities/impossibl.json +148 -148
  176. package/dist/capabilities/inception.json +3 -3
  177. package/dist/capabilities/inceptron.json +6 -6
  178. package/dist/capabilities/inco.json +4 -4
  179. package/dist/capabilities/infer.json +10 -10
  180. package/dist/capabilities/inferall.json +5 -5
  181. package/dist/capabilities/inference-coop.json +15 -15
  182. package/dist/capabilities/inferenceapis.json +17 -17
  183. package/dist/capabilities/inferris.json +4 -4
  184. package/dist/capabilities/infersia.json +12 -12
  185. package/dist/capabilities/infomaniak.json +2 -2
  186. package/dist/capabilities/io-net.json +2 -2
  187. package/dist/capabilities/isoquant.json +4 -4
  188. package/dist/capabilities/iteracompute.json +58 -58
  189. package/dist/capabilities/jad-ai.json +2 -2
  190. package/dist/capabilities/jalapeno.json +11 -11
  191. package/dist/capabilities/jiekou.json +62 -62
  192. package/dist/capabilities/jzstoken.json +47 -47
  193. package/dist/capabilities/keln.json +21 -21
  194. package/dist/capabilities/kenari.json +123 -123
  195. package/dist/capabilities/kilo.json +631 -621
  196. package/dist/capabilities/kimi-code-plan-cn.json +6 -6
  197. package/dist/capabilities/kimi-code-plan-global.json +6 -6
  198. package/dist/capabilities/kitani.json +4 -4
  199. package/dist/capabilities/klavo.json +21 -21
  200. package/dist/capabilities/korouter.json +33 -33
  201. package/dist/capabilities/kunavo.json +5 -5
  202. package/dist/capabilities/liquid.json +12 -12
  203. package/dist/capabilities/lithosai.json +2 -2
  204. package/dist/capabilities/llmgateway-providers.json +903 -894
  205. package/dist/capabilities/llmgateway.json +344 -336
  206. package/dist/capabilities/llmtr.json +23 -23
  207. package/dist/capabilities/logits.json +2 -2
  208. package/dist/capabilities/longcat.json +2 -2
  209. package/dist/capabilities/lowrouter.json +46 -46
  210. package/dist/capabilities/lyceum.json +14 -14
  211. package/dist/capabilities/melious.json +15 -15
  212. package/dist/capabilities/merge-gateway.json +292 -292
  213. package/dist/capabilities/meta.json +11 -11
  214. package/dist/capabilities/minimax-cn-coding-plan.json +2 -2
  215. package/dist/capabilities/minimax-cn.json +5 -5
  216. package/dist/capabilities/minimax-coding-plan.json +2 -2
  217. package/dist/capabilities/minimax.json +5 -5
  218. package/dist/capabilities/mistral.json +21 -21
  219. package/dist/capabilities/mixlayer.json +4 -4
  220. package/dist/capabilities/modal.json +14 -14
  221. package/dist/capabilities/model-oracle-ai.json +23 -23
  222. package/dist/capabilities/modelis.json +22 -22
  223. package/dist/capabilities/modelscope.json +2 -2
  224. package/dist/capabilities/modular.json +7 -7
  225. package/dist/capabilities/moneo.json +11 -11
  226. package/dist/capabilities/moonshotai-cn.json +6 -6
  227. package/dist/capabilities/moonshotai.json +6 -6
  228. package/dist/capabilities/morph.json +13 -13
  229. package/dist/capabilities/munito.json +2 -2
  230. package/dist/capabilities/nan.json +28 -28
  231. package/dist/capabilities/nano-gpt.json +599 -564
  232. package/dist/capabilities/nearai.json +96 -96
  233. package/dist/capabilities/nebius.json +32 -32
  234. package/dist/capabilities/neon.json +120 -120
  235. package/dist/capabilities/neuralwatt.json +37 -37
  236. package/dist/capabilities/nokeep.json +4 -4
  237. package/dist/capabilities/novita-ai.json +154 -154
  238. package/dist/capabilities/nvidia.json +28 -60
  239. package/dist/capabilities/oathbreaker.json +2 -2
  240. package/dist/capabilities/obscurify.json +20 -20
  241. package/dist/capabilities/oci.json +17 -8
  242. package/dist/capabilities/ofox.json +317 -317
  243. package/dist/capabilities/ollama-cloud.json +56 -56
  244. package/dist/capabilities/openai.json +78 -46
  245. package/dist/capabilities/opencode-go.json +86 -86
  246. package/dist/capabilities/openreason.json +5 -5
  247. package/dist/capabilities/openrouter.json +535 -519
  248. package/dist/capabilities/opper.json +27 -27
  249. package/dist/capabilities/orcarouter.json +217 -217
  250. package/dist/capabilities/outerlabs.json +31 -31
  251. package/dist/capabilities/ovhcloud.json +58 -4
  252. package/dist/capabilities/pareto.json +5 -5
  253. package/dist/capabilities/pendra.json +4 -4
  254. package/dist/capabilities/perplexity-agent.json +62 -62
  255. package/dist/capabilities/phala.json +36 -36
  256. package/dist/capabilities/pioneer.json +27 -27
  257. package/dist/capabilities/poe.json +110 -110
  258. package/dist/capabilities/poolside.json +3 -3
  259. package/dist/capabilities/powerspring.json +11 -11
  260. package/dist/capabilities/primalabs.json +10 -10
  261. package/dist/capabilities/prime.json +127 -111
  262. package/dist/capabilities/privatemode-ai.json +11 -11
  263. package/dist/capabilities/proxystacks.json +7 -7
  264. package/dist/capabilities/qiniu-ai.json +15 -15
  265. package/dist/capabilities/refuseless.json +9 -9
  266. package/dist/capabilities/regolo-ai.json +6 -6
  267. package/dist/capabilities/requesty.json +170 -170
  268. package/dist/capabilities/ruapi.json +20 -20
  269. package/dist/capabilities/runcrate.json +10 -10
  270. package/dist/capabilities/runinfra.json +16 -16
  271. package/dist/capabilities/sakana.json +6 -6
  272. package/dist/capabilities/sambanova.json +6 -6
  273. package/dist/capabilities/sandbase.json +11 -11
  274. package/dist/capabilities/sarvam.json +10 -10
  275. package/dist/capabilities/scaleway.json +14 -14
  276. package/dist/capabilities/scnet-token-plan.json +14 -14
  277. package/dist/capabilities/scx-ai.json +26 -26
  278. package/dist/capabilities/sensenova.json +12 -12
  279. package/dist/capabilities/siliconflow-cn.json +50 -50
  280. package/dist/capabilities/siliconflow.json +55 -55
  281. package/dist/capabilities/snowflake-cortex.json +19 -19
  282. package/dist/capabilities/sokkan.json +7 -7
  283. package/dist/capabilities/sparrowcodes.json +17 -17
  284. package/dist/capabilities/standardcompute.json +98 -98
  285. package/dist/capabilities/steadyrouter.json +38 -38
  286. package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
  287. package/dist/capabilities/stepfun-ai.json +5 -5
  288. package/dist/capabilities/stepfun-step-plan.json +5 -5
  289. package/dist/capabilities/stepfun.json +5 -5
  290. package/dist/capabilities/stepping-stone.json +17 -17
  291. package/dist/capabilities/subconscious.json +2 -2
  292. package/dist/capabilities/superbot-gg.json +4 -4
  293. package/dist/capabilities/synthetic.json +12 -12
  294. package/dist/capabilities/synthorai.json +22 -22
  295. package/dist/capabilities/teamorouter.json +24 -24
  296. package/dist/capabilities/teapot-router.json +12 -12
  297. package/dist/capabilities/tencent-token-plan.json +59 -35
  298. package/dist/capabilities/tencent-tokenhub.json +46 -46
  299. package/dist/capabilities/tensorx.json +47 -47
  300. package/dist/capabilities/tenstorrent.json +8 -8
  301. package/dist/capabilities/the-grid-ai.json +29 -29
  302. package/dist/capabilities/thinkingmachines.json +61 -61
  303. package/dist/capabilities/tinfoil.json +12 -12
  304. package/dist/capabilities/togetherai.json +62 -52
  305. package/dist/capabilities/tokengo.json +14 -14
  306. package/dist/capabilities/tokenify.json +9 -9
  307. package/dist/capabilities/trustedrouter.json +7 -7
  308. package/dist/capabilities/trustedtokens.json +15 -15
  309. package/dist/capabilities/umans-ai-coding-plan.json +16 -16
  310. package/dist/capabilities/umans-ai.json +13 -13
  311. package/dist/capabilities/uncensuredai.json +4 -4
  312. package/dist/capabilities/unrestricted.json +8 -8
  313. package/dist/capabilities/uplinkswitch.json +21 -21
  314. package/dist/capabilities/upstage.json +4 -4
  315. package/dist/capabilities/vancine.json +24 -24
  316. package/dist/capabilities/vercel.json +582 -582
  317. package/dist/capabilities/vivgrid.json +86 -86
  318. package/dist/capabilities/volcengine-coding-plan.json +23 -23
  319. package/dist/capabilities/volcengine.json +24 -24
  320. package/dist/capabilities/vultr.json +26 -26
  321. package/dist/capabilities/wafer.ai.json +16 -16
  322. package/dist/capabilities/wallaby.json +4 -4
  323. package/dist/capabilities/wally.json +11 -11
  324. package/dist/capabilities/wandb.json +21 -21
  325. package/dist/capabilities/watt.json +24 -24
  326. package/dist/capabilities/xai.json +6 -6
  327. package/dist/capabilities/xiaomi.json +2 -2
  328. package/dist/capabilities/xpersona.json +13 -13
  329. package/dist/capabilities/xxapi.json +28 -28
  330. package/dist/capabilities/zai-coding-plan.json +19 -19
  331. package/dist/capabilities/zai.json +26 -24
  332. package/dist/capabilities/zenifra.json +27 -27
  333. package/dist/capabilities/zenmux.json +172 -172
  334. package/dist/capabilities/zerogpu.json +8 -8
  335. package/dist/capabilities/zhipuai-coding-plan.json +7 -7
  336. package/dist/capabilities/zhipuai.json +23 -23
  337. package/dist/capabilities/zro.json +7 -7
  338. package/dist/channels/agent-channels.d.ts +2 -1
  339. package/dist/channels/formatting.d.ts +8 -0
  340. package/dist/channels/index.cjs +4 -2
  341. package/dist/channels/index.d.ts +1 -1
  342. package/dist/channels/index.js +3 -3
  343. package/dist/channels/types.d.ts +5 -3
  344. package/dist/{channels-Cz1y3W6u.js → channels-Wh32drgu.js} +1 -1
  345. package/dist/{channels-DQg4v_gm.cjs → channels-tVV_de9Q.cjs} +1 -1
  346. package/dist/coding-agent/index.cjs +1 -1
  347. package/dist/coding-agent/index.js +1 -1
  348. package/dist/datasets/index.cjs +2 -2
  349. package/dist/datasets/index.js +2 -2
  350. package/dist/deployer/index.d.ts +2 -2
  351. package/dist/docs/SKILL.md +1 -1
  352. package/dist/docs/assets/SOURCE_MAP.json +798 -798
  353. package/dist/docs/references/docs-agents-resumable-streams.md +15 -6
  354. package/dist/docs/references/docs-deployment-workers.md +3 -1
  355. package/dist/docs/references/docs-harness-background-tasks.md +4 -4
  356. package/dist/docs/references/docs-harness-durable-agents.md +39 -48
  357. package/dist/docs/references/docs-knowledge-importers.md +1 -1
  358. package/dist/docs/references/docs-mastra-platform-observability-overview.md +1 -1
  359. package/dist/docs/references/docs-sandbox-overview.md +1 -0
  360. package/dist/docs/references/docs-server-pubsub.md +1 -1
  361. package/dist/docs/references/docs-workflows-overview.md +67 -3
  362. package/dist/docs/references/integrations-agentic-ui-assistant-ui.md +2 -0
  363. package/dist/docs/references/integrations-frameworks-angular.md +39 -0
  364. package/dist/docs/references/integrations-frameworks-astro.md +5 -2
  365. package/dist/docs/references/integrations-frameworks-electron.md +40 -0
  366. package/dist/docs/references/integrations-frameworks-next-js.md +5 -2
  367. package/dist/docs/references/integrations-frameworks-nuxt.md +5 -2
  368. package/dist/docs/references/integrations-frameworks-sveltekit.md +5 -2
  369. package/dist/docs/references/integrations-frameworks-vite-react.md +40 -0
  370. package/dist/docs/references/integrations.md +3 -0
  371. package/dist/docs/references/reference-agent-controller-agent-controller-class.md +6 -0
  372. package/dist/docs/references/reference-agents-channels.md +1 -1
  373. package/dist/docs/references/reference-agents-durable-agent.md +3 -3
  374. package/dist/docs/references/reference-agents-generate.md +2 -0
  375. package/dist/docs/references/reference-configuration.md +1 -1
  376. package/dist/docs/references/reference-core-mastra-class.md +2 -0
  377. package/dist/docs/references/reference-knowledge-knowledge-class.md +1 -1
  378. package/dist/docs/references/reference-knowledge-knowledge-tools.md +11 -5
  379. package/dist/docs/references/reference-pubsub-caching-pubsub.md +2 -2
  380. package/dist/docs/references/reference-pubsub-redis-streams.md +2 -2
  381. package/dist/docs/references/reference-pubsub-valkey-streams.md +2 -2
  382. package/dist/docs/references/reference-workers-overview.md +2 -0
  383. package/dist/docs/references/reference-workflows-workflow-methods-create-run.md +2 -0
  384. package/dist/docs/references/reference-workflows-workflow.md +2 -0
  385. package/dist/docs/references/reference.md +1 -0
  386. package/dist/error/index.cjs +2 -1
  387. package/dist/error/index.d.ts +1 -1
  388. package/dist/error/index.js +2 -2
  389. package/dist/error/provider-error.d.ts +2 -1
  390. package/dist/{error-BLwEXqOK.js → error-BC9Au-22.js} +13 -1
  391. package/dist/{error-BdEvO8za.cjs → error-L1V4uUbd.cjs} +18 -0
  392. package/dist/evals/index.cjs +1 -1
  393. package/dist/evals/index.js +1 -1
  394. package/dist/evals/run/index.d.ts +1 -1
  395. package/dist/evals/scoreTraces/index.cjs +1 -1
  396. package/dist/evals/scoreTraces/index.js +1 -1
  397. package/dist/evals/types.d.ts +1 -1
  398. package/dist/events/caching-pubsub.d.ts +28 -0
  399. package/dist/events/index.cjs +4 -1
  400. package/dist/events/index.js +2 -2
  401. package/dist/events/topics.d.ts +55 -9
  402. package/dist/harness/index.cjs +1 -1
  403. package/dist/harness/index.js +1 -1
  404. package/dist/index.cjs +1 -1
  405. package/dist/index.js +1 -1
  406. package/dist/{inmemory-BDD0w8gx.js → inmemory-BK3zLwvM.js} +42 -12
  407. package/dist/{inmemory-fgR8sq-U.cjs → inmemory-Dc86VWGB.cjs} +42 -12
  408. package/dist/knowledge/changes.d.ts +17 -5
  409. package/dist/knowledge/importers/runner.d.ts +6 -0
  410. package/dist/knowledge/index.cjs +78 -16
  411. package/dist/knowledge/index.d.ts +2 -2
  412. package/dist/knowledge/index.js +78 -16
  413. package/dist/knowledge/search-snippet.d.ts +30 -0
  414. package/dist/llm/index.cjs +3 -3
  415. package/dist/llm/index.d.ts +2 -2
  416. package/dist/llm/index.js +3 -3
  417. package/dist/llm/model/aisdk/v4/model.d.ts +9 -9
  418. package/dist/llm/model/base.types.d.ts +2 -2
  419. package/dist/llm/model/embedding-router.d.ts +1 -1
  420. package/dist/llm/model/model-settings.d.ts +1 -1
  421. package/dist/llm/model/model.d.ts +1 -1
  422. package/dist/llm/model/model.loop.d.ts +1 -1
  423. package/dist/llm/model/model.loop.types.d.ts +1 -1
  424. package/dist/llm/model/provider-types.generated.d.ts +8011 -7996
  425. package/dist/llm/model/shared.types.d.ts +1 -1
  426. package/dist/{llm-B5A5cwJr.js → llm-B1zaFLYZ.js} +3 -3
  427. package/dist/{llm-8Av3mSjD.cjs → llm-BAiOsNAP.cjs} +3 -3
  428. package/dist/loop/index.cjs +2 -2
  429. package/dist/loop/index.js +2 -2
  430. package/dist/loop/loop-builder.d.ts +1 -1
  431. package/dist/loop/loop.d.ts +1 -1
  432. package/dist/loop/run-scope-keys.d.ts +1 -1
  433. package/dist/loop/shared/transcript-step.d.ts +1 -1
  434. package/dist/loop/types.d.ts +2 -2
  435. package/dist/loop/workflows/agentic-execution/background-task-check-step.d.ts +1 -1
  436. package/dist/loop/workflows/agentic-execution/build-messages-from-chunks.d.ts +1 -1
  437. package/dist/loop/workflows/agentic-execution/goal-step.d.ts +1 -1
  438. package/dist/loop/workflows/agentic-execution/index.d.ts +1 -1
  439. package/dist/loop/workflows/agentic-execution/is-task-complete-step.d.ts +1 -1
  440. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +1 -1
  441. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +1 -1
  442. package/dist/loop/workflows/agentic-execution/tool-call-concurrency.d.ts +1 -1
  443. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +1 -1
  444. package/dist/loop/workflows/agentic-loop/index.d.ts +1 -1
  445. package/dist/loop/workflows/schema.d.ts +2 -2
  446. package/dist/loop/workflows/stream.d.ts +1 -1
  447. package/dist/{manager-sv35JY-z.cjs → manager-BVX9nVrM.cjs} +2 -2
  448. package/dist/{manager-DfWQCJUK.js → manager-ChK9GdGz.js} +2 -2
  449. package/dist/mastra/index.cjs +1 -1
  450. package/dist/mastra/index.js +1 -1
  451. package/dist/{mastra-CigBrT7X.js → mastra-CUGfgEpZ.js} +28 -18
  452. package/dist/{mastra-D4hvfuxX.cjs → mastra-HSmofHEJ.cjs} +28 -18
  453. package/dist/memory/index.cjs +2 -2
  454. package/dist/memory/index.js +2 -2
  455. package/dist/memory/memory.d.ts +1 -1
  456. package/dist/memory/types.d.ts +2 -2
  457. package/dist/{model-CYtXw861.js → model-C47BJRtR.js} +1 -1
  458. package/dist/{model-BK93CMtl.cjs → model-WahorgzJ.cjs} +1 -1
  459. package/dist/{netlify-CuI1ZrwR.js → netlify-CfDXkuLf.js} +2 -2
  460. package/dist/{netlify-BAnn3ouY.cjs → netlify-D99AnEhW.cjs} +2 -2
  461. package/dist/notifications/index.cjs +1 -1
  462. package/dist/notifications/index.js +1 -1
  463. package/dist/observability/index.cjs +1 -0
  464. package/dist/observability/index.d.ts +1 -1
  465. package/dist/observability/index.js +2 -2
  466. package/dist/{output-helpers-CedRCE17.js → output-helpers-CVzhy1Y0.js} +126 -56
  467. package/dist/{output-helpers-1Zu4Vt9C.cjs → output-helpers-DgsH4aTb.cjs} +143 -55
  468. package/dist/processor-provider/index.cjs +1 -1
  469. package/dist/processor-provider/index.js +1 -1
  470. package/dist/processors/index.cjs +2 -2
  471. package/dist/processors/index.d.ts +2 -2
  472. package/dist/processors/index.js +2 -2
  473. package/dist/processors/runner.d.ts +3 -1
  474. package/dist/processors/step-schema.d.ts +1 -1
  475. package/dist/{provider-registry-BwuI_IpT.cjs → provider-registry-CO1NVbO5.cjs} +22070 -22050
  476. package/dist/{provider-registry-CmQLzLF_.js → provider-registry-CR385GJ4.js} +22070 -22050
  477. package/dist/provider-registry.json +22239 -22226
  478. package/dist/{registry-generator-C17V4WfG.js → registry-generator-B3erRqYS.js} +1 -1
  479. package/dist/{registry-generator-C_0ae7Ce.cjs → registry-generator-Cvp34qcB.cjs} +1 -1
  480. package/dist/{rehydrate-PnaVawGX.js → rehydrate-CJBLrZxs.js} +2 -2
  481. package/dist/{rehydrate-CDQ4dOYj.cjs → rehydrate-Da4hNuaK.cjs} +2 -2
  482. package/dist/relevance/index.cjs +2 -2
  483. package/dist/relevance/index.js +2 -2
  484. package/dist/{run-registry-BwEcwYlU.js → run-registry-DdeEBsVW.js} +1639 -568
  485. package/dist/{run-registry-BmckDVBk.cjs → run-registry-TOOfO3hT.cjs} +1668 -567
  486. package/dist/server/auth.d.ts +3 -3
  487. package/dist/server/composite-auth.d.ts +1 -1
  488. package/dist/server/simple-auth.d.ts +1 -1
  489. package/dist/server/types.d.ts +1 -1
  490. package/dist/storage/domains/inmemory-db.d.ts +1 -0
  491. package/dist/storage/domains/knowledge/base.d.ts +5 -0
  492. package/dist/storage/domains/knowledge/inmemory.d.ts +1 -0
  493. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +10 -2
  494. package/dist/storage/domains/knowledge/pages.d.ts +30 -0
  495. package/dist/storage/index.cjs +2 -2
  496. package/dist/storage/index.js +2 -2
  497. package/dist/storage/run-fencing.d.ts +5 -0
  498. package/dist/stream/RunOutput.d.ts +1 -1
  499. package/dist/stream/aisdk/v4/input.d.ts +1 -1
  500. package/dist/stream/aisdk/v5/compat/content.d.ts +1 -1
  501. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts +1 -1
  502. package/dist/stream/aisdk/v5/compat/ui-message.d.ts +1 -1
  503. package/dist/stream/aisdk/v5/compat/validation.d.ts +1 -1
  504. package/dist/stream/aisdk/v5/execute.d.ts +1 -1
  505. package/dist/stream/aisdk/v5/input.d.ts +1 -1
  506. package/dist/stream/aisdk/v5/output-helpers.d.ts +7 -7
  507. package/dist/stream/aisdk/v5/transform.d.ts +1 -1
  508. package/dist/stream/base/output.d.ts +4 -4
  509. package/dist/stream/base/schema.d.ts +1 -1
  510. package/dist/stream/index.cjs +2 -2
  511. package/dist/stream/index.js +2 -2
  512. package/dist/stream/types.d.ts +2 -2
  513. package/dist/{stream-D1y9GzoD.js → stream-C5PagEDs.js} +3 -3
  514. package/dist/{stream-0kdqBOOn.cjs → stream-DH7Qgz8l.cjs} +3 -3
  515. package/dist/test-utils/llm-mock.cjs +1 -1
  516. package/dist/test-utils/llm-mock.d.ts +3 -3
  517. package/dist/test-utils/llm-mock.js +1 -1
  518. package/dist/tool-loop-agent/index.cjs +1 -1
  519. package/dist/tool-loop-agent/index.js +1 -1
  520. package/dist/tool-loop-agent/utils.d.ts +1 -1
  521. package/dist/{tool-loop-agent-kWaZAT6Q.cjs → tool-loop-agent-CJTs4T8b.cjs} +3 -3
  522. package/dist/{tool-loop-agent-BdjWGVIb.js → tool-loop-agent-DVYJXlQJ.js} +3 -3
  523. package/dist/tools/builtin/web-search.d.ts +1 -1
  524. package/dist/tools/provider-tool-utils.d.ts +1 -1
  525. package/dist/tools/tool-builder/builder.d.ts +1 -1
  526. package/dist/tools/tool-title.d.ts +1 -1
  527. package/dist/tools/types.d.ts +1 -1
  528. package/dist/types/user.d.ts +1 -1
  529. package/dist/{utils-GHY3hmLx.js → utils-D8upuTwy.js} +1 -1
  530. package/dist/{utils-BKUCaZ12.cjs → utils-xJi_N6Tx.cjs} +1 -1
  531. package/dist/utils.cjs +1 -1
  532. package/dist/utils.d.ts +1 -1
  533. package/dist/utils.js +1 -1
  534. package/dist/{validate-De92squ7.cjs → validate-6eZ8Wssn.cjs} +1 -1
  535. package/dist/{validate-CB-q-R2F.js → validate-DTkW3Vlp.js} +1 -1
  536. package/dist/vector/embed.d.ts +4 -4
  537. package/dist/vector/index.cjs +1 -1
  538. package/dist/vector/index.js +1 -1
  539. package/dist/vector/vector.d.ts +4 -4
  540. package/dist/voice/aisdk/index.d.ts +1 -1
  541. package/dist/voice/aisdk/speech.d.ts +1 -1
  542. package/dist/voice/aisdk/transcription.d.ts +1 -1
  543. package/dist/voice/composite-voice.d.ts +1 -1
  544. package/dist/voice/default-voice.d.ts +1 -1
  545. package/dist/voice/index.d.ts +2 -2
  546. package/dist/voice/voice.d.ts +1 -1
  547. package/dist/worker/index.cjs +1 -1
  548. package/dist/worker/index.js +1 -1
  549. package/dist/{worker-CAKvQj9_.cjs → worker-24ORi-wV.cjs} +2 -2
  550. package/dist/{worker-BbWPQuPR.cjs → worker-BO3u_WjZ.cjs} +2 -2
  551. package/dist/{worker-C3u_xzY2.js → worker-DbcFkKJO.js} +2 -2
  552. package/dist/{worker-Kwm8EKcj.js → worker-Dqubrnf8.js} +2 -2
  553. package/dist/{workflow-CSjXeNcR.cjs → workflow-D5Fc5ieC.cjs} +4 -4
  554. package/dist/{workflow-CVmI1Sw-.js → workflow-wXOf72fO.js} +4 -4
  555. package/dist/workflows/builder/index.cjs +1 -1
  556. package/dist/workflows/builder/index.js +1 -1
  557. package/dist/workflows/evented/index.cjs +1 -1
  558. package/dist/workflows/evented/index.js +1 -1
  559. package/dist/workflows/index.cjs +4 -4
  560. package/dist/workflows/index.js +4 -4
  561. package/dist/workflows/run-ownership.d.ts +74 -8
  562. package/dist/workflows/types.d.ts +17 -1
  563. package/dist/workflows/workflow.d.ts +4 -0
  564. package/package.json +14 -14
  565. package/src/llm/model/provider-types.generated.d.ts +8011 -7996
  566. /package/dist/_types/{@internal_ai-sdk-v4@0.0.98 → @internal_ai-sdk-v4@0.0.99}/dist/index.d.ts +0 -0
  567. /package/dist/_types/{@internal_ai-sdk-v4@0.0.98 → @internal_ai-sdk-v4@0.0.99}/dist/test.d.ts +0 -0
  568. /package/dist/_types/{@internal_ai-sdk-v4@0.0.98 → @internal_ai-sdk-v4@0.0.99}/package.json +0 -0
  569. /package/dist/_types/{@internal_ai-sdk-v5@0.0.98 → @internal_ai-sdk-v5@0.0.99}/dist/index.d.ts +0 -0
  570. /package/dist/_types/{@internal_ai-sdk-v5@0.0.98 → @internal_ai-sdk-v5@0.0.99}/dist/test.d.ts +0 -0
  571. /package/dist/_types/{@internal_ai-sdk-v5@0.0.98 → @internal_ai-sdk-v5@0.0.99}/package.json +0 -0
  572. /package/dist/_types/{@internal_ai-v6@0.0.98 → @internal_ai-v6@0.0.99}/dist/index.d.ts +0 -0
  573. /package/dist/_types/{@internal_ai-v6@0.0.98 → @internal_ai-v6@0.0.99}/package.json +0 -0
  574. /package/dist/_types/{@internal_ai-v7@0.0.98 → @internal_ai-v7@0.0.99}/dist/index.d.ts +0 -0
  575. /package/dist/_types/{@internal_ai-v7@0.0.98 → @internal_ai-v7@0.0.99}/package.json +0 -0
  576. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/_types/@internal_core@0.1.4/dist/base/index.d.ts +0 -0
  577. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/_types/@internal_core@0.1.4/dist/index-Diz1p9N7.d.ts +0 -0
  578. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/capabilities.d.ts +0 -0
  579. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/defaults/index.d.ts +0 -0
  580. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/defaults/rbac/index.d.ts +0 -0
  581. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/defaults/rbac/static.d.ts +0 -0
  582. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/defaults/roles.d.ts +0 -0
  583. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/fga-check.d.ts +0 -0
  584. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/index.d.ts +0 -0
  585. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/interfaces/acl.d.ts +0 -0
  586. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/interfaces/fga.d.ts +0 -0
  587. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/interfaces/index.d.ts +0 -0
  588. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/interfaces/permissions.generated.d.ts +0 -0
  589. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/interfaces/rbac.d.ts +0 -0
  590. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/interfaces/user.d.ts +0 -0
  591. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/ee/license.d.ts +0 -0
  592. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/index.d.ts +0 -0
  593. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/provider/index.d.ts +0 -0
  594. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/session/cookie.d.ts +0 -0
  595. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/session/index.d.ts +0 -0
  596. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/session/memory.d.ts +0 -0
  597. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/dist/types/index.d.ts +0 -0
  598. /package/dist/_types/{@internal_auth@0.0.39 → @internal_auth@0.0.40}/package.json +0 -0
  599. /package/dist/_types/{@internal_deployer@0.0.4 → @internal_deployer@0.0.5}/dist/_types/@internal_core@0.1.4/dist/index-Diz1p9N7.d.ts +0 -0
  600. /package/dist/_types/{@internal_deployer@0.0.4 → @internal_deployer@0.0.5}/dist/_types/@internal_core@0.1.4/dist/logger/index.d.ts +0 -0
  601. /package/dist/_types/{@internal_deployer@0.0.4 → @internal_deployer@0.0.5}/dist/bundler.d.ts +0 -0
  602. /package/dist/_types/{@internal_deployer@0.0.4 → @internal_deployer@0.0.5}/dist/deployer.d.ts +0 -0
  603. /package/dist/_types/{@internal_deployer@0.0.4 → @internal_deployer@0.0.5}/dist/index.d.ts +0 -0
  604. /package/dist/_types/{@internal_deployer@0.0.4 → @internal_deployer@0.0.5}/package.json +0 -0
  605. /package/dist/_types/{@internal_external-types@0.0.101 → @internal_external-types@0.0.102}/dist/index.d.ts +0 -0
  606. /package/dist/_types/{@internal_external-types@0.0.101 → @internal_external-types@0.0.102}/package.json +0 -0
  607. /package/dist/_types/{@internal_voice@0.0.47/dist/_types/@internal_ai-sdk-v5@0.0.98 → @internal_voice@0.0.48/dist/_types/@internal_ai-sdk-v5@0.0.99}/dist/index.d.ts +0 -0
  608. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/@internal_core@0.1.4/dist/base/index.d.ts +0 -0
  609. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/@internal_core@0.1.4/dist/index-Diz1p9N7.d.ts +0 -0
  610. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/@internal_core@0.1.4/dist/request-context/index.d.ts +0 -0
  611. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/@internal_core@0.1.4/dist/types/index.d.ts +0 -0
  612. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/ZodError.d.ts +0 -0
  613. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/errors.d.ts +0 -0
  614. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/external.d.ts +0 -0
  615. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/helpers/enumUtil.d.ts +0 -0
  616. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/helpers/errorUtil.d.ts +0 -0
  617. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/helpers/parseUtil.d.ts +0 -0
  618. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/helpers/partialUtil.d.ts +0 -0
  619. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/helpers/typeAliases.d.ts +0 -0
  620. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/helpers/util.d.ts +0 -0
  621. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/index.d.ts +0 -0
  622. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/locales/en.d.ts +0 -0
  623. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/standard-schema.d.ts +0 -0
  624. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v3/types.d.ts +0 -0
  625. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/checks.d.ts +0 -0
  626. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/coerce.d.ts +0 -0
  627. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/compat.d.ts +0 -0
  628. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/deep-partial.d.ts +0 -0
  629. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/errors.d.ts +0 -0
  630. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/external.d.ts +0 -0
  631. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/from-json-schema.d.ts +0 -0
  632. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/in-out.d.ts +0 -0
  633. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/index.d.ts +0 -0
  634. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/iso.d.ts +0 -0
  635. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/parse.d.ts +0 -0
  636. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/classic/schemas.d.ts +0 -0
  637. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/api.d.ts +0 -0
  638. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/checks.d.ts +0 -0
  639. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/compile.d.ts +0 -0
  640. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/core.d.ts +0 -0
  641. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/doc.d.ts +0 -0
  642. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/errors.d.ts +0 -0
  643. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/index.d.ts +0 -0
  644. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/json-schema-generator.d.ts +0 -0
  645. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/json-schema-processors.d.ts +0 -0
  646. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/json-schema.d.ts +0 -0
  647. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/memoizer.d.ts +0 -0
  648. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/parse.d.ts +0 -0
  649. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/regexes.d.ts +0 -0
  650. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/registries.d.ts +0 -0
  651. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/schemas.d.ts +0 -0
  652. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/standard-schema.d.ts +0 -0
  653. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/to-json-schema.d.ts +0 -0
  654. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/util.d.ts +0 -0
  655. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/core/versions.d.ts +0 -0
  656. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/index.d.cts +0 -0
  657. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ar.d.ts +0 -0
  658. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/az.d.ts +0 -0
  659. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/be.d.ts +0 -0
  660. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/bg.d.ts +0 -0
  661. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/bn.d.ts +0 -0
  662. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ca.d.ts +0 -0
  663. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ckb.d.ts +0 -0
  664. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/cs.d.ts +0 -0
  665. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/da.d.ts +0 -0
  666. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/de.d.ts +0 -0
  667. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/el.d.ts +0 -0
  668. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/en.d.ts +0 -0
  669. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/eo.d.ts +0 -0
  670. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/es.d.ts +0 -0
  671. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/fa.d.ts +0 -0
  672. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/fi.d.ts +0 -0
  673. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/fr-CA.d.ts +0 -0
  674. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/fr.d.ts +0 -0
  675. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/gu.d.ts +0 -0
  676. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/he.d.ts +0 -0
  677. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/hi.d.ts +0 -0
  678. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/hr.d.ts +0 -0
  679. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/hu.d.ts +0 -0
  680. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/hy.d.ts +0 -0
  681. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/id.d.ts +0 -0
  682. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/index.d.ts +0 -0
  683. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/is.d.ts +0 -0
  684. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/it.d.ts +0 -0
  685. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ja.d.ts +0 -0
  686. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ka.d.ts +0 -0
  687. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/kh.d.ts +0 -0
  688. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/km.d.ts +0 -0
  689. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/kn.d.ts +0 -0
  690. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ko.d.ts +0 -0
  691. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/lt.d.ts +0 -0
  692. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/mk.d.ts +0 -0
  693. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ms.d.ts +0 -0
  694. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ne.d.ts +0 -0
  695. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/nl.d.ts +0 -0
  696. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/nn.d.ts +0 -0
  697. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/no.d.ts +0 -0
  698. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ota.d.ts +0 -0
  699. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/pl.d.ts +0 -0
  700. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ps.d.ts +0 -0
  701. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/pt-BR.d.ts +0 -0
  702. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/pt.d.ts +0 -0
  703. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ro.d.ts +0 -0
  704. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ru.d.ts +0 -0
  705. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/sk.d.ts +0 -0
  706. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/sl.d.ts +0 -0
  707. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/sv.d.ts +0 -0
  708. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ta.d.ts +0 -0
  709. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/tg.d.ts +0 -0
  710. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/th.d.ts +0 -0
  711. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/tk.d.ts +0 -0
  712. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/tr.d.ts +0 -0
  713. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ua.d.ts +0 -0
  714. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/uk.d.ts +0 -0
  715. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/ur.d.ts +0 -0
  716. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/uz.d.ts +0 -0
  717. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/vi.d.ts +0 -0
  718. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/yo.d.ts +0 -0
  719. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/zh-CN.d.ts +0 -0
  720. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/_types/zod@4.6.7/v4/locales/zh-TW.d.ts +0 -0
  721. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/index.d.ts +0 -0
  722. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/voice/aisdk/index.d.ts +0 -0
  723. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/voice/default-voice.d.ts +0 -0
  724. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/voice/index.d.ts +0 -0
  725. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/dist/voice/voice.d.ts +0 -0
  726. /package/dist/_types/{@internal_voice@0.0.47 → @internal_voice@0.0.48}/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-D1y9GzoD.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-C5PagEDs.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";
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
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";
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-B5A5cwJr.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-B1zaFLYZ.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-CmQLzLF_.js";
28
- import { t as InMemoryServerCache } from "./inmemory-BDD0w8gx.js";
27
+ import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-CR385GJ4.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-CYtXw861.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-GHY3hmLx.js";
30
+ import { t as MastraLLMV1 } from "./model-C47BJRtR.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-D8upuTwy.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-BnJfNLFo.js";
33
+ import { a as resolveBackgroundConfig, o as createBackgroundTask, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-IW7M4iD2.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;
10537
+ try {
10538
+ ownership = held ?? await this.#claimOwnership(true);
10539
+ } catch (error) {
10540
+ await onFailure?.();
10541
+ throw error;
10542
+ }
10543
+ if (!("release" in ownership)) return executeOrUndo();
10250
10544
  try {
10251
- return await execute();
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);
@@ -11915,8 +12213,16 @@ const AgentStreamEventTypes = {
11915
12213
  OWNERSHIP_CLAIMED: "ownership-claimed"
11916
12214
  };
11917
12215
  // 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;
12216
+ /**
12217
+ * Lifetime of a running or suspended run's record. Deliberately much longer
12218
+ * than the stream log's retention: the record is a single small key, and it is
12219
+ * what lets any replica authorize `observe()`/abort/resume on a run parked
12220
+ * overnight on a tool approval — long after its replay log expired (the log
12221
+ * is recreated with later indices and observers resync; see
12222
+ * `MastraServerCache.listPushIndexed`). A finished run's record is deleted by
12223
+ * run cleanup; this lifetime bounds it when cleanup never runs.
12224
+ */
12225
+ const AGENT_RUN_RECORD_TTL_MS = 864e5;
11920
12226
  const agentRunRecordKey = (agentId, runId) => `agent.run.${agentId}.${runId}`;
11921
12227
  async function writeAgentRunRecord(cache, record, key = agentRunRecordKey(record.agentId, record.runId)) {
11922
12228
  await cache.set(key, record, AGENT_RUN_RECORD_TTL_MS);
@@ -12895,10 +13201,14 @@ function createOwnerHandle({ pubsub, runId, cleanupTimeoutMs, logger, abortSigna
12895
13201
  await assertCleanupOwnership?.();
12896
13202
  if (record) {
12897
13203
  const current = await readAgentRunRecord(record.cache, record.agentId, runId, record.key);
12898
- if (current && current.publisherId !== publisherId) return false;
13204
+ if (current && current.publisherId !== publisherId) {
13205
+ logger?.info?.(`[AgentStream:${runId}] skipping stream cleanup: the run record belongs to publisher ${current.publisherId}, not ${publisherId}`);
13206
+ return false;
13207
+ }
12899
13208
  }
12900
13209
  return true;
12901
- } catch {
13210
+ } catch (error) {
13211
+ 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
13212
  return false;
12903
13213
  }
12904
13214
  };
@@ -12916,8 +13226,12 @@ function createOwnerHandle({ pubsub, runId, cleanupTimeoutMs, logger, abortSigna
12916
13226
  AGENT_STREAM_TOPIC(runId),
12917
13227
  AGENT_CONTROL_TOPIC(runId),
12918
13228
  abortAckTopic(runId)
12919
- ]) pubsub.clearTopic(topic).catch(() => {});
12920
- if (record) deleteAgentRunRecord(record.cache, record.agentId, runId, record.key).catch(() => {});
13229
+ ]) pubsub.clearTopic(topic).catch((error) => {
13230
+ logger?.warn?.(`[AgentStream:${runId}] failed to clear stream topic ${topic}`, { error });
13231
+ });
13232
+ if (record) deleteAgentRunRecord(record.cache, record.agentId, runId, record.key).catch((error) => {
13233
+ logger?.warn?.(`[AgentStream:${runId}] failed to delete the run record`, { error });
13234
+ });
12921
13235
  };
12922
13236
  const scheduleCleanup = () => {
12923
13237
  scheduleStreamCleanup(cleanupTimeoutMs, () => void cleanup())?.unref?.();
@@ -13102,9 +13416,11 @@ const streamOwnerKey = createRunScopeKey("execution-stream-owner");
13102
13416
  const executionTransport = Symbol("execution-stream-publisher-transport");
13103
13417
  function resolveExecutionPublisher({ runId, mastra, agentId, agent, claim, entry = getRunRegistryEntry(runId, mastra) }) {
13104
13418
  if (!entry && !claim) return;
13419
+ let createdPlaceholder = false;
13105
13420
  if (!entry) {
13106
13421
  entry = { isPlaceholder: true };
13107
13422
  if (!setRunRegistryEntry(runId, entry, mastra)) return;
13423
+ createdPlaceholder = true;
13108
13424
  }
13109
13425
  const scope = entry.runScope ??= createRunScope();
13110
13426
  if (agent) scope.set(streamOwnerKey, agent);
@@ -13128,16 +13444,17 @@ function resolveExecutionPublisher({ runId, mastra, agentId, agent, claim, entry
13128
13444
  executionClaim,
13129
13445
  requestContext,
13130
13446
  memoryInfo,
13131
- entry
13447
+ entry,
13448
+ createdPlaceholder
13132
13449
  };
13133
13450
  }
13134
13451
  /** Worker output keeps its captured execution authority and cannot settle or clean up the run. */
13135
13452
  function getExecutionStreamProducer(options) {
13136
13453
  const context = resolveExecutionPublisher(options);
13137
13454
  if (!context) return;
13138
- const { publisher, publisherId, runBus, requestContext } = context;
13455
+ const { publisher, publisherId, runBus, requestContext, entry, createdPlaceholder } = context;
13139
13456
  const { runId, agentId, mastra } = options;
13140
- return publisher.attachEventProducer({
13457
+ const producer = publisher.attachEventProducer({
13141
13458
  publisherId,
13142
13459
  pubsub: runBus.pubsub,
13143
13460
  assertOwnership: () => assertExecutionNotSuperseded({
@@ -13147,6 +13464,19 @@ function getExecutionStreamProducer(options) {
13147
13464
  requestContext
13148
13465
  })
13149
13466
  });
13467
+ if (!createdPlaceholder) return producer;
13468
+ return {
13469
+ async publishEvent(event, transport, publishOptions) {
13470
+ try {
13471
+ return await producer.publishEvent(event, transport, publishOptions);
13472
+ } catch (error) {
13473
+ const current = getRunRegistryEntry(runId, mastra);
13474
+ if (isExecutionFenceError(error) && current === entry && entry.isPlaceholder === true) deleteRunRegistryEntry(runId, mastra);
13475
+ throw error;
13476
+ }
13477
+ },
13478
+ detach: () => producer.detach()
13479
+ };
13150
13480
  }
13151
13481
  /** Owning readers settle and clean up using the authority of their captured execution. */
13152
13482
  function getExecutionStreamOwner(options) {
@@ -13235,23 +13565,6 @@ function withExecutionStreamProducer(pubsub, options) {
13235
13565
  return typeof value === "function" ? value.bind(target) : value;
13236
13566
  } });
13237
13567
  }
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
13568
  // src/agent/durable/execution-fence.ts
13256
13569
  /**
13257
13570
  * Execution fence for DurableAgent runs (#23734).
@@ -13280,10 +13593,12 @@ function currentRunFenceScope() {
13280
13593
  const EXECUTION_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
13281
13594
  const EXECUTION_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
13282
13595
  /**
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.
13596
+ * Heartbeat ticks a storage-backed execution goes without a confirmed renewal before it gives up the run: a TTL's
13597
+ * worth while renewals fail, and one more TTL while a renewal is still in flight, since one queued behind other writes
13598
+ * can still extend the lease. Ticks, not elapsed time, because a stalled process misses ticks without failing any.
13285
13599
  */
13286
- const STORAGE_RENEWAL_GRACE_MS = EXECUTION_LEASE_TTL_MS;
13600
+ const STORAGE_FAILED_RENEWAL_TICKS = Math.ceil(EXECUTION_LEASE_TTL_MS / EXECUTION_LEASE_RENEW_INTERVAL_MS);
13601
+ const STORAGE_PENDING_RENEWAL_TICKS = 2 * STORAGE_FAILED_RENEWAL_TICKS;
13287
13602
  /** Allowance for the store's clock running ahead of this process when reading a renewed lease's expiry. */
13288
13603
  const STORE_CLOCK_SKEW_MS = EXECUTION_LEASE_RENEW_INTERVAL_MS;
13289
13604
  const VERIFY_RETRY_DELAY_MS = 250;
@@ -13782,6 +14097,7 @@ var ExecutionFence = class ExecutionFence {
13782
14097
  /** The grace for a release of this claim is spent: a renewal already found it released before this fence settled. */
13783
14098
  #releaseSeen = false;
13784
14099
  #settlement;
14100
+ #detached = false;
13785
14101
  #settledAs;
13786
14102
  #resolveSettled;
13787
14103
  /** Resolves once {@link settle} has finished and the claim is released or left to its new holder. */
@@ -14001,6 +14317,10 @@ var ExecutionFence = class ExecutionFence {
14001
14317
  get settlement() {
14002
14318
  return this.#settledAs;
14003
14319
  }
14320
+ /** This process stopped coordinating the run and left its settlement to the workers. */
14321
+ get detached() {
14322
+ return this.#detached;
14323
+ }
14004
14324
  /** An owned deadline settlement revokes writes without handing its topics to another execution. */
14005
14325
  ownsRunTopics() {
14006
14326
  return this.#settledAs === "owned" || !this.#lossError;
@@ -14193,6 +14513,7 @@ var ExecutionFence = class ExecutionFence {
14193
14513
  /** Detach a coordinator without changing the claim shared with remote workers. */
14194
14514
  detach() {
14195
14515
  if (this.#settlement) return;
14516
+ this.#detached = true;
14196
14517
  this.stopHeartbeat();
14197
14518
  this.#settledAs = "superseded";
14198
14519
  this.#settlement = Promise.resolve("superseded");
@@ -14326,8 +14647,16 @@ var ExecutionFence = class ExecutionFence {
14326
14647
  }
14327
14648
  /**
14328
14649
  * 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
14650
+ * fence lost, which notifies {@link onLost} listeners.
14651
+ *
14652
+ * A storage claim is judged by the store's conditional renewal, not the
14653
+ * local clock: a blocked event loop moves the clock without letting this
14654
+ * process renew, so a stall alone must not lose the run (#30669). The
14655
+ * heartbeat counts its ticks since the last confirmed renewal instead:
14656
+ * failed renewals are tolerated for a TTL's worth of ticks, and one still
14657
+ * in flight for one more TTL. A pubsub lease has no generation to tell a
14658
+ * late renewal from a later holder's, so it keeps the local deadline, and
14659
+ * its backend errors are tolerated until then. A failed renewal can be caused
14331
14660
  * by this execution's own release: in this process, when the backend
14332
14661
  * confirmed the claim still held the run as it was released (without that
14333
14662
  * confirmation another execution claimed the run first); in another process,
@@ -14347,11 +14676,19 @@ var ExecutionFence = class ExecutionFence {
14347
14676
  let fences = renewingFencesByClaim.get(key);
14348
14677
  if (!fences) renewingFencesByClaim.set(key, fences = /* @__PURE__ */ new Set());
14349
14678
  fences.add(this);
14679
+ const storage = this.generation !== void 0;
14680
+ let unconfirmedTicks = 0;
14681
+ let lastFailure;
14350
14682
  this.#heartbeat = setInterval(() => {
14351
14683
  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) {
14684
+ if (storage) {
14685
+ unconfirmedTicks++;
14686
+ const limit = this.#renewalInFlight ? STORAGE_PENDING_RENEWAL_TICKS : STORAGE_FAILED_RENEWAL_TICKS;
14687
+ if (unconfirmedTicks >= limit) {
14688
+ this.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, this.#details(), lastFailure));
14689
+ return;
14690
+ }
14691
+ } else if (Date.now() >= this.#leaseExpiresAt) {
14355
14692
  this.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, this.#details()));
14356
14693
  return;
14357
14694
  }
@@ -14363,6 +14700,8 @@ var ExecutionFence = class ExecutionFence {
14363
14700
  const { leaseExpiresAt } = result;
14364
14701
  const reported = leaseExpiresAt ? Math.min(leaseExpiresAt.getTime() - STORE_CLOCK_SKEW_MS, Date.now() + EXECUTION_LEASE_TTL_MS) : 0;
14365
14702
  this.#leaseExpiresAt = Math.max(startedAt + EXECUTION_LEASE_TTL_MS, reported);
14703
+ unconfirmedTicks = 0;
14704
+ lastFailure = void 0;
14366
14705
  return;
14367
14706
  }
14368
14707
  if (await this.#releaseExplainsFailedRenewal(result.released)) return;
@@ -14370,7 +14709,8 @@ var ExecutionFence = class ExecutionFence {
14370
14709
  return this.#noteTakeover();
14371
14710
  }).catch(async (cause) => {
14372
14711
  if (this.#settlement && await releaseAnswer(this.#ownRelease.awaitAnswer())) return;
14373
- if (Date.now() >= this.#leaseExpiresAt) {
14712
+ if (storage && !this.#settlement) lastFailure = cause;
14713
+ else if (Date.now() >= this.#leaseExpiresAt) {
14374
14714
  this.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, this.#details(), cause));
14375
14715
  return;
14376
14716
  }
@@ -14683,46 +15023,6 @@ var EventProcessor = class {
14683
15023
  this.mastra = mastra;
14684
15024
  }
14685
15025
  };
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
15026
  // src/workflows/scheduler/definition-hash.ts
14727
15027
  /**
14728
15028
  * Computes a stable content hash of a workflow's serialized step graph.
@@ -20456,13 +20756,20 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
20456
20756
  */
20457
20757
  async handle(event) {
20458
20758
  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);
20759
+ if (!isStorageFencedExecution(new RequestContext(Object.entries(event.data?.requestContext ?? {})), event.runId, event.data?.parentWorkflow)) {
20760
+ await carryEndedSegment(this.mastra, event);
20761
+ const result = await this.#handleDelivery(event);
20762
+ if (result.ok) endFailedIteration(this.mastra, event);
20763
+ return result;
20764
+ }
20460
20765
  try {
20461
20766
  if (await retrySettledDurableExecution(this.mastra, event)) return { ok: true };
20462
20767
  const execute = async () => {
20463
20768
  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)));
20769
+ if (result.ok) {
20770
+ endFailedIteration(this.mastra, event);
20771
+ await settleEventedDurableExecution(this.mastra, event);
20772
+ } else if (!result.retry) await stopAbandonedDurableExecution(this.mastra, event, !this.#abandonedUnpublished.has(this.#deliveryKey(event)));
20466
20773
  return result;
20467
20774
  };
20468
20775
  return await participateInDurableExecution(this.mastra, event, execute);
@@ -39635,6 +39942,13 @@ const compareCodeUnits$1 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
39635
39942
  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
39943
  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
39944
  const newestFirst = (a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
39945
+ /** An oldest-first position: the event's insertion counter as plain decimal text. */
39946
+ function activityPosition(value) {
39947
+ if (value === void 0) return void 0;
39948
+ const n = /^(0|[1-9]\d*)$/.test(value) ? Number(value) : NaN;
39949
+ if (!Number.isSafeInteger(n)) throw new RangeError(`Knowledge activity position is not one this store issued: ${value}`);
39950
+ return n;
39951
+ }
39638
39952
  const oldestFirst = (a, b) => newestFirst(b, a);
39639
39953
  const clone$1 = (value) => structuredClone(value);
39640
39954
  const PIN_KINDS = ["page", "list"];
@@ -39646,6 +39960,8 @@ var InMemoryKnowledgePageStore = class {
39646
39960
  #activity = [];
39647
39961
  #bodyLinks = /* @__PURE__ */ new Map();
39648
39962
  #clock = 0;
39963
+ /** Insertion counter behind each event's `position`; never reset, so a held position can't be reused. */
39964
+ #activitySeq = 0;
39649
39965
  /** A deep copy of every page, note, pin, body link and event, for {@link restore}. */
39650
39966
  snapshot() {
39651
39967
  return structuredClone({
@@ -39664,6 +39980,9 @@ var InMemoryKnowledgePageStore = class {
39664
39980
  this.#pins = copy.pins;
39665
39981
  this.#activity = copy.activity;
39666
39982
  this.#bodyLinks = copy.bodyLinks;
39983
+ const positioned = (event) => Number.isSafeInteger(event.position === void 0 ? NaN : Number(event.position));
39984
+ for (const event of this.#activity) if (positioned(event)) this.#activitySeq = Math.max(this.#activitySeq, Number(event.position));
39985
+ if (!this.#activity.every(positioned)) for (const event of this.#activity) event.position = String(++this.#activitySeq);
39667
39986
  }
39668
39987
  /** Drops every page, note, pin, body link and event. */
39669
39988
  clear() {
@@ -39686,7 +40005,8 @@ var InMemoryKnowledgePageStore = class {
39686
40005
  pageId: page.id,
39687
40006
  ...noteId ? { noteId } : {},
39688
40007
  provenance: clone$1(provenance),
39689
- createdAt: this.#now()
40008
+ createdAt: this.#now(),
40009
+ position: String(++this.#activitySeq)
39690
40010
  });
39691
40011
  }
39692
40012
  #page(id) {
@@ -40274,25 +40594,40 @@ var InMemoryKnowledgePageStore = class {
40274
40594
  }
40275
40595
  async listPageActivity(input) {
40276
40596
  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);
40597
+ if (input.after !== void 0 && input.order !== "asc") throw new RangeError("Knowledge activity takes an after position only with order asc");
40598
+ if (input.after !== void 0 && input.cursor !== void 0) throw new RangeError("Knowledge activity takes either a cursor or an after position, not both");
40599
+ 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");
40600
+ if (input.order === "asc") {
40601
+ const after = activityPosition(input.after ?? input.cursor);
40602
+ if (after !== void 0 && after > this.#activitySeq) throw new RangeError(`Knowledge activity position is ahead of this feed: ${after}`);
40603
+ const size = pageSize(input.limit);
40604
+ const matched = this.#activity.filter((event) => this.#activityMatches(event, input) && (after === void 0 || Number(event.position) > after));
40605
+ const items = matched.slice(0, size);
40606
+ const last = items[items.length - 1];
40607
+ return {
40608
+ events: items.map(clone$1),
40609
+ ...matched.length > size && last ? { nextCursor: last.position } : {}
40610
+ };
40611
+ }
40612
+ 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
40613
  return {
40292
- events: items.map(clone$1),
40614
+ events: items.map(({ position: _position, ...event }) => clone$1(event)),
40293
40615
  ...nextCursor ? { nextCursor } : {}
40294
40616
  };
40295
40617
  }
40618
+ #activityMatches(event, input) {
40619
+ const page = this.#pages.get(event.pageId);
40620
+ if (!page || !this.#pageReadable(page, input.read)) return false;
40621
+ if (input.pageId !== void 0 && event.pageId !== input.pageId) return false;
40622
+ if (input.scopeId !== void 0 && page.scopeId !== input.scopeId) return false;
40623
+ if (event.noteId !== void 0) {
40624
+ const note = this.#notes.get(event.noteId);
40625
+ if (!note || !this.#noteVisible(note, input.read)) return false;
40626
+ }
40627
+ if (input.since !== void 0 && event.createdAt.getTime() < input.since.getTime()) return false;
40628
+ if (input.until !== void 0 && event.createdAt.getTime() >= input.until.getTime()) return false;
40629
+ return true;
40630
+ }
40296
40631
  async addPinAudience(input) {
40297
40632
  const page = this.#livePage(input.pageId);
40298
40633
  if (!input.audience.length) throw new Error("A Knowledge pin needs at least one audience scope");
@@ -40517,7 +40852,8 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40517
40852
  supportsExplicitReset: true,
40518
40853
  supportsPinKinds: true,
40519
40854
  supportsTransactions: true,
40520
- supportsActivityDateRange: true
40855
+ supportsActivityDateRange: true,
40856
+ supportsActivityAscending: true
40521
40857
  };
40522
40858
  }
40523
40859
  async inspectSchema() {
@@ -43876,7 +44212,8 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43876
44212
  generation: owner.generation,
43877
44213
  ownerId: owner.ownerId,
43878
44214
  leaseExpiresAt: owner.leaseExpiresAt ? new Date(owner.leaseExpiresAt) : null,
43879
- live: !!owner.leaseExpiresAt && owner.leaseExpiresAt.getTime() > Date.now()
44215
+ live: !!owner.leaseExpiresAt && owner.leaseExpiresAt.getTime() > Date.now(),
44216
+ updatedAt: new Date(owner.updatedAt)
43880
44217
  };
43881
44218
  }
43882
44219
  assertFence(explicit, runId, operation) {
@@ -43893,10 +44230,12 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43893
44230
  acquired: false,
43894
44231
  record: current
43895
44232
  };
44233
+ const now = Date.now();
43896
44234
  this.db.runOwners.set(runId, {
43897
- generation: current ? current.generation + 1 : Math.max(1, Date.now()),
44235
+ generation: current ? current.generation + 1 : Math.max(1, now),
43898
44236
  ownerId,
43899
- leaseExpiresAt: new Date(Date.now() + leaseMs)
44237
+ leaseExpiresAt: new Date(now + leaseMs),
44238
+ updatedAt: new Date(now)
43900
44239
  });
43901
44240
  return {
43902
44241
  acquired: true,
@@ -43909,7 +44248,9 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43909
44248
  renewed: false,
43910
44249
  record: this.ownershipRecord(fence.runId)
43911
44250
  };
43912
- owner.leaseExpiresAt = new Date(Date.now() + leaseMs);
44251
+ const now = Date.now();
44252
+ owner.leaseExpiresAt = new Date(now + leaseMs);
44253
+ owner.updatedAt = new Date(now);
43913
44254
  return {
43914
44255
  renewed: true,
43915
44256
  record: this.ownershipRecord(fence.runId)
@@ -43919,6 +44260,7 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43919
44260
  const owner = this.db.runOwners.get(fence.runId);
43920
44261
  if (!owner || !matchesRunFence(owner, fence)) return false;
43921
44262
  owner.leaseExpiresAt = null;
44263
+ owner.updatedAt = /* @__PURE__ */ new Date();
43922
44264
  return true;
43923
44265
  }
43924
44266
  async getRunOwnership({ runId }) {
@@ -47110,6 +47452,14 @@ function formatToolResult(toolName, argsSummary, resultText, isError, durationMs
47110
47452
  }
47111
47453
  return `${header} \u00B7 ${status}\n${isError && !resultText.startsWith("Error: ") ? `Error: ${resultText}` : resultText}`;
47112
47454
  }
47455
+ /**
47456
+ * Action id of a button that continues a stopped run. Put it on an error card
47457
+ * (see `formatError`); a click sends {@link CONTINUE_RUN_MESSAGE} to the agent
47458
+ * from the clicker, through the same handler as a reply in the thread.
47459
+ */
47460
+ const CONTINUE_RUN_ACTION_ID = "run_continue";
47461
+ /** What a click on a {@link CONTINUE_RUN_ACTION_ID} button says to the agent. */
47462
+ const CONTINUE_RUN_MESSAGE = "Continue.";
47113
47463
  /** Format a tool approval request message */
47114
47464
  function formatToolApproval(toolName, argsSummary, toolCallId, useCards) {
47115
47465
  const header = formatToolHeader(toolName, argsSummary);
@@ -47485,10 +47835,6 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47485
47835
  if (piece) textBuffer += piece;
47486
47836
  continue;
47487
47837
  }
47488
- if (chunk.type === "text-end") {
47489
- await flushText();
47490
- continue;
47491
- }
47492
47838
  if (chunk.type === "step-finish") {
47493
47839
  await flushText();
47494
47840
  continue;
@@ -47525,7 +47871,10 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47525
47871
  continue;
47526
47872
  }
47527
47873
  if (chunk.type === "tool-call") {
47528
- if (channelToolNames.has(chunk.payload.toolName)) continue;
47874
+ if (channelToolNames.has(chunk.payload.toolName)) {
47875
+ await flushText();
47876
+ continue;
47877
+ }
47529
47878
  const enr = tracker.trackStart({
47530
47879
  toolCallId: chunk.payload.toolCallId,
47531
47880
  toolName: chunk.payload.toolName,
@@ -47988,10 +48337,6 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
47988
48337
  pushToSession(piece);
47989
48338
  continue;
47990
48339
  }
47991
- if (chunk.type === "text-end") {
47992
- if (toolDisplay === "hidden") await closeSession();
47993
- continue;
47994
- }
47995
48340
  if (chunk.type === "step-finish") {
47996
48341
  if (toolDisplay !== "grouped") await closeSession();
47997
48342
  continue;
@@ -48027,7 +48372,10 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
48027
48372
  continue;
48028
48373
  }
48029
48374
  if (chunk.type === "tool-call") {
48030
- if (channelToolNames.has(chunk.payload.toolName)) continue;
48375
+ if (channelToolNames.has(chunk.payload.toolName)) {
48376
+ if (toolDisplay === "hidden") await closeSession();
48377
+ continue;
48378
+ }
48031
48379
  const enr = tracker.trackStart({
48032
48380
  toolCallId: chunk.payload.toolCallId,
48033
48381
  toolName: chunk.payload.toolName,
@@ -49784,9 +50132,53 @@ var AgentChannels = class {
49784
50132
  return defaultHandler();
49785
50133
  });
49786
50134
  if (onAction !== false) chat.onAction((event) => {
49787
- const { handlerContext } = beginMessage();
50135
+ const { defaultHandler: handleMessage, handlerContext } = beginMessage();
49788
50136
  const defaultHandler = async () => {
49789
50137
  const { actionId } = event;
50138
+ if (actionId === "run_continue") {
50139
+ const clickedThread = event.thread;
50140
+ if (!clickedThread || onSubscribedMessage === false) return;
50141
+ const threadId = this.resolveExternalThreadId({
50142
+ platform: event.adapter.name,
50143
+ chatThread: clickedThread,
50144
+ messageId: event.messageId
50145
+ });
50146
+ const text = CONTINUE_RUN_MESSAGE;
50147
+ const message = new ChatMessage({
50148
+ attachments: [],
50149
+ author: event.user,
50150
+ formatted: {
50151
+ type: "root",
50152
+ children: [{
50153
+ type: "paragraph",
50154
+ children: [{
50155
+ type: "text",
50156
+ value: text
50157
+ }]
50158
+ }]
50159
+ },
50160
+ id: event.triggerId ?? crypto.randomUUID(),
50161
+ isMention: true,
50162
+ metadata: {
50163
+ dateSent: /* @__PURE__ */ new Date(),
50164
+ edited: false
50165
+ },
50166
+ raw: event.raw,
50167
+ text,
50168
+ threadId
50169
+ });
50170
+ const chatThread = threadId === clickedThread.id ? clickedThread : new ThreadImpl({
50171
+ adapter: event.adapter,
50172
+ channelId: clickedThread.channelId,
50173
+ channelVisibility: clickedThread.channelVisibility,
50174
+ currentMessage: message,
50175
+ id: threadId,
50176
+ isDM: clickedThread.isDM,
50177
+ stateAdapter: this.stateAdapter
50178
+ });
50179
+ if (typeof onSubscribedMessage === "function") return onSubscribedMessage(chatThread, message, handleMessage, handlerContext);
50180
+ return handleMessage(chatThread, message);
50181
+ }
49790
50182
  if (!actionId.startsWith("tool_approve:") && !actionId.startsWith("tool_deny:")) return;
49791
50183
  const platform = event.adapter.name;
49792
50184
  const messageId = event.messageId;
@@ -51100,7 +51492,8 @@ var AgentChannels = class {
51100
51492
  * normally in cards/hidden modes.
51101
51493
  *
51102
51494
  * 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
51495
+ * left on the thread — set by this run or by a channel handler before it
51496
+ * dispatched — so runs that end without posting a message (e.g. terminated
51104
51497
  * by `stopWhen` on a tool call, or aborted) don't leave a stale status
51105
51498
  * pinned to the thread.
51106
51499
  */
@@ -51108,7 +51501,6 @@ var AgentChannels = class {
51108
51501
  const typingStatusOption = adapterConfig?.typingStatus;
51109
51502
  const typingStatusFn = typingStatusOption === false ? null : typeof typingStatusOption === "function" ? typingStatusOption : defaultTypingStatus;
51110
51503
  let currentTypingStatus;
51111
- let statusSent = false;
51112
51504
  try {
51113
51505
  for await (const chunk of stream) {
51114
51506
  if (typingStatusFn && !typingGate.active) {
@@ -51130,7 +51522,6 @@ var AgentChannels = class {
51130
51522
  }
51131
51523
  if (typeof result === "string" && result.length > 0 && result !== currentTypingStatus) {
51132
51524
  currentTypingStatus = result;
51133
- statusSent = true;
51134
51525
  chatThread.startTyping(result).catch((e) => {
51135
51526
  this.log("debug", "Typing indicator failed (best-effort)", {
51136
51527
  platform,
@@ -51144,7 +51535,7 @@ var AgentChannels = class {
51144
51535
  yield chunk;
51145
51536
  }
51146
51537
  } finally {
51147
- if (statusSent && !typingGate.active) chatThread.startTyping("").catch((e) => {
51538
+ if (typingStatusFn && !typingGate.active) chatThread.startTyping("").catch((e) => {
51148
51539
  this.log("debug", "Typing clear failed (best-effort)", {
51149
51540
  platform,
51150
51541
  threadId: chatThread.id,
@@ -61086,8 +61477,8 @@ function knowledgeBodyGrep(lines, terms, context, from = 0) {
61086
61477
  const half = 200;
61087
61478
  let cutStart = start + Math.max(0, at - half);
61088
61479
  let cutEnd = Math.min(end, start + at + half);
61089
- if (isLowSurrogate(lines.body.charCodeAt(cutStart))) cutStart--;
61090
- if (isLowSurrogate(lines.body.charCodeAt(cutEnd))) cutEnd++;
61480
+ if (isLowSurrogate$1(lines.body.charCodeAt(cutStart))) cutStart--;
61481
+ if (isLowSurrogate$1(lines.body.charCodeAt(cutEnd))) cutEnd++;
61091
61482
  parts.push({
61092
61483
  start: cutStart,
61093
61484
  end: cutEnd
@@ -61097,7 +61488,7 @@ function knowledgeBodyGrep(lines, terms, context, from = 0) {
61097
61488
  }
61098
61489
  return parts;
61099
61490
  }
61100
- function isLowSurrogate(code) {
61491
+ function isLowSurrogate$1(code) {
61101
61492
  return code >= 56320 && code <= 57343;
61102
61493
  }
61103
61494
  /**
@@ -61991,6 +62382,248 @@ function knowledgeRunPrincipals(runtime, context) {
61991
62382
  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
62383
  return [.../* @__PURE__ */ new Set([...knowledgeRunScopes(runtime.compiled, raw), ...memory])];
61993
62384
  }
62385
+ /** Longest heading line a hit shows ahead of its excerpt; a longer one is cut with `…`. */
62386
+ const HEADING_CHARS = 120;
62387
+ /** Characters of body looked at past a window's start when fitting it to the token budget. */
62388
+ const WINDOW_SCAN_CHARS = 720;
62389
+ /** Occurrences of each query word sampled as window anchors. */
62390
+ const OCCURRENCES_PER_WORD = 32;
62391
+ /** How far a window edge may move to land on whitespace. */
62392
+ const SNAP_CHARS = 20;
62393
+ /**
62394
+ * The words `knowledge_search` searches for: keyword search has no quoting, so quote marks become
62395
+ * spaces (`"refund" policy` searches `refund policy`).
62396
+ */
62397
+ function knowledgeSearchQuery(query) {
62398
+ return query.replace(/["`\u201C\u201D]/g, " ").trim();
62399
+ }
62400
+ /** Source code units per chunk when lowercasing the body and mapping offsets back. */
62401
+ const MAP_CHUNK = 4096;
62402
+ /**
62403
+ * Exact `toLowerCase()` substring matches of each word, as `[start, end)` offsets into `body`, the
62404
+ * way keyword search matches. The body is lowercased chunk by chunk, so each chunk's lowercased
62405
+ * length is known: lowercasing keeps the length for nearly all text, and where it doesn't (`İ` →
62406
+ * `i̇`) only the chunks a match lands in are walked code point by code point to map offsets back. A
62407
+ * body with no match returns before any mapping.
62408
+ */
62409
+ function lowercaseHits(body, words) {
62410
+ const sourceStarts = [];
62411
+ const loweredStarts = [];
62412
+ const pieces = [];
62413
+ let loweredLength = 0;
62414
+ for (let s = 0; s < body.length;) {
62415
+ let e = Math.min(body.length, s + MAP_CHUNK);
62416
+ if (e < body.length && isHighSurrogate(body.charCodeAt(e - 1))) e++;
62417
+ const piece = body.slice(s, e).toLowerCase();
62418
+ sourceStarts.push(s);
62419
+ loweredStarts.push(loweredLength);
62420
+ pieces.push(piece);
62421
+ loweredLength += piece.length;
62422
+ s = e;
62423
+ }
62424
+ sourceStarts.push(body.length);
62425
+ loweredStarts.push(loweredLength);
62426
+ const text = body.includes("\u03A3") ? body.toLowerCase() : pieces.join("");
62427
+ const found = [];
62428
+ words.forEach((word, w) => {
62429
+ let from = 0;
62430
+ for (let n = 0; n < OCCURRENCES_PER_WORD; n++) {
62431
+ const at = text.indexOf(word, from);
62432
+ if (at < 0) break;
62433
+ found.push({
62434
+ word: w,
62435
+ at,
62436
+ length: word.length
62437
+ });
62438
+ from = at + word.length;
62439
+ }
62440
+ });
62441
+ if (!found.length || loweredLength === body.length) return {
62442
+ hits: found.map(({ word, at, length }) => ({
62443
+ word,
62444
+ start: at,
62445
+ end: at + length
62446
+ })),
62447
+ text
62448
+ };
62449
+ const walked = /* @__PURE__ */ new Map();
62450
+ const widths = /* @__PURE__ */ new Map();
62451
+ const source = (index, edge) => {
62452
+ let chunk = 0;
62453
+ for (let lo = 0, hi = sourceStarts.length - 2; lo <= hi;) {
62454
+ const mid = lo + hi >> 1;
62455
+ if (loweredStarts[mid] <= index) {
62456
+ chunk = mid;
62457
+ lo = mid + 1;
62458
+ } else hi = mid - 1;
62459
+ }
62460
+ const sourceStart = sourceStarts[chunk];
62461
+ const loweredStart = loweredStarts[chunk];
62462
+ const sourceEnd = sourceStarts[chunk + 1];
62463
+ if (loweredStarts[chunk + 1] - loweredStart === sourceEnd - sourceStart) return Math.min(body.length, sourceStart + (index - loweredStart));
62464
+ let changes = walked.get(chunk);
62465
+ if (!changes) {
62466
+ changes = [];
62467
+ for (let i = sourceStart, l = loweredStart; i < sourceEnd;) {
62468
+ const point = body.codePointAt(i);
62469
+ const width = point > 65535 ? 2 : 1;
62470
+ let lowerWidth = point < 128 ? 1 : widths.get(point);
62471
+ if (lowerWidth === void 0) {
62472
+ lowerWidth = String.fromCodePoint(point).toLowerCase().length;
62473
+ widths.set(point, lowerWidth);
62474
+ }
62475
+ if (lowerWidth !== width) changes.push({
62476
+ lowered: l,
62477
+ source: i,
62478
+ width,
62479
+ lowerWidth
62480
+ });
62481
+ i += width;
62482
+ l += lowerWidth;
62483
+ }
62484
+ walked.set(chunk, changes);
62485
+ }
62486
+ let last = -1;
62487
+ for (let lo = 0, hi = changes.length - 1; lo <= hi;) {
62488
+ const mid = lo + hi >> 1;
62489
+ if (changes[mid].lowered <= index) {
62490
+ last = mid;
62491
+ lo = mid + 1;
62492
+ } else hi = mid - 1;
62493
+ }
62494
+ if (last < 0) return sourceStart + (index - loweredStart);
62495
+ const change = changes[last];
62496
+ const into = index - change.lowered;
62497
+ if (into === 0) return change.source;
62498
+ if (into < change.lowerWidth) return edge === "start" ? change.source : change.source + change.width;
62499
+ return Math.min(body.length, change.source + change.width + (into - change.lowerWidth));
62500
+ };
62501
+ return {
62502
+ hits: found.map(({ word, at, length }) => ({
62503
+ word,
62504
+ start: source(at, "start"),
62505
+ end: source(at + length, "end")
62506
+ })),
62507
+ text
62508
+ };
62509
+ }
62510
+ /**
62511
+ * The same matches as {@link lowercaseHits} without lowercasing the body, when that is provably
62512
+ * equivalent: every word is ASCII and the body has neither `İ` (lowercases to `i̇`, does not case-fold
62513
+ * to `i`) nor `ſ` (case-folds to `s`, does not lowercase to it). For ASCII words those are the only
62514
+ * characters where Unicode case folding and lowercasing disagree. `undefined` when not equivalent.
62515
+ */
62516
+ function foldedAsciiHits(body, words) {
62517
+ if (words.some((word) => /[^\x00-\x7f]/.test(word)) || /[\u0130\u017f]/.test(body)) return void 0;
62518
+ const hits = [];
62519
+ words.forEach((word, w) => {
62520
+ const pattern = new RegExp(word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "giu");
62521
+ for (let n = 0; n < OCCURRENCES_PER_WORD; n++) {
62522
+ const match = pattern.exec(body);
62523
+ if (!match) break;
62524
+ hits.push({
62525
+ word: w,
62526
+ start: match.index,
62527
+ end: match.index + match[0].length
62528
+ });
62529
+ }
62530
+ });
62531
+ return hits;
62532
+ }
62533
+ const isLowSurrogate = (code) => code >= 56320 && code <= 57343;
62534
+ const isHighSurrogate = (code) => code >= 55296 && code <= 56319;
62535
+ const isSpace = (char) => char !== void 0 && /\s/.test(char);
62536
+ /** How many lines of a search hit's body have a matched word. */
62537
+ function matchingLines(body, words, lowered) {
62538
+ const pattern = lowered ? void 0 : new RegExp(words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), "iu");
62539
+ let count = 0;
62540
+ (lowered ?? body).split("\n").forEach((line, i) => {
62541
+ if (!(pattern ? pattern.test(line) : words.some((word) => line.includes(word)))) return;
62542
+ count++;
62543
+ });
62544
+ return count;
62545
+ }
62546
+ /**
62547
+ * The nearest markdown heading above body offset `at`, as `12│## Heading` with its `knowledge_read`
62548
+ * line number, unless the heading starts inside the excerpt that begins at `windowStart`.
62549
+ */
62550
+ function headingAbove(body, at, windowStart, width) {
62551
+ let nearest;
62552
+ for (const section of knowledgeBodySections(body)) {
62553
+ if (section.start > at) break;
62554
+ nearest = section;
62555
+ }
62556
+ if (!nearest || nearest.start >= windowStart) return void 0;
62557
+ const lines = new KnowledgeBodyLines(body);
62558
+ const line = lines.lineAt(nearest.start);
62559
+ const text = body.slice(nearest.start, lines.lineEnd(line));
62560
+ return `${String(line).padStart(width)}\u2502${text.length > HEADING_CHARS ? `${Array.from(text).slice(0, 119).join("")}\u2026` : text}`;
62561
+ }
62562
+ /**
62563
+ * Where `body` matches the query words, or `undefined` when it contains none of them. Uses the same
62564
+ * words and the same rule as keyword search (case-insensitive substrings: a body matches exactly
62565
+ * when `body.toLowerCase()` contains the word). Each word's first {@link OCCURRENCES_PER_WORD}
62566
+ * occurrences anchor candidate windows of {@link KNOWLEDGE_SNIPPET_TOKENS} tokens; the window
62567
+ * holding the most distinct words wins, earliest on ties. Lines are counted over the whole body.
62568
+ * Cost: a scan per word and one lowercase copy of the body, except for ASCII words in a body with
62569
+ * no `İ` or `ſ`, which are matched without lowercasing; offsets are mapped only for actual matches.
62570
+ */
62571
+ function knowledgeBodyHit(body, query) {
62572
+ if (!body) return void 0;
62573
+ const words = knowledgeSearchWords(knowledgeSearchQuery(query));
62574
+ if (!words.length) return void 0;
62575
+ const folded = foldedAsciiHits(body, words);
62576
+ const lowercase = folded ? void 0 : lowercaseHits(body, words);
62577
+ const hits = folded ?? lowercase.hits;
62578
+ if (!hits.length) return void 0;
62579
+ const windowEnd = (start) => {
62580
+ const rest = body.slice(start, start + WINDOW_SCAN_CHARS);
62581
+ return start + (estimateTokenCount(rest) <= 60 ? rest.length : sliceByTokens(rest, 0, 60).length);
62582
+ };
62583
+ let best;
62584
+ for (const hit of hits) {
62585
+ const before = body.slice(Math.max(0, hit.start - 180), hit.start);
62586
+ const start = hit.start - sliceByTokens(before, -15).length;
62587
+ const end = Math.max(windowEnd(start), hit.end);
62588
+ const seen = /* @__PURE__ */ new Set();
62589
+ for (const other of hits) if (other.start >= start && other.end <= end) seen.add(other.word);
62590
+ const score = seen.size;
62591
+ if (!best || score > best.score || score === best.score && start < best.start) best = {
62592
+ start,
62593
+ end,
62594
+ anchor: hit.start,
62595
+ score
62596
+ };
62597
+ }
62598
+ let { start, end } = best;
62599
+ const { anchor } = best;
62600
+ if (start > 0) {
62601
+ for (let i = start; i < Math.min(anchor, start + SNAP_CHARS); i++) if (isSpace(body[i])) {
62602
+ start = i + 1;
62603
+ break;
62604
+ }
62605
+ }
62606
+ if (end < body.length) {
62607
+ for (let i = end; i > Math.max(anchor, end - SNAP_CHARS); i--) if (isSpace(body[i - 1])) {
62608
+ end = i - 1;
62609
+ break;
62610
+ }
62611
+ }
62612
+ if (start < body.length && isLowSurrogate(body.charCodeAt(start))) start++;
62613
+ if (end > start && isHighSurrogate(body.charCodeAt(end - 1))) end--;
62614
+ const lines = new KnowledgeBodyLines(body);
62615
+ const rows = lines.numbered(start, end > start && body[end - 1] === "\n" ? end - 1 : end).split("\n");
62616
+ const width = rows[0].indexOf("\u2502");
62617
+ if (start > 0) rows[0] = `${rows[0].slice(0, width + 1)}\u2026${rows[0].slice(width + 1)}`;
62618
+ if (end < body.length) rows[rows.length - 1] += "\u2026";
62619
+ const heading = headingAbove(body, anchor, start, width);
62620
+ const matches = matchingLines(body, words, lowercase?.text);
62621
+ return {
62622
+ snippet: heading ? `${heading}\n${rows.join("\n")}` : rows.join("\n"),
62623
+ line: lines.lineAt(anchor),
62624
+ matchingLines: matches
62625
+ };
62626
+ }
61994
62627
  // src/knowledge/page-tools.ts
61995
62628
  function maxTokensOf(host) {
61996
62629
  return host.maxTokens ?? 1e3;
@@ -62017,6 +62650,8 @@ function pageEmbedFailed(storage, page) {
62017
62650
  const RRF_K = 60;
62018
62651
  const DEFAULT_LIMIT = 10;
62019
62652
  const MAX_LIMIT = 50;
62653
+ /** The most words knowledge_read's `match` accepts; a search hint never emits a longer array. */
62654
+ const READ_MATCH_MAX_WORDS = 10;
62020
62655
  const MENTION = /\[\[([^\]]+)\]\]/g;
62021
62656
  /** Misses a note's mention linking may spend beyond its stored mentions (renamed or ambiguous refs). */
62022
62657
  const MENTION_LOOKUP_SLACK = 2;
@@ -62059,6 +62694,17 @@ function pageSummary(page, { refs, scopes }) {
62059
62694
  ...page.description ? { description: page.description } : {}
62060
62695
  };
62061
62696
  }
62697
+ /**
62698
+ * A page search hit: its summary, plus, when the body contains a matched word, a short excerpt around
62699
+ * it with every line numbered, the line it is centred on, and how many lines have a match.
62700
+ */
62701
+ function searchPageSummary(page, refs, words) {
62702
+ const hit = knowledgeBodyHit(page.body, words);
62703
+ return {
62704
+ ...pageSummary(page, refs),
62705
+ ...hit ?? {}
62706
+ };
62707
+ }
62062
62708
  function noteSummary(note, mentions) {
62063
62709
  return {
62064
62710
  id: note.id,
@@ -62156,7 +62802,7 @@ async function requireAudienceAuthority(run, audience) {
62156
62802
  function searchTool(host) {
62157
62803
  return createTool({
62158
62804
  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.",
62805
+ 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
62806
  inputSchema: {
62161
62807
  type: "object",
62162
62808
  properties: {
@@ -62182,7 +62828,7 @@ function searchTool(host) {
62182
62828
  const run = await start(host, context);
62183
62829
  const scopeIds = scope ? (await readableScopes(run, scope)).map((page) => page.id) : void 0;
62184
62830
  const max = limitOf(limit);
62185
- const words = query.replace(/["`\u201C\u201D]/g, " ").trim();
62831
+ const words = knowledgeSearchQuery(query);
62186
62832
  const lexical = words ? await run.storage.searchPages({
62187
62833
  query: words,
62188
62834
  read: run.read,
@@ -62235,16 +62881,22 @@ function searchTool(host) {
62235
62881
  }
62236
62882
  const addresses = await pageRefs(run, hits.map((hit) => hit.page));
62237
62883
  const mentionCache = /* @__PURE__ */ new Map();
62884
+ const results = await Promise.all(hits.map(async (hit) => hit.type === "page" ? {
62885
+ type: "page",
62886
+ page: searchPageSummary(hit.page, addresses, words)
62887
+ } : {
62888
+ type: "note",
62889
+ page: pageSummary(hit.page, addresses),
62890
+ note: noteSummary(hit.note, await noteMentions(run, hit.note, mentionCache))
62891
+ }));
62892
+ const matched = results.some((result) => result.type === "page" && "line" in result.page);
62893
+ const readWords = knowledgeSearchWords(words);
62894
+ 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)`;
62895
+ 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} }.`] : [];
62896
+ 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
62897
  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.`] } : {}
62898
+ results,
62899
+ ...more.length ? { more } : {}
62248
62900
  };
62249
62901
  }
62250
62902
  });
@@ -62429,7 +63081,7 @@ function readTool(host, canEdit) {
62429
63081
  minLength: 1
62430
63082
  },
62431
63083
  minItems: 1,
62432
- maxItems: 10
63084
+ maxItems: READ_MATCH_MAX_WORDS
62433
63085
  }],
62434
63086
  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
63087
  },
@@ -63306,6 +63958,7 @@ function decodeActivityCursor(value) {
63306
63958
  try {
63307
63959
  const cursor = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
63308
63960
  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;
63961
+ if (cursor?.v === 2 && (cursor.after === null || typeof cursor.after === "string" && cursor.after.length > 0) && typeof cursor.bind === "string") return cursor;
63309
63962
  } catch {}
63310
63963
  throw new Error("knowledge_activity: that cursor did not come from knowledge_activity.");
63311
63964
  }
@@ -63313,7 +63966,7 @@ function activityTool(host) {
63313
63966
  const maxTokens = maxTokensOf(host);
63314
63967
  return createTool({
63315
63968
  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).`,
63969
+ 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
63970
  inputSchema: {
63318
63971
  type: "object",
63319
63972
  properties: {
@@ -63332,6 +63985,11 @@ function activityTool(host) {
63332
63985
  minLength: 1,
63333
63986
  description: `Only changes to this page or scope. ${pageRefDescription}`
63334
63987
  },
63988
+ order: {
63989
+ type: "string",
63990
+ enum: ["newest", "oldest"],
63991
+ 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."
63992
+ },
63335
63993
  limit: {
63336
63994
  type: "integer",
63337
63995
  minimum: 1,
@@ -63341,20 +63999,24 @@ function activityTool(host) {
63341
63999
  cursor: {
63342
64000
  type: "string",
63343
64001
  minLength: 1,
63344
- description: "The previous result's cursor, for the changes after it (pass the same since, until and from)."
64002
+ description: "The previous result's cursor, for the changes after it (pass the same since, until, from and order)."
63345
64003
  }
63346
64004
  },
63347
64005
  additionalProperties: false
63348
64006
  },
63349
64007
  execute: async (input, context) => {
63350
64008
  const args = input;
64009
+ const oldest = args.order === "oldest";
63351
64010
  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
64011
  const since = args.since === void 0 ? void 0 : activityDate("since", args.since);
63353
64012
  const until = args.until === void 0 ? void 0 : activityDate("until", args.until);
63354
64013
  if (since && until && since.getTime() >= until.getTime()) throw new Error("knowledge_activity: since must be earlier than until.");
63355
64014
  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");
64015
+ const capabilities = (await host.getStorage()).getCapabilities();
64016
+ if (!capabilities.supportsActivityDateRange) throw new KnowledgeUnsupportedCapabilityError("listPageActivity date range");
64017
+ if (oldest && !capabilities.supportsActivityAscending) throw new KnowledgeUnsupportedCapabilityError("listPageActivity oldest first");
63357
64018
  const cursor = args.cursor === void 0 ? void 0 : decodeActivityCursor(args.cursor);
64019
+ 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
64020
  const run = await start(host, context);
63359
64021
  const origin = args.from ? await run.pageOrCloseMatches(args.from) : void 0;
63360
64022
  const filter = origin ? origin.isScope ? { scopeId: origin.id } : { pageId: origin.id } : {};
@@ -63362,15 +64024,24 @@ function activityTool(host) {
63362
64024
  since?.toISOString(),
63363
64025
  until?.toISOString(),
63364
64026
  "scopeId" in filter ? filter.scopeId : void 0,
63365
- "pageId" in filter ? filter.pageId : void 0
64027
+ "pageId" in filter ? filter.pageId : void 0,
64028
+ ...oldest ? ["oldest"] : []
63366
64029
  ]);
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.");
64030
+ 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
64031
  const entries = [];
63369
64032
  let used = 0;
63370
- let position = cursor ? {
64033
+ let position = !cursor ? void 0 : cursor.v === 2 ? cursor.after ?? void 0 : {
63371
64034
  createdAt: new Date(cursor.before[0]),
63372
64035
  id: cursor.before[1]
63373
- } : void 0;
64036
+ };
64037
+ const passed = (event) => {
64038
+ if (!oldest) return {
64039
+ createdAt: event.createdAt,
64040
+ id: event.id
64041
+ };
64042
+ if (!event.position) throw new Error("knowledge_activity: the store returned an oldest-first change without a position.");
64043
+ return event.position;
64044
+ };
63374
64045
  let more = false;
63375
64046
  let stopped = false;
63376
64047
  let batches = 0;
@@ -63382,7 +64053,12 @@ function activityTool(host) {
63382
64053
  ...filter,
63383
64054
  ...since ? { since } : {},
63384
64055
  ...until ? { until } : {},
63385
- ...position ? { before: position } : {},
64056
+ ...typeof position === "string" ? {
64057
+ order: "asc",
64058
+ after: position
64059
+ } : {},
64060
+ ...position && typeof position !== "string" ? { before: position } : {},
64061
+ ...oldest && !position ? { order: "asc" } : {},
63386
64062
  limit: limit - entries.length
63387
64063
  });
63388
64064
  more = batch.nextCursor !== void 0;
@@ -63410,10 +64086,7 @@ function activityTool(host) {
63410
64086
  const page = pages.get(event.pageId);
63411
64087
  const note = event.noteId ? notes.get(event.noteId) : void 0;
63412
64088
  if (!page || event.noteId && !note) {
63413
- position = {
63414
- createdAt: event.createdAt,
63415
- id: event.id
63416
- };
64089
+ position = passed(event);
63417
64090
  continue;
63418
64091
  }
63419
64092
  const entry = {
@@ -63455,10 +64128,7 @@ function activityTool(host) {
63455
64128
  }
63456
64129
  entries.push(entry);
63457
64130
  used += size;
63458
- position = {
63459
- createdAt: event.createdAt,
63460
- id: event.id
63461
- };
64131
+ position = passed(event);
63462
64132
  if (entries.length >= limit) break;
63463
64133
  }
63464
64134
  if (!more) break;
@@ -63472,7 +64142,14 @@ function activityTool(host) {
63472
64142
  name: origin.name
63473
64143
  } } : {},
63474
64144
  changes: entries,
63475
- ...hasMore && position ? {
64145
+ ...oldest ? {
64146
+ ...hasMore ? { more: true } : {},
64147
+ cursor: encodeActivityCursor({
64148
+ v: 2,
64149
+ after: typeof position === "string" ? position : null,
64150
+ bind
64151
+ })
64152
+ } : hasMore && position && typeof position !== "string" ? {
63476
64153
  more: true,
63477
64154
  cursor: encodeActivityCursor({
63478
64155
  v: 1,
@@ -70719,6 +71396,8 @@ const DurableStepIds = {
70719
71396
  /** isTaskComplete evaluation step */
70720
71397
  IS_TASK_COMPLETE: "durable-is-task-complete"
70721
71398
  };
71399
+ /** The loop's last step, which ends the run's spans when it succeeds. */
71400
+ const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
70722
71401
  const RECOVER_ALREADY_IN_PROGRESS_ERROR_ID = "DURABLE_AGENT_RECOVER_ALREADY_IN_PROGRESS";
70723
71402
  const RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID = "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND";
70724
71403
  const RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID = "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE";
@@ -70841,6 +71520,165 @@ async function runResumeDurableStreamUntilIdle(agent, runId, resumeData, streamO
70841
71520
  }
70842
71521
  });
70843
71522
  }
71523
+ // src/agent/durable/segment-spans.ts
71524
+ /**
71525
+ * Which AGENT_RUN + MODEL_GENERATION pair a durable execution reports under.
71526
+ *
71527
+ * A segment is one execution of the durable loop: the run's start, or a resume or a recovery, up
71528
+ * to its suspension or its end. Each segment has its own span pair and ends its own spans once.
71529
+ * The run's first pair travels in the workflow input. A resume or recovery opens the next pair and
71530
+ * carries it on the request context, which every engine hands to every step and persists with the
71531
+ * run, so the worker that finishes a segment ends that segment's spans wherever it runs.
71532
+ */
71533
+ /** The wire form of the pair a resume or recovery opened. */
71534
+ function openedSegment(agentSpan, modelSpan) {
71535
+ return {
71536
+ agentSpanData: agentSpan.snapshot?.() ?? agentSpan.exportSpan(),
71537
+ modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),
71538
+ stepParentId: resolveExportedSpanId(modelSpan ?? agentSpan)
71539
+ };
71540
+ }
71541
+ function hasRawAccess(target) {
71542
+ return typeof target.setRaw === "function";
71543
+ }
71544
+ function readCarrier(requestContext, runId) {
71545
+ const all = requestContext?.getRaw?.(MASTRA_DURABLE_SEGMENTS_KEY);
71546
+ if (!all || typeof all !== "object") return void 0;
71547
+ const segment = all[runId];
71548
+ if (segment === null) return null;
71549
+ return typeof segment?.agentSpanData?.id === "string" ? segment : void 0;
71550
+ }
71551
+ /**
71552
+ * Record the pair a resume or recovery opened for `runId`, or `null` when it opened none, on the
71553
+ * request context it hands the engine. Keyed by runId so a delegated durable sub-agent sharing the
71554
+ * caller's context cannot overwrite the parent's segment.
71555
+ */
71556
+ function carrySegmentSpans(target, runId, segment) {
71557
+ const current = hasRawAccess(target) ? target.getRaw(MASTRA_DURABLE_SEGMENTS_KEY) : target[MASTRA_DURABLE_SEGMENTS_KEY];
71558
+ const next = {
71559
+ ...current && typeof current === "object" ? current : {},
71560
+ [runId]: segment
71561
+ };
71562
+ if (hasRawAccess(target)) target.setRaw(MASTRA_DURABLE_SEGMENTS_KEY, next);
71563
+ else target[MASTRA_DURABLE_SEGMENTS_KEY] = next;
71564
+ }
71565
+ /**
71566
+ * The pair the current execution reports under: the one a resume or recovery carried for `runId`,
71567
+ * else the run's first pair from `state` (the workflow input or the loop state). A carried `null`
71568
+ * means the execution opened no spans, so its steps end none. `carried` tells the two apart.
71569
+ * `live` is this process's registry entry, the fallback when the context lost the carried pair.
71570
+ */
71571
+ function segmentSpanData(requestContext, runId, state, live) {
71572
+ const carried = readCarrier(requestContext, runId);
71573
+ if (carried === null) return { carried: true };
71574
+ if (carried) return {
71575
+ ...carried,
71576
+ carried: true
71577
+ };
71578
+ if (live?.resumeAgentSpan) return {
71579
+ ...openedSegment(live.resumeAgentSpan, live.resumeModelSpan),
71580
+ carried: true
71581
+ };
71582
+ return {
71583
+ agentSpanData: state.agentSpanData,
71584
+ modelSpanData: state.modelSpanData,
71585
+ carried: false
71586
+ };
71587
+ }
71588
+ /**
71589
+ * The generations whose MODEL_STEP the execution that persisted `requestContext` left open: its own
71590
+ * pair's, plus those it was itself finishing after an earlier crash. Every other step was ended by
71591
+ * the suspension before a resume. Undefined when that execution carried no pair.
71592
+ */
71593
+ function openStepsOfCrashedSegment(requestContext, runId) {
71594
+ const crashed = (requestContext?.[MASTRA_DURABLE_SEGMENTS_KEY])?.[runId];
71595
+ if (!crashed?.stepParentId || crashed.adoptsOpenSteps && !crashed.openStepsOf) return void 0;
71596
+ return [crashed.stepParentId, ...crashed.openStepsOf ?? []];
71597
+ }
71598
+ /** The live span behind `data` when this process holds it, so it is ended in place; otherwise undefined. */
71599
+ function liveSegmentSpan(data, ...candidates) {
71600
+ return data ? candidates.find((span) => span?.id === data.id) : void 0;
71601
+ }
71602
+ /**
71603
+ * Whether `segment` may end the MODEL_STEP `stepSpanData`. The run's first execution opened every
71604
+ * step it sees. A resumed one ends only the steps opened under its own pair: the step that
71605
+ * suspended was ended by that suspension. A recovered one also finishes the step its crashed
71606
+ * execution left open.
71607
+ */
71608
+ function segmentOwnsStep(segment, stepSpanData) {
71609
+ if (!segment.carried) return true;
71610
+ const parent = stepSpanData?.parentSpanId ?? void 0;
71611
+ if (segment.openStepsOf) return parent !== void 0 && [segment.stepParentId, ...segment.openStepsOf].includes(parent);
71612
+ if (segment.adoptsOpenSteps) return segment.endedStepsOf === void 0 || parent !== segment.endedStepsOf;
71613
+ return parent === segment.stepParentId;
71614
+ }
71615
+ /** Longer than any pause between the calls of one step; a key is only written when they run side by side. */
71616
+ const SEGMENT_END_TTL_MS = 864e5;
71617
+ /**
71618
+ * Whether `outcome` ends the spans of the run's first segment. Behind a broker, a tool call that suspends and one
71619
+ * beside it that fails the run are in different processes, and both end the same spans, so the first one to claim
71620
+ * them does. Undefined when no claim can be made, and in one process only the suspension asks.
71621
+ */
71622
+ async function claimSegmentEnd({ mastra, requestContext, runId, iterationCount, outcome }) {
71623
+ try {
71624
+ if (!mastra || !reachesOtherProcesses(mastra.pubsub)) return true;
71625
+ const claim = getExecutionClaim(requestContext, runId);
71626
+ const leases = resolveLeaseProvider(mastra.pubsub);
71627
+ if (claim?.generation === void 0 || leases === NoopLeaseProvider) return void 0;
71628
+ const key = `mastra:durable-segment-end:v1:${JSON.stringify([
71629
+ runId,
71630
+ claim.executionId,
71631
+ iterationCount
71632
+ ])}`;
71633
+ const { acquired, owner } = await leases.acquireLease(key, outcome, SEGMENT_END_TTL_MS);
71634
+ return acquired || (owner ? false : void 0);
71635
+ } catch {
71636
+ return;
71637
+ }
71638
+ }
71639
+ /** A MODEL_STEP the run's deadline stopped is interrupted, as on the regular agent; the run itself hit a limit. */
71640
+ function stepFailure(failure) {
71641
+ return isMastraTimeoutError(failure.error) ? {
71642
+ ...failure,
71643
+ outcome: "interrupted"
71644
+ } : failure;
71645
+ }
71646
+ /**
71647
+ * Whether a tool call that suspended beside the failed one already ended the spans of the segment. Only the failed
71648
+ * iteration's steps show it, so the settling engine takes it to the run's own failure as a carried `null` segment.
71649
+ */
71650
+ function segmentEndedBySuspension(segment, steps) {
71651
+ const { output, suspendPayload } = steps[DurableStepIds.TOOL_CALL] ?? {};
71652
+ return [suspendPayload?.__workflow_meta?.foreachOutput, output].flat().some((call) => call?.status === "suspended") && segmentOwnsStep(segment, steps[DurableStepIds.LLM_EXECUTION]?.output?.stepSpanData);
71653
+ }
71654
+ /**
71655
+ * End what a failed execution left open, from the facts the run carries, where the process that settles the
71656
+ * failure may hold none of the run's live spans. An iteration's failure ends its MODEL_STEP; the run's failure
71657
+ * ends the MODEL_GENERATION and AGENT_RUN its segment reports under. Never throws.
71658
+ */
71659
+ function endFailedSegmentSpans({ mastra, requestContext, runId, state, steps, error, live, firstPairOnly }) {
71660
+ try {
71661
+ const observability = mastra?.observability?.getSelectedInstance({ requestContext });
71662
+ if (!observability || !("input" in steps) || steps["map-final-output"]?.status === "success") return;
71663
+ const segment = segmentSpanData(requestContext, runId, state, live);
71664
+ const failure = {
71665
+ error,
71666
+ ...executionFailureTermination(error),
71667
+ endSpan: true
71668
+ };
71669
+ if (state.iterationCount !== void 0) {
71670
+ const stepSpanData = steps[DurableStepIds.LLM_EXECUTION]?.output?.stepSpanData;
71671
+ if (!stepSpanData || steps[DurableStepIds.LLM_MAPPING]?.status === "success") return;
71672
+ if (!segmentOwnsStep(segment, stepSpanData) || segmentEndedBySuspension(segment, steps)) return;
71673
+ (liveSegmentSpan(stepSpanData, live?.openStepSpan) ?? observability.rebuildSpan(stepSpanData)).error(stepFailure(failure));
71674
+ return;
71675
+ }
71676
+ if (firstPairOnly && segment.carried) return;
71677
+ const { modelSpanData, agentSpanData } = segment;
71678
+ if (modelSpanData) (liveSegmentSpan(modelSpanData, live?.resumeModelSpan, live?.modelSpan) ?? observability.rebuildSpan(modelSpanData)).error(failure);
71679
+ if (agentSpanData) (liveSegmentSpan(agentSpanData, live?.resumeAgentSpan, live?.agentSpan) ?? observability.rebuildSpan(agentSpanData)).error(failure);
71680
+ } catch {}
71681
+ }
70844
71682
  // ../_internal-core/dist/durable/index.js
70845
71683
  function toolModelOutput(result) {
70846
71684
  return typeof result === "string" ? {
@@ -71800,87 +72638,6 @@ function createDurableAgentStream(options) {
71800
72638
  ready
71801
72639
  };
71802
72640
  }
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
72641
  // src/agent/durable/utils/run-message-list.ts
71885
72642
  /** The id generator does not survive the serialize/deserialize round-trip a durable run makes on every step. */
71886
72643
  function createRunMessageList({ mastra, threadId, resourceId }) {
@@ -72371,7 +73128,7 @@ async function resolveRuntimeDependencies(options) {
72371
73128
  else if (mastra) try {
72372
73129
  const agent = await resolveRunAgent(mastra, agentId, runId, input.agentVersionId);
72373
73130
  rebuiltAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
72374
- const resolveRequestContext = restoreRequestContext$1(input.requestContextEntries, options.requestContext);
73131
+ const resolveRequestContext = restoreRequestContext(input.requestContextEntries, options.requestContext);
72375
73132
  backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
72376
73133
  tools = await agent.getToolsForExecution({
72377
73134
  runId,
@@ -72492,7 +73249,7 @@ async function rebuildRunToolsFromMastra(options) {
72492
73249
  const agent = await resolveRunAgent(mastra, agentId, runId, options.agentVersionId);
72493
73250
  agentResolved = true;
72494
73251
  const processorAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
72495
- const resolveRequestContext = restoreRequestContext$1(requestContextEntries, requestContext);
73252
+ const resolveRequestContext = restoreRequestContext(requestContextEntries, requestContext);
72496
73253
  const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
72497
73254
  const tools = await agent.getToolsForExecution({
72498
73255
  runId,
@@ -72532,12 +73289,17 @@ async function rebuildRunToolsFromMastra(options) {
72532
73289
  agent: processorAgent,
72533
73290
  ...backgroundTasks,
72534
73291
  ...rebuiltProcessors,
72535
- ...options.rehydrateProcessors ? { requestContext: resolveRequestContext } : {}
73292
+ ...options.rehydrateProcessors ? {
73293
+ requestContext: resolveRequestContext,
73294
+ requestContextRebuilt: true
73295
+ } : {}
72536
73296
  };
72537
73297
  existing = getRunRegistryEntry(runId, mastra);
72538
73298
  if (existing) {
72539
- const needsProcessorPipeline = !existing.outputProcessors || !existing.processorStates;
72540
- if (options.rehydrateProcessors && (existing.isPlaceholder && needsProcessorPipeline || !existing.requestContext)) existing.requestContext = resolveRequestContext;
73299
+ if (options.rehydrateProcessors && !existing.requestContext) {
73300
+ existing.requestContext = resolveRequestContext;
73301
+ existing.requestContextRebuilt = true;
73302
+ }
72541
73303
  const registryModel = existing.model;
72542
73304
  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
73305
  existing.workspace ??= workspace;
@@ -72935,9 +73697,9 @@ function runTranscriptRefs(params) {
72935
73697
  }
72936
73698
  /** The run's memory: the live instance in this process, else re-resolved from the agent. */
72937
73699
  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) });
73700
+ const entry = run.runId ? getRunRegistryEntry(run.runId, params.mastra) : void 0;
73701
+ if (entry?.memory || !params.mastra || !run.agentId) return entry?.memory;
73702
+ return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: restoreRequestContext(run.requestContextEntries, params.requestContext, getLiveRunRequestContext(entry)) });
72941
73703
  }
72942
73704
  /** The most recent transcript in a snapshot: workflow state, else the last step output carrying one. */
72943
73705
  function latestMessageListState(snapshot) {
@@ -72956,7 +73718,8 @@ function latestMessageListState(snapshot) {
72956
73718
  return latest?.value;
72957
73719
  }
72958
73720
  // src/agent/durable/workflows/finalize-run.ts
72959
- function restoreRequestContext(entries, fallback) {
73721
+ function mergeRequestContextForFinalization(entries, fallback, liveRunContext) {
73722
+ if (liveRunContext) return liveRunContext;
72960
73723
  if (!entries) return fallback ?? new RequestContext();
72961
73724
  const restored = new RequestContext(fallback?.entries());
72962
73725
  for (const [key, value] of Object.entries(withoutLiveRequestKeys(entries))) restored.set(key, value);
@@ -73012,7 +73775,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73012
73775
  error
73013
73776
  });
73014
73777
  }
73015
- const effectiveRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext);
73778
+ const effectiveRequestContext = mergeRequestContextForFinalization(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry));
73016
73779
  if (!effectiveRequestContext.has("MastraMemory") && durableState?.threadId) effectiveRequestContext.set("MastraMemory", {
73017
73780
  thread: { id: durableState.threadId },
73018
73781
  resourceId: durableState.resourceId,
@@ -73029,16 +73792,18 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73029
73792
  const liveStructuredOutput = registryEntry?.structuredOutput;
73030
73793
  const structuredOutputSchema = liveStructuredOutput?.schema ?? (structuredOutput?.schema ? toLiveStructuredOutputSchema(structuredOutput.schema, structuredOutput.nullToUndefined) : void 0);
73031
73794
  let structuredOutputChunks;
73795
+ let object;
73032
73796
  const structuringParts = structuredOutput?.hasStructuringModel ? responseStreamParts(messageList) : void 0;
73033
73797
  if (structuredOutputSchema && (structuredOutputText.trim() || structuringParts?.length)) {
73034
73798
  const finishReason = outputResult?.finishReason;
73035
73799
  const truncated = finishReason === "length" || finishReason === "content-filter";
73800
+ const failed = finishReason === "abort" || finishReason === "error";
73036
73801
  const errorStrategy = liveStructuredOutput ? liveStructuredOutput.errorStrategy : structuredOutput?.errorStrategy;
73037
73802
  const fallbackValue = liveStructuredOutput ? liveStructuredOutput.fallbackValue : structuredOutput?.fallbackValue;
73038
73803
  let value;
73039
73804
  if (structuredOutput?.hasStructuringModel) {
73040
73805
  const structuringModel = liveStructuredOutput?.model ?? structuredOutput.structuringModelConfig?.originalConfig;
73041
- if (structuringModel && !truncated && !(finishReason === "abort" || finishReason === "error")) {
73806
+ if (structuringModel && !truncated && !failed) {
73042
73807
  structuredOutputChunks = await runStructuringPass({
73043
73808
  options: {
73044
73809
  ...liveStructuredOutput ?? {},
@@ -73064,6 +73829,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73064
73829
  value = result?.success ? result.value : errorStrategy === "fallback" ? fallbackValue : void 0;
73065
73830
  }
73066
73831
  const lastAssistantMessage = messageList.get.response.db().findLast((message) => message.role === "assistant" && !message.content?.metadata?.completionResult);
73832
+ object = failed ? void 0 : value;
73067
73833
  if (value !== void 0 && lastAssistantMessage) lastAssistantMessage.content.metadata = {
73068
73834
  ...lastAssistantMessage.content.metadata,
73069
73835
  structuredOutput: value
@@ -73256,6 +74022,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73256
74022
  titleGeneration,
73257
74023
  titleForStream,
73258
74024
  structuredOutputChunks,
74025
+ object,
73259
74026
  outputResultChunks
73260
74027
  };
73261
74028
  }
@@ -73307,7 +74074,7 @@ function deadlineMessageListState(entry, fallback) {
73307
74074
  */
73308
74075
  async function runDurableDeadlineOutputPass({ runId, initData, messageListState, cutOffText, entry, mastra, tracingContext, logger }) {
73309
74076
  const durableState = initData.state;
73310
- const requestContext = restoreRequestContext(initData.requestContextEntries, entry.requestContext);
74077
+ const requestContext = mergeRequestContextForFinalization(initData.requestContextEntries, void 0, getLiveRunRequestContext(entry));
73311
74078
  if (!requestContext.has("MastraMemory") && durableState?.threadId) requestContext.set("MastraMemory", {
73312
74079
  thread: { id: durableState.threadId },
73313
74080
  resourceId: durableState.resourceId,
@@ -73750,11 +74517,17 @@ const accumulatedUsageSchema = z$1.object({
73750
74517
  reasoningTokens: z$1.number().optional()
73751
74518
  });
73752
74519
  /**
73753
- * Provider id and serving model of one response.
74520
+ * One response: the provider's id and model for it, the configured model that
74521
+ * answered, and the cost the provider reported for it.
73754
74522
  */
73755
74523
  const responseRecordSchema = z$1.object({
73756
74524
  id: z$1.string().optional(),
73757
- modelId: z$1.string().optional()
74525
+ modelId: z$1.string().optional(),
74526
+ servedBy: z$1.object({
74527
+ provider: z$1.string(),
74528
+ modelId: z$1.string()
74529
+ }).optional(),
74530
+ reportedCost: z$1.custom().optional()
73758
74531
  });
73759
74532
  /**
73760
74533
  * Schema for output from the durable agentic workflow
@@ -73814,6 +74587,8 @@ const baseIterationStateSchema = z$1.object({
73814
74587
  accumulatedSteps: z$1.array(z$1.any()).optional(),
73815
74588
  accumulatedUsage: accumulatedUsageSchema,
73816
74589
  usageAggregationVersion: z$1.literal(1).optional(),
74590
+ generationReportedUsage: accumulatedUsageSchema.optional(),
74591
+ generationReportedSteps: z$1.number().optional(),
73817
74592
  lastStepResult: z$1.any().optional(),
73818
74593
  deferredStepFinishChunk: z$1.any().optional(),
73819
74594
  backgroundTaskPending: z$1.boolean().optional(),
@@ -73836,6 +74611,7 @@ const baseIterationStateSchema = z$1.object({
73836
74611
  completionStartTime: z$1.coerce.date().optional(),
73837
74612
  timeToFirstTokenMs: z$1.number().optional(),
73838
74613
  lastResponse: responseRecordSchema.optional(),
74614
+ reportedCosts: z$1.array(z$1.custom().nullable()).optional(),
73839
74615
  tracingStopCause: z$1.enum(CONTINUATION_STOP_CAUSES).optional(),
73840
74616
  tracingTermination: z$1.custom().optional(),
73841
74617
  tracingDelegationFailure: z$1.custom().optional()
@@ -73888,7 +74664,7 @@ function buildStepRecord(executionOutput) {
73888
74664
  text: executionOutput.output.text,
73889
74665
  content: executionOutput.output.content,
73890
74666
  toolCalls: executionOutput.output.toolCalls,
73891
- toolResults: executionOutput.toolResults?.map(({ stepSpanData: _stepSpanData, tracingDelegationFailure: _tracingDelegationFailure, ...result }) => result),
74667
+ toolResults: executionOutput.toolResults?.map(({ stepSpanData: _stepSpanData, tracingDelegationFailure: _tracingDelegationFailure, response: _response, sideBySide: _sideBySide, ...result }) => result),
73892
74668
  usage: executionOutput.output.usage,
73893
74669
  finishReason: executionOutput.stepResult.reason,
73894
74670
  tripwire: executionOutput.stepResult.tripwire
@@ -73973,6 +74749,13 @@ function createBaseIterationStateUpdate(input) {
73973
74749
  accumulatedSteps: signalPreempted ? previousSteps : [...withReleasedToolResults(previousSteps, executionOutput.releasedToolResultIds), buildStepRecord(executionOutput)],
73974
74750
  accumulatedUsage: newUsage,
73975
74751
  usageAggregationVersion: signalPreempted ? currentState.usageAggregationVersion : 1,
74752
+ ...currentState.generationReportedUsage && executionOutput.suspensionReportedUsage && !isUsageIncomplete(newUsage) ? {
74753
+ generationReportedUsage: newUsage,
74754
+ generationReportedSteps: previousSteps.length + 1
74755
+ } : {
74756
+ generationReportedUsage: currentState.generationReportedUsage,
74757
+ generationReportedSteps: currentState.generationReportedSteps
74758
+ },
73976
74759
  lastStepResult,
73977
74760
  deferredStepFinishChunk: executionOutput.deferredStepFinishChunk,
73978
74761
  backgroundTaskPending: executionOutput.backgroundTaskPending,
@@ -73991,6 +74774,7 @@ function createBaseIterationStateUpdate(input) {
73991
74774
  timeToFirstTokenMs: executionOutput.timeToFirstTokenMs
73992
74775
  },
73993
74776
  lastResponse: signalPreempted ? currentState.lastResponse : executionOutput.response,
74777
+ reportedCosts: signalPreempted ? currentState.reportedCosts : [...previousSteps.map((_, index) => currentState.reportedCosts?.[index] ?? null), executionOutput.response?.reportedCost ?? null],
73994
74778
  tracingTermination: executionOutput.tracingTermination,
73995
74779
  tracingDelegationFailure: executionOutput.tracingDelegationFailure
73996
74780
  };
@@ -74068,6 +74852,14 @@ function resolveDurableToolCallConcurrency({ options, toolsMetadata, toolCalls }
74068
74852
  if (consideredTools.some((tool) => tool.hasSuspendSchema || tool.requireApproval)) return 1;
74069
74853
  return limit > 0 ? limit : DurableAgentDefaults.TOOL_CALL_CONCURRENCY;
74070
74854
  }
74855
+ /**
74856
+ * Whether the step's tool calls run at the same time. Then more than one can suspend in the same
74857
+ * execution, on workers that share no memory, so none of them can report the step's model usage
74858
+ * exactly once. The run's last execution reports it instead.
74859
+ */
74860
+ function toolCallsRunSideBySide(args) {
74861
+ return (args.toolCalls?.length ?? 0) > 1 && resolveDurableToolCallConcurrency(args) > 1;
74862
+ }
74071
74863
  // src/agent/durable/workflows/steps/background-task-check.ts
74072
74864
  const BG_CHECK_STEP_ID = `${DurableStepIds.AGENTIC_EXECUTION}-bg-task-check`;
74073
74865
  /**
@@ -75026,6 +75818,9 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
75026
75818
  }
75027
75819
  }
75028
75820
  spans.flushSpansLeftOpen(parts);
75821
+ if (!chunks.some((chunk) => chunk.type === "finish" || chunk.type === "step-finish")) {
75822
+ for (const part of parts) if (part.type === "text" || part.type === "reasoning") dropResponseItemIds(part);
75823
+ }
75029
75824
  const nonEmptyParts = parts.filter((p) => !(p.type === "text" && p.text === "" && p.providerMetadata == null));
75030
75825
  const finalParts = [];
75031
75826
  for (let i = 0; i < nonEmptyParts.length; i++) {
@@ -75046,6 +75841,16 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
75046
75841
  }
75047
75842
  }];
75048
75843
  }
75844
+ function dropResponseItemIds(part) {
75845
+ if (!part.providerMetadata) return;
75846
+ const providerMetadata = Object.fromEntries(Object.entries(part.providerMetadata).map(([provider, value]) => {
75847
+ if (!value || typeof value !== "object" || !("itemId" in value)) return [provider, value];
75848
+ const { itemId: _itemId, ...rest } = value;
75849
+ return [provider, rest];
75850
+ }).filter(([, value]) => !(value && typeof value === "object" && Object.keys(value).length === 0)));
75851
+ if (Object.keys(providerMetadata).length > 0) part.providerMetadata = providerMetadata;
75852
+ else delete part.providerMetadata;
75853
+ }
75049
75854
  // src/loop/workflows/agentic-execution/provider-tool-spans.ts
75050
75855
  function endPendingProviderToolSpan({ toolCallId, pending, parentSpan, result, logger }) {
75051
75856
  let span;
@@ -75116,6 +75921,20 @@ function resolveMaxProcessorRetries({ maxProcessorRetries, hasErrorProcessors, h
75116
75921
  }
75117
75922
  return 3;
75118
75923
  }
75924
+ // src/agent/durable/workflows/shared/reported-cost.ts
75925
+ /**
75926
+ * The part of a step's provider metadata that says what the call cost. The rest, such as search
75927
+ * grounding, can be large, and the loop state that carries this is saved with the run.
75928
+ */
75929
+ function reportedCost(metadata) {
75930
+ const cost = metadata?.gateway?.cost;
75931
+ const usage = metadata?.openrouter?.usage;
75932
+ if (cost === void 0 && usage === void 0) return void 0;
75933
+ return {
75934
+ ...cost === void 0 ? {} : { gateway: { cost } },
75935
+ ...usage === void 0 ? {} : { openrouter: { usage } }
75936
+ };
75937
+ }
75119
75938
  // src/agent/durable/workflows/steps/llm-execution.ts
75120
75939
  /**
75121
75940
  * Detect a run-level budget expiry (`modelSettings.timeout.totalMs`, #21724
@@ -75267,12 +76086,13 @@ function createDurableLLMExecutionStep(_options) {
75267
76086
  inputSchema: durableLLMInputSchema,
75268
76087
  outputSchema: durableLLMOutputSchema,
75269
76088
  execute: withStepLifetime(async (params, stepLifetime) => {
75270
- const { inputData, mastra, tracingContext, requestContext, abortSignal } = params;
76089
+ const { inputData, mastra, tracingContext, abortSignal } = params;
75271
76090
  const ownership = getExecutionOwnershipGuard(params);
75272
76091
  const pubsub = params[PUBSUB_SYMBOL];
75273
76092
  const typedInput = inputData;
75274
76093
  const { agentId, messageId, options: execOptions } = typedInput;
75275
76094
  const runId = typedInput.runId;
76095
+ const requestContext = getLiveRunRequestContext(getRunRegistryEntry(runId, mastra)) ?? params.requestContext;
75276
76096
  const logger = mastra?.getLogger?.();
75277
76097
  if (pubsub) await emitIterationStartEvent(pubsub, runId, inputData.stepIndex ?? 0);
75278
76098
  const { messageList, tools, model: resolvedModel, modelList: resolvedModelList, inputProcessors: resolvedInputProcessors, llmRequestInputProcessors: resolvedLlmRequestInputProcessors, outputProcessors: resolvedOutputProcessors } = await resolveRuntimeDependencies({
@@ -75303,7 +76123,7 @@ function createDurableLLMExecutionStep(_options) {
75303
76123
  }
75304
76124
  } : void 0;
75305
76125
  if (pubsub) try {
75306
- await ensureRemoteAbortListener(pubsub, runId, mastra, readRunDeadline(requestContext));
76126
+ await ensureRemoteAbortListener(pubsub, runId, mastra, readRunDeadline(params.requestContext));
75307
76127
  } catch (error) {
75308
76128
  ownership?.throwIfLost();
75309
76129
  logger?.warn?.("Failed to subscribe to cross-process abort requests", {
@@ -75311,6 +76131,8 @@ function createDurableLLMExecutionStep(_options) {
75311
76131
  error: error instanceof Error ? error.message : String(error)
75312
76132
  });
75313
76133
  }
76134
+ const runEntry = getRunRegistryEntry(runId, mastra);
76135
+ if (runEntry) runEntry.openStepSpan = void 0;
75314
76136
  let request = {};
75315
76137
  let terminateAttemptSpans;
75316
76138
  let tracingTermination;
@@ -76966,6 +77788,7 @@ function createDurableLLMExecutionStep(_options) {
76966
77788
  tripwire: stepTripwire
76967
77789
  });
76968
77790
  const stepSpanData = hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.exportCurrentStep() : void 0;
77791
+ if (registryEntry && stepSpanData) registryEntry.openStepSpan = observability?.rebuildSpan(stepSpanData);
76969
77792
  const stepFinishPayload = hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.getPendingStepFinishPayload() : void 0;
76970
77793
  const output = {
76971
77794
  ...await storeStepTranscript(),
@@ -76989,7 +77812,12 @@ function createDurableLLMExecutionStep(_options) {
76989
77812
  },
76990
77813
  response: deferredStepFinishChunk ? {
76991
77814
  id: deferredStepFinishChunk.payload?.metadata?.id,
76992
- modelId: resolveResponseModelId(deferredStepFinishChunk.payload?.metadata?.providerMetadata, deferredStepFinishChunk.payload?.metadata?.modelId)
77815
+ modelId: resolveResponseModelId(deferredStepFinishChunk.payload?.metadata?.providerMetadata, deferredStepFinishChunk.payload?.metadata?.modelId),
77816
+ ...cachedResponse ? {} : { servedBy: {
77817
+ provider: currentModel.provider,
77818
+ modelId: currentModel.modelId
77819
+ } },
77820
+ reportedCost: reportedCost(deferredStepFinishChunk.payload?.metadata?.providerMetadata)
76993
77821
  } : void 0,
76994
77822
  state: typedInput.state,
76995
77823
  modelSpanData: hasToolCalls && !processOutputStepTripwire ? modelSpan?.snapshot?.() ?? modelSpan?.exportSpan() : void 0,
@@ -77000,6 +77828,7 @@ function createDurableLLMExecutionStep(_options) {
77000
77828
  ...releasedToolResultIds.length ? { releasedToolResultIds } : {},
77001
77829
  tracingTermination
77002
77830
  };
77831
+ if (effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) getToolResultRunner().endStreamProcessorSpans(registryEntry.processorStates, { stepScopedOnly: true });
77003
77832
  if (!hasToolCalls || processOutputStepTripwire) {
77004
77833
  const pendingPayload = modelSpanTracker?.getPendingStepFinishPayload();
77005
77834
  if (pendingPayload) {
@@ -78055,7 +78884,9 @@ const durableToolCallInputSchema = z$1.object({
78055
78884
  stepSpanData: z$1.any().optional(),
78056
78885
  completionStartTime: z$1.coerce.date().optional(),
78057
78886
  timeToFirstTokenMs: z$1.number().optional(),
78058
- stepUsage: z$1.any().optional()
78887
+ stepUsage: z$1.any().optional(),
78888
+ sideBySide: z$1.boolean().optional(),
78889
+ response: responseRecordSchema.optional()
78059
78890
  });
78060
78891
  /**
78061
78892
  * Output schema for the durable tool call step.
@@ -78273,7 +79104,7 @@ function createDurableToolCallStep() {
78273
79104
  const initData = getInitData();
78274
79105
  const { runId, options: agentOptions, state } = initData;
78275
79106
  const logger = mastra?.getLogger?.();
78276
- const endSpansAsSuspended = (info) => {
79107
+ const endSpansAsSuspended = async (info) => {
78277
79108
  try {
78278
79109
  const obs = mastra?.observability?.getSelectedInstance({ requestContext });
78279
79110
  if (!obs) return;
@@ -78285,6 +79116,15 @@ function createDurableToolCallStep() {
78285
79116
  };
78286
79117
  const reg = getRunRegistryEntry(runId, mastra);
78287
79118
  const segment = segmentSpanData(requestContext, runId, initData, reg);
79119
+ if (typedInput.sideBySide && !segment.carried) {
79120
+ if (!(await claimSegmentEnd({
79121
+ mastra,
79122
+ requestContext,
79123
+ runId,
79124
+ iterationCount: initData.iterationCount,
79125
+ outcome: "suspend"
79126
+ }) ?? await assertOwned().then(() => true, (error) => !isExecutionFenceError(error)))) return;
79127
+ }
78288
79128
  const { agentSpanData, modelSpanData } = segment;
78289
79129
  const attributes = carriedSpanClocks(reg, initData.completionStartTime ? {
78290
79130
  completionStartTime: initData.completionStartTime,
@@ -78293,26 +79133,57 @@ function createDurableToolCallStep() {
78293
79133
  completionStartTime: typedInput.completionStartTime,
78294
79134
  timeToFirstTokenMs: typedInput.timeToFirstTokenMs
78295
79135
  }, 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({
79136
+ const ownsStep = !!typedInput.stepSpanData && segmentOwnsStep(segment, typedInput.stepSpanData);
79137
+ const reported = initData.generationReportedUsage;
79138
+ const total = calculateAccumulatedUsage(initData.accumulatedUsage, typedInput.stepUsage);
79139
+ const usage = reported && ownsStep && !typedInput.sideBySide && !isUsageIncomplete(total) ? subtractReportedUsage(total, reported) : void 0;
79140
+ if (ownsStep) {
79141
+ const stepSpanData = typedInput.stepSpanData;
79142
+ (liveSegmentSpan(stepSpanData, reg?.openStepSpan) ?? obs.rebuildSpan(stepSpanData))?.end({
79143
+ output,
79144
+ ...reported ? { attributes: { usage: extractUsageMetrics(typedInput.stepUsage) } } : {},
79145
+ outcome: "suspend",
79146
+ stopReason: info.reason === "approval" ? "approval_required" : null,
79147
+ stopReasonContext: info.reason === "approval" ? compactStopReasonContext("approval_required", {
79148
+ toolCallId: info.toolCallId,
79149
+ toolName: info.toolName
79150
+ }) : null
79151
+ });
79152
+ }
79153
+ const agentSpan = agentSpanData && obs.rebuildSpan(agentSpanData);
79154
+ if (modelSpanData) {
79155
+ const end = {
79156
+ output,
79157
+ attributes,
79158
+ outcome: "suspend",
79159
+ stopReason: info.reason === "approval" ? "approval_required" : null,
79160
+ stopReasonContext: info.reason === "approval" ? compactStopReasonContext("approval_required", {
79161
+ toolCallId: info.toolCallId,
79162
+ toolName: info.toolName
79163
+ }) : null
79164
+ };
79165
+ const modelSpan = obs.rebuildSpan(modelSpanData);
79166
+ if (modelSpan?.isInternal) modelSpan.parent ??= agentSpan;
79167
+ if (usage) {
79168
+ const servedBy = typedInput.response?.servedBy;
79169
+ const servedName = servedBy && `llm: '${servedBy.modelId}'`;
79170
+ if (servedName && modelSpan && modelSpan.name !== servedName) modelSpan.update({ name: servedName });
79171
+ const costs = initData.reportedCosts?.slice(initData.generationReportedSteps ?? 0) ?? [];
79172
+ modelSpan?.createTracker()?.endGeneration({
79173
+ ...end,
79174
+ attributes: {
79175
+ ...attributes,
79176
+ ...servedBy ? {
79177
+ model: servedBy.modelId,
79178
+ provider: servedBy.provider
79179
+ } : {}
79180
+ },
79181
+ usage,
79182
+ stepProviderMetadata: [...costs, typedInput.response?.reportedCost].map((cost) => cost ?? void 0)
79183
+ });
79184
+ } else modelSpan?.end(end);
79185
+ }
79186
+ agentSpan?.end({
78316
79187
  output,
78317
79188
  attributes,
78318
79189
  outcome: "suspend",
@@ -78503,7 +79374,7 @@ function createDurableToolCallStep() {
78503
79374
  }).add(invocation, "memory");
78504
79375
  }
78505
79376
  if (saveQueueManager && messagesToFlush && memory && state?.threadId && state.resourceId && !state.memoryConfig?.readOnly) {
78506
- const authorizationRequestContext = registryEntry?.requestContext ?? restoreRequestContext$1(initData.requestContextEntries, requestContext);
79377
+ const authorizationRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext);
78507
79378
  const authorizeMemory = (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
78508
79379
  mastra,
78509
79380
  user: authorizationRequestContext.get("user"),
@@ -78547,7 +79418,7 @@ function createDurableToolCallStep() {
78547
79418
  };
78548
79419
  const registryRequireToolApproval = registryEntry?.requireToolApproval;
78549
79420
  const effectiveRequireToolApproval = registryRequireToolApproval !== void 0 ? registryRequireToolApproval : agentOptions.requireToolApproval;
78550
- const approvalRequestContext = registryEntry?.requestContext ?? restoreRequestContext$1(initData.requestContextEntries, requestContext);
79421
+ const approvalRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext);
78551
79422
  const requiresApproval = await toolRequiresApproval(tool, effectiveRequireToolApproval, args, {
78552
79423
  toolName,
78553
79424
  requestContext: Object.fromEntries([...approvalRequestContext.entries()].filter(([key]) => !INTERNAL_APPROVAL_KEYS.has(key))),
@@ -78780,7 +79651,7 @@ function createDurableToolCallStep() {
78780
79651
  type: "approval",
78781
79652
  resumeSchema: approvalResumeSchema
78782
79653
  }));
78783
- endSpansAsSuspended({
79654
+ await endSpansAsSuspended({
78784
79655
  toolCallId,
78785
79656
  toolName,
78786
79657
  reason: "approval"
@@ -79002,7 +79873,7 @@ function createDurableToolCallStep() {
79002
79873
  type: "approval",
79003
79874
  resumeSchema: approvalResumeSchema
79004
79875
  }));
79005
- endSpansAsSuspended({
79876
+ await endSpansAsSuspended({
79006
79877
  toolCallId,
79007
79878
  toolName: approvalToolName,
79008
79879
  reason: "approval"
@@ -79057,7 +79928,7 @@ function createDurableToolCallStep() {
79057
79928
  await publishAfterPersist(() => emitChunkEvent(pubsub, runId, suspensionChunk));
79058
79929
  await publishAfterPersist(() => emitSuspendedEvent(pubsub, runId, suspendedEventData));
79059
79930
  }
79060
- endSpansAsSuspended({
79931
+ await endSpansAsSuspended({
79061
79932
  toolCallId,
79062
79933
  toolName,
79063
79934
  reason: "suspension"
@@ -79272,7 +80143,7 @@ function createDurableToolCallStep() {
79272
80143
  toolCallId: params.toolCallId,
79273
80144
  toolName: params.toolName,
79274
80145
  status: params.status === "failed" ? "failed" : "completed",
79275
- requestContext: registryEntry?.requestContext ?? restoreRequestContext$1(initData.requestContextEntries, requestContext)
80146
+ requestContext: restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext)
79276
80147
  });
79277
80148
  } catch (error) {
79278
80149
  resolveReconciliation({ error });
@@ -79813,7 +80684,8 @@ const durableLLMMappingOutputSchema = z$1.object({
79813
80684
  deferredStepFinishChunk: z$1.any().optional(),
79814
80685
  completionStartTime: z$1.coerce.date().optional(),
79815
80686
  timeToFirstTokenMs: z$1.number().optional(),
79816
- response: responseRecordSchema.optional()
80687
+ response: responseRecordSchema.optional(),
80688
+ suspensionReportedUsage: z$1.boolean().optional()
79817
80689
  });
79818
80690
  /**
79819
80691
  * Create a durable LLM mapping step.
@@ -79884,8 +80756,19 @@ function createDurableLLMMappingStep() {
79884
80756
  const isPendingClientCall = (toolResult) => toolResult.result === void 0 && !toolResult.error && !toolResult.aborted && !toolResult.resultBlocked && !toolResult.providerExecuted && !isDeniedApproval(toolResult);
79885
80757
  const registryTools = registryEntry?.tools;
79886
80758
  let stepSpan;
80759
+ let suspensionReportedUsage = false;
79887
80760
  if (llmOutput.stepSpanData) try {
79888
- if (segmentOwnsStep(segmentSpanData(requestContext, _runId, getInitData(), getRunRegistryEntry(_runId, mastra)), llmOutput.stepSpanData)) stepSpan = (mastra?.observability?.getSelectedInstance({ requestContext }))?.rebuildSpan(llmOutput.stepSpanData);
80761
+ const initData = getInitData();
80762
+ const reg = getRunRegistryEntry(_runId, mastra);
80763
+ if (segmentOwnsStep(segmentSpanData(requestContext, _runId, initData, reg), llmOutput.stepSpanData)) {
80764
+ const observability = mastra?.observability?.getSelectedInstance({ requestContext });
80765
+ const stepSpanData = llmOutput.stepSpanData;
80766
+ stepSpan = liveSegmentSpan(stepSpanData, reg?.openStepSpan) ?? observability?.rebuildSpan(stepSpanData);
80767
+ } else suspensionReportedUsage = !toolCallsRunSideBySide({
80768
+ options: initData.options,
80769
+ toolsMetadata: initData.toolsMetadata,
80770
+ toolCalls: llmOutput.toolCalls
80771
+ });
79889
80772
  } catch {}
79890
80773
  if (toolResults.length > 0) {
79891
80774
  const runStopped = toolResults.some((result) => result.deadlineTimeout || result.runAborted);
@@ -80020,6 +80903,7 @@ function createDurableLLMMappingStep() {
80020
80903
  delegationBailed,
80021
80904
  tracingDelegationFailure,
80022
80905
  tracingTermination: llmOutput.tracingTermination,
80906
+ ...suspensionReportedUsage ? { suspensionReportedUsage } : {},
80023
80907
  ...deadlineTimeout ? { deadlineTimeout } : {},
80024
80908
  ...runAborted ? { runAborted } : {},
80025
80909
  deferredStepFinishChunk,
@@ -80323,7 +81207,7 @@ function createDurableIsTaskCompleteStep(defaultMaxSteps = DurableAgentDefaults.
80323
81207
  const restored = await restoreCompletionPolicy({
80324
81208
  agent,
80325
81209
  persisted: initData.options.isTaskComplete,
80326
- requestContext: restoreRequestContext$1(initData.requestContextEntries, registryEntry?.requestContext),
81210
+ requestContext: restoreRequestContext(initData.requestContextEntries, registryEntry?.requestContext, getLiveRunRequestContext(registryEntry)),
80327
81211
  runId: state.runId,
80328
81212
  logger: mastra?.getLogger?.()
80329
81213
  });
@@ -80407,9 +81291,10 @@ function createDurableGoalStep() {
80407
81291
  const registryEntry = getRunRegistryEntry(state.runId, mastra);
80408
81292
  let goalConfig = registryEntry?.goal;
80409
81293
  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);
81294
+ const liveRunContext = getLiveRunRequestContext(registryEntry);
81295
+ const currentRequestContext = liveRunContext ?? params.requestContext;
81296
+ const requestContext = restoreRequestContext(initData.requestContextEntries, params.requestContext, liveRunContext);
81297
+ const customContext = restoreCustomContext(initData.requestContextEntries, currentRequestContext);
80413
81298
  if (!goalConfig) return state;
80414
81299
  const messageListState = await readMessageListState(params, state);
80415
81300
  let messageList;
@@ -80480,7 +81365,6 @@ function withParams(params, overrides) {
80480
81365
  };
80481
81366
  return Object.defineProperties({}, descriptors);
80482
81367
  }
80483
- const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
80484
81368
  /**
80485
81369
  * Historical default persistence policy for durable agent workflows.
80486
81370
  *
@@ -80832,14 +81716,22 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80832
81716
  completionStartTime: state.completionStartTime,
80833
81717
  timeToFirstTokenMs: state.timeToFirstTokenMs
80834
81718
  };
80835
- }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData }) => {
81719
+ }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData, getInitData }) => {
80836
81720
  const llmOutput = inputData;
81721
+ const state = getInitData();
81722
+ const sideBySide = toolCallsRunSideBySide({
81723
+ options: state?.options,
81724
+ toolsMetadata: state?.toolsMetadata,
81725
+ toolCalls: llmOutput.toolCalls
81726
+ });
80837
81727
  return (llmOutput.toolCalls ?? []).map((toolCall) => ({
80838
81728
  ...toolCall,
80839
81729
  stepSpanData: llmOutput.stepSpanData,
80840
81730
  completionStartTime: llmOutput.completionStartTime,
80841
81731
  timeToFirstTokenMs: llmOutput.timeToFirstTokenMs,
80842
- stepUsage: llmOutput.stepResult?.totalUsage
81732
+ stepUsage: llmOutput.stepResult?.totalUsage,
81733
+ response: llmOutput.response,
81734
+ ...sideBySide ? { sideBySide } : {}
80843
81735
  }));
80844
81736
  }, { id: "extract-tool-calls" }).foreach(toolCallStep, { concurrency: ({ inputData, getInitData }) => {
80845
81737
  const state = getInitData();
@@ -81125,6 +82017,11 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81125
82017
  totalTokens: 0
81126
82018
  },
81127
82019
  usageAggregationVersion: 1,
82020
+ generationReportedUsage: {
82021
+ inputTokens: 0,
82022
+ outputTokens: 0,
82023
+ totalTokens: 0
82024
+ },
81128
82025
  lastStepResult: void 0
81129
82026
  };
81130
82027
  }, { id: "init-iteration-state" }).dowhile(this.buildIterationWorkflow(), markFrameworkCondition(this.buildContinuationPredicate())).map(async (params) => {
@@ -81150,13 +82047,24 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81150
82047
  user: finalMessageList.get.input.aiV5.model(),
81151
82048
  nonUser: finalMessageList.get.response.aiV5.model()
81152
82049
  };
82050
+ const reg = getRunRegistryEntry(initData.runId, mastra);
82051
+ let observability;
82052
+ let segment;
82053
+ let agentSpan;
82054
+ try {
82055
+ observability = mastra?.observability?.getSelectedInstance({ requestContext });
82056
+ segment = segmentSpanData(requestContext, initData.runId, initData, reg);
82057
+ agentSpan = liveOrRebuiltAgentSpan(segment.agentSpanData, reg, observability);
82058
+ } catch (error) {
82059
+ logger?.warn?.(`[DurableAgent] Error resolving the run span: ${error}`);
82060
+ }
81153
82061
  const finishResult = await runDurableFinishSideEffects({
81154
82062
  runId: state.runId,
81155
82063
  initData,
81156
82064
  messageListState,
81157
82065
  mastra,
81158
82066
  requestContext,
81159
- tracingContext,
82067
+ tracingContext: agentSpan ? { currentSpan: agentSpan } : tracingContext,
81160
82068
  logger,
81161
82069
  messageId: state.messageId,
81162
82070
  outputResult: {
@@ -81230,7 +82138,6 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81230
82138
  },
81231
82139
  state: state.state
81232
82140
  };
81233
- const reg = getRunRegistryEntry(initData.runId, mastra);
81234
82141
  const stopCause = state.tracingStopCause ?? reg?.tracingStopCause;
81235
82142
  if (pubsub) await emitFinishEvent(pubsub, state.runId, {
81236
82143
  output: finalOutput.output,
@@ -81243,30 +82150,35 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81243
82150
  const finishReason = finalOutput.stepResult?.reason;
81244
82151
  const recordedTermination = state.tracingTermination ?? reg?.tracingTermination;
81245
82152
  if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) logger?.warn?.(`[DurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
82153
+ const runTripwire = tripwire ?? state.lastStepResult?.tripwire ?? initData.inputTripwire;
81246
82154
  const termination = ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
81247
82155
  stopCause,
81248
82156
  delegationFailure: state.tracingDelegationFailure ?? reg?.tracingDelegationFailure,
81249
82157
  finishReason,
81250
- tripwire: tripwire ?? state.lastStepResult?.tripwire,
82158
+ tripwire: runTripwire,
81251
82159
  maxSteps: initData.options?.maxSteps
81252
82160
  });
81253
82161
  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);
82162
+ const clocks = carriedSpanClocks(reg, state, segment?.carried);
81257
82163
  if (observability) {
82164
+ const modelSpanData = segment?.modelSpanData;
81258
82165
  if (modelSpanData) {
81259
82166
  const modelSpan = liveSegmentSpan(modelSpanData, reg?.resumeModelSpan, reg?.modelSpan) ?? observability.rebuildSpan(modelSpanData);
82167
+ if (modelSpan?.isInternal) modelSpan.parent ??= agentSpan;
81260
82168
  const toolCalls = steps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
81261
82169
  toolCallId: tc.toolCallId,
81262
82170
  toolName: tc.toolName,
81263
82171
  args: tc.args
81264
82172
  })));
81265
82173
  const usageIncomplete = isUsageIncomplete(state.accumulatedUsage);
82174
+ const servedBy = state.lastResponse?.servedBy;
82175
+ const servedName = servedBy && `llm: '${servedBy.modelId}'`;
82176
+ if (servedName && modelSpan && modelSpan.name !== servedName) modelSpan.update({ name: servedName });
81266
82177
  modelSpan?.createTracker()?.endGeneration({
81267
82178
  ...termination,
81268
82179
  output: {
81269
82180
  text: finalText,
82181
+ object: finishResult.object,
81270
82182
  toolCalls: toolCalls.length ? toolCalls : void 0
81271
82183
  },
81272
82184
  attributes: {
@@ -81274,15 +82186,32 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81274
82186
  ...usageIncomplete ? { usageIncomplete: true } : {},
81275
82187
  ...clocks,
81276
82188
  responseId: state.lastResponse?.id,
81277
- responseModel: state.lastResponse?.modelId
82189
+ responseModel: state.lastResponse?.modelId,
82190
+ ...servedBy ? {
82191
+ model: servedBy.modelId,
82192
+ provider: servedBy.provider
82193
+ } : {}
81278
82194
  },
81279
- usage: usageIncomplete ? calculateObservedUsage(steps) : state.accumulatedUsage
82195
+ usage: subtractReportedUsage(usageIncomplete ? calculateObservedUsage(steps) : state.accumulatedUsage, state.generationReportedUsage),
82196
+ stepProviderMetadata: state.reportedCosts?.slice(state.generationReportedSteps ?? 0).map((cost) => cost ?? void 0)
81280
82197
  });
81281
82198
  }
81282
- liveOrRebuiltAgentSpan(agentSpanData, reg, observability)?.end({
82199
+ agentSpan?.end({
81283
82200
  ...termination,
81284
- output: { text: finalText },
81285
- ...clocks ? { attributes: clocks } : {}
82201
+ output: {
82202
+ text: finalText,
82203
+ object: finishResult.object,
82204
+ ...runTripwire ? { tripwire: runTripwire } : {}
82205
+ },
82206
+ attributes: {
82207
+ ...clocks,
82208
+ ...runTripwire ? { tripwireAbort: {
82209
+ reason: runTripwire.reason,
82210
+ processorId: runTripwire.processorId,
82211
+ retry: runTripwire.retry,
82212
+ metadata: runTripwire.metadata
82213
+ } } : {}
82214
+ }
81286
82215
  });
81287
82216
  }
81288
82217
  } catch (error) {
@@ -81381,19 +82310,20 @@ var DefaultAgentExecutionEngine = class {
81381
82310
  keepReplayEvent,
81382
82311
  attachedAtLogIndex
81383
82312
  };
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
- }
82313
+ let first;
82314
+ let floor;
82315
+ for (const event of history) {
82316
+ const index = event.index;
82317
+ if (typeof index !== "number" || index >= offset) continue;
82318
+ if (first === void 0 || index < first) first = index;
82319
+ const generation = event.generation;
82320
+ if (typeof generation === "number" && (floor === void 0 || generation > floor)) floor = generation;
82321
+ }
82322
+ if (first !== void 0) return {
82323
+ minGeneration: floor,
82324
+ keepReplayEvent,
82325
+ attachedAtLogIndex
82326
+ };
81397
82327
  return {
81398
82328
  minGeneration: await readRunGeneration(this.mastra, runId),
81399
82329
  keepReplayEvent,
@@ -81432,7 +82362,13 @@ var DefaultAgentExecutionEngine = class {
81432
82362
  if (typeof historyPubsub.getHistory !== "function") return "latest";
81433
82363
  try {
81434
82364
  const history = await historyPubsub.getHistory(AGENT_STREAM_TOPIC(runId));
81435
- return Array.isArray(history) && history.length > 0 ? history.length : "latest";
82365
+ if (!Array.isArray(history) || history.length === 0) return "latest";
82366
+ let newest = -1;
82367
+ for (const event of history) {
82368
+ const index = event?.index;
82369
+ if (typeof index === "number" && index > newest) newest = index;
82370
+ }
82371
+ return newest >= 0 ? newest + 1 : "latest";
81436
82372
  } catch {
81437
82373
  return "latest";
81438
82374
  }
@@ -81958,12 +82894,15 @@ var DefaultAgentExecutionEngine = class {
81958
82894
  }
81959
82895
  });
81960
82896
  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);
82897
+ const results = Object.values(snapshot.context ?? {});
82898
+ const stepSuspended = results.some((result) => result?.status === "suspended");
82899
+ const resumed = stepSuspended || results.some((result) => result?.resumedAt != null);
81962
82900
  return {
81963
82901
  snapshot,
81964
82902
  workflowInput,
81965
82903
  finishPublishedBeforeCrash,
81966
- originalSpansEnded: finishPublishedBeforeCrash || resumed
82904
+ originalSpansEnded: finishPublishedBeforeCrash || resumed,
82905
+ openStepsOf: stepSuspended ? [] : openStepsOfCrashedSegment(snapshot.requestContext, runId)
81967
82906
  };
81968
82907
  }
81969
82908
  async loadSuspendedRequestContextValue(workflowsStore, runId, agent, key) {
@@ -82488,7 +83427,7 @@ async function prepareForDurableExecution(options) {
82488
83427
  });
82489
83428
  let tripwireData;
82490
83429
  if (inputProcessors.length > 0) try {
82491
- const { ProcessorRunner } = await import("./stream-D1y9GzoD.js").then((n) => n.I);
83430
+ const { ProcessorRunner } = await import("./stream-C5PagEDs.js").then((n) => n.I);
82492
83431
  await new ProcessorRunner({
82493
83432
  inputProcessors,
82494
83433
  outputProcessors,
@@ -82563,6 +83502,8 @@ async function prepareForDurableExecution(options) {
82563
83502
  } catch (error) {
82564
83503
  logger?.warn?.(`[DurableAgent] Error converting tools: ${error}`);
82565
83504
  }
83505
+ const toolNames = Object.keys(tools);
83506
+ if (!resumedSpans && toolNames.length > 0) agentSpan?.update({ attributes: { availableTools: toolNames } });
82566
83507
  if (!tripwireData) {
82567
83508
  await fireClientToolOutputHooks({
82568
83509
  messages,
@@ -82623,18 +83564,36 @@ async function prepareForDurableExecution(options) {
82623
83564
  type: "model_generation",
82624
83565
  outcome: null,
82625
83566
  name: `llm: '${model.modelId}'`,
83567
+ input: { messages: [...messageList.getAllSystemMessages(), ...messageList.get.all.aiV5.model()] },
82626
83568
  attributes: {
82627
83569
  model: model.modelId,
82628
83570
  provider: model.provider,
82629
- streaming: true
83571
+ streaming: true,
83572
+ parameters: serializeModelSettings(execOptions?.modelSettings),
83573
+ tools: agentSpan?.isValid ? getToolDefinitionsForTracing({
83574
+ tools,
83575
+ toolChoice: execOptions?.toolChoice,
83576
+ activeTools: execOptions?.activeTools,
83577
+ stripToolsWhenNone: sendsNativeResponseFormat(execOptions?.structuredOutput, model)
83578
+ }) : void 0
82630
83579
  },
82631
83580
  metadata: {
82632
83581
  runId,
82633
83582
  threadId,
82634
83583
  resourceId
82635
83584
  },
83585
+ tracingPolicy: agentTracingPolicy,
82636
83586
  requestContext
82637
83587
  });
83588
+ const modelSnapshot = modelSpan?.snapshot?.() ?? modelSpan?.exportSpan();
83589
+ const modelSnapshotWithoutPromptOrTools = modelSnapshot && {
83590
+ ...modelSnapshot,
83591
+ input: void 0,
83592
+ attributes: {
83593
+ ...modelSnapshot.attributes,
83594
+ tools: void 0
83595
+ }
83596
+ };
82638
83597
  return {
82639
83598
  runId,
82640
83599
  messageId,
@@ -82700,7 +83659,7 @@ async function prepareForDurableExecution(options) {
82700
83659
  },
82701
83660
  messageId,
82702
83661
  agentSpanData: agentSpan?.snapshot?.() ?? agentSpan?.exportSpan(),
82703
- modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),
83662
+ modelSpanData: modelSnapshotWithoutPromptOrTools,
82704
83663
  requestContextEntries: requestContextEntriesSnapshot,
82705
83664
  inputTripwire: tripwireData
82706
83665
  }),
@@ -92036,11 +92995,14 @@ var Agent = class Agent extends MastraBase {
92036
92995
  if (generation !== executionFence.generation || !executionFence.ownsRunTopics()) return;
92037
92996
  const currentFence = getRunRegistryEntry(runId, this.#mastra)?.executionFence;
92038
92997
  if (currentFence && currentFence !== executionFence) return;
92998
+ if (executionFence.detached) return;
92039
92999
  try {
92040
93000
  await publisher?.settle(status);
92041
93001
  } catch (error) {
92042
- if (!(error instanceof DurableExecutionFenceError) || error.id !== "DURABLE_AGENT_EXECUTION_UNVERIFIED") throw error;
92043
- this.#unverifiedReaderFences.add(executionFence);
93002
+ const unverified = error instanceof DurableExecutionFenceError && error.id === "DURABLE_AGENT_EXECUTION_UNVERIFIED";
93003
+ if (unverified) this.#unverifiedReaderFences.add(executionFence);
93004
+ if (executionFence.detached) return;
93005
+ if (!unverified) throw error;
92044
93006
  this.logger.warn(`[DurableAgent:${this.id}] run ${runId}: terminal ownership could not be verified`, { error });
92045
93007
  }
92046
93008
  };
@@ -92231,7 +93193,7 @@ var Agent = class Agent extends MastraBase {
92231
93193
  }
92232
93194
  }
92233
93195
  /** Rebuilds process-local recovery state from the persisted durable workflow input. */
92234
- async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, latestMessageListState }) {
93196
+ async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, openStepsOf, latestMessageListState }) {
92235
93197
  const requestContext = workflowInput.requestContextEntries ? new RequestContext(Object.entries(workflowInput.requestContextEntries)) : new RequestContext();
92236
93198
  restoreRunAgentScopes(requestContext);
92237
93199
  const messageListMemoryInfo = workflowInput.messageListState?.memoryInfo;
@@ -92385,6 +93347,7 @@ var Agent = class Agent extends MastraBase {
92385
93347
  provider: model?.provider,
92386
93348
  streaming: true
92387
93349
  },
93350
+ tracingPolicy: agentTracingPolicy,
92388
93351
  metadata: {
92389
93352
  runId,
92390
93353
  recovered: true
@@ -92398,7 +93361,7 @@ var Agent = class Agent extends MastraBase {
92398
93361
  carrySegmentSpans(requestContext, runId, recoverAgentSpan ? {
92399
93362
  ...openedSegment(recoverAgentSpan, recoverModelSpan),
92400
93363
  adoptsOpenSteps: true,
92401
- ...originalSpansEnded && origModelSpanData?.id ? { endedStepsOf: origModelSpanData.id } : {}
93364
+ ...openStepsOf ? { openStepsOf } : originalSpansEnded && origModelSpanData?.id ? { endedStepsOf: origModelSpanData.id } : {}
92402
93365
  } : null);
92403
93366
  executionFence.throwIfLost();
92404
93367
  const registryEntry = {
@@ -92468,7 +93431,9 @@ var Agent = class Agent extends MastraBase {
92468
93431
  * @internal
92469
93432
  */
92470
93433
  async emitError(runId, error, generation) {
92471
- endRunSpansWithError(runId, error);
93434
+ const evented = this.executionEngine.resolveWorkflowEngine(this.workflowEngine, this.logger) === "evented";
93435
+ const bus = this.#mastra?.pubsub ?? this.getPubSub();
93436
+ endRunSpansWithError(runId, error, { endStep: !evented || !bus || !reachesOtherProcesses(bus) });
92472
93437
  await runOutsideRunFenceScope(() => emitErrorEvent(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId, error, generation, shouldRejectStream(error) ? "reject" : void 0));
92473
93438
  }
92474
93439
  /**
@@ -92745,6 +93710,7 @@ var Agent = class Agent extends MastraBase {
92745
93710
  abortController,
92746
93711
  executionFence,
92747
93712
  originalSpansEnded: loaded.originalSpansEnded,
93713
+ openStepsOf: loaded.openStepsOf,
92748
93714
  latestMessageListState: await this.loadLatestMessageListState(workflowsStore, runId, loaded.snapshot)
92749
93715
  });
92750
93716
  await this.coverMemory(executionFence, recoveryState.requestContext, true);
@@ -93098,6 +94064,15 @@ var Agent = class Agent extends MastraBase {
93098
94064
  const resourceId = workflowInput.state?.resourceId ?? memoryInfo?.resourceId;
93099
94065
  if (sharedExecution && pubsub && entry?.requestContext && executionFence && threadId) {
93100
94066
  await agentThreadStreamRuntime.claimDurableThreadLease(pubsub, runId, threadId, resourceId, executionFence.generation, executionFence.executionId);
94067
+ try {
94068
+ await executionFence.verify();
94069
+ } catch (error) {
94070
+ 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", {
94071
+ runId,
94072
+ error: releaseError
94073
+ }));
94074
+ throw error;
94075
+ }
93101
94076
  setExecutionClaim(entry.requestContext, runId, {
93102
94077
  ...executionFence.claim,
93103
94078
  threadId,
@@ -93701,9 +94676,6 @@ var Agent = class Agent extends MastraBase {
93701
94676
  requestContextKeys
93702
94677
  };
93703
94678
  resumeRequestContext = resolvedOptions.requestContext ?? resumeRequestContext;
93704
- entry.requestContext = resumeRequestContext;
93705
- const globalEntryForContext = getRunRegistryEntry(runId, this.#mastra);
93706
- if (globalEntryForContext) globalEntryForContext.requestContext = resumeRequestContext;
93707
94679
  if (resolvedOptions.untilIdle) {
93708
94680
  const { untilIdle, ...rest } = resolvedOptions;
93709
94681
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
@@ -93734,41 +94706,6 @@ var Agent = class Agent extends MastraBase {
93734
94706
  });
93735
94707
  const priorExecution = getRunRegistryEntry(runId, this.#mastra)?.workflowExecution;
93736
94708
  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
94709
  const executionFence = await this.#claimExecution(runId, "acquire");
93773
94710
  let initialToolCalls;
93774
94711
  let resumedText;
@@ -93807,16 +94744,58 @@ var Agent = class Agent extends MastraBase {
93807
94744
  }
93808
94745
  });
93809
94746
  if (resumeRequestContext) await this.coverMemory(executionFence, resumeRequestContext);
93810
- await this.loadRecalledMessages(runId, coldSnapshot, resumeRequestContext);
93811
94747
  ({toolCalls: initialToolCalls, resumedText} = await this.#loadSuspendedIteration(runId));
93812
94748
  resumeOffset = await this.executionEngine.getPubsubOffset(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId);
93813
94749
  persistedInput = current?.context?.input;
93814
94750
  suspendedToolCallIds = Object.keys(current?.resumeLabels ?? {});
93815
94751
  await agentThreadStreamRuntime.reacquireParkedRunLease(runId, this.getPubSub());
94752
+ entry.requestContext = resumeRequestContext;
94753
+ entry.requestContextRebuilt = false;
94754
+ const globalEntryForContext = getRunRegistryEntry(runId, this.#mastra);
94755
+ if (globalEntryForContext) {
94756
+ globalEntryForContext.requestContext = resumeRequestContext;
94757
+ globalEntryForContext.requestContextRebuilt = false;
94758
+ }
94759
+ await this.loadRecalledMessages(runId, coldSnapshot, resumeRequestContext);
93816
94760
  } catch (error) {
93817
94761
  await executionFence.settle(async () => {});
93818
94762
  throw error;
93819
94763
  }
94764
+ if (!coldSnapshot && (options?.requestContext || options?.delegation || options?.hooks || droppedStartingUser)) try {
94765
+ const requestTools = await this.agentForExecution.getToolsForExecution({
94766
+ toolsets: resolvedOptions.toolsets,
94767
+ clientTools: resolvedOptions.clientTools,
94768
+ threadId: memoryInfo?.threadId,
94769
+ resourceId: memoryInfo?.resourceId,
94770
+ runId,
94771
+ requestContext: resumeRequestContext,
94772
+ memoryConfig: resolvedOptions.memory?.options,
94773
+ autoResumeSuspendedTools: resolvedOptions.autoResumeSuspendedTools,
94774
+ delegation: options?.delegation ? resolvedOptions.delegation : entry.delegation ?? resolvedOptions.delegation,
94775
+ hooks: resolvedOptions.hooks,
94776
+ methodType: entry.methodType ?? "stream",
94777
+ backgroundTaskEnabled: Boolean(entry.backgroundTaskManager),
94778
+ backgroundTaskPolicy: resolvedOptions.backgroundTaskPolicy,
94779
+ model: entry.model
94780
+ });
94781
+ const refresh = (current, previous) => {
94782
+ const next = { ...current };
94783
+ for (const [name, tool] of Object.entries(requestTools)) if (name in current ? current[name] === previous?.[name] : !previous || !(name in previous)) next[name] = tool;
94784
+ return next;
94785
+ };
94786
+ for (const reg of /* @__PURE__ */ new Set([entry, getRunRegistryEntry(runId, this.#mastra)])) {
94787
+ if (!reg) continue;
94788
+ reg.tools = rebindProcessorTools(refresh(reg.tools ?? {}, reg.requestTools), resumeRequestContext);
94789
+ if (reg.baseTools) reg.baseTools = rebindProcessorTools(refresh(reg.baseTools, reg.requestTools), resumeRequestContext);
94790
+ reg.requestTools = {
94791
+ ...reg.requestTools,
94792
+ ...requestTools
94793
+ };
94794
+ if (options?.delegation) reg.delegation = resolvedOptions.delegation;
94795
+ }
94796
+ } catch (error) {
94797
+ this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] resume(${runId}) tool resolution failed: ${error}`);
94798
+ }
93820
94799
  setExecutionClaim(resumeRequestContext, runId, executionFence.claim);
93821
94800
  for (const reg of [entry, getRunRegistryEntry(runId, this.#mastra)]) {
93822
94801
  if (!reg) continue;
@@ -93905,6 +94884,7 @@ var Agent = class Agent extends MastraBase {
93905
94884
  provider: resumeModel?.provider,
93906
94885
  streaming: true
93907
94886
  },
94887
+ tracingPolicy: agentTracingPolicy,
93908
94888
  metadata: {
93909
94889
  runId,
93910
94890
  resumed: true
@@ -99190,6 +100170,21 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
99190
100170
  let currentIteration = 0;
99191
100171
  let eagerAbortListenerRegistered = false;
99192
100172
  const transcriptSteps = [];
100173
+ const apiErrorRows = [];
100174
+ const restoreApiErrorRows = (messageId) => {
100175
+ const parts = messageList.get.all.db().find((message) => message.id === messageId)?.content.parts ?? [];
100176
+ 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);
100177
+ if (missing.length === 0) return;
100178
+ messageList.add({
100179
+ id: messageId,
100180
+ role: "assistant",
100181
+ content: {
100182
+ format: 2,
100183
+ parts: missing
100184
+ },
100185
+ createdAt: /* @__PURE__ */ new Date()
100186
+ }, "response");
100187
+ };
99193
100188
  const pendingProviderToolCallsByToolCallId = /* @__PURE__ */ new Map();
99194
100189
  const cleanupProviderToolSpans = (terminal) => {
99195
100190
  if (!terminal) return;
@@ -99408,6 +100403,19 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
99408
100403
  start: messageList.get.response.aiV5.ui().find((message) => message.id === currentMessageId)?.parts.length ?? 0,
99409
100404
  end: 0
99410
100405
  };
100406
+ const apiErrorWriter = outputWriter ? { custom: async (data, options) => {
100407
+ if (isDataChunk(data) && !data.transient) apiErrorRows.push({
100408
+ messageId: currentMessageId,
100409
+ part: {
100410
+ type: data.type,
100411
+ data: data.data
100412
+ }
100413
+ });
100414
+ return outputWriter(data, {
100415
+ ...options,
100416
+ messageId: currentMessageId
100417
+ });
100418
+ } } : void 0;
99411
100419
  modelSpanTracker?.startStep();
99412
100420
  let modelResult;
99413
100421
  let warnings;
@@ -100135,10 +101143,6 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100135
101143
  });
100136
101144
  const currentRetryCount = inputData.processorRetryCount || 0;
100137
101145
  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
101146
  const errorResult = await processorRunner.runProcessAPIError({
100143
101147
  error,
100144
101148
  messages: messageList.get.all.db(),
@@ -100383,7 +101387,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100383
101387
  }
100384
101388
  const currentRetryCount = inputData.processorRetryCount || 0;
100385
101389
  const canRetryError = maxErrorProcessorRetries !== void 0 && currentRetryCount < maxErrorProcessorRetries && !eagerCoordinator?.hasSuspendedHandback;
100386
- const processorRunner = new ProcessorRunner({
101390
+ const errorResult = await new ProcessorRunner({
100387
101391
  inputProcessors: inputProcessors || [],
100388
101392
  outputProcessors: outputProcessors || [],
100389
101393
  errorProcessors: errorProcessors || [],
@@ -100391,12 +101395,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100391
101395
  agentName: agentId || "unknown",
100392
101396
  agent,
100393
101397
  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({
101398
+ }).runProcessAPIError({
100400
101399
  error: runState.state.apiError,
100401
101400
  messages: messageList.get.all.db(),
100402
101401
  messageList,
@@ -100405,7 +101404,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100405
101404
  retryCount: currentRetryCount,
100406
101405
  requestContext,
100407
101406
  tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,
100408
- writer: apiErrorWriter2,
101407
+ writer: apiErrorWriter,
100409
101408
  abortSignal: options?.abortSignal,
100410
101409
  messageId: currentMessageId,
100411
101410
  rotateResponseMessageId: () => {
@@ -100475,6 +101474,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100475
101474
  cleanupProviderToolSpans(true);
100476
101475
  eagerCoordinator?.recarryCommittedWork(transcriptStep.messageId);
100477
101476
  messageList.rollbackToStepBoundary(transcriptStep.messageId, iterationBoundary);
101477
+ restoreApiErrorRows(transcriptStep.messageId);
100478
101478
  await discardAttemptEagerWork();
100479
101479
  if (runAbortSignal?.aborted) {
100480
101480
  await options?.onAbort?.({
@@ -102880,6 +103880,8 @@ function isStaleRequest(expiresAt) {
102880
103880
  /** Thread lease TTL and renew interval; shared with the durable execution lease. */
102881
103881
  const AGENT_THREAD_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
102882
103882
  const AGENT_THREAD_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
103883
+ const DURABLE_THREAD_CLAIM_WAIT_MS = 5e3;
103884
+ const DURABLE_THREAD_CLAIM_POLL_MS = 100;
102883
103885
  /**
102884
103886
  * TTL for a suspended run's warm in-memory state — the parked thread-run record
102885
103887
  * (swept by #sweepStaleSuspendedRecords). The Mastra internal-workflow registry
@@ -103239,11 +104241,24 @@ var AgentThreadStreamRuntime = class {
103239
104241
  }
103240
104242
  /** @internal Qualify a shared thread lease before dispatching this execution. */
103241
104243
  async claimDurableThreadLease(pubsub, runId, threadId, resourceId, generation, executionId) {
103242
- const lease = await this.#acquireThreadLease(pubsub, this.#threadKey(resourceId, threadId), runId, threadLeaseOwner(runId, generation, executionId));
104244
+ const key = this.#threadKey(resourceId, threadId);
104245
+ const owner = threadLeaseOwner(runId, generation, executionId);
104246
+ let lease = await this.#acquireThreadLease(pubsub, key, runId, owner);
104247
+ const previousOwner = parseThreadLeaseOwner(lease.owner);
104248
+ if (!lease.acquired && (lease.owner === void 0 || previousOwner && previousOwner[0] !== runId && (previousOwner[1] === "generation" || previousOwner[1] === "execution"))) {
104249
+ const blockingOwner = lease.owner;
104250
+ const deadline = Date.now() + DURABLE_THREAD_CLAIM_WAIT_MS;
104251
+ while (!lease.acquired && (lease.owner === void 0 || lease.owner === blockingOwner)) {
104252
+ const remaining = deadline - Date.now();
104253
+ if (remaining <= 0) break;
104254
+ await new Promise((resolve) => setTimeout(resolve, Math.min(remaining, DURABLE_THREAD_CLAIM_POLL_MS)));
104255
+ lease = await this.#acquireThreadLease(pubsub, key, runId, owner);
104256
+ }
104257
+ }
103243
104258
  if (!lease.acquired) throw new AgentThreadLeaseConflictError(runId, lease.owner ?? "another owner");
103244
104259
  if (this.#getState(pubsub).leaseRenewalTimers.has(runId)) {
103245
104260
  this.#stopLeaseRenewal(pubsub, runId);
103246
- this.#startLeaseRenewal(pubsub, this.#threadKey(resourceId, threadId), runId, threadLeaseOwner(runId, generation, executionId));
104261
+ this.#startLeaseRenewal(pubsub, key, runId, owner);
103247
104262
  }
103248
104263
  }
103249
104264
  /** @internal Renew only the captured execution's thread lease; never acquire or transfer it. */
@@ -103547,6 +104562,7 @@ var AgentThreadStreamRuntime = class {
103547
104562
  this.#stopLeaseRenewal(pubsub, runId, timer);
103548
104563
  this.#abortLeaseLostRun(state, runId);
103549
104564
  }
104565
+ if (state.threadRunsById.get(runId)?.lifecycle === "suspended" && typeof owner === "string" && threadLeaseRunId(owner) === runId) return;
103550
104566
  throw new AgentThreadLeaseLostError(runId);
103551
104567
  };
103552
104568
  }
@@ -104599,7 +105615,7 @@ var AgentThreadStreamRuntime = class {
104599
105615
  releaseMessageIdentity(getErrorFromUnknown(error));
104600
105616
  throw error;
104601
105617
  }
104602
- const callerRequestContext = remoteRequestContextEntries ? restoreRequestContext$1(remoteRequestContextEntries, ownerStreamOptions?.requestContext) : incomingStreamOptions?.requestContext;
105618
+ const callerRequestContext = remoteRequestContextEntries ? restoreRequestContext(remoteRequestContextEntries, ownerStreamOptions?.requestContext) : incomingStreamOptions?.requestContext;
104603
105619
  const incomingRequestContext = callerRequestContext && claimedOwnerRequestContext(callerRequestContext, ownerStreamOptions?.requestContext);
104604
105620
  streamOptions = incomingRequestContext === void 0 ? ownerStreamOptions : {
104605
105621
  ...ownerStreamOptions,
@@ -108517,6 +109533,7 @@ async function participateInDurableExecution(mastra, event, execute) {
108517
109533
  const fence = await participant.fence;
108518
109534
  if (!fence) return await execute();
108519
109535
  await fence.verify();
109536
+ await carryEndedSegment(mastra, event);
108520
109537
  let parentRunId = runId;
108521
109538
  for (const nestedRunId of nestedRunIds) {
108522
109539
  fence.coverNestedRun(parentRunId, nestedRunId);
@@ -108555,6 +109572,51 @@ async function retrySettledDurableExecution(mastra, event) {
108555
109572
  await settleEventedDurableExecution(mastra, event);
108556
109573
  return true;
108557
109574
  }
109575
+ /**
109576
+ * When a suspension beside the failed tool call ends the segment's spans, tell this failure and the run's own, through
109577
+ * the request context they inherit. Called before the delivery passes that context on.
109578
+ */
109579
+ async function carryEndedSegment(mastra, event) {
109580
+ const { workflowId, stepResults, requestContext } = event.data ?? {};
109581
+ const state = stepResults?.input;
109582
+ const calls = stepResults?.[DurableStepIds.TOOL_CALL];
109583
+ if (event.type !== "workflow.fail" || workflowId !== DurableStepIds.AGENTIC_EXECUTION || !state?.runId) return;
109584
+ if (calls?.status !== "failed" || Array.isArray(calls.payload) && !calls.payload[0]?.sideBySide) return;
109585
+ const context = new RequestContext(Object.entries(requestContext ?? {}));
109586
+ const segment = segmentSpanData(context, state.runId, state);
109587
+ if (segment.carried) return;
109588
+ const { runId, iterationCount } = state;
109589
+ if (await claimSegmentEnd({
109590
+ mastra,
109591
+ requestContext: context,
109592
+ runId,
109593
+ iterationCount,
109594
+ outcome: "fail"
109595
+ }) ?? !segmentEndedBySuspension(segment, stepResults)) return;
109596
+ event.data.requestContext = { ...requestContext };
109597
+ carrySegmentSpans(event.data.requestContext, runId, null);
109598
+ }
109599
+ function endFailedSpans(mastra, event) {
109600
+ const { stepResults, prevResult, requestContext } = event.data ?? {};
109601
+ const runId = stepResults?.input?.runId;
109602
+ if (!runId || isExecutionFenceError(prevResult?.error)) return;
109603
+ endFailedSegmentSpans({
109604
+ mastra,
109605
+ requestContext: new RequestContext(Object.entries(requestContext ?? {})),
109606
+ runId,
109607
+ state: stepResults.input,
109608
+ steps: stepResults,
109609
+ error: getErrorFromUnknown(prevResult?.error ?? "Workflow execution failed"),
109610
+ live: getRunRegistryEntry(runId, mastra),
109611
+ firstPairOnly: true
109612
+ });
109613
+ }
109614
+ /** End the MODEL_STEP of a failed iteration. Only the iteration's own event still carries it. */
109615
+ function endFailedIteration(mastra, event) {
109616
+ if (event.type !== "workflow.fail" || event.data?.workflowId !== DurableStepIds.AGENTIC_EXECUTION) return;
109617
+ if (isWorkflowStepConflictError(event.data.prevResult?.error)) return;
109618
+ endFailedSpans(mastra, event);
109619
+ }
108558
109620
  /** Called only after the root terminal handler has persisted and published its outcome. */
108559
109621
  async function settleEventedDurableExecution(mastra, event) {
108560
109622
  if (!isRootTerminal(event)) return;
@@ -108591,6 +109653,7 @@ async function settleEventedDurableExecution(mastra, event) {
108591
109653
  fence
108592
109654
  });
108593
109655
  await ExecutionFence.releaseSharedClaim(mastra, event.runId, claim, "settled");
109656
+ if (event.type === "workflow.fail" && !released) endFailedSpans(mastra, event);
108594
109657
  if (claim.threadId && event.type !== "workflow.suspend") await agentThreadStreamRuntime.releaseDurableThreadLease(mastra.pubsub, event.runId, claim.threadId, claim.resourceId, claim.generation, claim.executionId);
108595
109658
  if (claim.memoryFenced && fence) await (await mastra.getStorage()?.getStore("memory"))?.retireRunFence(fence);
108596
109659
  await mastra.__getRunScope(event.runId)?.get(PARTICIPANTS)?.get(claim.executionId)?.stop();
@@ -108648,6 +109711,9 @@ function getRunRegistryEntry(runId, mastra) {
108648
109711
  }
108649
109712
  return unwrapMastraTracingProxy(entry.mastra) === unwrapMastraTracingProxy(mastra) ? entry : void 0;
108650
109713
  }
109714
+ function getLiveRunRequestContext(entry) {
109715
+ return entry?.requestContextRebuilt ? void 0 : entry?.requestContext;
109716
+ }
108651
109717
  /**
108652
109718
  * Publish an entry for `runId`, owned by `mastra`, unless the slot holds
108653
109719
  * another Mastra instance's live run. Returns whether the entry was stored.
@@ -108805,6 +109871,11 @@ async function abandonDurableAgentExecutions(mastra) {
108805
109871
  function endRunSpansWithError(runId, error, options = {}) {
108806
109872
  try {
108807
109873
  const entry = globalRunRegistry.has(runId) ? globalRunRegistry.get(runId) : void 0;
109874
+ if (options.endStep ?? options.endSpan ?? true) entry?.openStepSpan?.error(stepFailure({
109875
+ error,
109876
+ ...executionFailureTermination(error),
109877
+ endSpan: true
109878
+ }));
108808
109879
  (entry?.resumeModelSpan ?? entry?.modelSpan)?.error({
108809
109880
  error,
108810
109881
  ...executionFailureTermination(error),
@@ -108953,4 +110024,4 @@ var ExtendedRunRegistry = class extends RunRegistry {
108953
110024
  this.#memoryInfo.clear();
108954
110025
  }
108955
110026
  };
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 };
110027
+ export { resolveDurableToolCallConcurrency as $, planSpanQuery as $a, getSingleStepEntryId as $c, createValidator as $i, resolveRunFence as $l, MessageHistory as $n, AgentsMDInjector as $o, MAX_NOTIFICATION_DELIVERY_ATTEMPTS as $r, AgentStreamBus as $s, validateModelTimeoutSettings as $t, assembleAgentFromFsEntry as A, TracePageError as Aa, repeatAfterSettled as Ac, MAX_KNOWLEDGE_PAGE_LINKS as Ai, ProcessorMessageSchema as Al, buildKnowledgeInstructions as An, chunkMessageText as Ao, createEmptyWorkflowSnapshot as Ar, PrefillErrorHandler as As, RUN_DEADLINE_KEY as At, createDurableGoalStep as B, threadQueryIdentitySchema as Ba, RESUME_SNAPSHOT_POLL_INTERVAL_MS as Bc, knowledgePositionBetween as Bi, TextPartSchema as Bl, formatToolApproval as Bn, augmentWithInit as Bo, SchedulesStorage as Br, createWorkflow$1 as Bs, getServerSideFallbackInfo as Bt, ScorerRunError as C, parseDuration as Ca, nestedRunStatusOf as Cc, KnowledgePageHasChildrenError as Ci, FilePartSchema as Cl, compileKnowledgeScopes as Cn, ObservabilityStorage as Co, FilesystemStore as Cr, isMalformedFunctionCallError as Cs, segmentEndedBySuspension as Ct, notScorable as D, transformRow as Da, validateScoringPredicate as Dc, MAX_KNOWLEDGE_PAGE_BODY_LINKS as Di, ProcessorInputPhaseSchema as Dl, strongerKnowledgeRole as Dn, DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS as Do, WorkflowsInMemory as Dr, StreamErrorRetryProcessor as Ds, DURABLE_STOP_WHEN_ERROR_ID as Dt, isNotScorable as E, storageMessageMatchesMetadataFilter as Ea, evaluateScoringPredicate as Ec, MAX_KNOWLEDGE_NOTE_TOKENS as Ei, MessagePartSchema as El, knowledgeScopeAddress as En, UniqueViolationError as Eo, MockStore as Er, FILE_UPLOAD_ERROR_CODES as Es, runResumeDurableStreamUntilIdle as Et, prepareForDurableExecution as F, tracePageResponseSchema as Fa, runWithConcurrency as Fc, assertKnowledgePageDescriptionWithinBound as Fi, ProcessorStepOutputSchema as Fl, ChatChannelProcessor as Fn, MastraMemory as Fo, InMemoryToolProviderConnectionsStorage as Fr, EventedRun as Fs, getScopeStreamSlot as Ft, serializeDurableOptions as G, SPAN_QUERY_MAX_CURSOR_BYTES as Ga, cleanStepResult as Gc, HarnessStorage as Gi, isWorkflowStepConflictError as Gl, createChannelTools as Gn, RESPONSE_CACHE_CONTEXT_KEY as Go, createNotificationSignal as Gr, diffResponseMessages as Gs, generateFinalResult as Gt, createDurableLLMMappingStep as H, threadQueryResponseSchema as Ha, abortableSleep as Hc, parseKnowledgePageRef as Hi, isAgentCompatible as Hl, DEFAULT_CHANNEL_TOOLS_SETTINGS as Hn, createBackgroundWorkSignalProcessor as Ho, InMemoryNotificationsStorage as Hr, StepExecutor as Hs, formatCompletionFeedback as Ht, applyReservedMemoryContextKeys as I, THREAD_QUERY_DEFAULT_LIMIT as Ia, createMappingStep as Ic, canonicalKnowledgeName as Ii, ProcessorStepSchema as Il, CHAT_CHANNEL_RENDER_CONTEXT_KEY as In, MemoryProcessor as Io, ToolProviderConnectionsStorage as Ir, EventedWorkflow as Is, untilIdleHandlesBackgroundTask as It, serializeToolsMetadata as J, SPAN_QUERY_ORDER_FIELDS as Ja, createTimeTravelExecutionParams as Jc, DatasetsInMemory as Ji, RunFenceConflictError as Jl, BaseProcessor as Jn, WorkspaceInstructionsProcessor as Jo, notificationSignalMetadata as Jr, emitErrorEvent as Js, runCompletionScorers as Jt, serializeDurableState as K, SPAN_QUERY_MAX_LIMIT as Ka, createDeprecationProxy as Kc, ExperimentsInMemory as Ki, RUN_FENCE_CONFLICT_ERROR_ID as Kl, resolveChannelToolsSettings as Kn, ResponseCache as Ko, createNotificationSummarySignal as Kr, emitAbortEvent as Ks, generateStructuredFinalResult as Kt, persistDurableRunInput as L, THREAD_QUERY_MAX_LIMIT as La, createStepFromAgent$1 as Lc, knowledgeLinkRefKey as Li, ReasoningPartSchema as Ll, renderBuiltInToolEvent as Ln, memoryDefaultOptions as Lo, ScoresInMemory as Lr, cloneStep as Ls, pruneAgentLoopSnapshot as Lt, AGENT_RESUME_CLAIM_STALE_MS as M, tracePageIdSchema as Ma, ExecutionEngine as Mc, MAX_KNOWLEDGE_PAGE_LIST_LIMIT as Mi, ProcessorOutputStepPhaseSchema as Ml, resolveWaitUntil as Mn, messageVectorId as Mo, mergeWorkflowStepResult as Mr, cloneWorkflow as Ms, readRunDeadline as Mt, Agent as N, tracePageNodeSchema as Na, createConcurrencyLimiter as Nc, MAX_KNOWLEDGE_PIN_LIST_DEPTH as Ni, ProcessorOutputStreamPhaseSchema as Nl, defaultTypingStatus as Nn, resolveMaxChunkChars as No, InMemoryWorkflowDefinitionsStorage as Nr, createEventedWorkflow as Ns, __registerMastraCtor as Nt, agentConfig as O, transformScoreRow as Oa, WORKFLOW_RUN_LEASE_TTL_MS as Oc, MAX_KNOWLEDGE_PAGE_DEPTH as Oi, ProcessorInputStepPhaseSchema as Ol, decodeKnowledgeScopeId as On, MESSAGE_EMBEDDING_CHARS_PER_TOKEN as Oo, cloneRunData as Or, isBadRequestError as Os, DurableAgentDefaults as Ot, normalizeResumeGenerateArgs as P, tracePageRequestSchema as Pa, normalizeConcurrency as Pc, assertKnowledgeNoteTextWithinBound as Pi, ProcessorStepInputSchema as Pl, MastraStateAdapter as Pn, upsertMessageVectors as Po, WorkflowDefinitionsStorage as Pr, createWorkflow as Ps, getRunStreamSlot as Pt, createDurableBackgroundTaskCheckStep as Q, parseSpanQueryRequest as Qa, getResumeLabelsByStepId as Qc, assertSupportedPatterns as Qi, matchesRunFence as Ql, WorkingMemory as Qn, ToolSearchProcessor as Qo, readNotificationRoutingRequirement as Qr, emitSuspendedEvent as Qs, loop as Qt, detachFullStreamOnEnd as R, encodeThreadQueryCursor as Ra, createStepFromClassifier as Rc, knowledgePagePath as Ri, SourcePartSchema as Rl, CONTINUE_RUN_ACTION_ID as Rn, filterSystemReminderMessages as Ro, ScoresStorage as Rr, cloneWorkflow$1 as Rs, DEFAULT_TOOL_DECLINE_REASON as Rt, MastraScorer as S, jsonValueEquals as Sa, nestedRunRecoveryAction as Sc, KnowledgePageDepthError as Si, isDurableAgentLike as Sl, KnowledgeDeclarationError as Sn, ObservabilityInMemory as So, createGitHubSourceControlProviderFromEnv as Sr, defaultStabilityErrorProcessors as Ss, liveSegmentSpan as St, filterRun as T, serializeDate as Ta, SCORING_PREDICATE_ROOTS as Tc, MAX_KNOWLEDGE_MOVE_PAGES as Ti, MessageContentSchema as Tl, knowledgeRunScopes as Tn, FactoryStorageDomain as To, InMemoryStore as Tr, FileUploadProcessor as Ts, runDurableStreamUntilIdle as Tt, createDurableToolCallStep as U, threadQueryRowSchema as Ua, applyStateDelta as Uc, KnowledgeInvalidCursorError as Ui, WorkflowStepConflictError as Ul, channelToolScopeResolver as Un, CyberRefusalHandler as Uo, NotificationsStorage as Ur, computeScheduleDefinitionHash as Us, formatStreamCompletionFeedback as Ut, createDurableIsTaskCompleteStep as V, threadQueryRequestSchema as Va, RESUME_SNAPSHOT_WAIT_STATUSES as Vc, knowledgeScopeReadable as Vi, ToolInvocationPartSchema as Vl, ChannelSessionRejectedError as Vn, getStorageSource as Vo, normalizeScheduleTarget as Vr, WorkflowEventProcessor as Vs, formatCheckFeedback as Vt, createWorkflowInput as W, SPAN_QUERY_MAX_COST_METRICS as Wa, assertTimeTravelGraphMatchesSnapshot as Wc, InMemoryHarness as Wi, assertWorkflowStepGuard as Wl, createChannelToolScope as Wn, DEFAULT_RESPONSE_CACHE_TTL_SECONDS as Wo, dispatchDueNotifications as Wr, __resetExecutionFencesForTests as Ws, formatValidationFeedback as Wt, MessagePartSpans as X, createSpanQueryPreview as Xa, defineStateAccessors as Xc, DatasetItemIdentityConflictError as Xi, currentRunGeneration as Xl, SemanticRecall as Xn, SkillsProcessor as Xo, notificationSummarySignalMetadata as Xr, emitStepFinishEvent as Xs, runStreamCompletionScorers as Xt, createDurableLLMExecutionStep as Y, buildSpanQueryResponse as Ya, defineLazyWriter as Yc, DatasetsStorage as Yi, coverNestedRun as Yl, MemoryInputFilter as Yn, SkillSearchProcessor as Yo, notificationSummaryContents as Yr, emitFinishEvent as Ys, runDefaultCompletionCheck as Yt, isSpanChunk as Z, encodeSpanQueryCursor as Za, getRestartStartIndex as Zc, SchemaValidator as Zi, isRunFenceConflictError as Zl, globalEmbeddingCache as Zn, formatSkillsCatalog as Zo, summarizeNotifications as Zr, emitStepStartEvent as Zs, runValidation as Zt, runEvals as _, ensureDate as _a, predicateToCondition as _c, assertKnowledgeSchemaCompatible as _i, assertDrainTimeout as _l, syncKnowledgePageBodyLinks as _n, buildUpdateSpanRecord as _o, knowledgeVisibleScopeKeys as _r, PIIDetector as _s, toolRequiresApproval as _t, endRunSpansWithError as a, ChannelsStorage as aa, AGENT_STREAM_TOPIC as ac, InMemoryKnowledgeStorage as ai, omitPriorSuspensionFields as al, addKnowledgeNote as an, spanQueryResponseSchema as ao, MAX_KNOWLEDGE_SCOPE_TAGS as ar, TokenLimiterProcessor as as, baseIterationStateSchema as at, validateAndSaveScore as b, getSqlType as ba, createNestedRunParentStatusLookup as bc, parseKnowledgeWikilinks as bi, hasDurableExecution as bl, knowledgeReadScopeFor as bn, serializeSpanAttributes as bo, StoreOperations as br, UnicodeNormalizer as bs, carrySegmentSpans as bt, globalRunRegistry as c, BackgroundTasksInMemory as ca, EventedExecutionEngine as cc, KnowledgeImportersStorage as ci, setLongTimeout as cl, removeKnowledgePage as cn, encodeTraceQueryDeltaCursor as co, assertKnowledgeRecordTextWithinBound as cr, advanceMemoryTokenBoundary as cs, modelListEntrySchema as ct, takeRunScorerInstances as d, resolveRetentionTargets as da, Run as dc, KnowledgeConflictError as di, validateStepResumeData as dl, KnowledgeSemanticIndex as dn, planTraceQuery as do, createKnowledgeNodeCursor as dr, normalizeMessageHistoryConfig as ds, loadRunStoredMessages as dt, getSchemaValidator as ea, publishAbortRequest as ec, defaultNotificationDeliveryDecision as ei, getStepIds as el, PINNED_READ_MEMO_KEY as en, resolveSpanQueryCost as eo, MemoryRunState as er, ToolCallFilter as es, buildStepRecord as et, runFencingNotSupportedError as eu, AgentThreadLeaseLostError as f, retentionCutoffMs as fa, Workflow as fc, KnowledgeNotFoundError$1 as fi, validateStepStateData as fl, embed$2 as fn, buildCreateSpanRecord as fo, expandKnowledgeScope as fr, BatchPartsProcessor as fs, rebuildRunToolsFromMastra as ft, describeNonSuccessFinishReason as g, createVectorErrorId as ga, mapVariable as gc, KnowledgeUnsupportedCapabilityError as gi, getEntryWorkflow as gl, reindexKnowledgeLinks as gn, buildScoreRecord as go, knowledgeSemanticIdempotencyKey as gr, LanguageDetector as gs, resolveTool$1 as gt, AGENTIC_LOOP_WORKFLOW_ID as h, createStoreErrorId as ha, isProcessor$1 as hc, KnowledgeTransactionDeadlineError as hi, getEntryId as hl, refreshKnowledgeLinksTo as hn, buildMetricRecord as ho, knowledgeSemanticDocumentId as hr, StructuredOutputProcessor as hs, resolveRuntimeDependencies as ht, deleteRunRegistryEntry as i, InMemoryChannelsStorage as ia, AGENT_CONTROL_TOPIC as ic, MemoryStorage as ii, omitPriorCompletionFields as il, knowledgeRunPrincipals as in, spanQueryRequestSchema as io, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH as ir, SystemPromptScrubber as is, baseDurableAgenticInputSchema as it, MAX_FS_SUBAGENT_DEPTH as j, readTracePage as ja, runFenceConflictOf as jc, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH as ji, ProcessorOutputResultPhaseSchema as jl, AgentChannels as jn, extractMessageEmbeddingText as jo, mergeStepResult as jr, getGoalActivityDurationMs as js, ensureRemoteAbortListener as jt, agentInstructions as k, validateStorageMetadataFilter as ka, renewWorkflowLease as kc, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS as ki, ProcessorMessageContentSchema as kl, encodeKnowledgeScopeId as kn, buildMessageEmbeddingRows as ko, WorkflowsStorage as kr, isRetryableOpenAIResponsesStreamError as ks, DurableStepIds as kt, isDurableAgentExecutionDetached as l, BackgroundTasksStorage as la, getNestedWorkflow as lc, KNOWLEDGE_STORAGE_CONTRACT_VERSION as li, validateStepInput as ll, updateKnowledgeNote as ln, getTraceQueryDeltaWatermark as lo, assertKnowledgeScopeWithinCeiling as lr, getMemoryTokenBoundary as ls, executeDurableAgentScorers as lt, AGENTIC_EXECUTION_WORKFLOW_ID as m, createStorageErrorId as ma, createStep$1 as mc, KnowledgeStorage as mi, waitForSuspendedSnapshot as ml, knowledgeSubtree as mn, buildLogRecord as mo, knowledgeScopeKey as mr, ClassifierProcessor as ms, resolveModel as mt, RunRegistry as n, SchemaUpdateValidationError as na, subscribeToAbortRequests as nc, resolveNotificationDeliveryDecision as ni, isEntryFinished as nl, buildKnowledgePageTools as nn, spanQueryIdentityKey as no, MockMemory as nr, CostGuardProcessor as ns, createBaseIterationStateUpdate as nt, setRunFenceContext as nu, getActiveDurableAgentWorkflowExecutions as o, InMemoryBlobStore as oa, AgentControlEventTypes as oc, KnowledgeImporterBindingConflictError as oi, resolveForeachConcurrency as ol, moveKnowledgePage as on, spanQueryRowSchema as oo, assertKnowledgeCeilingRaised as or, groupLinkedToolMessages as os, durableAgenticOutputSchema as ot, agentThreadStreamRuntime as p, runRetentionBatches as pa, cloneStep$1 as pc, KnowledgeSchemaResetRequiredError as pi, validateStepSuspendData as pl, KnowledgeLinkRefreshIncompleteError as pn, buildFeedbackRecord as po, isKnowledgeScopeVisible as pr, ModelSelectionProcessor as ps, resolveInternalState as pt, serializeModelConfig as q, SPAN_QUERY_MAX_PREVIEW_CHARACTERS as qa, createRestartExecutionParams as qc, ExperimentsStorage as qi, RUN_FENCING_NOT_SUPPORTED_ERROR_ID as ql, toChatLogger as qn, buildResponseCacheKey as qo, notificationSignalAttributes as qr, emitChunkEvent as qs, runChecks as qt, abandonDurableAgentExecutions as r, SchemaValidationError as ra, createRunAbortController as rc, InMemoryMemory as ri, isSingleStepEntry as rl, KnowledgeRun as rn, spanQueryIdentitySchema as ro, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH as rr, TokenCostControl as rs, accumulatedUsageSchema as rt, getRunRegistryEntry as s, BlobStore as sa, AgentStreamEventTypes as sc, KnowledgeImporterRunStateError as si, runCountDeprecationMessage as sl, removeKnowledgeNote as sn, encodeTraceQueryCursor as so, assertKnowledgeDescriptionWithinBound as sr, loadMessageHistory as ss, modelConfigSchema as st, ExtendedRunRegistry as t, UnsupportedSchemaPatternError as ta, requestAcknowledgedAbort as tc, resolveDeliveryFailureUpdate as ti, hydrateSerializedStepErrors as tl, knowledgeDeliveredPins as tn, spanQueryCostSchema as to, getMemoryRunState as tr, RegexFilterProcessor as ts, calculateAccumulatedUsage as tt, runOutsideRunFenceScope as tu, setRunRegistryEntry as u, executeRetentionPrune as ua, getStepEntry as uc, KNOWLEDGE_STORAGE_SCHEMA_VERSION as ui, validateStepRequestContext as ul, upsertKnowledgePage as un, planThreadQuery as uo, canonicalizeKnowledgeScope as ur, isAfterMemoryTokenBoundary as us, runDurableFinishSideEffects as ut, flushBeforeTraceRead as v, filterByDateRange as va, evaluatePredicate as vc, createKnowledgeUlid as vi, waitMs as vl, updateKnowledgeLinks as vn, getObjectOrNull as vo, parseKnowledgeNodeCursor as vr, PromptInjectionDetector as vs, resolveAgentById as vt, createScorer as w, safelyParseJSON as wa, DefaultExecutionEngine as wc, KnowledgePageKeyConflictError as wi, ImagePartSchema as wl, knowledgeMemoryScopes as wn, FactoryStorage as wo, FilesystemDB as wr, UnsupportedFileHandler as ws, segmentSpanData as wt, createClassifierScorer as x, hasErrorCode as xa, nestedRunParentOf as xc, KnowledgeMoveTooLargeError as xi, hasResumableStreams as xl, knowledgeRoleOn as xn, toEntityType as xo, GitHubSourceControlProvider as xr, STABILITY_ERROR_PROCESSOR_IDS as xs, endFailedSegmentSpans as xt, createOnScorerHook as y, getDefaultValue as ya, cancelNestedRun as yc, inspectKnowledgeSchema as yi, workflowTermination as yl, knowledgeAccessGrants as yn, getStringOrNull as yo, StoreOperationsInMemory as yr, ModerationProcessor as ys, createDurableAgentStream as yt, createDurableAgenticWorkflow as z, planThreadRowsQuery as za, createStepFromTool as zc, knowledgePinDepth as zi, StepStartPartSchema as zl, CONTINUE_RUN_MESSAGE as zn, isSystemReminderMessage as zo, InMemorySchedulesStorage as zr, createStep as zs, resolveDeclineReason as zt };