@mastra/core 1.86.0 → 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 (446) hide show
  1. package/dist/agent/durable/constants.d.ts +2 -0
  2. package/dist/agent/durable/evented-execution.d.ts +7 -0
  3. package/dist/agent/durable/execution-engine.d.ts +1 -0
  4. package/dist/agent/durable/execution-fence.d.ts +2 -0
  5. package/dist/agent/durable/index.cjs +3 -1
  6. package/dist/agent/durable/index.d.ts +1 -1
  7. package/dist/agent/durable/index.js +2 -2
  8. package/dist/agent/durable/run-registry.d.ts +2 -0
  9. package/dist/agent/durable/segment-spans.d.ts +54 -1
  10. package/dist/agent/durable/types.d.ts +10 -0
  11. package/dist/agent/durable/workflows/durable-loop-builder.d.ts +57 -2
  12. package/dist/agent/durable/workflows/finalize-run.d.ts +2 -0
  13. package/dist/agent/durable/workflows/shared/index.d.ts +1 -1
  14. package/dist/agent/durable/workflows/shared/reported-cost.d.ts +7 -0
  15. package/dist/agent/durable/workflows/shared/schemas.d.ts +16 -1
  16. package/dist/agent/durable/workflows/shared/tool-call-concurrency.d.ts +6 -0
  17. package/dist/agent/durable/workflows/steps/llm-execution.d.ts +5 -0
  18. package/dist/agent/durable/workflows/steps/llm-mapping.d.ts +6 -0
  19. package/dist/agent/durable/workflows/steps/tool-call.d.ts +20 -0
  20. package/dist/agent/index.cjs +2 -2
  21. package/dist/agent/index.js +2 -2
  22. package/dist/agent/request-context-snapshot.d.ts +3 -2
  23. package/dist/agent/streams/run-records.d.ts +9 -1
  24. package/dist/agent-builder/ee/index.cjs +1 -1
  25. package/dist/agent-builder/ee/index.js +1 -1
  26. package/dist/agent-controller/index.cjs +1 -1
  27. package/dist/agent-controller/index.js +1 -1
  28. package/dist/agent-controller/session-run-engine.d.ts +5 -2
  29. package/dist/agent-controller/session.d.ts +2 -0
  30. package/dist/agent-controller/types.d.ts +23 -0
  31. package/dist/{agent-controller-D5EKeS1H.js → agent-controller-B8LoFdtu.js} +43 -13
  32. package/dist/{agent-controller-D_5Dc8d3.cjs → agent-controller-DSnFynpa.cjs} +43 -13
  33. package/dist/background-tasks/index.cjs +1 -1
  34. package/dist/background-tasks/index.js +1 -1
  35. package/dist/background-tasks/manager.d.ts +4 -1
  36. package/dist/{background-tasks-BVxb0VGV.cjs → background-tasks-Ci5h0dhj.cjs} +139 -51
  37. package/dist/{background-tasks-idnlMbqD.js → background-tasks-IW7M4iD2.js} +139 -51
  38. package/dist/browser/index.cjs +1 -1
  39. package/dist/browser/index.js +1 -1
  40. package/dist/{builder-CBWoYNck.cjs → builder-14Uptu8y.cjs} +2 -2
  41. package/dist/{builder-Cuq-j2w3.js → builder-DI2c2xjy.js} +2 -2
  42. package/dist/cache/base.d.ts +40 -10
  43. package/dist/cache/index.cjs +1 -1
  44. package/dist/cache/index.js +1 -1
  45. package/dist/capabilities/302ai.json +200 -200
  46. package/dist/capabilities/abliteratedllm.json +34 -34
  47. package/dist/capabilities/abliteration-ai.json +8 -8
  48. package/dist/capabilities/above.json +24 -24
  49. package/dist/capabilities/adaption.json +15 -15
  50. package/dist/capabilities/adzuki.json +29 -29
  51. package/dist/capabilities/agentrouter.json +12 -12
  52. package/dist/capabilities/agnes.json +2 -2
  53. package/dist/capabilities/ai-router.json +5 -5
  54. package/dist/capabilities/aiand.json +25 -25
  55. package/dist/capabilities/aigrow.json +13 -13
  56. package/dist/capabilities/aimlapi.json +149 -152
  57. package/dist/capabilities/aixy.json +20 -20
  58. package/dist/capabilities/aki-io.json +10 -10
  59. package/dist/capabilities/alibaba-cn.json +85 -85
  60. package/dist/capabilities/alibaba-coding-plan-cn.json +5 -5
  61. package/dist/capabilities/alibaba-coding-plan.json +5 -5
  62. package/dist/capabilities/alibaba-token-plan-cn.json +44 -44
  63. package/dist/capabilities/alibaba-token-plan.json +47 -47
  64. package/dist/capabilities/alibaba.json +62 -62
  65. package/dist/capabilities/ambient.json +14 -14
  66. package/dist/capabilities/amd.json +8 -8
  67. package/dist/capabilities/anthropic.json +39 -39
  68. package/dist/capabilities/anyapi.json +13 -13
  69. package/dist/capabilities/apiko.json +5 -5
  70. package/dist/capabilities/arcee.json +11 -11
  71. package/dist/capabilities/augure.json +4 -4
  72. package/dist/capabilities/auriko.json +21 -21
  73. package/dist/capabilities/bailing.json +4 -4
  74. package/dist/capabilities/baseten.json +33 -33
  75. package/dist/capabilities/bee.json +5 -5
  76. package/dist/capabilities/berget.json +4 -4
  77. package/dist/capabilities/bothub.json +16 -16
  78. package/dist/capabilities/boundless.json +37 -37
  79. package/dist/capabilities/bumo.json +48 -48
  80. package/dist/capabilities/byteplus.json +25 -25
  81. package/dist/capabilities/cheapaimodel.json +5 -5
  82. package/dist/capabilities/cheapest-token.json +28 -28
  83. package/dist/capabilities/chutes.json +11 -14
  84. package/dist/capabilities/cline-pass.json +41 -41
  85. package/dist/capabilities/cloudcode.json +9 -9
  86. package/dist/capabilities/cloudferro-sherlock.json +4 -4
  87. package/dist/capabilities/cloudflare-workers-ai.json +18 -79
  88. package/dist/capabilities/commandcode.json +155 -155
  89. package/dist/capabilities/concentrate.json +279 -270
  90. package/dist/capabilities/cortecs.json +100 -100
  91. package/dist/capabilities/crossmodel.json +178 -178
  92. package/dist/capabilities/crusoe.json +9 -9
  93. package/dist/capabilities/daoxe.json +9 -9
  94. package/dist/capabilities/databricks.json +137 -137
  95. package/dist/capabilities/deepinfra.json +124 -61
  96. package/dist/capabilities/deepseek.json +3 -3
  97. package/dist/capabilities/digitalocean.json +113 -113
  98. package/dist/capabilities/dothoosh.json +32 -32
  99. package/dist/capabilities/doubleword.json +26 -26
  100. package/dist/capabilities/edenai.json +448 -473
  101. package/dist/capabilities/empiriolabs.json +163 -165
  102. package/dist/capabilities/engy.json +19 -19
  103. package/dist/capabilities/entrim.json +6 -6
  104. package/dist/capabilities/evroc.json +16 -16
  105. package/dist/capabilities/ezkielyna.json +12 -12
  106. package/dist/capabilities/fastrouter.json +73 -73
  107. package/dist/capabilities/fireworks-ai.json +83 -62
  108. package/dist/capabilities/freemodel.json +15 -15
  109. package/dist/capabilities/friendli.json +2 -2
  110. package/dist/capabilities/frogbot.json +99 -99
  111. package/dist/capabilities/gisoo.json +17 -17
  112. package/dist/capabilities/gmicloud.json +14 -14
  113. package/dist/capabilities/google.json +57 -57
  114. package/dist/capabilities/graphn.json +9 -9
  115. package/dist/capabilities/greenpt.json +36 -36
  116. package/dist/capabilities/groq.json +8 -8
  117. package/dist/capabilities/helicone.json +82 -82
  118. package/dist/capabilities/hopper.json +2 -2
  119. package/dist/capabilities/hostinger-router.json +10 -10
  120. package/dist/capabilities/hpc-ai.json +14 -14
  121. package/dist/capabilities/huawei-maas.json +16 -16
  122. package/dist/capabilities/hubris.json +29 -29
  123. package/dist/capabilities/huggingface.json +94 -84
  124. package/dist/capabilities/humain.json +2 -2
  125. package/dist/capabilities/hyper.json +23 -23
  126. package/dist/capabilities/impossibl.json +136 -136
  127. package/dist/capabilities/inception.json +2 -2
  128. package/dist/capabilities/inceptron.json +8 -8
  129. package/dist/capabilities/inco.json +2 -2
  130. package/dist/capabilities/infer.json +14 -14
  131. package/dist/capabilities/inferall.json +7 -7
  132. package/dist/capabilities/inference-coop.json +3 -3
  133. package/dist/capabilities/inferenceapis.json +20 -20
  134. package/dist/capabilities/inferris.json +3 -3
  135. package/dist/capabilities/infersia.json +8 -8
  136. package/dist/capabilities/inferx.json +3 -3
  137. package/dist/capabilities/infomaniak.json +2 -2
  138. package/dist/capabilities/io-net.json +4 -4
  139. package/dist/capabilities/isoquant.json +4 -4
  140. package/dist/capabilities/iteracompute.json +61 -61
  141. package/dist/capabilities/jalapeno.json +12 -12
  142. package/dist/capabilities/jiekou.json +60 -60
  143. package/dist/capabilities/joingonka.json +4 -4
  144. package/dist/capabilities/jzstoken.json +55 -55
  145. package/dist/capabilities/keln.json +25 -25
  146. package/dist/capabilities/kenari.json +122 -122
  147. package/dist/capabilities/kilo.json +633 -617
  148. package/dist/capabilities/kimi-code-plan-cn.json +6 -6
  149. package/dist/capabilities/kimi-code-plan-global.json +6 -6
  150. package/dist/capabilities/kitani.json +6 -6
  151. package/dist/capabilities/klavo.json +20 -20
  152. package/dist/capabilities/korouter.json +32 -32
  153. package/dist/capabilities/kunavo.json +9 -9
  154. package/dist/capabilities/liquid.json +12 -12
  155. package/dist/capabilities/lithosai.json +3 -3
  156. package/dist/capabilities/llmgateway-providers.json +912 -903
  157. package/dist/capabilities/llmgateway.json +346 -338
  158. package/dist/capabilities/llmtr.json +30 -30
  159. package/dist/capabilities/logits.json +2 -2
  160. package/dist/capabilities/lowrouter.json +53 -53
  161. package/dist/capabilities/lyceum.json +10 -10
  162. package/dist/capabilities/melious.json +12 -12
  163. package/dist/capabilities/merge-gateway.json +276 -276
  164. package/dist/capabilities/meta.json +10 -10
  165. package/dist/capabilities/mistral.json +21 -21
  166. package/dist/capabilities/mixlayer.json +2 -2
  167. package/dist/capabilities/modal.json +6 -6
  168. package/dist/capabilities/model-oracle-ai.json +25 -25
  169. package/dist/capabilities/modelis.json +15 -15
  170. package/dist/capabilities/modelscope.json +2 -2
  171. package/dist/capabilities/modular.json +6 -6
  172. package/dist/capabilities/moneo.json +14 -14
  173. package/dist/capabilities/moonshotai-cn.json +7 -7
  174. package/dist/capabilities/moonshotai.json +7 -7
  175. package/dist/capabilities/morph.json +16 -16
  176. package/dist/capabilities/munito-eu.json +6 -6
  177. package/dist/capabilities/munito.json +10 -10
  178. package/dist/capabilities/nan.json +24 -24
  179. package/dist/capabilities/nano-gpt.json +612 -579
  180. package/dist/capabilities/nearai.json +97 -97
  181. package/dist/capabilities/nebius.json +32 -32
  182. package/dist/capabilities/neon.json +131 -131
  183. package/dist/capabilities/neuralwatt.json +43 -43
  184. package/dist/capabilities/nokeep.json +4 -4
  185. package/dist/capabilities/novita-ai.json +148 -148
  186. package/dist/capabilities/nvidia.json +17 -49
  187. package/dist/capabilities/obscurify.json +26 -26
  188. package/dist/capabilities/oci.json +16 -7
  189. package/dist/capabilities/ofox.json +344 -344
  190. package/dist/capabilities/ollama-cloud.json +56 -56
  191. package/dist/capabilities/openai.json +81 -49
  192. package/dist/capabilities/opencode-go.json +90 -90
  193. package/dist/capabilities/openreason.json +5 -5
  194. package/dist/capabilities/openrouter.json +563 -547
  195. package/dist/capabilities/opper.json +29 -29
  196. package/dist/capabilities/orcarouter.json +252 -252
  197. package/dist/capabilities/outerlabs.json +33 -33
  198. package/dist/capabilities/ovhcloud.json +59 -5
  199. package/dist/capabilities/pareto.json +5 -5
  200. package/dist/capabilities/perplexity-agent.json +66 -66
  201. package/dist/capabilities/phala.json +30 -30
  202. package/dist/capabilities/pioneer.json +24 -24
  203. package/dist/capabilities/poe.json +117 -117
  204. package/dist/capabilities/poolside.json +2 -2
  205. package/dist/capabilities/powerspring.json +14 -14
  206. package/dist/capabilities/primalabs.json +11 -11
  207. package/dist/capabilities/prime.json +129 -113
  208. package/dist/capabilities/privatemode-ai.json +14 -14
  209. package/dist/capabilities/proxystacks.json +6 -6
  210. package/dist/capabilities/qiniu-ai.json +14 -14
  211. package/dist/capabilities/refuseless.json +5 -5
  212. package/dist/capabilities/regolo-ai.json +9 -9
  213. package/dist/capabilities/requesty.json +172 -172
  214. package/dist/capabilities/ruapi.json +18 -18
  215. package/dist/capabilities/runcrate.json +15 -15
  216. package/dist/capabilities/runinfra.json +16 -16
  217. package/dist/capabilities/sakana.json +6 -6
  218. package/dist/capabilities/sambanova.json +9 -9
  219. package/dist/capabilities/sandbase.json +21 -21
  220. package/dist/capabilities/sarvam.json +8 -8
  221. package/dist/capabilities/scaleway.json +18 -18
  222. package/dist/capabilities/scnet-token-plan.json +9 -9
  223. package/dist/capabilities/scx-ai.json +30 -30
  224. package/dist/capabilities/sensenova.json +8 -8
  225. package/dist/capabilities/siliconflow-cn.json +62 -62
  226. package/dist/capabilities/siliconflow.json +58 -58
  227. package/dist/capabilities/snowflake-cortex.json +22 -22
  228. package/dist/capabilities/sokkan.json +10 -10
  229. package/dist/capabilities/sparrowcodes.json +22 -22
  230. package/dist/capabilities/standardcompute.json +101 -101
  231. package/dist/capabilities/steadyrouter.json +43 -43
  232. package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
  233. package/dist/capabilities/stepfun-ai.json +5 -5
  234. package/dist/capabilities/stepfun-step-plan.json +5 -5
  235. package/dist/capabilities/stepfun.json +5 -5
  236. package/dist/capabilities/stepping-stone.json +22 -22
  237. package/dist/capabilities/subconscious.json +2 -2
  238. package/dist/capabilities/superbot-gg.json +4 -4
  239. package/dist/capabilities/synthetic.json +14 -14
  240. package/dist/capabilities/synthorai.json +22 -22
  241. package/dist/capabilities/teamorouter.json +23 -23
  242. package/dist/capabilities/teapot-router.json +16 -16
  243. package/dist/capabilities/tencent-token-plan.json +57 -33
  244. package/dist/capabilities/tencent-tokenhub.json +48 -48
  245. package/dist/capabilities/tensorx.json +46 -46
  246. package/dist/capabilities/tenstorrent.json +2 -2
  247. package/dist/capabilities/the-grid-ai.json +31 -31
  248. package/dist/capabilities/thinkingmachines.json +44 -44
  249. package/dist/capabilities/tinfoil.json +11 -11
  250. package/dist/capabilities/toapis.json +3 -3
  251. package/dist/capabilities/togetherai.json +53 -51
  252. package/dist/capabilities/tokengo.json +24 -24
  253. package/dist/capabilities/tokenify.json +10 -10
  254. package/dist/capabilities/trustedrouter.json +6 -6
  255. package/dist/capabilities/trustedtokens.json +16 -16
  256. package/dist/capabilities/umans-ai-coding-plan.json +15 -15
  257. package/dist/capabilities/umans-ai.json +9 -9
  258. package/dist/capabilities/unrestricted.json +8 -8
  259. package/dist/capabilities/uplinkswitch.json +21 -21
  260. package/dist/capabilities/upstage.json +6 -6
  261. package/dist/capabilities/vancine.json +21 -21
  262. package/dist/capabilities/vercel.json +578 -578
  263. package/dist/capabilities/vivgrid.json +81 -81
  264. package/dist/capabilities/volcengine-coding-plan.json +26 -26
  265. package/dist/capabilities/volcengine.json +27 -27
  266. package/dist/capabilities/vultr.json +25 -25
  267. package/dist/capabilities/wafer.ai.json +18 -18
  268. package/dist/capabilities/wallaby.json +5 -5
  269. package/dist/capabilities/wally.json +12 -12
  270. package/dist/capabilities/wandb.json +19 -19
  271. package/dist/capabilities/watt.json +22 -22
  272. package/dist/capabilities/xai.json +7 -7
  273. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -2
  274. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -2
  275. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -2
  276. package/dist/capabilities/xiaomi.json +2 -2
  277. package/dist/capabilities/xpersona.json +11 -11
  278. package/dist/capabilities/xxapi.json +32 -32
  279. package/dist/capabilities/zai-coding-plan.json +16 -16
  280. package/dist/capabilities/zai.json +34 -32
  281. package/dist/capabilities/zenifra.json +26 -26
  282. package/dist/capabilities/zenmux.json +187 -187
  283. package/dist/capabilities/zerogpu.json +13 -13
  284. package/dist/capabilities/zhipuai-coding-plan.json +7 -7
  285. package/dist/capabilities/zhipuai.json +29 -29
  286. package/dist/capabilities/zro.json +6 -6
  287. package/dist/channels/agent-channels.d.ts +2 -1
  288. package/dist/channels/formatting.d.ts +8 -0
  289. package/dist/channels/index.cjs +4 -2
  290. package/dist/channels/index.d.ts +1 -1
  291. package/dist/channels/index.js +3 -3
  292. package/dist/channels/types.d.ts +5 -3
  293. package/dist/{channels-DSOCNoab.js → channels-Wh32drgu.js} +1 -1
  294. package/dist/{channels-D7bBM9xD.cjs → channels-tVV_de9Q.cjs} +1 -1
  295. package/dist/coding-agent/index.cjs +1 -1
  296. package/dist/coding-agent/index.js +1 -1
  297. package/dist/datasets/index.cjs +2 -2
  298. package/dist/datasets/index.js +2 -2
  299. package/dist/docs/SKILL.md +1 -1
  300. package/dist/docs/assets/SOURCE_MAP.json +789 -789
  301. package/dist/docs/references/docs-agents-resumable-streams.md +15 -6
  302. package/dist/docs/references/docs-deployment-workers.md +3 -1
  303. package/dist/docs/references/docs-harness-background-tasks.md +4 -4
  304. package/dist/docs/references/docs-harness-durable-agents.md +39 -48
  305. package/dist/docs/references/docs-knowledge-importers.md +1 -1
  306. package/dist/docs/references/docs-mastra-platform-observability-overview.md +1 -1
  307. package/dist/docs/references/docs-sandbox-overview.md +1 -0
  308. package/dist/docs/references/docs-server-pubsub.md +1 -1
  309. package/dist/docs/references/docs-workflows-overview.md +67 -3
  310. package/dist/docs/references/integrations-agentic-ui-assistant-ui.md +2 -0
  311. package/dist/docs/references/integrations-frameworks-angular.md +39 -0
  312. package/dist/docs/references/integrations-frameworks-astro.md +5 -2
  313. package/dist/docs/references/integrations-frameworks-electron.md +40 -0
  314. package/dist/docs/references/integrations-frameworks-next-js.md +5 -2
  315. package/dist/docs/references/integrations-frameworks-nuxt.md +5 -2
  316. package/dist/docs/references/integrations-frameworks-sveltekit.md +5 -2
  317. package/dist/docs/references/integrations-frameworks-vite-react.md +40 -0
  318. package/dist/docs/references/integrations.md +3 -0
  319. package/dist/docs/references/reference-agent-controller-agent-controller-class.md +6 -0
  320. package/dist/docs/references/reference-agents-channels.md +1 -1
  321. package/dist/docs/references/reference-agents-durable-agent.md +3 -3
  322. package/dist/docs/references/reference-agents-generate.md +2 -0
  323. package/dist/docs/references/reference-configuration.md +1 -1
  324. package/dist/docs/references/reference-core-mastra-class.md +2 -0
  325. package/dist/docs/references/reference-knowledge-knowledge-class.md +1 -1
  326. package/dist/docs/references/reference-knowledge-knowledge-tools.md +11 -5
  327. package/dist/docs/references/reference-pubsub-caching-pubsub.md +2 -2
  328. package/dist/docs/references/reference-pubsub-redis-streams.md +2 -2
  329. package/dist/docs/references/reference-pubsub-valkey-streams.md +2 -2
  330. package/dist/docs/references/reference-workers-overview.md +2 -0
  331. package/dist/docs/references/reference-workflows-workflow-methods-create-run.md +2 -0
  332. package/dist/docs/references/reference-workflows-workflow.md +2 -0
  333. package/dist/docs/references/reference.md +1 -0
  334. package/dist/error/index.cjs +2 -1
  335. package/dist/error/index.d.ts +1 -1
  336. package/dist/error/index.js +2 -2
  337. package/dist/error/provider-error.d.ts +2 -1
  338. package/dist/{error-BLwEXqOK.js → error-BC9Au-22.js} +13 -1
  339. package/dist/{error-BdEvO8za.cjs → error-L1V4uUbd.cjs} +18 -0
  340. package/dist/evals/index.cjs +1 -1
  341. package/dist/evals/index.js +1 -1
  342. package/dist/evals/scoreTraces/index.cjs +1 -1
  343. package/dist/evals/scoreTraces/index.js +1 -1
  344. package/dist/events/caching-pubsub.d.ts +28 -0
  345. package/dist/events/index.cjs +4 -1
  346. package/dist/events/index.js +2 -2
  347. package/dist/events/topics.d.ts +55 -9
  348. package/dist/harness/index.cjs +1 -1
  349. package/dist/harness/index.js +1 -1
  350. package/dist/index.cjs +1 -1
  351. package/dist/index.js +1 -1
  352. package/dist/{inmemory-BDD0w8gx.js → inmemory-BK3zLwvM.js} +42 -12
  353. package/dist/{inmemory-fgR8sq-U.cjs → inmemory-Dc86VWGB.cjs} +42 -12
  354. package/dist/knowledge/changes.d.ts +17 -5
  355. package/dist/knowledge/importers/runner.d.ts +6 -0
  356. package/dist/knowledge/index.cjs +78 -16
  357. package/dist/knowledge/index.d.ts +2 -2
  358. package/dist/knowledge/index.js +78 -16
  359. package/dist/knowledge/search-snippet.d.ts +30 -0
  360. package/dist/llm/index.cjs +3 -3
  361. package/dist/llm/index.js +3 -3
  362. package/dist/llm/model/provider-types.generated.d.ts +7986 -7970
  363. package/dist/{llm-DMNEZIV9.js → llm-B1zaFLYZ.js} +3 -3
  364. package/dist/{llm-BOQR5g0t.cjs → llm-BAiOsNAP.cjs} +3 -3
  365. package/dist/loop/index.cjs +2 -2
  366. package/dist/loop/index.js +2 -2
  367. package/dist/{manager-CyCR9IpR.cjs → manager-BVX9nVrM.cjs} +2 -2
  368. package/dist/{manager-BzNynLwT.js → manager-ChK9GdGz.js} +2 -2
  369. package/dist/mastra/index.cjs +1 -1
  370. package/dist/mastra/index.js +1 -1
  371. package/dist/{mastra-CqBmnzjM.js → mastra-CUGfgEpZ.js} +28 -18
  372. package/dist/{mastra-D2B01_gg.cjs → mastra-HSmofHEJ.cjs} +28 -18
  373. package/dist/memory/index.cjs +2 -2
  374. package/dist/memory/index.js +2 -2
  375. package/dist/{model-3AeJKHLU.js → model-C47BJRtR.js} +1 -1
  376. package/dist/{model-CrXDhcbw.cjs → model-WahorgzJ.cjs} +1 -1
  377. package/dist/{netlify-DUPSTzi6.js → netlify-CfDXkuLf.js} +2 -2
  378. package/dist/{netlify-DTXLQiG1.cjs → netlify-D99AnEhW.cjs} +2 -2
  379. package/dist/notifications/index.cjs +1 -1
  380. package/dist/notifications/index.js +1 -1
  381. package/dist/observability/index.cjs +1 -0
  382. package/dist/observability/index.d.ts +1 -1
  383. package/dist/observability/index.js +2 -2
  384. package/dist/{output-helpers-CedRCE17.js → output-helpers-CVzhy1Y0.js} +126 -56
  385. package/dist/{output-helpers-1Zu4Vt9C.cjs → output-helpers-DgsH4aTb.cjs} +143 -55
  386. package/dist/processor-provider/index.cjs +1 -1
  387. package/dist/processor-provider/index.js +1 -1
  388. package/dist/processors/index.cjs +2 -2
  389. package/dist/processors/index.js +2 -2
  390. package/dist/processors/runner.d.ts +2 -0
  391. package/dist/{provider-registry-B_rC-5aL.cjs → provider-registry-CO1NVbO5.cjs} +22281 -22258
  392. package/dist/{provider-registry-BeB8RQO8.js → provider-registry-CR385GJ4.js} +22281 -22258
  393. package/dist/provider-registry.json +22871 -22855
  394. package/dist/{registry-generator-Cv6GnxLG.js → registry-generator-B3erRqYS.js} +1 -1
  395. package/dist/{registry-generator-DbBoIOby.cjs → registry-generator-Cvp34qcB.cjs} +1 -1
  396. package/dist/{rehydrate-3f-i1Ga2.js → rehydrate-CJBLrZxs.js} +2 -2
  397. package/dist/{rehydrate-BWaa2eGN.cjs → rehydrate-Da4hNuaK.cjs} +2 -2
  398. package/dist/relevance/index.cjs +2 -2
  399. package/dist/relevance/index.js +2 -2
  400. package/dist/{run-registry-Bx06ZIN_.js → run-registry-DdeEBsVW.js} +1639 -568
  401. package/dist/{run-registry-Bk6QxNE4.cjs → run-registry-TOOfO3hT.cjs} +1668 -567
  402. package/dist/storage/domains/inmemory-db.d.ts +1 -0
  403. package/dist/storage/domains/knowledge/base.d.ts +5 -0
  404. package/dist/storage/domains/knowledge/inmemory.d.ts +1 -0
  405. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +10 -2
  406. package/dist/storage/domains/knowledge/pages.d.ts +30 -0
  407. package/dist/storage/index.cjs +2 -2
  408. package/dist/storage/index.js +2 -2
  409. package/dist/storage/run-fencing.d.ts +5 -0
  410. package/dist/stream/index.cjs +2 -2
  411. package/dist/stream/index.js +2 -2
  412. package/dist/{stream-DVy0Z-m0.js → stream-C5PagEDs.js} +3 -3
  413. package/dist/{stream-BIXX67WE.cjs → stream-DH7Qgz8l.cjs} +3 -3
  414. package/dist/test-utils/llm-mock.cjs +1 -1
  415. package/dist/test-utils/llm-mock.js +1 -1
  416. package/dist/tool-loop-agent/index.cjs +1 -1
  417. package/dist/tool-loop-agent/index.js +1 -1
  418. package/dist/{tool-loop-agent-DDeKGwtr.cjs → tool-loop-agent-CJTs4T8b.cjs} +3 -3
  419. package/dist/{tool-loop-agent-PSKeNhuT.js → tool-loop-agent-DVYJXlQJ.js} +3 -3
  420. package/dist/{utils-BJiQF8Pi.js → utils-D8upuTwy.js} +1 -1
  421. package/dist/{utils-CAnUlnUm.cjs → utils-xJi_N6Tx.cjs} +1 -1
  422. package/dist/utils.cjs +1 -1
  423. package/dist/utils.js +1 -1
  424. package/dist/{validate-BMNxfs4Z.cjs → validate-6eZ8Wssn.cjs} +1 -1
  425. package/dist/{validate-BAVwAgtT.js → validate-DTkW3Vlp.js} +1 -1
  426. package/dist/vector/index.cjs +1 -1
  427. package/dist/vector/index.js +1 -1
  428. package/dist/worker/index.cjs +1 -1
  429. package/dist/worker/index.js +1 -1
  430. package/dist/{worker-CFUKBBCF.cjs → worker-24ORi-wV.cjs} +2 -2
  431. package/dist/{worker-Brwa-HqM.cjs → worker-BO3u_WjZ.cjs} +2 -2
  432. package/dist/{worker-BlvJM_Hu.js → worker-DbcFkKJO.js} +2 -2
  433. package/dist/{worker-CVoD3tts.js → worker-Dqubrnf8.js} +2 -2
  434. package/dist/{workflow-zvQGBMCM.cjs → workflow-D5Fc5ieC.cjs} +4 -4
  435. package/dist/{workflow-BSLS7_vB.js → workflow-wXOf72fO.js} +4 -4
  436. package/dist/workflows/builder/index.cjs +1 -1
  437. package/dist/workflows/builder/index.js +1 -1
  438. package/dist/workflows/evented/index.cjs +1 -1
  439. package/dist/workflows/evented/index.js +1 -1
  440. package/dist/workflows/index.cjs +4 -4
  441. package/dist/workflows/index.js +4 -4
  442. package/dist/workflows/run-ownership.d.ts +74 -8
  443. package/dist/workflows/types.d.ts +16 -0
  444. package/dist/workflows/workflow.d.ts +4 -0
  445. package/package.json +6 -6
  446. package/src/llm/model/provider-types.generated.d.ts +7986 -7970
@@ -3,15 +3,15 @@ const require_logger = require("./logger-CvzZYuJd.cjs");
3
3
  const require_base = require("./base-BIzR1D3_.cjs");
4
4
  const require_observability = require("./observability-B0R_D1PZ.cjs");
5
5
  const require_error = require("./error-D90lJ6M7.cjs");
6
- const require_error$1 = require("./error-BdEvO8za.cjs");
7
- const require_stream = require("./stream-BIXX67WE.cjs");
6
+ const require_error$1 = require("./error-L1V4uUbd.cjs");
7
+ const require_stream = require("./stream-DH7Qgz8l.cjs");
8
8
  const require_request_context = require("./request-context-D9RXYCy8.cjs");
9
- const require_output_helpers = require("./output-helpers-1Zu4Vt9C.cjs");
9
+ const require_output_helpers = require("./output-helpers-DgsH4aTb.cjs");
10
10
  const require_message_list = require("./message-list-Cj0Sq_JP.cjs");
11
11
  const require_storage = require("./storage-CfG0I2aF.cjs");
12
12
  const require_utils = require("./utils-D-eNsgDM.cjs");
13
13
  const require_error_count = require("./error-count-DeDpeWU2.cjs");
14
- const require_llm = require("./llm-BOQR5g0t.cjs");
14
+ const require_llm = require("./llm-BAiOsNAP.cjs");
15
15
  const require_payload_transform = require("./payload-transform-CWgnsO9w.cjs");
16
16
  const require_utils_safe_stringify = require("./utils/safe-stringify.cjs");
17
17
  const require_signals = require("./signals-CWxAMEmE.cjs");
@@ -23,13 +23,13 @@ const require_tool = require("./tool-CYlT2UA-.cjs");
23
23
  const require_toolchecks = require("./toolchecks-MFU48cit.cjs");
24
24
  const require_fetchWithRetry = require("./fetchWithRetry-f5k4p7_1.cjs");
25
25
  const require_model = require("./model-jBymoqGa.cjs");
26
- const require_provider_registry = require("./provider-registry-B_rC-5aL.cjs");
27
- const require_inmemory = require("./inmemory-fgR8sq-U.cjs");
26
+ const require_provider_registry = require("./provider-registry-CO1NVbO5.cjs");
27
+ const require_inmemory = require("./inmemory-Dc86VWGB.cjs");
28
28
  const require_dynamic_argument = require("./dynamic-argument-CUc1BBOS.cjs");
29
- const require_model$1 = require("./model-CrXDhcbw.cjs");
30
- const require_utils$1 = require("./utils-CAnUlnUm.cjs");
29
+ const require_model$1 = require("./model-WahorgzJ.cjs");
30
+ const require_utils$1 = require("./utils-xJi_N6Tx.cjs");
31
31
  const require_ee_iTj2bRDt = require("./ee-iTj2bRDt-D3-QLGDF.cjs");
32
- const require_background_tasks = require("./background-tasks-BVxb0VGV.cjs");
32
+ const require_background_tasks = require("./background-tasks-Ci5h0dhj.cjs");
33
33
  const require_stream$1 = require("./stream-BGbj9jAU.cjs");
34
34
  const require_predicate_index = require("./predicate/index.cjs");
35
35
  const require_classifier_index = require("./classifier/index.cjs");
@@ -194,6 +194,46 @@ function currentRunGeneration(runId) {
194
194
  function resolveRunFence(store, fence, runId) {
195
195
  return fence ?? getRunFenceContext()?.current()?.fenceFor(store, runId);
196
196
  }
197
+ // src/storage/workflow-step-guard.ts
198
+ var WorkflowStepConflictError = class extends Error {
199
+ reason;
200
+ storedResult;
201
+ storedRequestContext;
202
+ storedSnapshot;
203
+ code = "WORKFLOW_STEP_CONFLICT";
204
+ constructor(reason, storedResult, storedRequestContext, storedSnapshot) {
205
+ super(`Workflow step delivery rejected (${reason}).`);
206
+ this.reason = reason;
207
+ this.storedResult = storedResult;
208
+ this.storedRequestContext = storedRequestContext;
209
+ this.storedSnapshot = storedSnapshot;
210
+ }
211
+ };
212
+ function isWorkflowStepConflictError(error) {
213
+ return typeof error === "object" && error !== null && "code" in error && error.code === "WORKFLOW_STEP_CONFLICT";
214
+ }
215
+ /** Call inside the adapter's snapshot lock, before mutating results, state, or request context. */
216
+ function assertWorkflowStepGuard({ snapshot, stepId, startGuard, completionGuard }) {
217
+ if (!startGuard && !completionGuard) return;
218
+ if (!snapshot) throw new WorkflowStepConflictError("missing");
219
+ const stored = snapshot.context[stepId];
220
+ const startedBy = stored?.metadata?.startedBy;
221
+ if (stored && !startedBy) return;
222
+ if (startedBy === (startGuard ?? completionGuard).eventId) {
223
+ if (completionGuard?.pruneOnly) {
224
+ if (stored?.status === "success") return;
225
+ throw new WorkflowStepConflictError("stale", stored);
226
+ }
227
+ if (stored?.status === "running") return;
228
+ if (stored?.metadata?.__continuationStarted) throw new WorkflowStepConflictError("stale", stored);
229
+ throw new WorkflowStepConflictError("completed", stored, snapshot.requestContext, snapshot);
230
+ }
231
+ if (startGuard) {
232
+ if (!stored && startGuard.expectedStartedBy === void 0) return;
233
+ if (stored && (stored.status !== "running" || stored.metadata?.__restartPending === true) && startedBy === startGuard.expectedStartedBy) return;
234
+ }
235
+ throw new WorkflowStepConflictError("stale", stored);
236
+ }
197
237
  // src/stream/aisdk/v5/compat/prepare-tools.ts
198
238
  /**
199
239
  * Recursively fixes JSON Schema properties that lack a 'type' key.
@@ -2552,6 +2592,340 @@ function markFrameworkCondition(condition) {
2552
2592
  function isFrameworkCondition(condition) {
2553
2593
  return typeof condition === "function" && condition[FRAMEWORK_CONDITION] === true;
2554
2594
  }
2595
+ // src/agent/durable/run-fence-scope.ts
2596
+ const runFenceScope = new async_hooks.AsyncLocalStorage();
2597
+ const runFenceContext = setRunFenceContext({
2598
+ current: () => runFenceScope.getStore(),
2599
+ run: (scope, fn) => runFenceScope.run(scope, fn)
2600
+ });
2601
+ /**
2602
+ * Run `fn` with `scope` supplying the fence of every storage write it makes,
2603
+ * including writes from processors, tools and memory that never see the fence.
2604
+ */
2605
+ function runInRunFenceScope(scope, fn) {
2606
+ return runFenceContext.run(scope, fn);
2607
+ }
2608
+ /** The scope installed for the current async context, if any. */
2609
+ function currentRunFenceScope() {
2610
+ return runFenceContext.current();
2611
+ }
2612
+ // src/agent/run-ownership.ts
2613
+ /**
2614
+ * TTL for the cross-process leases that mark a live process driving an agent
2615
+ * thread or durable run. Kept short so a crashed owner frees the run quickly;
2616
+ * owners renew while they work. Overridable via
2617
+ * `MASTRA_AGENT_THREAD_LEASE_TTL_MS` (production keeps the 15s default).
2618
+ */
2619
+ const AGENT_LEASE_TTL_MS = require_utils$1.readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_TTL_MS", 15e3);
2620
+ const DEFAULT_RENEW_INTERVAL_MS = Math.max(1, Math.floor(AGENT_LEASE_TTL_MS / 3));
2621
+ const configuredRenewIntervalMs = require_utils$1.readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_RENEW_INTERVAL_MS", DEFAULT_RENEW_INTERVAL_MS);
2622
+ /**
2623
+ * Interval at which an owner renews its lease. Defaults to TTL/3, leaving room
2624
+ * for two missed renewals (network blip, GC pause) before the lease expires.
2625
+ * Overridable via `MASTRA_AGENT_THREAD_LEASE_RENEW_INTERVAL_MS`; a value not
2626
+ * shorter than the TTL would let the lease expire before its first renewal, so
2627
+ * it falls back to the default.
2628
+ */
2629
+ const AGENT_LEASE_RENEW_INTERVAL_MS = configuredRenewIntervalMs < AGENT_LEASE_TTL_MS ? configuredRenewIntervalMs : DEFAULT_RENEW_INTERVAL_MS;
2630
+ /**
2631
+ * How long a run that lost its thread lease lets a tool call that is already running go on before stopping it.
2632
+ * The thread's new owner may be working meanwhile, so a tool that never returns must not keep the old run going for
2633
+ * long. Overridable via `MASTRA_AGENT_THREAD_LEASE_LOST_TOOL_GRACE_MS`.
2634
+ */
2635
+ const AGENT_LEASE_LOST_TOOL_GRACE_MS = require_utils$1.readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_LOST_TOOL_GRACE_MS", 3e5);
2636
+ // src/workflows/run-ownership.ts
2637
+ const WORKFLOW_RUN_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
2638
+ const WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
2639
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
2640
+ const MAX_LEASE_MS = 3 * MAX_TIMER_DELAY_MS;
2641
+ /** The longest `leaseTtlMs`, so that even after every doubling the lease stays within {@link MAX_LEASE_MS}. */
2642
+ const MAX_WORKFLOW_RUN_LEASE_TTL_MS = Math.floor(MAX_LEASE_MS / 8);
2643
+ /**
2644
+ * The shortest `leaseTtlMs`. A run renews every third of its lease with one storage write, and
2645
+ * `createRun()` options can come from a request body, so a tiny value must not set that rate.
2646
+ */
2647
+ const MIN_WORKFLOW_RUN_LEASE_TTL_MS = 1e3;
2648
+ /**
2649
+ * `leaseTtlMs` as configured, rounded up to whole milliseconds and kept between
2650
+ * {@link MIN_WORKFLOW_RUN_LEASE_TTL_MS} and {@link MAX_WORKFLOW_RUN_LEASE_TTL_MS}, or `fallback`
2651
+ * when it is not a positive finite number. `fallback` is used as is, so the default lease from
2652
+ * `MASTRA_AGENT_THREAD_LEASE_TTL_MS` can be shorter than the minimum.
2653
+ */
2654
+ function normalizeLeaseTtlMs(leaseTtlMs, fallback) {
2655
+ if (typeof leaseTtlMs !== "number" || !Number.isFinite(leaseTtlMs) || leaseTtlMs <= 0) return fallback;
2656
+ return Math.min(Math.max(Math.ceil(leaseTtlMs), MIN_WORKFLOW_RUN_LEASE_TTL_MS), MAX_WORKFLOW_RUN_LEASE_TTL_MS);
2657
+ }
2658
+ /** How often a lease of `leaseMs` is renewed: a third of it, or the configured interval for the default lease. */
2659
+ function renewIntervalFor(leaseMs) {
2660
+ if (leaseMs === WORKFLOW_RUN_LEASE_TTL_MS) return WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS;
2661
+ return Math.min(Math.max(1, Math.floor(leaseMs / 3)), MAX_TIMER_DELAY_MS);
2662
+ }
2663
+ /**
2664
+ * The lease a restart claims a run with. After a lease that lapsed without being released, its
2665
+ * last owner stopped renewing (it crashed, or blocked its event loop past the lease), so the
2666
+ * restart doubles that lease to give a step that blocks the same way room to finish. The previous
2667
+ * length is the owners row's `leaseExpiresAt - updatedAt`, which stores write in one statement.
2668
+ * Stores that read their clock twice there can come out a few milliseconds short; the result
2669
+ * never drops below `baseMs` or the previous length, so that only trims the doubling.
2670
+ */
2671
+ function leaseAfterTakeover(baseMs, previous) {
2672
+ if (!previous?.leaseExpiresAt || previous.live || !previous.updatedAt) return { leaseMs: baseMs };
2673
+ const previousLeaseMs = previous.leaseExpiresAt.getTime() - previous.updatedAt.getTime();
2674
+ if (!(previousLeaseMs > 0)) return { leaseMs: baseMs };
2675
+ const capMs = baseMs * 8;
2676
+ const leaseMs = Math.max(baseMs, previousLeaseMs, Math.min(previousLeaseMs * 2, capMs));
2677
+ return {
2678
+ leaseMs: Math.min(leaseMs, MAX_LEASE_MS),
2679
+ previousLeaseMs
2680
+ };
2681
+ }
2682
+ let lastStallWarningAt = -Infinity;
2683
+ /** The handle of a run that holds no claim: saves stay unfenced and nothing is released. */
2684
+ const UNCLAIMED_WORKFLOW_RUN = {
2685
+ release: async () => {},
2686
+ run: (_runId, fn) => fn()
2687
+ };
2688
+ /**
2689
+ * Runs `tick` `intervalMs` after it starts, then again `intervalMs` after
2690
+ * each run of it settles, until the returned function is called. A tick that
2691
+ * is running when the chain is stopped finishes, and nothing runs after it.
2692
+ * Every tick runs in the async context this function was called in, and the
2693
+ * timer is unref'd. `tick` reports its own failures and must not reject.
2694
+ *
2695
+ * `intervalMs` can be a function, read before each wait, for a delay that
2696
+ * follows what the last tick saw. With `immediately`, the first tick runs at
2697
+ * once instead of after the first wait.
2698
+ */
2699
+ function repeatAfterSettled(tick, intervalMs, { immediately = false } = {}) {
2700
+ let stopped = false;
2701
+ let timer;
2702
+ const arm = () => {
2703
+ timer = setTimeout(() => void run(), typeof intervalMs === "number" ? intervalMs : intervalMs());
2704
+ timer.unref?.();
2705
+ };
2706
+ const run = async () => {
2707
+ try {
2708
+ await tick();
2709
+ } finally {
2710
+ if (!stopped) {
2711
+ const { refresh } = timer ?? {};
2712
+ if (refresh && typeof intervalMs === "number") refresh.call(timer);
2713
+ else arm();
2714
+ }
2715
+ }
2716
+ };
2717
+ if (immediately) run();
2718
+ else arm();
2719
+ return () => {
2720
+ stopped = true;
2721
+ clearTimeout(timer);
2722
+ };
2723
+ }
2724
+ /**
2725
+ * Renews the lease `fence` holds, `leaseMs` long, every third of it (every
2726
+ * {@link WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS} for the default lease) until
2727
+ * the returned function is called, counting each interval from the end of the
2728
+ * previous renewal. Stops by itself after the first renewal that finds the
2729
+ * claim superseded, reporting it through `onLost`.
2730
+ *
2731
+ * When a renewal, or the returned function, finds that a lease length passed
2732
+ * since the last renewal (or the claim, sent at `since`) that succeeded, the
2733
+ * lease may have lapsed meanwhile: that is reported through `onStall`, once
2734
+ * per stall in this process. Gaps after a failed renewal are left to `onError`.
2735
+ */
2736
+ function renewWorkflowLease({ store, fence, leaseMs = WORKFLOW_RUN_LEASE_TTL_MS, since = Date.now(), onLost, onError, onStall }) {
2737
+ const intervalMs = renewIntervalFor(leaseMs);
2738
+ let renewedAt = since;
2739
+ let inFlightSince;
2740
+ let failing = false;
2741
+ let lost = false;
2742
+ const checkStall = (sentAt) => {
2743
+ const now = Date.now();
2744
+ if (!onStall || failing || lost || now - sentAt < leaseMs || sentAt < lastStallWarningAt) return;
2745
+ lastStallWarningAt = now;
2746
+ onStall(now - sentAt);
2747
+ };
2748
+ const stop = repeatAfterSettled(async () => {
2749
+ checkStall(renewedAt);
2750
+ const sentAt = inFlightSince = Date.now();
2751
+ try {
2752
+ const result = await store.renewRunOwnership({
2753
+ ...fence,
2754
+ leaseMs
2755
+ });
2756
+ failing = false;
2757
+ if (result.renewed) {
2758
+ renewedAt = sentAt;
2759
+ return;
2760
+ }
2761
+ lost = true;
2762
+ stop();
2763
+ onLost(result.record);
2764
+ } catch (error) {
2765
+ failing = true;
2766
+ onError(error);
2767
+ } finally {
2768
+ inFlightSince = void 0;
2769
+ }
2770
+ }, intervalMs);
2771
+ return () => {
2772
+ checkStall(inFlightSince ?? renewedAt);
2773
+ stop();
2774
+ };
2775
+ }
2776
+ /**
2777
+ * Marks this process as the live driver of a workflow run through the storage
2778
+ * run-ownership lease (the one durable agents use), renewing it while the run
2779
+ * executes. The lease tells the recovery sweep on other replicas that the run
2780
+ * is not orphaned, and saves made inside {@link WorkflowRunOwnership.run} carry
2781
+ * it, so a process that lost the run can't overwrite the new owner's saves.
2782
+ *
2783
+ * Returns the current owner record instead of a handle when `force` is off and
2784
+ * another execution holds a live lease. Stores without run fencing get a no-op
2785
+ * handle, keeping their previous behaviour.
2786
+ *
2787
+ * The lease is `leaseMs` long. With `backOff`, a claim over a lease that lapsed
2788
+ * takes a longer one (see {@link leaseAfterTakeover}).
2789
+ */
2790
+ async function claimWorkflowRunOwnership({ store, runId, force, logger, leaseMs: baseLeaseMs = WORKFLOW_RUN_LEASE_TTL_MS, backOff = false }) {
2791
+ if (!store || !await store.supportsRunFencing()) return UNCLAIMED_WORKFLOW_RUN;
2792
+ let previous = null;
2793
+ if (backOff) try {
2794
+ previous = await store.getRunOwnership({ runId });
2795
+ } catch (error) {
2796
+ logger?.debug("Failed to read the previous workflow run ownership lease", {
2797
+ runId,
2798
+ error
2799
+ });
2800
+ }
2801
+ const { leaseMs, previousLeaseMs } = leaseAfterTakeover(baseLeaseMs, previous);
2802
+ const claimedAt = Date.now();
2803
+ const claim = await store.claimRunOwnership({
2804
+ runId,
2805
+ ownerId: crypto.randomUUID(),
2806
+ leaseMs,
2807
+ force
2808
+ });
2809
+ if (!claim.acquired) return { owner: claim.record };
2810
+ 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.", {
2811
+ runId,
2812
+ previousLeaseMs,
2813
+ leaseMs
2814
+ });
2815
+ const fence = {
2816
+ runId,
2817
+ generation: claim.record.generation,
2818
+ ownerId: claim.record.ownerId
2819
+ };
2820
+ const stopRenewing = renewWorkflowLease({
2821
+ store,
2822
+ fence,
2823
+ leaseMs,
2824
+ since: claimedAt,
2825
+ 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.`, {
2826
+ runId,
2827
+ sinceRenewalMs,
2828
+ leaseMs
2829
+ }),
2830
+ onLost: (owner) => {
2831
+ if (matchesRunFence(owner, fence) && owner?.leaseExpiresAt === null) return;
2832
+ logger?.warn("Lost the ownership lease of a running workflow run; another process may now recover it", {
2833
+ runId,
2834
+ owner: owner?.ownerId
2835
+ });
2836
+ },
2837
+ onError: (error) => logger?.warn("Failed to renew workflow run ownership lease", {
2838
+ runId,
2839
+ error
2840
+ })
2841
+ });
2842
+ const claimState = {
2843
+ store,
2844
+ fence,
2845
+ logger,
2846
+ nestedRunIds: /* @__PURE__ */ new Set(),
2847
+ refused: false
2848
+ };
2849
+ return {
2850
+ release: async () => {
2851
+ stopRenewing();
2852
+ try {
2853
+ await store.releaseRunOwnership(fence);
2854
+ } catch (error) {
2855
+ logger?.warn("Failed to release workflow run ownership lease", {
2856
+ runId,
2857
+ error
2858
+ });
2859
+ }
2860
+ },
2861
+ run: (target, fn) => {
2862
+ if (target !== runId) claimState.nestedRunIds.add(target);
2863
+ return runInRunFenceScope(new WorkflowRunClaimScope(claimState, currentRunFenceScope()), fn);
2864
+ }
2865
+ };
2866
+ }
2867
+ /**
2868
+ * The fence scope of a workflow run claim. Saves to the claimed run and the nested runs it covers
2869
+ * carry the claim; everything else (other runs, memory) goes to the scope it was installed in,
2870
+ * such as a durable agent running the workflow or an enclosing workflow run.
2871
+ */
2872
+ var WorkflowRunClaimScope = class {
2873
+ claim;
2874
+ outer;
2875
+ constructor(claim, outer) {
2876
+ this.claim = claim;
2877
+ this.outer = outer;
2878
+ }
2879
+ covers(runId) {
2880
+ return runId === this.claim.fence.runId || this.claim.nestedRunIds.has(runId);
2881
+ }
2882
+ fenceFor(store, runId) {
2883
+ if (runId === void 0 || !this.covers(runId)) return this.outer?.fenceFor(store, runId);
2884
+ if (store !== this.claim.store) this.claim.logger?.error("A workflow run saved to a different store than the one holding its lease", { runId });
2885
+ return this.claim.fence;
2886
+ }
2887
+ onConflict(fence) {
2888
+ if (!matchesRunFence(this.claim.fence, fence)) return this.outer?.onConflict?.(fence);
2889
+ if (this.claim.refused) return;
2890
+ this.claim.refused = true;
2891
+ this.claim.logger?.warn("Stopped driving a workflow run that another process took over; its saves are refused", {
2892
+ runId: fence.runId,
2893
+ generation: fence.generation
2894
+ });
2895
+ }
2896
+ coverNestedRun(parentRunId, nestedRunId) {
2897
+ if (this.covers(parentRunId)) this.claim.nestedRunIds.add(nestedRunId);
2898
+ else this.outer?.coverNestedRun?.(parentRunId, nestedRunId);
2899
+ }
2900
+ generationFor(runId) {
2901
+ return this.covers(runId) ? this.claim.fence.generation : this.outer?.generationFor?.(runId);
2902
+ }
2903
+ };
2904
+ /** The fence of the `RunFenceConflictError` in `error` or its cause chain, if there is one. */
2905
+ function runFenceConflictOf(error) {
2906
+ let current = error;
2907
+ for (let depth = 0; depth < 8 && current && typeof current === "object"; depth++) {
2908
+ const { id, code, details } = current;
2909
+ if ((id === "STORAGE_RUN_FENCE_CONFLICT" || code === "STORAGE_RUN_FENCE_CONFLICT") && details?.runId !== void 0) return details;
2910
+ current = current.cause;
2911
+ }
2912
+ }
2913
+ /**
2914
+ * Whether storage refused `error`'s save because the claim the current fence scope holds was
2915
+ * replaced, so this execution lost its run. A conflict on another run (one a step started) is not.
2916
+ */
2917
+ function isOwnRunFenceConflict(error) {
2918
+ const fence = runFenceConflictOf(error);
2919
+ return !!fence && currentRunGeneration(fence.runId) === fence.generation;
2920
+ }
2921
+ /**
2922
+ * Makes the saves of `nestedRunId` carry the claim of the workflow run execution this runs in, when
2923
+ * that claim covers `parentRunId`. Unlike `coverNestedRun`, it leaves a durable agent's fence alone.
2924
+ */
2925
+ function coverNestedWorkflowRun(parentRunId, nestedRunId) {
2926
+ const scope = currentRunFenceScope();
2927
+ if (scope instanceof WorkflowRunClaimScope && scope.covers(parentRunId)) scope.claim.nestedRunIds.add(nestedRunId);
2928
+ }
2555
2929
  /** Every workflow run status. Internal to core: not re-exported from `@mastra/core/storage`. */
2556
2930
  const WORKFLOW_RUN_STATUSES = Object.keys({
2557
2931
  running: true,
@@ -4953,7 +5327,10 @@ async function executeForeach(engine, params) {
4953
5327
  });
4954
5328
  } catch (err) {
4955
5329
  checkpointError = err instanceof Error ? err : new Error(String(err));
4956
- engine.getLogger()?.error("Failed to checkpoint foreach progress", {
5330
+ if (isOwnRunFenceConflict(err)) {
5331
+ killQueue();
5332
+ if (inFlight === 0) resolveCompletion?.();
5333
+ } else engine.getLogger()?.error("Failed to checkpoint foreach progress", {
4957
5334
  stepId,
4958
5335
  runId,
4959
5336
  error: checkpointError
@@ -5838,6 +6215,7 @@ var DefaultExecutionEngine = class extends ExecutionEngine {
5838
6215
  }))
5839
6216
  };
5840
6217
  } catch (e) {
6218
+ if (isOwnRunFenceConflict(e)) throw e;
5841
6219
  const isNonRetryable = e instanceof require_error.MastraNonRetryableError;
5842
6220
  if (isNonRetryable || i === params.retries) {
5843
6221
  const errorInstance = require_error.getErrorFromUnknown(e, {
@@ -6743,140 +7121,6 @@ function resolveCurrentState(params) {
6743
7121
  const { stepResult, stepResults, state } = params;
6744
7122
  return stepResult?.__state ?? stepResults?.__state ?? state ?? {};
6745
7123
  }
6746
- // src/agent/run-ownership.ts
6747
- /**
6748
- * TTL for the cross-process leases that mark a live process driving an agent
6749
- * thread or durable run. Kept short so a crashed owner frees the run quickly;
6750
- * owners renew while they work. Overridable via
6751
- * `MASTRA_AGENT_THREAD_LEASE_TTL_MS` (production keeps the 15s default).
6752
- */
6753
- const AGENT_LEASE_TTL_MS = require_utils$1.readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_TTL_MS", 15e3);
6754
- const DEFAULT_RENEW_INTERVAL_MS = Math.max(1, Math.floor(AGENT_LEASE_TTL_MS / 3));
6755
- const configuredRenewIntervalMs = require_utils$1.readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_RENEW_INTERVAL_MS", DEFAULT_RENEW_INTERVAL_MS);
6756
- /**
6757
- * Interval at which an owner renews its lease. Defaults to TTL/3, leaving room
6758
- * for two missed renewals (network blip, GC pause) before the lease expires.
6759
- * Overridable via `MASTRA_AGENT_THREAD_LEASE_RENEW_INTERVAL_MS`; a value not
6760
- * shorter than the TTL would let the lease expire before its first renewal, so
6761
- * it falls back to the default.
6762
- */
6763
- const AGENT_LEASE_RENEW_INTERVAL_MS = configuredRenewIntervalMs < AGENT_LEASE_TTL_MS ? configuredRenewIntervalMs : DEFAULT_RENEW_INTERVAL_MS;
6764
- /**
6765
- * How long a run that lost its thread lease lets a tool call that is already running go on before stopping it.
6766
- * The thread's new owner may be working meanwhile, so a tool that never returns must not keep the old run going for
6767
- * long. Overridable via `MASTRA_AGENT_THREAD_LEASE_LOST_TOOL_GRACE_MS`.
6768
- */
6769
- const AGENT_LEASE_LOST_TOOL_GRACE_MS = require_utils$1.readPositiveIntEnv("MASTRA_AGENT_THREAD_LEASE_LOST_TOOL_GRACE_MS", 3e5);
6770
- // src/workflows/run-ownership.ts
6771
- const WORKFLOW_RUN_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
6772
- const WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
6773
- const UNFENCED = { release: async () => {} };
6774
- /**
6775
- * Runs `tick` `intervalMs` after it starts, then again `intervalMs` after
6776
- * each run of it settles, until the returned function is called. A tick that
6777
- * is running when the chain is stopped finishes, and nothing runs after it.
6778
- * Every tick runs in the async context this function was called in, and the
6779
- * timer is unref'd. `tick` reports its own failures and must not reject.
6780
- *
6781
- * `intervalMs` can be a function, read before each wait, for a delay that
6782
- * follows what the last tick saw. With `immediately`, the first tick runs at
6783
- * once instead of after the first wait.
6784
- */
6785
- function repeatAfterSettled(tick, intervalMs, { immediately = false } = {}) {
6786
- let stopped = false;
6787
- let timer;
6788
- const arm = () => {
6789
- timer = setTimeout(() => void run(), typeof intervalMs === "number" ? intervalMs : intervalMs());
6790
- timer.unref?.();
6791
- };
6792
- const run = async () => {
6793
- try {
6794
- await tick();
6795
- } finally {
6796
- if (!stopped) {
6797
- const { refresh } = timer ?? {};
6798
- if (refresh && typeof intervalMs === "number") refresh.call(timer);
6799
- else arm();
6800
- }
6801
- }
6802
- };
6803
- if (immediately) run();
6804
- else arm();
6805
- return () => {
6806
- stopped = true;
6807
- clearTimeout(timer);
6808
- };
6809
- }
6810
- /**
6811
- * Renews the lease `fence` holds every {@link WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS}
6812
- * until the returned function is called, counting each interval from the end
6813
- * of the previous renewal. Stops by itself after the first renewal that finds
6814
- * the claim superseded, reporting it through `onLost`.
6815
- */
6816
- function renewWorkflowLease({ store, fence, onLost, onError }) {
6817
- const stop = repeatAfterSettled(async () => {
6818
- try {
6819
- const result = await store.renewRunOwnership({
6820
- ...fence,
6821
- leaseMs: WORKFLOW_RUN_LEASE_TTL_MS
6822
- });
6823
- if (result.renewed) return;
6824
- stop();
6825
- onLost(result.record);
6826
- } catch (error) {
6827
- onError(error);
6828
- }
6829
- }, WORKFLOW_RUN_LEASE_RENEW_INTERVAL_MS);
6830
- return stop;
6831
- }
6832
- /**
6833
- * Marks this process as the live driver of a workflow run through the storage
6834
- * run-ownership lease (the one durable agents use), renewing it while the run
6835
- * executes. Writes stay unfenced: the lease only tells the boot-time recovery
6836
- * sweep on other replicas that the run is not orphaned.
6837
- *
6838
- * Returns the current owner record instead of a handle when `force` is off and
6839
- * another execution holds a live lease. Stores without run fencing get a no-op
6840
- * handle, keeping their previous behaviour.
6841
- */
6842
- async function claimWorkflowRunOwnership({ store, runId, force, logger }) {
6843
- if (!store || !await store.supportsRunFencing()) return UNFENCED;
6844
- const claim = await store.claimRunOwnership({
6845
- runId,
6846
- ownerId: crypto.randomUUID(),
6847
- leaseMs: WORKFLOW_RUN_LEASE_TTL_MS,
6848
- force
6849
- });
6850
- if (!claim.acquired) return { owner: claim.record };
6851
- const fence = {
6852
- runId,
6853
- generation: claim.record.generation,
6854
- ownerId: claim.record.ownerId
6855
- };
6856
- const stopRenewing = renewWorkflowLease({
6857
- store,
6858
- fence,
6859
- onLost: (owner) => logger?.warn("Lost the ownership lease of a running workflow run; another process may now recover it", {
6860
- runId,
6861
- owner: owner?.ownerId
6862
- }),
6863
- onError: (error) => logger?.warn("Failed to renew workflow run ownership lease", {
6864
- runId,
6865
- error
6866
- })
6867
- });
6868
- return { release: async () => {
6869
- stopRenewing();
6870
- try {
6871
- await store.releaseRunOwnership(fence);
6872
- } catch (error) {
6873
- logger?.warn("Failed to release workflow run ownership lease", {
6874
- runId,
6875
- error
6876
- });
6877
- }
6878
- } };
6879
- }
6880
7124
  // src/workflows/nested-run-recovery.ts
6881
7125
  const FINISHED_STATUSES = /* @__PURE__ */ new Set([
6882
7126
  "success",
@@ -8129,7 +8373,8 @@ var Workflow = class Workflow extends require_base.MastraBase {
8129
8373
  onFinish: options.onFinish,
8130
8374
  onError: options.onError,
8131
8375
  sharePubsub: options.sharePubsub,
8132
- autoRestartActiveRuns: options.autoRestartActiveRuns
8376
+ autoRestartActiveRuns: options.autoRestartActiveRuns,
8377
+ leaseTtlMs: options.leaseTtlMs
8133
8378
  };
8134
8379
  if (!executionEngine) this.executionEngine = new DefaultExecutionEngine({
8135
8380
  mastra: this.#mastra,
@@ -8863,7 +9108,10 @@ var Workflow = class Workflow extends require_base.MastraBase {
8863
9108
  nestedRun,
8864
9109
  lookUpStoredRun
8865
9110
  });
8866
- const run = this.#runs.get(runIdToUse) ?? new Run({
9111
+ const leaseTtlMs = normalizeLeaseTtlMs(options?.leaseTtlMs, normalizeLeaseTtlMs(this.#options.leaseTtlMs, WORKFLOW_RUN_LEASE_TTL_MS));
9112
+ const reused = this.#runs.get(runIdToUse);
9113
+ if (reused && options?.leaseTtlMs !== void 0) setRunLeaseTtlMs(reused, leaseTtlMs);
9114
+ const run = reused ?? new Run({
8867
9115
  workflowId: this.id,
8868
9116
  stateSchema: this.stateSchema,
8869
9117
  inputSchema: this.inputSchema,
@@ -8888,7 +9136,8 @@ var Workflow = class Workflow extends require_base.MastraBase {
8888
9136
  workflowEngineType: this.engineType,
8889
9137
  pubsub: options?.pubsub,
8890
9138
  storageVersion,
8891
- recoverable: this.engineType === "default" && this.#options.autoRestartActiveRuns !== false && this.type !== "processor"
9139
+ recoverable: this.engineType === "default" && this.#options.autoRestartActiveRuns !== false && this.type !== "processor",
9140
+ leaseTtlMs
8892
9141
  });
8893
9142
  this.#runs.set(runIdToUse, run);
8894
9143
  if (options?.shouldPersistSnapshot) this.executionEngine.setRunPersistenceOverride(runIdToUse, options.shouldPersistSnapshot);
@@ -8982,6 +9231,8 @@ var Workflow = class Workflow extends require_base.MastraBase {
8982
9231
  if (startedFrom) startState = copyState(state);
8983
9232
  }
8984
9233
  const inheritedState = !restart && !isResume ? await parentState?.(startState) : void 0;
9234
+ const nestedRunId = isResume ? resume.runId : runId;
9235
+ if (parentWorkflow && nestedRunId) coverNestedWorkflowRun(parentWorkflow.runId, nestedRunId);
8985
9236
  this.#nestedRun = {
8986
9237
  storageVersion: parentState ? 2 : 1,
8987
9238
  start: !isResume ? {
@@ -9253,6 +9504,13 @@ var Workflow = class Workflow extends require_base.MastraBase {
9253
9504
  });
9254
9505
  return;
9255
9506
  }
9507
+ if (runFenceConflictOf(error)?.runId === runSnapshot.runId) {
9508
+ this.logger.debug("Stopped restarting workflow run another process took over", {
9509
+ workflowId: this.id,
9510
+ runId: runSnapshot.runId
9511
+ });
9512
+ return;
9513
+ }
9256
9514
  this.logger.error("Failed to restart workflow run", {
9257
9515
  workflowId: this.id,
9258
9516
  runId: runSnapshot.runId,
@@ -9460,6 +9718,7 @@ const TERMINAL_WORKFLOW_RUN_STATUSES = /* @__PURE__ */ new Set([
9460
9718
  "tripwire",
9461
9719
  "bailed"
9462
9720
  ]);
9721
+ let setRunLeaseTtlMs;
9463
9722
  /**
9464
9723
  * Represents a workflow run that can be executed
9465
9724
  */
@@ -9552,6 +9811,12 @@ var Run = class {
9552
9811
  #mastra;
9553
9812
  #observerHandlers = [];
9554
9813
  #recoverable;
9814
+ #leaseTtlMs;
9815
+ static {
9816
+ setRunLeaseTtlMs = (run, leaseTtlMs) => {
9817
+ run.#leaseTtlMs = leaseTtlMs;
9818
+ };
9819
+ }
9555
9820
  get mastra() {
9556
9821
  return this.#mastra;
9557
9822
  }
@@ -9593,6 +9858,7 @@ var Run = class {
9593
9858
  getStore: async () => (this.executionEngine.mastra ?? this.#mastra)?.getStorage()?.getStore("workflows")
9594
9859
  });
9595
9860
  this.#recoverable = params.recoverable ?? false;
9861
+ this.#leaseTtlMs = params.leaseTtlMs ?? WORKFLOW_RUN_LEASE_TTL_MS;
9596
9862
  }
9597
9863
  get abortController() {
9598
9864
  if (!this.#abortController) this.#abortController = new AbortController();
@@ -9617,6 +9883,7 @@ var Run = class {
9617
9883
  actor
9618
9884
  });
9619
9885
  })().catch((error) => {
9886
+ if (runFenceConflictOf(error)?.runId === parent.runId) return;
9620
9887
  this.#mastra?.getLogger()?.error("Failed to resume parent workflow after nested child completion.", error);
9621
9888
  });
9622
9889
  }
@@ -9803,11 +10070,12 @@ var Run = class {
9803
10070
  waitingPaths: {},
9804
10071
  timestamp: Date.now()
9805
10072
  };
10073
+ const ownership = "release" in held ? held : UNCLAIMED_WORKFLOW_RUN;
9806
10074
  try {
9807
- await this.runStorage.writeSnapshot(this.executionEngine.options.pruneSnapshot && this.storageVersion === 1 ? this.executionEngine.options.pruneSnapshot({
10075
+ await ownership.run(this.runId, () => this.runStorage.writeSnapshot(this.executionEngine.options.pruneSnapshot && this.storageVersion === 1 ? this.executionEngine.options.pruneSnapshot({
9808
10076
  snapshot: initialRunSnapshot,
9809
10077
  workflowStatus: "waiting"
9810
- }) : initialRunSnapshot, this.resourceId);
10078
+ }) : initialRunSnapshot, this.resourceId));
9811
10079
  } catch (error) {
9812
10080
  workflowSpan?.error({
9813
10081
  ...require_observability.executionFailureTermination(error),
@@ -9877,6 +10145,7 @@ var Run = class {
9877
10145
  const execution = this._start(args, notifyStarted);
9878
10146
  await Promise.race([started, execution]);
9879
10147
  execution.catch((error) => {
10148
+ if (runFenceConflictOf(error)?.runId === this.runId) return;
9880
10149
  this.mastra?.getLogger()?.error(`[Workflow ${this.workflowId}] Background execution failed:`, error);
9881
10150
  });
9882
10151
  return { runId: this.runId };
@@ -10212,6 +10481,8 @@ var Run = class {
10212
10481
  */
10213
10482
  async resumeAsync(params) {
10214
10483
  this._resume(params).catch((err) => {
10484
+ const conflictRunId = runFenceConflictOf(err)?.runId;
10485
+ if (conflictRunId !== void 0 && (conflictRunId === this.runId || conflictRunId === this.parentWorkflow?.runId)) return;
10215
10486
  this.mastra?.getLogger()?.error(`[Workflow ${this.workflowId}] Background resume failed:`, err);
10216
10487
  });
10217
10488
  return { runId: this.runId };
@@ -10229,6 +10500,8 @@ var Run = class {
10229
10500
  * parent's lease unless `nested` is set. The sweep lists `running` and `waiting` runs of registered
10230
10501
  * workflows, so a run that persists neither is never swept. Internal workflows aren't registered,
10231
10502
  * so persisting `waiting` alone doesn't make their runs claim.
10503
+ *
10504
+ * A claim without `force` is a restart's, which backs off from a lease that lapsed.
10232
10505
  */
10233
10506
  async #claimOwnership(force, { nested = false } = {}) {
10234
10507
  const shouldPersistSnapshot = this.executionEngine.getRunPersistenceOverride(this.runId) ?? this.executionEngine.options.shouldPersistSnapshot;
@@ -10239,20 +10512,41 @@ var Run = class {
10239
10512
  workflowStatus: "waiting",
10240
10513
  stepResults: {}
10241
10514
  });
10242
- if (!this.#recoverable || this.parentWorkflow && !nested || !swept) return { release: async () => {} };
10515
+ if (!this.#recoverable || this.parentWorkflow && !nested || !swept) return UNCLAIMED_WORKFLOW_RUN;
10243
10516
  return claimWorkflowRunOwnership({
10244
- store: await this.#mastra?.getStorage()?.getStore("workflows"),
10517
+ store: await (this.executionEngine.mastra ?? this.#mastra)?.getStorage()?.getStore("workflows"),
10245
10518
  runId: this.runId,
10246
10519
  force,
10247
- logger: this.#mastra?.getLogger()
10520
+ logger: this.#mastra?.getLogger(),
10521
+ leaseMs: this.#leaseTtlMs,
10522
+ backOff: !force
10248
10523
  });
10249
10524
  }
10250
- /** Runs `execute` under the run's lease: `held`, when the caller hands one over, or a new claim. */
10251
- async #executeOwned(execute, held) {
10252
- const ownership = held ?? await this.#claimOwnership(true);
10253
- if (!("release" in ownership)) return execute();
10525
+ /**
10526
+ * Runs `execute` under the run's lease: `held`, when the caller hands one over, or a new claim.
10527
+ * Its saves carry that claim, or `fencedBy` when the run executes under another run's lease (a
10528
+ * nested run resumed while it holds its parent's). `onFailure` undoes the caller's own claim when
10529
+ * `execute` rejects, still under the lease, since a rejection can mean another process owns the run.
10530
+ */
10531
+ async #executeOwned(execute, held, { fencedBy, onFailure } = {}) {
10532
+ const executeOrUndo = async () => {
10533
+ try {
10534
+ return await execute();
10535
+ } catch (error) {
10536
+ await onFailure?.();
10537
+ throw error;
10538
+ }
10539
+ };
10540
+ let ownership;
10541
+ try {
10542
+ ownership = held ?? await this.#claimOwnership(true);
10543
+ } catch (error) {
10544
+ await onFailure?.();
10545
+ throw error;
10546
+ }
10547
+ if (!("release" in ownership)) return executeOrUndo();
10254
10548
  try {
10255
- return await execute();
10549
+ return await (fencedBy ?? ownership).run(this.runId, executeOrUndo);
10256
10550
  } finally {
10257
10551
  await ownership.release();
10258
10552
  }
@@ -10433,6 +10727,7 @@ var Run = class {
10433
10727
  expectedStatus: "running"
10434
10728
  });
10435
10729
  } catch (releaseError) {
10730
+ if (isOwnRunFenceConflict(releaseError)) return;
10436
10731
  this.#mastra?.getLogger()?.warn(`[Workflow ${this.workflowId}] Failed to release resume claim for run ${this.runId}`, releaseError);
10437
10732
  }
10438
10733
  };
@@ -10497,6 +10792,7 @@ var Run = class {
10497
10792
  claimedParent = {
10498
10793
  run: parentRun,
10499
10794
  snapshot: parentSnapshot,
10795
+ lease: parentLease,
10500
10796
  takeLease: () => {
10501
10797
  if (leaseHandedOver) return;
10502
10798
  leaseHandedOver = true;
@@ -10515,13 +10811,14 @@ var Run = class {
10515
10811
  }
10516
10812
  const releaseParentClaim = async () => {
10517
10813
  if (!claimedParent) return;
10814
+ const { run: parentRun, lease } = claimedParent;
10518
10815
  try {
10519
- await claimedParent.run.runStorage.updateHeader({
10816
+ await (lease ?? UNCLAIMED_WORKFLOW_RUN).run(parentRun.runId, () => parentRun.runStorage.updateHeader({
10520
10817
  status: "suspended",
10521
10818
  expectedStatus: "running"
10522
- });
10819
+ }));
10523
10820
  } catch (releaseError) {
10524
- this.#mastra?.getLogger()?.warn(`[Workflow ${this.workflowId}] Failed to release parent resume claim for run ${claimedParent.run.runId}`, releaseError);
10821
+ 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);
10525
10822
  }
10526
10823
  await claimedParent.releaseLease();
10527
10824
  };
@@ -10556,13 +10853,20 @@ var Run = class {
10556
10853
  perStep: params.perStep,
10557
10854
  storageVersion: this.storageVersion,
10558
10855
  storedState: this.runStorage.storedState(snapshot)
10559
- }), params.takeHeldOwnership?.() ?? ownLease).then(async (result) => {
10856
+ }), params.takeHeldOwnership?.() ?? ownLease, {
10857
+ fencedBy: claimedParent?.lease,
10858
+ onFailure: async () => {
10859
+ await releaseParentClaim();
10860
+ await releaseClaimIfUnused();
10861
+ }
10862
+ }).then(async (result) => {
10560
10863
  if (!params.isVNext && result.status !== "suspended") this.closeStreamAction?.().catch(() => {});
10561
10864
  this.workflowRunStatus = result.status;
10562
10865
  if (result.status !== "suspended") this.cleanup?.();
10563
10866
  if (result.status === "success") {
10564
10867
  if (claimedParent && this.parentWorkflow) {
10565
10868
  let parentExecutionStarted = false;
10869
+ const parentRunId = claimedParent.run.runId;
10566
10870
  claimedParent.run._resume({
10567
10871
  step: this.parentWorkflow.stepId,
10568
10872
  forEachIndex: this.parentWorkflow.foreachIndex,
@@ -10575,6 +10879,7 @@ var Run = class {
10575
10879
  }
10576
10880
  }).catch(async (error) => {
10577
10881
  if (!parentExecutionStarted) await releaseParentClaim();
10882
+ if (runFenceConflictOf(error)?.runId === parentRunId) return;
10578
10883
  this.#mastra?.getLogger()?.error("Failed to resume parent workflow after nested child completion.", error);
10579
10884
  });
10580
10885
  } else if (!params.skipParentWorkflowClaim) this.#wakeParentWorkflow({
@@ -10585,10 +10890,6 @@ var Run = class {
10585
10890
  result.traceId = traceId;
10586
10891
  result.spanId = spanId;
10587
10892
  return result;
10588
- }).catch(async (error) => {
10589
- await releaseParentClaim();
10590
- await releaseClaimIfUnused();
10591
- throw error;
10592
10893
  });
10593
10894
  this.executionResults = executionResultPromise;
10594
10895
  return executionResultPromise.then((result) => {
@@ -10713,7 +11014,7 @@ var Run = class {
10713
11014
  const spanId = workflowSpan?.id;
10714
11015
  let result;
10715
11016
  try {
10716
- result = await this.executionEngine.execute({
11017
+ result = await ownership.run(this.runId, () => this.executionEngine.execute({
10717
11018
  workflowId: this.workflowId,
10718
11019
  runId: this.runId,
10719
11020
  parentWorkflow: this.parentWorkflow,
@@ -10732,7 +11033,7 @@ var Run = class {
10732
11033
  workflowSpan,
10733
11034
  storageVersion: this.storageVersion,
10734
11035
  storedState: this.runStorage.storedState(snapshot)
10735
- });
11036
+ }));
10736
11037
  } finally {
10737
11038
  await ownership.release();
10738
11039
  }
@@ -10825,36 +11126,31 @@ var Run = class {
10825
11126
  expectedStatus: "running"
10826
11127
  });
10827
11128
  } catch (releaseError) {
11129
+ if (isOwnRunFenceConflict(releaseError)) return;
10828
11130
  this.#mastra?.getLogger()?.warn(`[Workflow ${this.workflowId}] Failed to release time travel claim for run ${this.runId}`, releaseError);
10829
11131
  }
10830
11132
  };
10831
- let result;
10832
- try {
10833
- result = await this.#executeOwned(() => this.executionEngine.execute({
10834
- workflowId: this.workflowId,
10835
- runId: this.runId,
10836
- parentWorkflow: this.parentWorkflow,
10837
- resourceId: this.resourceId,
10838
- disableScorers: this.disableScorers,
10839
- graph: this.executionGraph,
10840
- timeTravel: timeTravelData,
10841
- serializedStepGraph: this.serializedStepGraph,
10842
- pubsub: this.pubsub,
10843
- retryConfig: this.retryConfig,
10844
- requestContext: requestContextToUse,
10845
- actor,
10846
- abortController: this.abortController,
10847
- outputWriter,
10848
- workflowSpan,
10849
- outputOptions,
10850
- perStep,
10851
- storageVersion: this.storageVersion,
10852
- inheritedState
10853
- }));
10854
- } catch (error) {
10855
- await releaseClaimIfUnused();
10856
- throw error;
10857
- }
11133
+ const result = await this.#executeOwned(() => this.executionEngine.execute({
11134
+ workflowId: this.workflowId,
11135
+ runId: this.runId,
11136
+ parentWorkflow: this.parentWorkflow,
11137
+ resourceId: this.resourceId,
11138
+ disableScorers: this.disableScorers,
11139
+ graph: this.executionGraph,
11140
+ timeTravel: timeTravelData,
11141
+ serializedStepGraph: this.serializedStepGraph,
11142
+ pubsub: this.pubsub,
11143
+ retryConfig: this.retryConfig,
11144
+ requestContext: requestContextToUse,
11145
+ actor,
11146
+ abortController: this.abortController,
11147
+ outputWriter,
11148
+ workflowSpan,
11149
+ outputOptions,
11150
+ perStep,
11151
+ storageVersion: this.storageVersion,
11152
+ inheritedState
11153
+ }), void 0, { onFailure: releaseClaimIfUnused });
10858
11154
  this.workflowRunStatus = result.status;
10859
11155
  if (result.status !== "suspended") this.cleanup?.();
10860
11156
  result.traceId = traceId;
@@ -11723,9 +12019,11 @@ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
11723
12019
  * already rebuilt in the step's scope — falling back to it is what keeps
11724
12020
  * request-scoped resolution (tenant/user, workspace, dynamic model/memory)
11725
12021
  * working for tools rebuilt on a cross-process worker, including a delegated
11726
- * subagent's.
12022
+ * subagent's. Pass `liveRunContext` only for the same run's original context,
12023
+ * not an engine-rebuilt context or another caller's context.
11727
12024
  */
11728
- function restoreRequestContext$1(entries, runLevel) {
12025
+ function restoreRequestContext(entries, runLevel, liveRunContext) {
12026
+ if (liveRunContext) return liveRunContext;
11729
12027
  if (entries) {
11730
12028
  const restored = new require_request_context.RequestContext([...Object.entries(require_request_context.withoutLiveRequestKeys(entries)), ...liveRequestEntries(runLevel)]);
11731
12029
  restoreRunAgentScopes(restored);
@@ -11919,8 +12217,16 @@ const AgentStreamEventTypes = {
11919
12217
  OWNERSHIP_CLAIMED: "ownership-claimed"
11920
12218
  };
11921
12219
  // src/agent/streams/run-records.ts
11922
- /** Lifetime of a record. Matches the stream log so ownership never outlives the history it guards by more than one write. */
11923
- const AGENT_RUN_RECORD_TTL_MS = require_output_helpers.RUN_LOG_TTL_MS;
12220
+ /**
12221
+ * Lifetime of a running or suspended run's record. Deliberately much longer
12222
+ * than the stream log's retention: the record is a single small key, and it is
12223
+ * what lets any replica authorize `observe()`/abort/resume on a run parked
12224
+ * overnight on a tool approval — long after its replay log expired (the log
12225
+ * is recreated with later indices and observers resync; see
12226
+ * `MastraServerCache.listPushIndexed`). A finished run's record is deleted by
12227
+ * run cleanup; this lifetime bounds it when cleanup never runs.
12228
+ */
12229
+ const AGENT_RUN_RECORD_TTL_MS = 864e5;
11924
12230
  const agentRunRecordKey = (agentId, runId) => `agent.run.${agentId}.${runId}`;
11925
12231
  async function writeAgentRunRecord(cache, record, key = agentRunRecordKey(record.agentId, record.runId)) {
11926
12232
  await cache.set(key, record, AGENT_RUN_RECORD_TTL_MS);
@@ -12899,10 +13205,14 @@ function createOwnerHandle({ pubsub, runId, cleanupTimeoutMs, logger, abortSigna
12899
13205
  await assertCleanupOwnership?.();
12900
13206
  if (record) {
12901
13207
  const current = await readAgentRunRecord(record.cache, record.agentId, runId, record.key);
12902
- if (current && current.publisherId !== publisherId) return false;
13208
+ if (current && current.publisherId !== publisherId) {
13209
+ logger?.info?.(`[AgentStream:${runId}] skipping stream cleanup: the run record belongs to publisher ${current.publisherId}, not ${publisherId}`);
13210
+ return false;
13211
+ }
12903
13212
  }
12904
13213
  return true;
12905
- } catch {
13214
+ } catch (error) {
13215
+ 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 });
12906
13216
  return false;
12907
13217
  }
12908
13218
  };
@@ -12920,8 +13230,12 @@ function createOwnerHandle({ pubsub, runId, cleanupTimeoutMs, logger, abortSigna
12920
13230
  AGENT_STREAM_TOPIC(runId),
12921
13231
  AGENT_CONTROL_TOPIC(runId),
12922
13232
  abortAckTopic(runId)
12923
- ]) pubsub.clearTopic(topic).catch(() => {});
12924
- if (record) deleteAgentRunRecord(record.cache, record.agentId, runId, record.key).catch(() => {});
13233
+ ]) pubsub.clearTopic(topic).catch((error) => {
13234
+ logger?.warn?.(`[AgentStream:${runId}] failed to clear stream topic ${topic}`, { error });
13235
+ });
13236
+ if (record) deleteAgentRunRecord(record.cache, record.agentId, runId, record.key).catch((error) => {
13237
+ logger?.warn?.(`[AgentStream:${runId}] failed to delete the run record`, { error });
13238
+ });
12925
13239
  };
12926
13240
  const scheduleCleanup = () => {
12927
13241
  scheduleStreamCleanup(cleanupTimeoutMs, () => void cleanup())?.unref?.();
@@ -13106,9 +13420,11 @@ const streamOwnerKey = require_stream.createRunScopeKey("execution-stream-owner"
13106
13420
  const executionTransport = Symbol("execution-stream-publisher-transport");
13107
13421
  function resolveExecutionPublisher({ runId, mastra, agentId, agent, claim, entry = getRunRegistryEntry(runId, mastra) }) {
13108
13422
  if (!entry && !claim) return;
13423
+ let createdPlaceholder = false;
13109
13424
  if (!entry) {
13110
13425
  entry = { isPlaceholder: true };
13111
13426
  if (!setRunRegistryEntry(runId, entry, mastra)) return;
13427
+ createdPlaceholder = true;
13112
13428
  }
13113
13429
  const scope = entry.runScope ??= require_stream.createRunScope();
13114
13430
  if (agent) scope.set(streamOwnerKey, agent);
@@ -13132,16 +13448,17 @@ function resolveExecutionPublisher({ runId, mastra, agentId, agent, claim, entry
13132
13448
  executionClaim,
13133
13449
  requestContext,
13134
13450
  memoryInfo,
13135
- entry
13451
+ entry,
13452
+ createdPlaceholder
13136
13453
  };
13137
13454
  }
13138
13455
  /** Worker output keeps its captured execution authority and cannot settle or clean up the run. */
13139
13456
  function getExecutionStreamProducer(options) {
13140
13457
  const context = resolveExecutionPublisher(options);
13141
13458
  if (!context) return;
13142
- const { publisher, publisherId, runBus, requestContext } = context;
13459
+ const { publisher, publisherId, runBus, requestContext, entry, createdPlaceholder } = context;
13143
13460
  const { runId, agentId, mastra } = options;
13144
- return publisher.attachEventProducer({
13461
+ const producer = publisher.attachEventProducer({
13145
13462
  publisherId,
13146
13463
  pubsub: runBus.pubsub,
13147
13464
  assertOwnership: () => assertExecutionNotSuperseded({
@@ -13151,6 +13468,19 @@ function getExecutionStreamProducer(options) {
13151
13468
  requestContext
13152
13469
  })
13153
13470
  });
13471
+ if (!createdPlaceholder) return producer;
13472
+ return {
13473
+ async publishEvent(event, transport, publishOptions) {
13474
+ try {
13475
+ return await producer.publishEvent(event, transport, publishOptions);
13476
+ } catch (error) {
13477
+ const current = getRunRegistryEntry(runId, mastra);
13478
+ if (isExecutionFenceError(error) && current === entry && entry.isPlaceholder === true) deleteRunRegistryEntry(runId, mastra);
13479
+ throw error;
13480
+ }
13481
+ },
13482
+ detach: () => producer.detach()
13483
+ };
13154
13484
  }
13155
13485
  /** Owning readers settle and clean up using the authority of their captured execution. */
13156
13486
  function getExecutionStreamOwner(options) {
@@ -13239,23 +13569,6 @@ function withExecutionStreamProducer(pubsub, options) {
13239
13569
  return typeof value === "function" ? value.bind(target) : value;
13240
13570
  } });
13241
13571
  }
13242
- // src/agent/durable/run-fence-scope.ts
13243
- const runFenceScope = new async_hooks.AsyncLocalStorage();
13244
- const runFenceContext = setRunFenceContext({
13245
- current: () => runFenceScope.getStore(),
13246
- run: (scope, fn) => runFenceScope.run(scope, fn)
13247
- });
13248
- /**
13249
- * Run `fn` with `scope` supplying the fence of every storage write it makes,
13250
- * including writes from processors, tools and memory that never see the fence.
13251
- */
13252
- function runInRunFenceScope(scope, fn) {
13253
- return runFenceContext.run(scope, fn);
13254
- }
13255
- /** The scope installed for the current async context, if any. */
13256
- function currentRunFenceScope() {
13257
- return runFenceContext.current();
13258
- }
13259
13572
  // src/agent/durable/execution-fence.ts
13260
13573
  /**
13261
13574
  * Execution fence for DurableAgent runs (#23734).
@@ -13284,10 +13597,12 @@ function currentRunFenceScope() {
13284
13597
  const EXECUTION_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
13285
13598
  const EXECUTION_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
13286
13599
  /**
13287
- * How long past its local lease deadline a storage-backed execution waits for a renewal still in flight. A renewal
13288
- * queued behind other writes can still extend the lease; one that never returns must not keep the execution going.
13600
+ * Heartbeat ticks a storage-backed execution goes without a confirmed renewal before it gives up the run: a TTL's
13601
+ * worth while renewals fail, and one more TTL while a renewal is still in flight, since one queued behind other writes
13602
+ * can still extend the lease. Ticks, not elapsed time, because a stalled process misses ticks without failing any.
13289
13603
  */
13290
- const STORAGE_RENEWAL_GRACE_MS = EXECUTION_LEASE_TTL_MS;
13604
+ const STORAGE_FAILED_RENEWAL_TICKS = Math.ceil(EXECUTION_LEASE_TTL_MS / EXECUTION_LEASE_RENEW_INTERVAL_MS);
13605
+ const STORAGE_PENDING_RENEWAL_TICKS = 2 * STORAGE_FAILED_RENEWAL_TICKS;
13291
13606
  /** Allowance for the store's clock running ahead of this process when reading a renewed lease's expiry. */
13292
13607
  const STORE_CLOCK_SKEW_MS = EXECUTION_LEASE_RENEW_INTERVAL_MS;
13293
13608
  const VERIFY_RETRY_DELAY_MS = 250;
@@ -13786,6 +14101,7 @@ var ExecutionFence = class ExecutionFence {
13786
14101
  /** The grace for a release of this claim is spent: a renewal already found it released before this fence settled. */
13787
14102
  #releaseSeen = false;
13788
14103
  #settlement;
14104
+ #detached = false;
13789
14105
  #settledAs;
13790
14106
  #resolveSettled;
13791
14107
  /** Resolves once {@link settle} has finished and the claim is released or left to its new holder. */
@@ -14005,6 +14321,10 @@ var ExecutionFence = class ExecutionFence {
14005
14321
  get settlement() {
14006
14322
  return this.#settledAs;
14007
14323
  }
14324
+ /** This process stopped coordinating the run and left its settlement to the workers. */
14325
+ get detached() {
14326
+ return this.#detached;
14327
+ }
14008
14328
  /** An owned deadline settlement revokes writes without handing its topics to another execution. */
14009
14329
  ownsRunTopics() {
14010
14330
  return this.#settledAs === "owned" || !this.#lossError;
@@ -14197,6 +14517,7 @@ var ExecutionFence = class ExecutionFence {
14197
14517
  /** Detach a coordinator without changing the claim shared with remote workers. */
14198
14518
  detach() {
14199
14519
  if (this.#settlement) return;
14520
+ this.#detached = true;
14200
14521
  this.stopHeartbeat();
14201
14522
  this.#settledAs = "superseded";
14202
14523
  this.#settlement = Promise.resolve("superseded");
@@ -14330,8 +14651,16 @@ var ExecutionFence = class ExecutionFence {
14330
14651
  }
14331
14652
  /**
14332
14653
  * Keep the claim alive between write checks. A `false` renewal marks the
14333
- * fence lost, which notifies {@link onLost} listeners. Backend errors are
14334
- * tolerated until the local lease deadline. A failed renewal can be caused
14654
+ * fence lost, which notifies {@link onLost} listeners.
14655
+ *
14656
+ * A storage claim is judged by the store's conditional renewal, not the
14657
+ * local clock: a blocked event loop moves the clock without letting this
14658
+ * process renew, so a stall alone must not lose the run (#30669). The
14659
+ * heartbeat counts its ticks since the last confirmed renewal instead:
14660
+ * failed renewals are tolerated for a TTL's worth of ticks, and one still
14661
+ * in flight for one more TTL. A pubsub lease has no generation to tell a
14662
+ * late renewal from a later holder's, so it keeps the local deadline, and
14663
+ * its backend errors are tolerated until then. A failed renewal can be caused
14335
14664
  * by this execution's own release: in this process, when the backend
14336
14665
  * confirmed the claim still held the run as it was released (without that
14337
14666
  * confirmation another execution claimed the run first); in another process,
@@ -14351,11 +14680,19 @@ var ExecutionFence = class ExecutionFence {
14351
14680
  let fences = renewingFencesByClaim.get(key);
14352
14681
  if (!fences) renewingFencesByClaim.set(key, fences = /* @__PURE__ */ new Set());
14353
14682
  fences.add(this);
14683
+ const storage = this.generation !== void 0;
14684
+ let unconfirmedTicks = 0;
14685
+ let lastFailure;
14354
14686
  this.#heartbeat = setInterval(() => {
14355
14687
  if (this.#settlement || this.#lossError) return;
14356
- const now = Date.now();
14357
- if (this.#renewalInFlight && this.generation !== void 0 && now < this.#leaseExpiresAt + STORAGE_RENEWAL_GRACE_MS) return;
14358
- if (now >= this.#leaseExpiresAt) {
14688
+ if (storage) {
14689
+ unconfirmedTicks++;
14690
+ const limit = this.#renewalInFlight ? STORAGE_PENDING_RENEWAL_TICKS : STORAGE_FAILED_RENEWAL_TICKS;
14691
+ if (unconfirmedTicks >= limit) {
14692
+ this.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, this.#details(), lastFailure));
14693
+ return;
14694
+ }
14695
+ } else if (Date.now() >= this.#leaseExpiresAt) {
14359
14696
  this.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, this.#details()));
14360
14697
  return;
14361
14698
  }
@@ -14367,6 +14704,8 @@ var ExecutionFence = class ExecutionFence {
14367
14704
  const { leaseExpiresAt } = result;
14368
14705
  const reported = leaseExpiresAt ? Math.min(leaseExpiresAt.getTime() - STORE_CLOCK_SKEW_MS, Date.now() + EXECUTION_LEASE_TTL_MS) : 0;
14369
14706
  this.#leaseExpiresAt = Math.max(startedAt + EXECUTION_LEASE_TTL_MS, reported);
14707
+ unconfirmedTicks = 0;
14708
+ lastFailure = void 0;
14370
14709
  return;
14371
14710
  }
14372
14711
  if (await this.#releaseExplainsFailedRenewal(result.released)) return;
@@ -14374,7 +14713,8 @@ var ExecutionFence = class ExecutionFence {
14374
14713
  return this.#noteTakeover();
14375
14714
  }).catch(async (cause) => {
14376
14715
  if (this.#settlement && await releaseAnswer(this.#ownRelease.awaitAnswer())) return;
14377
- if (Date.now() >= this.#leaseExpiresAt) {
14716
+ if (storage && !this.#settlement) lastFailure = cause;
14717
+ else if (Date.now() >= this.#leaseExpiresAt) {
14378
14718
  this.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, this.#details(), cause));
14379
14719
  return;
14380
14720
  }
@@ -14687,46 +15027,6 @@ var EventProcessor = class {
14687
15027
  this.mastra = mastra;
14688
15028
  }
14689
15029
  };
14690
- // src/storage/workflow-step-guard.ts
14691
- var WorkflowStepConflictError = class extends Error {
14692
- reason;
14693
- storedResult;
14694
- storedRequestContext;
14695
- storedSnapshot;
14696
- code = "WORKFLOW_STEP_CONFLICT";
14697
- constructor(reason, storedResult, storedRequestContext, storedSnapshot) {
14698
- super(`Workflow step delivery rejected (${reason}).`);
14699
- this.reason = reason;
14700
- this.storedResult = storedResult;
14701
- this.storedRequestContext = storedRequestContext;
14702
- this.storedSnapshot = storedSnapshot;
14703
- }
14704
- };
14705
- function isWorkflowStepConflictError(error) {
14706
- return typeof error === "object" && error !== null && "code" in error && error.code === "WORKFLOW_STEP_CONFLICT";
14707
- }
14708
- /** Call inside the adapter's snapshot lock, before mutating results, state, or request context. */
14709
- function assertWorkflowStepGuard({ snapshot, stepId, startGuard, completionGuard }) {
14710
- if (!startGuard && !completionGuard) return;
14711
- if (!snapshot) throw new WorkflowStepConflictError("missing");
14712
- const stored = snapshot.context[stepId];
14713
- const startedBy = stored?.metadata?.startedBy;
14714
- if (stored && !startedBy) return;
14715
- if (startedBy === (startGuard ?? completionGuard).eventId) {
14716
- if (completionGuard?.pruneOnly) {
14717
- if (stored?.status === "success") return;
14718
- throw new WorkflowStepConflictError("stale", stored);
14719
- }
14720
- if (stored?.status === "running") return;
14721
- if (stored?.metadata?.__continuationStarted) throw new WorkflowStepConflictError("stale", stored);
14722
- throw new WorkflowStepConflictError("completed", stored, snapshot.requestContext, snapshot);
14723
- }
14724
- if (startGuard) {
14725
- if (!stored && startGuard.expectedStartedBy === void 0) return;
14726
- if (stored && (stored.status !== "running" || stored.metadata?.__restartPending === true) && startedBy === startGuard.expectedStartedBy) return;
14727
- }
14728
- throw new WorkflowStepConflictError("stale", stored);
14729
- }
14730
15030
  // src/workflows/scheduler/definition-hash.ts
14731
15031
  /**
14732
15032
  * Computes a stable content hash of a workflow's serialized step graph.
@@ -20460,13 +20760,20 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
20460
20760
  */
20461
20761
  async handle(event) {
20462
20762
  if (!reachesOtherProcesses(this.mastra.pubsub)) return this.#handleDelivery(event);
20463
- if (!isStorageFencedExecution(new require_request_context.RequestContext(Object.entries(event.data?.requestContext ?? {})), event.runId, event.data?.parentWorkflow)) return this.#handleDelivery(event);
20763
+ if (!isStorageFencedExecution(new require_request_context.RequestContext(Object.entries(event.data?.requestContext ?? {})), event.runId, event.data?.parentWorkflow)) {
20764
+ await carryEndedSegment(this.mastra, event);
20765
+ const result = await this.#handleDelivery(event);
20766
+ if (result.ok) endFailedIteration(this.mastra, event);
20767
+ return result;
20768
+ }
20464
20769
  try {
20465
20770
  if (await retrySettledDurableExecution(this.mastra, event)) return { ok: true };
20466
20771
  const execute = async () => {
20467
20772
  const result = await this.#handleDelivery(event);
20468
- if (result.ok) await settleEventedDurableExecution(this.mastra, event);
20469
- else if (!result.retry) await stopAbandonedDurableExecution(this.mastra, event, !this.#abandonedUnpublished.has(this.#deliveryKey(event)));
20773
+ if (result.ok) {
20774
+ endFailedIteration(this.mastra, event);
20775
+ await settleEventedDurableExecution(this.mastra, event);
20776
+ } else if (!result.retry) await stopAbandonedDurableExecution(this.mastra, event, !this.#abandonedUnpublished.has(this.#deliveryKey(event)));
20470
20777
  return result;
20471
20778
  };
20472
20779
  return await participateInDurableExecution(this.mastra, event, execute);
@@ -39641,6 +39948,13 @@ const compareCodeUnits$1 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
39641
39948
  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;
39642
39949
  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;
39643
39950
  const newestFirst = (a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
39951
+ /** An oldest-first position: the event's insertion counter as plain decimal text. */
39952
+ function activityPosition(value) {
39953
+ if (value === void 0) return void 0;
39954
+ const n = /^(0|[1-9]\d*)$/.test(value) ? Number(value) : NaN;
39955
+ if (!Number.isSafeInteger(n)) throw new RangeError(`Knowledge activity position is not one this store issued: ${value}`);
39956
+ return n;
39957
+ }
39644
39958
  const oldestFirst = (a, b) => newestFirst(b, a);
39645
39959
  const clone$1 = (value) => structuredClone(value);
39646
39960
  const PIN_KINDS = ["page", "list"];
@@ -39652,6 +39966,8 @@ var InMemoryKnowledgePageStore = class {
39652
39966
  #activity = [];
39653
39967
  #bodyLinks = /* @__PURE__ */ new Map();
39654
39968
  #clock = 0;
39969
+ /** Insertion counter behind each event's `position`; never reset, so a held position can't be reused. */
39970
+ #activitySeq = 0;
39655
39971
  /** A deep copy of every page, note, pin, body link and event, for {@link restore}. */
39656
39972
  snapshot() {
39657
39973
  return structuredClone({
@@ -39670,6 +39986,9 @@ var InMemoryKnowledgePageStore = class {
39670
39986
  this.#pins = copy.pins;
39671
39987
  this.#activity = copy.activity;
39672
39988
  this.#bodyLinks = copy.bodyLinks;
39989
+ const positioned = (event) => Number.isSafeInteger(event.position === void 0 ? NaN : Number(event.position));
39990
+ for (const event of this.#activity) if (positioned(event)) this.#activitySeq = Math.max(this.#activitySeq, Number(event.position));
39991
+ if (!this.#activity.every(positioned)) for (const event of this.#activity) event.position = String(++this.#activitySeq);
39673
39992
  }
39674
39993
  /** Drops every page, note, pin, body link and event. */
39675
39994
  clear() {
@@ -39692,7 +40011,8 @@ var InMemoryKnowledgePageStore = class {
39692
40011
  pageId: page.id,
39693
40012
  ...noteId ? { noteId } : {},
39694
40013
  provenance: clone$1(provenance),
39695
- createdAt: this.#now()
40014
+ createdAt: this.#now(),
40015
+ position: String(++this.#activitySeq)
39696
40016
  });
39697
40017
  }
39698
40018
  #page(id) {
@@ -40280,25 +40600,40 @@ var InMemoryKnowledgePageStore = class {
40280
40600
  }
40281
40601
  async listPageActivity(input) {
40282
40602
  if (input.before !== void 0 && input.cursor !== void 0) throw new RangeError("Knowledge activity takes either a cursor or a before position, not both");
40283
- const { items, nextCursor } = paginate(this.#activity.filter((event) => {
40284
- const page = this.#pages.get(event.pageId);
40285
- if (!page || !this.#pageReadable(page, input.read)) return false;
40286
- if (input.pageId !== void 0 && event.pageId !== input.pageId) return false;
40287
- if (input.scopeId !== void 0 && page.scopeId !== input.scopeId) return false;
40288
- if (event.noteId !== void 0) {
40289
- const note = this.#notes.get(event.noteId);
40290
- if (!note || !this.#noteVisible(note, input.read)) return false;
40291
- }
40292
- if (input.since !== void 0 && event.createdAt.getTime() < input.since.getTime()) return false;
40293
- if (input.until !== void 0 && event.createdAt.getTime() >= input.until.getTime()) return false;
40294
- if (input.before !== void 0 && newestFirst(event, input.before) <= 0) return false;
40295
- return true;
40296
- }).sort(newestFirst), input.cursor, input.limit);
40603
+ if (input.after !== void 0 && input.order !== "asc") throw new RangeError("Knowledge activity takes an after position only with order asc");
40604
+ if (input.after !== void 0 && input.cursor !== void 0) throw new RangeError("Knowledge activity takes either a cursor or an after position, not both");
40605
+ 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");
40606
+ if (input.order === "asc") {
40607
+ const after = activityPosition(input.after ?? input.cursor);
40608
+ if (after !== void 0 && after > this.#activitySeq) throw new RangeError(`Knowledge activity position is ahead of this feed: ${after}`);
40609
+ const size = pageSize(input.limit);
40610
+ const matched = this.#activity.filter((event) => this.#activityMatches(event, input) && (after === void 0 || Number(event.position) > after));
40611
+ const items = matched.slice(0, size);
40612
+ const last = items[items.length - 1];
40613
+ return {
40614
+ events: items.map(clone$1),
40615
+ ...matched.length > size && last ? { nextCursor: last.position } : {}
40616
+ };
40617
+ }
40618
+ 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);
40297
40619
  return {
40298
- events: items.map(clone$1),
40620
+ events: items.map(({ position: _position, ...event }) => clone$1(event)),
40299
40621
  ...nextCursor ? { nextCursor } : {}
40300
40622
  };
40301
40623
  }
40624
+ #activityMatches(event, input) {
40625
+ const page = this.#pages.get(event.pageId);
40626
+ if (!page || !this.#pageReadable(page, input.read)) return false;
40627
+ if (input.pageId !== void 0 && event.pageId !== input.pageId) return false;
40628
+ if (input.scopeId !== void 0 && page.scopeId !== input.scopeId) return false;
40629
+ if (event.noteId !== void 0) {
40630
+ const note = this.#notes.get(event.noteId);
40631
+ if (!note || !this.#noteVisible(note, input.read)) return false;
40632
+ }
40633
+ if (input.since !== void 0 && event.createdAt.getTime() < input.since.getTime()) return false;
40634
+ if (input.until !== void 0 && event.createdAt.getTime() >= input.until.getTime()) return false;
40635
+ return true;
40636
+ }
40302
40637
  async addPinAudience(input) {
40303
40638
  const page = this.#livePage(input.pageId);
40304
40639
  if (!input.audience.length) throw new Error("A Knowledge pin needs at least one audience scope");
@@ -40523,7 +40858,8 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40523
40858
  supportsExplicitReset: true,
40524
40859
  supportsPinKinds: true,
40525
40860
  supportsTransactions: true,
40526
- supportsActivityDateRange: true
40861
+ supportsActivityDateRange: true,
40862
+ supportsActivityAscending: true
40527
40863
  };
40528
40864
  }
40529
40865
  async inspectSchema() {
@@ -43882,7 +44218,8 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43882
44218
  generation: owner.generation,
43883
44219
  ownerId: owner.ownerId,
43884
44220
  leaseExpiresAt: owner.leaseExpiresAt ? new Date(owner.leaseExpiresAt) : null,
43885
- live: !!owner.leaseExpiresAt && owner.leaseExpiresAt.getTime() > Date.now()
44221
+ live: !!owner.leaseExpiresAt && owner.leaseExpiresAt.getTime() > Date.now(),
44222
+ updatedAt: new Date(owner.updatedAt)
43886
44223
  };
43887
44224
  }
43888
44225
  assertFence(explicit, runId, operation) {
@@ -43899,10 +44236,12 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43899
44236
  acquired: false,
43900
44237
  record: current
43901
44238
  };
44239
+ const now = Date.now();
43902
44240
  this.db.runOwners.set(runId, {
43903
- generation: current ? current.generation + 1 : Math.max(1, Date.now()),
44241
+ generation: current ? current.generation + 1 : Math.max(1, now),
43904
44242
  ownerId,
43905
- leaseExpiresAt: new Date(Date.now() + leaseMs)
44243
+ leaseExpiresAt: new Date(now + leaseMs),
44244
+ updatedAt: new Date(now)
43906
44245
  });
43907
44246
  return {
43908
44247
  acquired: true,
@@ -43915,7 +44254,9 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43915
44254
  renewed: false,
43916
44255
  record: this.ownershipRecord(fence.runId)
43917
44256
  };
43918
- owner.leaseExpiresAt = new Date(Date.now() + leaseMs);
44257
+ const now = Date.now();
44258
+ owner.leaseExpiresAt = new Date(now + leaseMs);
44259
+ owner.updatedAt = new Date(now);
43919
44260
  return {
43920
44261
  renewed: true,
43921
44262
  record: this.ownershipRecord(fence.runId)
@@ -43925,6 +44266,7 @@ var WorkflowsInMemory = class extends WorkflowsStorage {
43925
44266
  const owner = this.db.runOwners.get(fence.runId);
43926
44267
  if (!owner || !matchesRunFence(owner, fence)) return false;
43927
44268
  owner.leaseExpiresAt = null;
44269
+ owner.updatedAt = /* @__PURE__ */ new Date();
43928
44270
  return true;
43929
44271
  }
43930
44272
  async getRunOwnership({ runId }) {
@@ -47116,6 +47458,14 @@ function formatToolResult(toolName, argsSummary, resultText, isError, durationMs
47116
47458
  }
47117
47459
  return `${header} \u00B7 ${status}\n${isError && !resultText.startsWith("Error: ") ? `Error: ${resultText}` : resultText}`;
47118
47460
  }
47461
+ /**
47462
+ * Action id of a button that continues a stopped run. Put it on an error card
47463
+ * (see `formatError`); a click sends {@link CONTINUE_RUN_MESSAGE} to the agent
47464
+ * from the clicker, through the same handler as a reply in the thread.
47465
+ */
47466
+ const CONTINUE_RUN_ACTION_ID = "run_continue";
47467
+ /** What a click on a {@link CONTINUE_RUN_ACTION_ID} button says to the agent. */
47468
+ const CONTINUE_RUN_MESSAGE = "Continue.";
47119
47469
  /** Format a tool approval request message */
47120
47470
  function formatToolApproval(toolName, argsSummary, toolCallId, useCards) {
47121
47471
  const header = formatToolHeader(toolName, argsSummary);
@@ -47491,10 +47841,6 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47491
47841
  if (piece) textBuffer += piece;
47492
47842
  continue;
47493
47843
  }
47494
- if (chunk.type === "text-end") {
47495
- await flushText();
47496
- continue;
47497
- }
47498
47844
  if (chunk.type === "step-finish") {
47499
47845
  await flushText();
47500
47846
  continue;
@@ -47531,7 +47877,10 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47531
47877
  continue;
47532
47878
  }
47533
47879
  if (chunk.type === "tool-call") {
47534
- if (channelToolNames.has(chunk.payload.toolName)) continue;
47880
+ if (channelToolNames.has(chunk.payload.toolName)) {
47881
+ await flushText();
47882
+ continue;
47883
+ }
47535
47884
  const enr = tracker.trackStart({
47536
47885
  toolCallId: chunk.payload.toolCallId,
47537
47886
  toolName: chunk.payload.toolName,
@@ -47994,10 +48343,6 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
47994
48343
  pushToSession(piece);
47995
48344
  continue;
47996
48345
  }
47997
- if (chunk.type === "text-end") {
47998
- if (toolDisplay === "hidden") await closeSession();
47999
- continue;
48000
- }
48001
48346
  if (chunk.type === "step-finish") {
48002
48347
  if (toolDisplay !== "grouped") await closeSession();
48003
48348
  continue;
@@ -48033,7 +48378,10 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
48033
48378
  continue;
48034
48379
  }
48035
48380
  if (chunk.type === "tool-call") {
48036
- if (channelToolNames.has(chunk.payload.toolName)) continue;
48381
+ if (channelToolNames.has(chunk.payload.toolName)) {
48382
+ if (toolDisplay === "hidden") await closeSession();
48383
+ continue;
48384
+ }
48037
48385
  const enr = tracker.trackStart({
48038
48386
  toolCallId: chunk.payload.toolCallId,
48039
48387
  toolName: chunk.payload.toolName,
@@ -49790,9 +50138,53 @@ var AgentChannels = class {
49790
50138
  return defaultHandler();
49791
50139
  });
49792
50140
  if (onAction !== false) chat.onAction((event) => {
49793
- const { handlerContext } = beginMessage();
50141
+ const { defaultHandler: handleMessage, handlerContext } = beginMessage();
49794
50142
  const defaultHandler = async () => {
49795
50143
  const { actionId } = event;
50144
+ if (actionId === "run_continue") {
50145
+ const clickedThread = event.thread;
50146
+ if (!clickedThread || onSubscribedMessage === false) return;
50147
+ const threadId = this.resolveExternalThreadId({
50148
+ platform: event.adapter.name,
50149
+ chatThread: clickedThread,
50150
+ messageId: event.messageId
50151
+ });
50152
+ const text = CONTINUE_RUN_MESSAGE;
50153
+ const message = new ChatMessage({
50154
+ attachments: [],
50155
+ author: event.user,
50156
+ formatted: {
50157
+ type: "root",
50158
+ children: [{
50159
+ type: "paragraph",
50160
+ children: [{
50161
+ type: "text",
50162
+ value: text
50163
+ }]
50164
+ }]
50165
+ },
50166
+ id: event.triggerId ?? crypto.randomUUID(),
50167
+ isMention: true,
50168
+ metadata: {
50169
+ dateSent: /* @__PURE__ */ new Date(),
50170
+ edited: false
50171
+ },
50172
+ raw: event.raw,
50173
+ text,
50174
+ threadId
50175
+ });
50176
+ const chatThread = threadId === clickedThread.id ? clickedThread : new ThreadImpl({
50177
+ adapter: event.adapter,
50178
+ channelId: clickedThread.channelId,
50179
+ channelVisibility: clickedThread.channelVisibility,
50180
+ currentMessage: message,
50181
+ id: threadId,
50182
+ isDM: clickedThread.isDM,
50183
+ stateAdapter: this.stateAdapter
50184
+ });
50185
+ if (typeof onSubscribedMessage === "function") return onSubscribedMessage(chatThread, message, handleMessage, handlerContext);
50186
+ return handleMessage(chatThread, message);
50187
+ }
49796
50188
  if (!actionId.startsWith("tool_approve:") && !actionId.startsWith("tool_deny:")) return;
49797
50189
  const platform = event.adapter.name;
49798
50190
  const messageId = event.messageId;
@@ -51106,7 +51498,8 @@ var AgentChannels = class {
51106
51498
  * normally in cards/hidden modes.
51107
51499
  *
51108
51500
  * When the run's stream ends, an empty status is sent to clear any status
51109
- * this run set, so runs that end without posting a message (e.g. terminated
51501
+ * left on the thread — set by this run or by a channel handler before it
51502
+ * dispatched — so runs that end without posting a message (e.g. terminated
51110
51503
  * by `stopWhen` on a tool call, or aborted) don't leave a stale status
51111
51504
  * pinned to the thread.
51112
51505
  */
@@ -51114,7 +51507,6 @@ var AgentChannels = class {
51114
51507
  const typingStatusOption = adapterConfig?.typingStatus;
51115
51508
  const typingStatusFn = typingStatusOption === false ? null : typeof typingStatusOption === "function" ? typingStatusOption : defaultTypingStatus;
51116
51509
  let currentTypingStatus;
51117
- let statusSent = false;
51118
51510
  try {
51119
51511
  for await (const chunk of stream) {
51120
51512
  if (typingStatusFn && !typingGate.active) {
@@ -51136,7 +51528,6 @@ var AgentChannels = class {
51136
51528
  }
51137
51529
  if (typeof result === "string" && result.length > 0 && result !== currentTypingStatus) {
51138
51530
  currentTypingStatus = result;
51139
- statusSent = true;
51140
51531
  chatThread.startTyping(result).catch((e) => {
51141
51532
  this.log("debug", "Typing indicator failed (best-effort)", {
51142
51533
  platform,
@@ -51150,7 +51541,7 @@ var AgentChannels = class {
51150
51541
  yield chunk;
51151
51542
  }
51152
51543
  } finally {
51153
- if (statusSent && !typingGate.active) chatThread.startTyping("").catch((e) => {
51544
+ if (typingStatusFn && !typingGate.active) chatThread.startTyping("").catch((e) => {
51154
51545
  this.log("debug", "Typing clear failed (best-effort)", {
51155
51546
  platform,
51156
51547
  threadId: chatThread.id,
@@ -61092,8 +61483,8 @@ function knowledgeBodyGrep(lines, terms, context, from = 0) {
61092
61483
  const half = 200;
61093
61484
  let cutStart = start + Math.max(0, at - half);
61094
61485
  let cutEnd = Math.min(end, start + at + half);
61095
- if (isLowSurrogate(lines.body.charCodeAt(cutStart))) cutStart--;
61096
- if (isLowSurrogate(lines.body.charCodeAt(cutEnd))) cutEnd++;
61486
+ if (isLowSurrogate$1(lines.body.charCodeAt(cutStart))) cutStart--;
61487
+ if (isLowSurrogate$1(lines.body.charCodeAt(cutEnd))) cutEnd++;
61097
61488
  parts.push({
61098
61489
  start: cutStart,
61099
61490
  end: cutEnd
@@ -61103,7 +61494,7 @@ function knowledgeBodyGrep(lines, terms, context, from = 0) {
61103
61494
  }
61104
61495
  return parts;
61105
61496
  }
61106
- function isLowSurrogate(code) {
61497
+ function isLowSurrogate$1(code) {
61107
61498
  return code >= 56320 && code <= 57343;
61108
61499
  }
61109
61500
  /**
@@ -61997,6 +62388,248 @@ function knowledgeRunPrincipals(runtime, context) {
61997
62388
  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()\`).`);
61998
62389
  return [.../* @__PURE__ */ new Set([...knowledgeRunScopes(runtime.compiled, raw), ...memory])];
61999
62390
  }
62391
+ /** Longest heading line a hit shows ahead of its excerpt; a longer one is cut with `…`. */
62392
+ const HEADING_CHARS = 120;
62393
+ /** Characters of body looked at past a window's start when fitting it to the token budget. */
62394
+ const WINDOW_SCAN_CHARS = 720;
62395
+ /** Occurrences of each query word sampled as window anchors. */
62396
+ const OCCURRENCES_PER_WORD = 32;
62397
+ /** How far a window edge may move to land on whitespace. */
62398
+ const SNAP_CHARS = 20;
62399
+ /**
62400
+ * The words `knowledge_search` searches for: keyword search has no quoting, so quote marks become
62401
+ * spaces (`"refund" policy` searches `refund policy`).
62402
+ */
62403
+ function knowledgeSearchQuery(query) {
62404
+ return query.replace(/["`\u201C\u201D]/g, " ").trim();
62405
+ }
62406
+ /** Source code units per chunk when lowercasing the body and mapping offsets back. */
62407
+ const MAP_CHUNK = 4096;
62408
+ /**
62409
+ * Exact `toLowerCase()` substring matches of each word, as `[start, end)` offsets into `body`, the
62410
+ * way keyword search matches. The body is lowercased chunk by chunk, so each chunk's lowercased
62411
+ * length is known: lowercasing keeps the length for nearly all text, and where it doesn't (`İ` →
62412
+ * `i̇`) only the chunks a match lands in are walked code point by code point to map offsets back. A
62413
+ * body with no match returns before any mapping.
62414
+ */
62415
+ function lowercaseHits(body, words) {
62416
+ const sourceStarts = [];
62417
+ const loweredStarts = [];
62418
+ const pieces = [];
62419
+ let loweredLength = 0;
62420
+ for (let s = 0; s < body.length;) {
62421
+ let e = Math.min(body.length, s + MAP_CHUNK);
62422
+ if (e < body.length && isHighSurrogate(body.charCodeAt(e - 1))) e++;
62423
+ const piece = body.slice(s, e).toLowerCase();
62424
+ sourceStarts.push(s);
62425
+ loweredStarts.push(loweredLength);
62426
+ pieces.push(piece);
62427
+ loweredLength += piece.length;
62428
+ s = e;
62429
+ }
62430
+ sourceStarts.push(body.length);
62431
+ loweredStarts.push(loweredLength);
62432
+ const text = body.includes("\u03A3") ? body.toLowerCase() : pieces.join("");
62433
+ const found = [];
62434
+ words.forEach((word, w) => {
62435
+ let from = 0;
62436
+ for (let n = 0; n < OCCURRENCES_PER_WORD; n++) {
62437
+ const at = text.indexOf(word, from);
62438
+ if (at < 0) break;
62439
+ found.push({
62440
+ word: w,
62441
+ at,
62442
+ length: word.length
62443
+ });
62444
+ from = at + word.length;
62445
+ }
62446
+ });
62447
+ if (!found.length || loweredLength === body.length) return {
62448
+ hits: found.map(({ word, at, length }) => ({
62449
+ word,
62450
+ start: at,
62451
+ end: at + length
62452
+ })),
62453
+ text
62454
+ };
62455
+ const walked = /* @__PURE__ */ new Map();
62456
+ const widths = /* @__PURE__ */ new Map();
62457
+ const source = (index, edge) => {
62458
+ let chunk = 0;
62459
+ for (let lo = 0, hi = sourceStarts.length - 2; lo <= hi;) {
62460
+ const mid = lo + hi >> 1;
62461
+ if (loweredStarts[mid] <= index) {
62462
+ chunk = mid;
62463
+ lo = mid + 1;
62464
+ } else hi = mid - 1;
62465
+ }
62466
+ const sourceStart = sourceStarts[chunk];
62467
+ const loweredStart = loweredStarts[chunk];
62468
+ const sourceEnd = sourceStarts[chunk + 1];
62469
+ if (loweredStarts[chunk + 1] - loweredStart === sourceEnd - sourceStart) return Math.min(body.length, sourceStart + (index - loweredStart));
62470
+ let changes = walked.get(chunk);
62471
+ if (!changes) {
62472
+ changes = [];
62473
+ for (let i = sourceStart, l = loweredStart; i < sourceEnd;) {
62474
+ const point = body.codePointAt(i);
62475
+ const width = point > 65535 ? 2 : 1;
62476
+ let lowerWidth = point < 128 ? 1 : widths.get(point);
62477
+ if (lowerWidth === void 0) {
62478
+ lowerWidth = String.fromCodePoint(point).toLowerCase().length;
62479
+ widths.set(point, lowerWidth);
62480
+ }
62481
+ if (lowerWidth !== width) changes.push({
62482
+ lowered: l,
62483
+ source: i,
62484
+ width,
62485
+ lowerWidth
62486
+ });
62487
+ i += width;
62488
+ l += lowerWidth;
62489
+ }
62490
+ walked.set(chunk, changes);
62491
+ }
62492
+ let last = -1;
62493
+ for (let lo = 0, hi = changes.length - 1; lo <= hi;) {
62494
+ const mid = lo + hi >> 1;
62495
+ if (changes[mid].lowered <= index) {
62496
+ last = mid;
62497
+ lo = mid + 1;
62498
+ } else hi = mid - 1;
62499
+ }
62500
+ if (last < 0) return sourceStart + (index - loweredStart);
62501
+ const change = changes[last];
62502
+ const into = index - change.lowered;
62503
+ if (into === 0) return change.source;
62504
+ if (into < change.lowerWidth) return edge === "start" ? change.source : change.source + change.width;
62505
+ return Math.min(body.length, change.source + change.width + (into - change.lowerWidth));
62506
+ };
62507
+ return {
62508
+ hits: found.map(({ word, at, length }) => ({
62509
+ word,
62510
+ start: source(at, "start"),
62511
+ end: source(at + length, "end")
62512
+ })),
62513
+ text
62514
+ };
62515
+ }
62516
+ /**
62517
+ * The same matches as {@link lowercaseHits} without lowercasing the body, when that is provably
62518
+ * equivalent: every word is ASCII and the body has neither `İ` (lowercases to `i̇`, does not case-fold
62519
+ * to `i`) nor `ſ` (case-folds to `s`, does not lowercase to it). For ASCII words those are the only
62520
+ * characters where Unicode case folding and lowercasing disagree. `undefined` when not equivalent.
62521
+ */
62522
+ function foldedAsciiHits(body, words) {
62523
+ if (words.some((word) => /[^\x00-\x7f]/.test(word)) || /[\u0130\u017f]/.test(body)) return void 0;
62524
+ const hits = [];
62525
+ words.forEach((word, w) => {
62526
+ const pattern = new RegExp(word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "giu");
62527
+ for (let n = 0; n < OCCURRENCES_PER_WORD; n++) {
62528
+ const match = pattern.exec(body);
62529
+ if (!match) break;
62530
+ hits.push({
62531
+ word: w,
62532
+ start: match.index,
62533
+ end: match.index + match[0].length
62534
+ });
62535
+ }
62536
+ });
62537
+ return hits;
62538
+ }
62539
+ const isLowSurrogate = (code) => code >= 56320 && code <= 57343;
62540
+ const isHighSurrogate = (code) => code >= 55296 && code <= 56319;
62541
+ const isSpace = (char) => char !== void 0 && /\s/.test(char);
62542
+ /** How many lines of a search hit's body have a matched word. */
62543
+ function matchingLines(body, words, lowered) {
62544
+ const pattern = lowered ? void 0 : new RegExp(words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), "iu");
62545
+ let count = 0;
62546
+ (lowered ?? body).split("\n").forEach((line, i) => {
62547
+ if (!(pattern ? pattern.test(line) : words.some((word) => line.includes(word)))) return;
62548
+ count++;
62549
+ });
62550
+ return count;
62551
+ }
62552
+ /**
62553
+ * The nearest markdown heading above body offset `at`, as `12│## Heading` with its `knowledge_read`
62554
+ * line number, unless the heading starts inside the excerpt that begins at `windowStart`.
62555
+ */
62556
+ function headingAbove(body, at, windowStart, width) {
62557
+ let nearest;
62558
+ for (const section of knowledgeBodySections(body)) {
62559
+ if (section.start > at) break;
62560
+ nearest = section;
62561
+ }
62562
+ if (!nearest || nearest.start >= windowStart) return void 0;
62563
+ const lines = new KnowledgeBodyLines(body);
62564
+ const line = lines.lineAt(nearest.start);
62565
+ const text = body.slice(nearest.start, lines.lineEnd(line));
62566
+ return `${String(line).padStart(width)}\u2502${text.length > HEADING_CHARS ? `${Array.from(text).slice(0, 119).join("")}\u2026` : text}`;
62567
+ }
62568
+ /**
62569
+ * Where `body` matches the query words, or `undefined` when it contains none of them. Uses the same
62570
+ * words and the same rule as keyword search (case-insensitive substrings: a body matches exactly
62571
+ * when `body.toLowerCase()` contains the word). Each word's first {@link OCCURRENCES_PER_WORD}
62572
+ * occurrences anchor candidate windows of {@link KNOWLEDGE_SNIPPET_TOKENS} tokens; the window
62573
+ * holding the most distinct words wins, earliest on ties. Lines are counted over the whole body.
62574
+ * Cost: a scan per word and one lowercase copy of the body, except for ASCII words in a body with
62575
+ * no `İ` or `ſ`, which are matched without lowercasing; offsets are mapped only for actual matches.
62576
+ */
62577
+ function knowledgeBodyHit(body, query) {
62578
+ if (!body) return void 0;
62579
+ const words = knowledgeSearchWords(knowledgeSearchQuery(query));
62580
+ if (!words.length) return void 0;
62581
+ const folded = foldedAsciiHits(body, words);
62582
+ const lowercase = folded ? void 0 : lowercaseHits(body, words);
62583
+ const hits = folded ?? lowercase.hits;
62584
+ if (!hits.length) return void 0;
62585
+ const windowEnd = (start) => {
62586
+ const rest = body.slice(start, start + WINDOW_SCAN_CHARS);
62587
+ return start + (require_workspace.estimateTokenCount(rest) <= 60 ? rest.length : require_workspace.sliceByTokens(rest, 0, 60).length);
62588
+ };
62589
+ let best;
62590
+ for (const hit of hits) {
62591
+ const before = body.slice(Math.max(0, hit.start - 180), hit.start);
62592
+ const start = hit.start - require_workspace.sliceByTokens(before, -15).length;
62593
+ const end = Math.max(windowEnd(start), hit.end);
62594
+ const seen = /* @__PURE__ */ new Set();
62595
+ for (const other of hits) if (other.start >= start && other.end <= end) seen.add(other.word);
62596
+ const score = seen.size;
62597
+ if (!best || score > best.score || score === best.score && start < best.start) best = {
62598
+ start,
62599
+ end,
62600
+ anchor: hit.start,
62601
+ score
62602
+ };
62603
+ }
62604
+ let { start, end } = best;
62605
+ const { anchor } = best;
62606
+ if (start > 0) {
62607
+ for (let i = start; i < Math.min(anchor, start + SNAP_CHARS); i++) if (isSpace(body[i])) {
62608
+ start = i + 1;
62609
+ break;
62610
+ }
62611
+ }
62612
+ if (end < body.length) {
62613
+ for (let i = end; i > Math.max(anchor, end - SNAP_CHARS); i--) if (isSpace(body[i - 1])) {
62614
+ end = i - 1;
62615
+ break;
62616
+ }
62617
+ }
62618
+ if (start < body.length && isLowSurrogate(body.charCodeAt(start))) start++;
62619
+ if (end > start && isHighSurrogate(body.charCodeAt(end - 1))) end--;
62620
+ const lines = new KnowledgeBodyLines(body);
62621
+ const rows = lines.numbered(start, end > start && body[end - 1] === "\n" ? end - 1 : end).split("\n");
62622
+ const width = rows[0].indexOf("\u2502");
62623
+ if (start > 0) rows[0] = `${rows[0].slice(0, width + 1)}\u2026${rows[0].slice(width + 1)}`;
62624
+ if (end < body.length) rows[rows.length - 1] += "\u2026";
62625
+ const heading = headingAbove(body, anchor, start, width);
62626
+ const matches = matchingLines(body, words, lowercase?.text);
62627
+ return {
62628
+ snippet: heading ? `${heading}\n${rows.join("\n")}` : rows.join("\n"),
62629
+ line: lines.lineAt(anchor),
62630
+ matchingLines: matches
62631
+ };
62632
+ }
62000
62633
  // src/knowledge/page-tools.ts
62001
62634
  function maxTokensOf(host) {
62002
62635
  return host.maxTokens ?? 1e3;
@@ -62023,6 +62656,8 @@ function pageEmbedFailed(storage, page) {
62023
62656
  const RRF_K = 60;
62024
62657
  const DEFAULT_LIMIT = 10;
62025
62658
  const MAX_LIMIT = 50;
62659
+ /** The most words knowledge_read's `match` accepts; a search hint never emits a longer array. */
62660
+ const READ_MATCH_MAX_WORDS = 10;
62026
62661
  const MENTION = /\[\[([^\]]+)\]\]/g;
62027
62662
  /** Misses a note's mention linking may spend beyond its stored mentions (renamed or ambiguous refs). */
62028
62663
  const MENTION_LOOKUP_SLACK = 2;
@@ -62065,6 +62700,17 @@ function pageSummary(page, { refs, scopes }) {
62065
62700
  ...page.description ? { description: page.description } : {}
62066
62701
  };
62067
62702
  }
62703
+ /**
62704
+ * A page search hit: its summary, plus, when the body contains a matched word, a short excerpt around
62705
+ * it with every line numbered, the line it is centred on, and how many lines have a match.
62706
+ */
62707
+ function searchPageSummary(page, refs, words) {
62708
+ const hit = knowledgeBodyHit(page.body, words);
62709
+ return {
62710
+ ...pageSummary(page, refs),
62711
+ ...hit ?? {}
62712
+ };
62713
+ }
62068
62714
  function noteSummary(note, mentions) {
62069
62715
  return {
62070
62716
  id: note.id,
@@ -62162,7 +62808,7 @@ async function requireAudienceAuthority(run, audience) {
62162
62808
  function searchTool(host) {
62163
62809
  return require_tool.createTool({
62164
62810
  id: "knowledge_search",
62165
- description: "Search the knowledge this run can read: page names, descriptions, bodies and notes. Optional `scope` narrows to pages in those scopes.",
62811
+ 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.",
62166
62812
  inputSchema: {
62167
62813
  type: "object",
62168
62814
  properties: {
@@ -62188,7 +62834,7 @@ function searchTool(host) {
62188
62834
  const run = await start(host, context);
62189
62835
  const scopeIds = scope ? (await readableScopes(run, scope)).map((page) => page.id) : void 0;
62190
62836
  const max = limitOf(limit);
62191
- const words = query.replace(/["`\u201C\u201D]/g, " ").trim();
62837
+ const words = knowledgeSearchQuery(query);
62192
62838
  const lexical = words ? await run.storage.searchPages({
62193
62839
  query: words,
62194
62840
  read: run.read,
@@ -62241,16 +62887,22 @@ function searchTool(host) {
62241
62887
  }
62242
62888
  const addresses = await pageRefs(run, hits.map((hit) => hit.page));
62243
62889
  const mentionCache = /* @__PURE__ */ new Map();
62890
+ const results = await Promise.all(hits.map(async (hit) => hit.type === "page" ? {
62891
+ type: "page",
62892
+ page: searchPageSummary(hit.page, addresses, words)
62893
+ } : {
62894
+ type: "note",
62895
+ page: pageSummary(hit.page, addresses),
62896
+ note: noteSummary(hit.note, await noteMentions(run, hit.note, mentionCache))
62897
+ }));
62898
+ const matched = results.some((result) => result.type === "page" && "line" in result.page);
62899
+ const readWords = knowledgeSearchWords(words);
62900
+ 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)`;
62901
+ 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} }.`] : [];
62902
+ 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];
62244
62903
  return {
62245
- results: await Promise.all(hits.map(async (hit) => hit.type === "page" ? {
62246
- type: "page",
62247
- page: pageSummary(hit.page, addresses)
62248
- } : {
62249
- type: "note",
62250
- page: pageSummary(hit.page, addresses),
62251
- note: noteSummary(hit.note, await noteMentions(run, hit.note, mentionCache))
62252
- })),
62253
- ...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.`] } : {}
62904
+ results,
62905
+ ...more.length ? { more } : {}
62254
62906
  };
62255
62907
  }
62256
62908
  });
@@ -62435,7 +63087,7 @@ function readTool(host, canEdit) {
62435
63087
  minLength: 1
62436
63088
  },
62437
63089
  minItems: 1,
62438
- maxItems: 10
63090
+ maxItems: READ_MATCH_MAX_WORDS
62439
63091
  }],
62440
63092
  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."
62441
63093
  },
@@ -63312,6 +63964,7 @@ function decodeActivityCursor(value) {
63312
63964
  try {
63313
63965
  const cursor = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
63314
63966
  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;
63967
+ if (cursor?.v === 2 && (cursor.after === null || typeof cursor.after === "string" && cursor.after.length > 0) && typeof cursor.bind === "string") return cursor;
63315
63968
  } catch {}
63316
63969
  throw new Error("knowledge_activity: that cursor did not come from knowledge_activity.");
63317
63970
  }
@@ -63319,7 +63972,7 @@ function activityTool(host) {
63319
63972
  const maxTokens = maxTokensOf(host);
63320
63973
  return require_tool.createTool({
63321
63974
  id: "knowledge_activity",
63322
- 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).`,
63975
+ 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\`.`,
63323
63976
  inputSchema: {
63324
63977
  type: "object",
63325
63978
  properties: {
@@ -63338,6 +63991,11 @@ function activityTool(host) {
63338
63991
  minLength: 1,
63339
63992
  description: `Only changes to this page or scope. ${pageRefDescription}`
63340
63993
  },
63994
+ order: {
63995
+ type: "string",
63996
+ enum: ["newest", "oldest"],
63997
+ 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."
63998
+ },
63341
63999
  limit: {
63342
64000
  type: "integer",
63343
64001
  minimum: 1,
@@ -63347,20 +64005,24 @@ function activityTool(host) {
63347
64005
  cursor: {
63348
64006
  type: "string",
63349
64007
  minLength: 1,
63350
- description: "The previous result's cursor, for the changes after it (pass the same since, until and from)."
64008
+ description: "The previous result's cursor, for the changes after it (pass the same since, until, from and order)."
63351
64009
  }
63352
64010
  },
63353
64011
  additionalProperties: false
63354
64012
  },
63355
64013
  execute: async (input, context) => {
63356
64014
  const args = input;
64015
+ const oldest = args.order === "oldest";
63357
64016
  if (args.since === void 0 && args.until === void 0) throw new Error("knowledge_activity needs since or until, e.g. since: \"2026-07-01\".");
63358
64017
  const since = args.since === void 0 ? void 0 : activityDate("since", args.since);
63359
64018
  const until = args.until === void 0 ? void 0 : activityDate("until", args.until);
63360
64019
  if (since && until && since.getTime() >= until.getTime()) throw new Error("knowledge_activity: since must be earlier than until.");
63361
64020
  const limit = Math.min(Math.max(args.limit ?? ACTIVITY_DEFAULT_LIMIT, 1), ACTIVITY_MAX_LIMIT);
63362
- if (!(await host.getStorage()).getCapabilities().supportsActivityDateRange) throw new KnowledgeUnsupportedCapabilityError("listPageActivity date range");
64021
+ const capabilities = (await host.getStorage()).getCapabilities();
64022
+ if (!capabilities.supportsActivityDateRange) throw new KnowledgeUnsupportedCapabilityError("listPageActivity date range");
64023
+ if (oldest && !capabilities.supportsActivityAscending) throw new KnowledgeUnsupportedCapabilityError("listPageActivity oldest first");
63363
64024
  const cursor = args.cursor === void 0 ? void 0 : decodeActivityCursor(args.cursor);
64025
+ 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.");
63364
64026
  const run = await start(host, context);
63365
64027
  const origin = args.from ? await run.pageOrCloseMatches(args.from) : void 0;
63366
64028
  const filter = origin ? origin.isScope ? { scopeId: origin.id } : { pageId: origin.id } : {};
@@ -63368,15 +64030,24 @@ function activityTool(host) {
63368
64030
  since?.toISOString(),
63369
64031
  until?.toISOString(),
63370
64032
  "scopeId" in filter ? filter.scopeId : void 0,
63371
- "pageId" in filter ? filter.pageId : void 0
64033
+ "pageId" in filter ? filter.pageId : void 0,
64034
+ ...oldest ? ["oldest"] : []
63372
64035
  ]);
63373
- 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.");
64036
+ 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.");
63374
64037
  const entries = [];
63375
64038
  let used = 0;
63376
- let position = cursor ? {
64039
+ let position = !cursor ? void 0 : cursor.v === 2 ? cursor.after ?? void 0 : {
63377
64040
  createdAt: new Date(cursor.before[0]),
63378
64041
  id: cursor.before[1]
63379
- } : void 0;
64042
+ };
64043
+ const passed = (event) => {
64044
+ if (!oldest) return {
64045
+ createdAt: event.createdAt,
64046
+ id: event.id
64047
+ };
64048
+ if (!event.position) throw new Error("knowledge_activity: the store returned an oldest-first change without a position.");
64049
+ return event.position;
64050
+ };
63380
64051
  let more = false;
63381
64052
  let stopped = false;
63382
64053
  let batches = 0;
@@ -63388,7 +64059,12 @@ function activityTool(host) {
63388
64059
  ...filter,
63389
64060
  ...since ? { since } : {},
63390
64061
  ...until ? { until } : {},
63391
- ...position ? { before: position } : {},
64062
+ ...typeof position === "string" ? {
64063
+ order: "asc",
64064
+ after: position
64065
+ } : {},
64066
+ ...position && typeof position !== "string" ? { before: position } : {},
64067
+ ...oldest && !position ? { order: "asc" } : {},
63392
64068
  limit: limit - entries.length
63393
64069
  });
63394
64070
  more = batch.nextCursor !== void 0;
@@ -63416,10 +64092,7 @@ function activityTool(host) {
63416
64092
  const page = pages.get(event.pageId);
63417
64093
  const note = event.noteId ? notes.get(event.noteId) : void 0;
63418
64094
  if (!page || event.noteId && !note) {
63419
- position = {
63420
- createdAt: event.createdAt,
63421
- id: event.id
63422
- };
64095
+ position = passed(event);
63423
64096
  continue;
63424
64097
  }
63425
64098
  const entry = {
@@ -63461,10 +64134,7 @@ function activityTool(host) {
63461
64134
  }
63462
64135
  entries.push(entry);
63463
64136
  used += size;
63464
- position = {
63465
- createdAt: event.createdAt,
63466
- id: event.id
63467
- };
64137
+ position = passed(event);
63468
64138
  if (entries.length >= limit) break;
63469
64139
  }
63470
64140
  if (!more) break;
@@ -63478,7 +64148,14 @@ function activityTool(host) {
63478
64148
  name: origin.name
63479
64149
  } } : {},
63480
64150
  changes: entries,
63481
- ...hasMore && position ? {
64151
+ ...oldest ? {
64152
+ ...hasMore ? { more: true } : {},
64153
+ cursor: encodeActivityCursor({
64154
+ v: 2,
64155
+ after: typeof position === "string" ? position : null,
64156
+ bind
64157
+ })
64158
+ } : hasMore && position && typeof position !== "string" ? {
63482
64159
  more: true,
63483
64160
  cursor: encodeActivityCursor({
63484
64161
  v: 1,
@@ -70725,6 +71402,8 @@ const DurableStepIds = {
70725
71402
  /** isTaskComplete evaluation step */
70726
71403
  IS_TASK_COMPLETE: "durable-is-task-complete"
70727
71404
  };
71405
+ /** The loop's last step, which ends the run's spans when it succeeds. */
71406
+ const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
70728
71407
  const RECOVER_ALREADY_IN_PROGRESS_ERROR_ID = "DURABLE_AGENT_RECOVER_ALREADY_IN_PROGRESS";
70729
71408
  const RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID = "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND";
70730
71409
  const RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID = "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE";
@@ -70847,6 +71526,165 @@ async function runResumeDurableStreamUntilIdle(agent, runId, resumeData, streamO
70847
71526
  }
70848
71527
  });
70849
71528
  }
71529
+ // src/agent/durable/segment-spans.ts
71530
+ /**
71531
+ * Which AGENT_RUN + MODEL_GENERATION pair a durable execution reports under.
71532
+ *
71533
+ * A segment is one execution of the durable loop: the run's start, or a resume or a recovery, up
71534
+ * to its suspension or its end. Each segment has its own span pair and ends its own spans once.
71535
+ * The run's first pair travels in the workflow input. A resume or recovery opens the next pair and
71536
+ * carries it on the request context, which every engine hands to every step and persists with the
71537
+ * run, so the worker that finishes a segment ends that segment's spans wherever it runs.
71538
+ */
71539
+ /** The wire form of the pair a resume or recovery opened. */
71540
+ function openedSegment(agentSpan, modelSpan) {
71541
+ return {
71542
+ agentSpanData: agentSpan.snapshot?.() ?? agentSpan.exportSpan(),
71543
+ modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),
71544
+ stepParentId: require_utils.resolveExportedSpanId(modelSpan ?? agentSpan)
71545
+ };
71546
+ }
71547
+ function hasRawAccess(target) {
71548
+ return typeof target.setRaw === "function";
71549
+ }
71550
+ function readCarrier(requestContext, runId) {
71551
+ const all = requestContext?.getRaw?.(MASTRA_DURABLE_SEGMENTS_KEY);
71552
+ if (!all || typeof all !== "object") return void 0;
71553
+ const segment = all[runId];
71554
+ if (segment === null) return null;
71555
+ return typeof segment?.agentSpanData?.id === "string" ? segment : void 0;
71556
+ }
71557
+ /**
71558
+ * Record the pair a resume or recovery opened for `runId`, or `null` when it opened none, on the
71559
+ * request context it hands the engine. Keyed by runId so a delegated durable sub-agent sharing the
71560
+ * caller's context cannot overwrite the parent's segment.
71561
+ */
71562
+ function carrySegmentSpans(target, runId, segment) {
71563
+ const current = hasRawAccess(target) ? target.getRaw(MASTRA_DURABLE_SEGMENTS_KEY) : target[MASTRA_DURABLE_SEGMENTS_KEY];
71564
+ const next = {
71565
+ ...current && typeof current === "object" ? current : {},
71566
+ [runId]: segment
71567
+ };
71568
+ if (hasRawAccess(target)) target.setRaw(MASTRA_DURABLE_SEGMENTS_KEY, next);
71569
+ else target[MASTRA_DURABLE_SEGMENTS_KEY] = next;
71570
+ }
71571
+ /**
71572
+ * The pair the current execution reports under: the one a resume or recovery carried for `runId`,
71573
+ * else the run's first pair from `state` (the workflow input or the loop state). A carried `null`
71574
+ * means the execution opened no spans, so its steps end none. `carried` tells the two apart.
71575
+ * `live` is this process's registry entry, the fallback when the context lost the carried pair.
71576
+ */
71577
+ function segmentSpanData(requestContext, runId, state, live) {
71578
+ const carried = readCarrier(requestContext, runId);
71579
+ if (carried === null) return { carried: true };
71580
+ if (carried) return {
71581
+ ...carried,
71582
+ carried: true
71583
+ };
71584
+ if (live?.resumeAgentSpan) return {
71585
+ ...openedSegment(live.resumeAgentSpan, live.resumeModelSpan),
71586
+ carried: true
71587
+ };
71588
+ return {
71589
+ agentSpanData: state.agentSpanData,
71590
+ modelSpanData: state.modelSpanData,
71591
+ carried: false
71592
+ };
71593
+ }
71594
+ /**
71595
+ * The generations whose MODEL_STEP the execution that persisted `requestContext` left open: its own
71596
+ * pair's, plus those it was itself finishing after an earlier crash. Every other step was ended by
71597
+ * the suspension before a resume. Undefined when that execution carried no pair.
71598
+ */
71599
+ function openStepsOfCrashedSegment(requestContext, runId) {
71600
+ const crashed = (requestContext?.[MASTRA_DURABLE_SEGMENTS_KEY])?.[runId];
71601
+ if (!crashed?.stepParentId || crashed.adoptsOpenSteps && !crashed.openStepsOf) return void 0;
71602
+ return [crashed.stepParentId, ...crashed.openStepsOf ?? []];
71603
+ }
71604
+ /** The live span behind `data` when this process holds it, so it is ended in place; otherwise undefined. */
71605
+ function liveSegmentSpan(data, ...candidates) {
71606
+ return data ? candidates.find((span) => span?.id === data.id) : void 0;
71607
+ }
71608
+ /**
71609
+ * Whether `segment` may end the MODEL_STEP `stepSpanData`. The run's first execution opened every
71610
+ * step it sees. A resumed one ends only the steps opened under its own pair: the step that
71611
+ * suspended was ended by that suspension. A recovered one also finishes the step its crashed
71612
+ * execution left open.
71613
+ */
71614
+ function segmentOwnsStep(segment, stepSpanData) {
71615
+ if (!segment.carried) return true;
71616
+ const parent = stepSpanData?.parentSpanId ?? void 0;
71617
+ if (segment.openStepsOf) return parent !== void 0 && [segment.stepParentId, ...segment.openStepsOf].includes(parent);
71618
+ if (segment.adoptsOpenSteps) return segment.endedStepsOf === void 0 || parent !== segment.endedStepsOf;
71619
+ return parent === segment.stepParentId;
71620
+ }
71621
+ /** Longer than any pause between the calls of one step; a key is only written when they run side by side. */
71622
+ const SEGMENT_END_TTL_MS = 864e5;
71623
+ /**
71624
+ * Whether `outcome` ends the spans of the run's first segment. Behind a broker, a tool call that suspends and one
71625
+ * beside it that fails the run are in different processes, and both end the same spans, so the first one to claim
71626
+ * them does. Undefined when no claim can be made, and in one process only the suspension asks.
71627
+ */
71628
+ async function claimSegmentEnd({ mastra, requestContext, runId, iterationCount, outcome }) {
71629
+ try {
71630
+ if (!mastra || !reachesOtherProcesses(mastra.pubsub)) return true;
71631
+ const claim = getExecutionClaim(requestContext, runId);
71632
+ const leases = resolveLeaseProvider(mastra.pubsub);
71633
+ if (claim?.generation === void 0 || leases === require_output_helpers.NoopLeaseProvider) return void 0;
71634
+ const key = `mastra:durable-segment-end:v1:${JSON.stringify([
71635
+ runId,
71636
+ claim.executionId,
71637
+ iterationCount
71638
+ ])}`;
71639
+ const { acquired, owner } = await leases.acquireLease(key, outcome, SEGMENT_END_TTL_MS);
71640
+ return acquired || (owner ? false : void 0);
71641
+ } catch {
71642
+ return;
71643
+ }
71644
+ }
71645
+ /** A MODEL_STEP the run's deadline stopped is interrupted, as on the regular agent; the run itself hit a limit. */
71646
+ function stepFailure(failure) {
71647
+ return require_stream.isMastraTimeoutError(failure.error) ? {
71648
+ ...failure,
71649
+ outcome: "interrupted"
71650
+ } : failure;
71651
+ }
71652
+ /**
71653
+ * Whether a tool call that suspended beside the failed one already ended the spans of the segment. Only the failed
71654
+ * iteration's steps show it, so the settling engine takes it to the run's own failure as a carried `null` segment.
71655
+ */
71656
+ function segmentEndedBySuspension(segment, steps) {
71657
+ const { output, suspendPayload } = steps[DurableStepIds.TOOL_CALL] ?? {};
71658
+ return [suspendPayload?.__workflow_meta?.foreachOutput, output].flat().some((call) => call?.status === "suspended") && segmentOwnsStep(segment, steps[DurableStepIds.LLM_EXECUTION]?.output?.stepSpanData);
71659
+ }
71660
+ /**
71661
+ * End what a failed execution left open, from the facts the run carries, where the process that settles the
71662
+ * failure may hold none of the run's live spans. An iteration's failure ends its MODEL_STEP; the run's failure
71663
+ * ends the MODEL_GENERATION and AGENT_RUN its segment reports under. Never throws.
71664
+ */
71665
+ function endFailedSegmentSpans({ mastra, requestContext, runId, state, steps, error, live, firstPairOnly }) {
71666
+ try {
71667
+ const observability = mastra?.observability?.getSelectedInstance({ requestContext });
71668
+ if (!observability || !("input" in steps) || steps["map-final-output"]?.status === "success") return;
71669
+ const segment = segmentSpanData(requestContext, runId, state, live);
71670
+ const failure = {
71671
+ error,
71672
+ ...require_observability.executionFailureTermination(error),
71673
+ endSpan: true
71674
+ };
71675
+ if (state.iterationCount !== void 0) {
71676
+ const stepSpanData = steps[DurableStepIds.LLM_EXECUTION]?.output?.stepSpanData;
71677
+ if (!stepSpanData || steps[DurableStepIds.LLM_MAPPING]?.status === "success") return;
71678
+ if (!segmentOwnsStep(segment, stepSpanData) || segmentEndedBySuspension(segment, steps)) return;
71679
+ (liveSegmentSpan(stepSpanData, live?.openStepSpan) ?? observability.rebuildSpan(stepSpanData)).error(stepFailure(failure));
71680
+ return;
71681
+ }
71682
+ if (firstPairOnly && segment.carried) return;
71683
+ const { modelSpanData, agentSpanData } = segment;
71684
+ if (modelSpanData) (liveSegmentSpan(modelSpanData, live?.resumeModelSpan, live?.modelSpan) ?? observability.rebuildSpan(modelSpanData)).error(failure);
71685
+ if (agentSpanData) (liveSegmentSpan(agentSpanData, live?.resumeAgentSpan, live?.agentSpan) ?? observability.rebuildSpan(agentSpanData)).error(failure);
71686
+ } catch {}
71687
+ }
70850
71688
  // ../_internal-core/dist/durable/index.js
70851
71689
  function toolModelOutput(result) {
70852
71690
  return typeof result === "string" ? {
@@ -71806,87 +72644,6 @@ function createDurableAgentStream(options) {
71806
72644
  ready
71807
72645
  };
71808
72646
  }
71809
- // src/agent/durable/segment-spans.ts
71810
- /**
71811
- * Which AGENT_RUN + MODEL_GENERATION pair a durable execution reports under.
71812
- *
71813
- * A segment is one execution of the durable loop: the run's start, or a resume or a recovery, up
71814
- * to its suspension or its end. Each segment has its own span pair and ends its own spans once.
71815
- * The run's first pair travels in the workflow input. A resume or recovery opens the next pair and
71816
- * carries it on the request context, which every engine hands to every step and persists with the
71817
- * run, so the worker that finishes a segment ends that segment's spans wherever it runs.
71818
- */
71819
- /** The wire form of the pair a resume or recovery opened. */
71820
- function openedSegment(agentSpan, modelSpan) {
71821
- return {
71822
- agentSpanData: agentSpan.snapshot?.() ?? agentSpan.exportSpan(),
71823
- modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),
71824
- stepParentId: require_utils.resolveExportedSpanId(modelSpan ?? agentSpan)
71825
- };
71826
- }
71827
- function hasRawAccess(target) {
71828
- return typeof target.setRaw === "function";
71829
- }
71830
- function readCarrier(requestContext, runId) {
71831
- const all = requestContext?.getRaw?.(MASTRA_DURABLE_SEGMENTS_KEY);
71832
- if (!all || typeof all !== "object") return void 0;
71833
- const segment = all[runId];
71834
- if (segment === null) return null;
71835
- return typeof segment?.agentSpanData?.id === "string" ? segment : void 0;
71836
- }
71837
- /**
71838
- * Record the pair a resume or recovery opened for `runId`, or `null` when it opened none, on the
71839
- * request context it hands the engine. Keyed by runId so a delegated durable sub-agent sharing the
71840
- * caller's context cannot overwrite the parent's segment.
71841
- */
71842
- function carrySegmentSpans(target, runId, segment) {
71843
- const current = hasRawAccess(target) ? target.getRaw(MASTRA_DURABLE_SEGMENTS_KEY) : target[MASTRA_DURABLE_SEGMENTS_KEY];
71844
- const next = {
71845
- ...current && typeof current === "object" ? current : {},
71846
- [runId]: segment
71847
- };
71848
- if (hasRawAccess(target)) target.setRaw(MASTRA_DURABLE_SEGMENTS_KEY, next);
71849
- else target[MASTRA_DURABLE_SEGMENTS_KEY] = next;
71850
- }
71851
- /**
71852
- * The pair the current execution reports under: the one a resume or recovery carried for `runId`,
71853
- * else the run's first pair from `state` (the workflow input or the loop state). A carried `null`
71854
- * means the execution opened no spans, so its steps end none. `carried` tells the two apart.
71855
- * `live` is this process's registry entry, the fallback when the context lost the carried pair.
71856
- */
71857
- function segmentSpanData(requestContext, runId, state, live) {
71858
- const carried = readCarrier(requestContext, runId);
71859
- if (carried === null) return { carried: true };
71860
- if (carried) return {
71861
- ...carried,
71862
- carried: true
71863
- };
71864
- if (live?.resumeAgentSpan) return {
71865
- ...openedSegment(live.resumeAgentSpan, live.resumeModelSpan),
71866
- carried: true
71867
- };
71868
- return {
71869
- agentSpanData: state.agentSpanData,
71870
- modelSpanData: state.modelSpanData,
71871
- carried: false
71872
- };
71873
- }
71874
- /** The live span behind `data` when this process holds it, so it is ended in place; otherwise undefined. */
71875
- function liveSegmentSpan(data, ...candidates) {
71876
- return data ? candidates.find((span) => span?.id === data.id) : void 0;
71877
- }
71878
- /**
71879
- * Whether `segment` may end the MODEL_STEP `stepSpanData`. The run's first execution opened every
71880
- * step it sees. A resumed one ends only the steps opened under its own pair: the step that
71881
- * suspended was ended by that suspension. A recovered one also finishes the step its crashed
71882
- * execution left open.
71883
- */
71884
- function segmentOwnsStep(segment, stepSpanData) {
71885
- if (!segment.carried) return true;
71886
- const parent = stepSpanData?.parentSpanId ?? void 0;
71887
- if (segment.adoptsOpenSteps) return segment.endedStepsOf === void 0 || parent !== segment.endedStepsOf;
71888
- return parent === segment.stepParentId;
71889
- }
71890
72647
  // src/agent/durable/utils/run-message-list.ts
71891
72648
  /** The id generator does not survive the serialize/deserialize round-trip a durable run makes on every step. */
71892
72649
  function createRunMessageList({ mastra, threadId, resourceId }) {
@@ -72377,7 +73134,7 @@ async function resolveRuntimeDependencies(options) {
72377
73134
  else if (mastra) try {
72378
73135
  const agent = await resolveRunAgent(mastra, agentId, runId, input.agentVersionId);
72379
73136
  rebuiltAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
72380
- const resolveRequestContext = restoreRequestContext$1(input.requestContextEntries, options.requestContext);
73137
+ const resolveRequestContext = restoreRequestContext(input.requestContextEntries, options.requestContext);
72381
73138
  backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
72382
73139
  tools = await agent.getToolsForExecution({
72383
73140
  runId,
@@ -72498,7 +73255,7 @@ async function rebuildRunToolsFromMastra(options) {
72498
73255
  const agent = await resolveRunAgent(mastra, agentId, runId, options.agentVersionId);
72499
73256
  agentResolved = true;
72500
73257
  const processorAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
72501
- const resolveRequestContext = restoreRequestContext$1(requestContextEntries, requestContext);
73258
+ const resolveRequestContext = restoreRequestContext(requestContextEntries, requestContext);
72502
73259
  const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
72503
73260
  const tools = await agent.getToolsForExecution({
72504
73261
  runId,
@@ -72538,12 +73295,17 @@ async function rebuildRunToolsFromMastra(options) {
72538
73295
  agent: processorAgent,
72539
73296
  ...backgroundTasks,
72540
73297
  ...rebuiltProcessors,
72541
- ...options.rehydrateProcessors ? { requestContext: resolveRequestContext } : {}
73298
+ ...options.rehydrateProcessors ? {
73299
+ requestContext: resolveRequestContext,
73300
+ requestContextRebuilt: true
73301
+ } : {}
72542
73302
  };
72543
73303
  existing = getRunRegistryEntry(runId, mastra);
72544
73304
  if (existing) {
72545
- const needsProcessorPipeline = !existing.outputProcessors || !existing.processorStates;
72546
- if (options.rehydrateProcessors && (existing.isPlaceholder && needsProcessorPipeline || !existing.requestContext)) existing.requestContext = resolveRequestContext;
73305
+ if (options.rehydrateProcessors && !existing.requestContext) {
73306
+ existing.requestContext = resolveRequestContext;
73307
+ existing.requestContextRebuilt = true;
73308
+ }
72547
73309
  const registryModel = existing.model;
72548
73310
  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;
72549
73311
  existing.workspace ??= workspace;
@@ -72941,9 +73703,9 @@ function runTranscriptRefs(params) {
72941
73703
  }
72942
73704
  /** The run's memory: the live instance in this process, else re-resolved from the agent. */
72943
73705
  async function runMemory(params, run) {
72944
- const memory = run.runId ? getRunRegistryEntry(run.runId, params.mastra)?.memory : void 0;
72945
- if (memory || !params.mastra || !run.agentId) return memory;
72946
- return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: restoreRequestContext$1(run.requestContextEntries, params.requestContext) });
73706
+ const entry = run.runId ? getRunRegistryEntry(run.runId, params.mastra) : void 0;
73707
+ if (entry?.memory || !params.mastra || !run.agentId) return entry?.memory;
73708
+ return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: restoreRequestContext(run.requestContextEntries, params.requestContext, getLiveRunRequestContext(entry)) });
72947
73709
  }
72948
73710
  /** The most recent transcript in a snapshot: workflow state, else the last step output carrying one. */
72949
73711
  function latestMessageListState(snapshot) {
@@ -72962,7 +73724,8 @@ function latestMessageListState(snapshot) {
72962
73724
  return latest?.value;
72963
73725
  }
72964
73726
  // src/agent/durable/workflows/finalize-run.ts
72965
- function restoreRequestContext(entries, fallback) {
73727
+ function mergeRequestContextForFinalization(entries, fallback, liveRunContext) {
73728
+ if (liveRunContext) return liveRunContext;
72966
73729
  if (!entries) return fallback ?? new require_request_context.RequestContext();
72967
73730
  const restored = new require_request_context.RequestContext(fallback?.entries());
72968
73731
  for (const [key, value] of Object.entries(require_request_context.withoutLiveRequestKeys(entries))) restored.set(key, value);
@@ -73018,7 +73781,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73018
73781
  error
73019
73782
  });
73020
73783
  }
73021
- const effectiveRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext);
73784
+ const effectiveRequestContext = mergeRequestContextForFinalization(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry));
73022
73785
  if (!effectiveRequestContext.has("MastraMemory") && durableState?.threadId) effectiveRequestContext.set("MastraMemory", {
73023
73786
  thread: { id: durableState.threadId },
73024
73787
  resourceId: durableState.resourceId,
@@ -73035,16 +73798,18 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73035
73798
  const liveStructuredOutput = registryEntry?.structuredOutput;
73036
73799
  const structuredOutputSchema = liveStructuredOutput?.schema ?? (structuredOutput?.schema ? toLiveStructuredOutputSchema(structuredOutput.schema, structuredOutput.nullToUndefined) : void 0);
73037
73800
  let structuredOutputChunks;
73801
+ let object;
73038
73802
  const structuringParts = structuredOutput?.hasStructuringModel ? responseStreamParts(messageList) : void 0;
73039
73803
  if (structuredOutputSchema && (structuredOutputText.trim() || structuringParts?.length)) {
73040
73804
  const finishReason = outputResult?.finishReason;
73041
73805
  const truncated = finishReason === "length" || finishReason === "content-filter";
73806
+ const failed = finishReason === "abort" || finishReason === "error";
73042
73807
  const errorStrategy = liveStructuredOutput ? liveStructuredOutput.errorStrategy : structuredOutput?.errorStrategy;
73043
73808
  const fallbackValue = liveStructuredOutput ? liveStructuredOutput.fallbackValue : structuredOutput?.fallbackValue;
73044
73809
  let value;
73045
73810
  if (structuredOutput?.hasStructuringModel) {
73046
73811
  const structuringModel = liveStructuredOutput?.model ?? structuredOutput.structuringModelConfig?.originalConfig;
73047
- if (structuringModel && !truncated && !(finishReason === "abort" || finishReason === "error")) {
73812
+ if (structuringModel && !truncated && !failed) {
73048
73813
  structuredOutputChunks = await runStructuringPass({
73049
73814
  options: {
73050
73815
  ...liveStructuredOutput ?? {},
@@ -73070,6 +73835,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73070
73835
  value = result?.success ? result.value : errorStrategy === "fallback" ? fallbackValue : void 0;
73071
73836
  }
73072
73837
  const lastAssistantMessage = messageList.get.response.db().findLast((message) => message.role === "assistant" && !message.content?.metadata?.completionResult);
73838
+ object = failed ? void 0 : value;
73073
73839
  if (value !== void 0 && lastAssistantMessage) lastAssistantMessage.content.metadata = {
73074
73840
  ...lastAssistantMessage.content.metadata,
73075
73841
  structuredOutput: value
@@ -73262,6 +74028,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73262
74028
  titleGeneration,
73263
74029
  titleForStream,
73264
74030
  structuredOutputChunks,
74031
+ object,
73265
74032
  outputResultChunks
73266
74033
  };
73267
74034
  }
@@ -73313,7 +74080,7 @@ function deadlineMessageListState(entry, fallback) {
73313
74080
  */
73314
74081
  async function runDurableDeadlineOutputPass({ runId, initData, messageListState, cutOffText, entry, mastra, tracingContext, logger }) {
73315
74082
  const durableState = initData.state;
73316
- const requestContext = restoreRequestContext(initData.requestContextEntries, entry.requestContext);
74083
+ const requestContext = mergeRequestContextForFinalization(initData.requestContextEntries, void 0, getLiveRunRequestContext(entry));
73317
74084
  if (!requestContext.has("MastraMemory") && durableState?.threadId) requestContext.set("MastraMemory", {
73318
74085
  thread: { id: durableState.threadId },
73319
74086
  resourceId: durableState.resourceId,
@@ -73756,11 +74523,17 @@ const accumulatedUsageSchema = zod.z.object({
73756
74523
  reasoningTokens: zod.z.number().optional()
73757
74524
  });
73758
74525
  /**
73759
- * Provider id and serving model of one response.
74526
+ * One response: the provider's id and model for it, the configured model that
74527
+ * answered, and the cost the provider reported for it.
73760
74528
  */
73761
74529
  const responseRecordSchema = zod.z.object({
73762
74530
  id: zod.z.string().optional(),
73763
- modelId: zod.z.string().optional()
74531
+ modelId: zod.z.string().optional(),
74532
+ servedBy: zod.z.object({
74533
+ provider: zod.z.string(),
74534
+ modelId: zod.z.string()
74535
+ }).optional(),
74536
+ reportedCost: zod.z.custom().optional()
73764
74537
  });
73765
74538
  /**
73766
74539
  * Schema for output from the durable agentic workflow
@@ -73820,6 +74593,8 @@ const baseIterationStateSchema = zod.z.object({
73820
74593
  accumulatedSteps: zod.z.array(zod.z.any()).optional(),
73821
74594
  accumulatedUsage: accumulatedUsageSchema,
73822
74595
  usageAggregationVersion: zod.z.literal(1).optional(),
74596
+ generationReportedUsage: accumulatedUsageSchema.optional(),
74597
+ generationReportedSteps: zod.z.number().optional(),
73823
74598
  lastStepResult: zod.z.any().optional(),
73824
74599
  deferredStepFinishChunk: zod.z.any().optional(),
73825
74600
  backgroundTaskPending: zod.z.boolean().optional(),
@@ -73842,6 +74617,7 @@ const baseIterationStateSchema = zod.z.object({
73842
74617
  completionStartTime: zod.z.coerce.date().optional(),
73843
74618
  timeToFirstTokenMs: zod.z.number().optional(),
73844
74619
  lastResponse: responseRecordSchema.optional(),
74620
+ reportedCosts: zod.z.array(zod.z.custom().nullable()).optional(),
73845
74621
  tracingStopCause: zod.z.enum(CONTINUATION_STOP_CAUSES).optional(),
73846
74622
  tracingTermination: zod.z.custom().optional(),
73847
74623
  tracingDelegationFailure: zod.z.custom().optional()
@@ -73894,7 +74670,7 @@ function buildStepRecord(executionOutput) {
73894
74670
  text: executionOutput.output.text,
73895
74671
  content: executionOutput.output.content,
73896
74672
  toolCalls: executionOutput.output.toolCalls,
73897
- toolResults: executionOutput.toolResults?.map(({ stepSpanData: _stepSpanData, tracingDelegationFailure: _tracingDelegationFailure, ...result }) => result),
74673
+ toolResults: executionOutput.toolResults?.map(({ stepSpanData: _stepSpanData, tracingDelegationFailure: _tracingDelegationFailure, response: _response, sideBySide: _sideBySide, ...result }) => result),
73898
74674
  usage: executionOutput.output.usage,
73899
74675
  finishReason: executionOutput.stepResult.reason,
73900
74676
  tripwire: executionOutput.stepResult.tripwire
@@ -73979,6 +74755,13 @@ function createBaseIterationStateUpdate(input) {
73979
74755
  accumulatedSteps: signalPreempted ? previousSteps : [...withReleasedToolResults(previousSteps, executionOutput.releasedToolResultIds), buildStepRecord(executionOutput)],
73980
74756
  accumulatedUsage: newUsage,
73981
74757
  usageAggregationVersion: signalPreempted ? currentState.usageAggregationVersion : 1,
74758
+ ...currentState.generationReportedUsage && executionOutput.suspensionReportedUsage && !require_observability.isUsageIncomplete(newUsage) ? {
74759
+ generationReportedUsage: newUsage,
74760
+ generationReportedSteps: previousSteps.length + 1
74761
+ } : {
74762
+ generationReportedUsage: currentState.generationReportedUsage,
74763
+ generationReportedSteps: currentState.generationReportedSteps
74764
+ },
73982
74765
  lastStepResult,
73983
74766
  deferredStepFinishChunk: executionOutput.deferredStepFinishChunk,
73984
74767
  backgroundTaskPending: executionOutput.backgroundTaskPending,
@@ -73997,6 +74780,7 @@ function createBaseIterationStateUpdate(input) {
73997
74780
  timeToFirstTokenMs: executionOutput.timeToFirstTokenMs
73998
74781
  },
73999
74782
  lastResponse: signalPreempted ? currentState.lastResponse : executionOutput.response,
74783
+ reportedCosts: signalPreempted ? currentState.reportedCosts : [...previousSteps.map((_, index) => currentState.reportedCosts?.[index] ?? null), executionOutput.response?.reportedCost ?? null],
74000
74784
  tracingTermination: executionOutput.tracingTermination,
74001
74785
  tracingDelegationFailure: executionOutput.tracingDelegationFailure
74002
74786
  };
@@ -74074,6 +74858,14 @@ function resolveDurableToolCallConcurrency({ options, toolsMetadata, toolCalls }
74074
74858
  if (consideredTools.some((tool) => tool.hasSuspendSchema || tool.requireApproval)) return 1;
74075
74859
  return limit > 0 ? limit : DurableAgentDefaults.TOOL_CALL_CONCURRENCY;
74076
74860
  }
74861
+ /**
74862
+ * Whether the step's tool calls run at the same time. Then more than one can suspend in the same
74863
+ * execution, on workers that share no memory, so none of them can report the step's model usage
74864
+ * exactly once. The run's last execution reports it instead.
74865
+ */
74866
+ function toolCallsRunSideBySide(args) {
74867
+ return (args.toolCalls?.length ?? 0) > 1 && resolveDurableToolCallConcurrency(args) > 1;
74868
+ }
74077
74869
  // src/agent/durable/workflows/steps/background-task-check.ts
74078
74870
  const BG_CHECK_STEP_ID = `${DurableStepIds.AGENTIC_EXECUTION}-bg-task-check`;
74079
74871
  /**
@@ -75032,6 +75824,9 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
75032
75824
  }
75033
75825
  }
75034
75826
  spans.flushSpansLeftOpen(parts);
75827
+ if (!chunks.some((chunk) => chunk.type === "finish" || chunk.type === "step-finish")) {
75828
+ for (const part of parts) if (part.type === "text" || part.type === "reasoning") dropResponseItemIds(part);
75829
+ }
75035
75830
  const nonEmptyParts = parts.filter((p) => !(p.type === "text" && p.text === "" && p.providerMetadata == null));
75036
75831
  const finalParts = [];
75037
75832
  for (let i = 0; i < nonEmptyParts.length; i++) {
@@ -75052,6 +75847,16 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
75052
75847
  }
75053
75848
  }];
75054
75849
  }
75850
+ function dropResponseItemIds(part) {
75851
+ if (!part.providerMetadata) return;
75852
+ const providerMetadata = Object.fromEntries(Object.entries(part.providerMetadata).map(([provider, value]) => {
75853
+ if (!value || typeof value !== "object" || !("itemId" in value)) return [provider, value];
75854
+ const { itemId: _itemId, ...rest } = value;
75855
+ return [provider, rest];
75856
+ }).filter(([, value]) => !(value && typeof value === "object" && Object.keys(value).length === 0)));
75857
+ if (Object.keys(providerMetadata).length > 0) part.providerMetadata = providerMetadata;
75858
+ else delete part.providerMetadata;
75859
+ }
75055
75860
  // src/loop/workflows/agentic-execution/provider-tool-spans.ts
75056
75861
  function endPendingProviderToolSpan({ toolCallId, pending, parentSpan, result, logger }) {
75057
75862
  let span;
@@ -75122,6 +75927,20 @@ function resolveMaxProcessorRetries({ maxProcessorRetries, hasErrorProcessors, h
75122
75927
  }
75123
75928
  return 3;
75124
75929
  }
75930
+ // src/agent/durable/workflows/shared/reported-cost.ts
75931
+ /**
75932
+ * The part of a step's provider metadata that says what the call cost. The rest, such as search
75933
+ * grounding, can be large, and the loop state that carries this is saved with the run.
75934
+ */
75935
+ function reportedCost(metadata) {
75936
+ const cost = metadata?.gateway?.cost;
75937
+ const usage = metadata?.openrouter?.usage;
75938
+ if (cost === void 0 && usage === void 0) return void 0;
75939
+ return {
75940
+ ...cost === void 0 ? {} : { gateway: { cost } },
75941
+ ...usage === void 0 ? {} : { openrouter: { usage } }
75942
+ };
75943
+ }
75125
75944
  // src/agent/durable/workflows/steps/llm-execution.ts
75126
75945
  /**
75127
75946
  * Detect a run-level budget expiry (`modelSettings.timeout.totalMs`, #21724
@@ -75273,12 +76092,13 @@ function createDurableLLMExecutionStep(_options) {
75273
76092
  inputSchema: durableLLMInputSchema,
75274
76093
  outputSchema: durableLLMOutputSchema,
75275
76094
  execute: withStepLifetime(async (params, stepLifetime) => {
75276
- const { inputData, mastra, tracingContext, requestContext, abortSignal } = params;
76095
+ const { inputData, mastra, tracingContext, abortSignal } = params;
75277
76096
  const ownership = getExecutionOwnershipGuard(params);
75278
76097
  const pubsub = params[require_workflows_constants.PUBSUB_SYMBOL];
75279
76098
  const typedInput = inputData;
75280
76099
  const { agentId, messageId, options: execOptions } = typedInput;
75281
76100
  const runId = typedInput.runId;
76101
+ const requestContext = getLiveRunRequestContext(getRunRegistryEntry(runId, mastra)) ?? params.requestContext;
75282
76102
  const logger = mastra?.getLogger?.();
75283
76103
  if (pubsub) await emitIterationStartEvent(pubsub, runId, inputData.stepIndex ?? 0);
75284
76104
  const { messageList, tools, model: resolvedModel, modelList: resolvedModelList, inputProcessors: resolvedInputProcessors, llmRequestInputProcessors: resolvedLlmRequestInputProcessors, outputProcessors: resolvedOutputProcessors } = await resolveRuntimeDependencies({
@@ -75309,7 +76129,7 @@ function createDurableLLMExecutionStep(_options) {
75309
76129
  }
75310
76130
  } : void 0;
75311
76131
  if (pubsub) try {
75312
- await ensureRemoteAbortListener(pubsub, runId, mastra, readRunDeadline(requestContext));
76132
+ await ensureRemoteAbortListener(pubsub, runId, mastra, readRunDeadline(params.requestContext));
75313
76133
  } catch (error) {
75314
76134
  ownership?.throwIfLost();
75315
76135
  logger?.warn?.("Failed to subscribe to cross-process abort requests", {
@@ -75317,6 +76137,8 @@ function createDurableLLMExecutionStep(_options) {
75317
76137
  error: error instanceof Error ? error.message : String(error)
75318
76138
  });
75319
76139
  }
76140
+ const runEntry = getRunRegistryEntry(runId, mastra);
76141
+ if (runEntry) runEntry.openStepSpan = void 0;
75320
76142
  let request = {};
75321
76143
  let terminateAttemptSpans;
75322
76144
  let tracingTermination;
@@ -76972,6 +77794,7 @@ function createDurableLLMExecutionStep(_options) {
76972
77794
  tripwire: stepTripwire
76973
77795
  });
76974
77796
  const stepSpanData = hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.exportCurrentStep() : void 0;
77797
+ if (registryEntry && stepSpanData) registryEntry.openStepSpan = observability?.rebuildSpan(stepSpanData);
76975
77798
  const stepFinishPayload = hasToolCalls && !processOutputStepTripwire ? modelSpanTracker?.getPendingStepFinishPayload() : void 0;
76976
77799
  const output = {
76977
77800
  ...await storeStepTranscript(),
@@ -76995,7 +77818,12 @@ function createDurableLLMExecutionStep(_options) {
76995
77818
  },
76996
77819
  response: deferredStepFinishChunk ? {
76997
77820
  id: deferredStepFinishChunk.payload?.metadata?.id,
76998
- modelId: resolveResponseModelId(deferredStepFinishChunk.payload?.metadata?.providerMetadata, deferredStepFinishChunk.payload?.metadata?.modelId)
77821
+ modelId: resolveResponseModelId(deferredStepFinishChunk.payload?.metadata?.providerMetadata, deferredStepFinishChunk.payload?.metadata?.modelId),
77822
+ ...cachedResponse ? {} : { servedBy: {
77823
+ provider: currentModel.provider,
77824
+ modelId: currentModel.modelId
77825
+ } },
77826
+ reportedCost: reportedCost(deferredStepFinishChunk.payload?.metadata?.providerMetadata)
76999
77827
  } : void 0,
77000
77828
  state: typedInput.state,
77001
77829
  modelSpanData: hasToolCalls && !processOutputStepTripwire ? modelSpan?.snapshot?.() ?? modelSpan?.exportSpan() : void 0,
@@ -77006,6 +77834,7 @@ function createDurableLLMExecutionStep(_options) {
77006
77834
  ...releasedToolResultIds.length ? { releasedToolResultIds } : {},
77007
77835
  tracingTermination
77008
77836
  };
77837
+ if (effectiveOutputProcessors.length > 0 && registryEntry?.processorStates) getToolResultRunner().endStreamProcessorSpans(registryEntry.processorStates, { stepScopedOnly: true });
77009
77838
  if (!hasToolCalls || processOutputStepTripwire) {
77010
77839
  const pendingPayload = modelSpanTracker?.getPendingStepFinishPayload();
77011
77840
  if (pendingPayload) {
@@ -78061,7 +78890,9 @@ const durableToolCallInputSchema = zod.z.object({
78061
78890
  stepSpanData: zod.z.any().optional(),
78062
78891
  completionStartTime: zod.z.coerce.date().optional(),
78063
78892
  timeToFirstTokenMs: zod.z.number().optional(),
78064
- stepUsage: zod.z.any().optional()
78893
+ stepUsage: zod.z.any().optional(),
78894
+ sideBySide: zod.z.boolean().optional(),
78895
+ response: responseRecordSchema.optional()
78065
78896
  });
78066
78897
  /**
78067
78898
  * Output schema for the durable tool call step.
@@ -78279,7 +79110,7 @@ function createDurableToolCallStep() {
78279
79110
  const initData = getInitData();
78280
79111
  const { runId, options: agentOptions, state } = initData;
78281
79112
  const logger = mastra?.getLogger?.();
78282
- const endSpansAsSuspended = (info) => {
79113
+ const endSpansAsSuspended = async (info) => {
78283
79114
  try {
78284
79115
  const obs = mastra?.observability?.getSelectedInstance({ requestContext });
78285
79116
  if (!obs) return;
@@ -78291,6 +79122,15 @@ function createDurableToolCallStep() {
78291
79122
  };
78292
79123
  const reg = getRunRegistryEntry(runId, mastra);
78293
79124
  const segment = segmentSpanData(requestContext, runId, initData, reg);
79125
+ if (typedInput.sideBySide && !segment.carried) {
79126
+ if (!(await claimSegmentEnd({
79127
+ mastra,
79128
+ requestContext,
79129
+ runId,
79130
+ iterationCount: initData.iterationCount,
79131
+ outcome: "suspend"
79132
+ }) ?? await assertOwned().then(() => true, (error) => !isExecutionFenceError(error)))) return;
79133
+ }
78294
79134
  const { agentSpanData, modelSpanData } = segment;
78295
79135
  const attributes = carriedSpanClocks(reg, initData.completionStartTime ? {
78296
79136
  completionStartTime: initData.completionStartTime,
@@ -78299,26 +79139,57 @@ function createDurableToolCallStep() {
78299
79139
  completionStartTime: typedInput.completionStartTime,
78300
79140
  timeToFirstTokenMs: typedInput.timeToFirstTokenMs
78301
79141
  }, segment.carried);
78302
- if (typedInput.stepSpanData && segmentOwnsStep(segment, typedInput.stepSpanData)) obs.rebuildSpan(typedInput.stepSpanData)?.end({
78303
- output,
78304
- outcome: "suspend",
78305
- stopReason: info.reason === "approval" ? "approval_required" : null,
78306
- stopReasonContext: info.reason === "approval" ? require_observability.compactStopReasonContext("approval_required", {
78307
- toolCallId: info.toolCallId,
78308
- toolName: info.toolName
78309
- }) : null
78310
- });
78311
- if (modelSpanData) obs.rebuildSpan(modelSpanData)?.end({
78312
- output,
78313
- attributes,
78314
- outcome: "suspend",
78315
- stopReason: info.reason === "approval" ? "approval_required" : null,
78316
- stopReasonContext: info.reason === "approval" ? require_observability.compactStopReasonContext("approval_required", {
78317
- toolCallId: info.toolCallId,
78318
- toolName: info.toolName
78319
- }) : null
78320
- });
78321
- if (agentSpanData) obs.rebuildSpan(agentSpanData)?.end({
79142
+ const ownsStep = !!typedInput.stepSpanData && segmentOwnsStep(segment, typedInput.stepSpanData);
79143
+ const reported = initData.generationReportedUsage;
79144
+ const total = calculateAccumulatedUsage(initData.accumulatedUsage, typedInput.stepUsage);
79145
+ const usage = reported && ownsStep && !typedInput.sideBySide && !require_observability.isUsageIncomplete(total) ? require_observability.subtractReportedUsage(total, reported) : void 0;
79146
+ if (ownsStep) {
79147
+ const stepSpanData = typedInput.stepSpanData;
79148
+ (liveSegmentSpan(stepSpanData, reg?.openStepSpan) ?? obs.rebuildSpan(stepSpanData))?.end({
79149
+ output,
79150
+ ...reported ? { attributes: { usage: require_observability.extractUsageMetrics(typedInput.stepUsage) } } : {},
79151
+ outcome: "suspend",
79152
+ stopReason: info.reason === "approval" ? "approval_required" : null,
79153
+ stopReasonContext: info.reason === "approval" ? require_observability.compactStopReasonContext("approval_required", {
79154
+ toolCallId: info.toolCallId,
79155
+ toolName: info.toolName
79156
+ }) : null
79157
+ });
79158
+ }
79159
+ const agentSpan = agentSpanData && obs.rebuildSpan(agentSpanData);
79160
+ if (modelSpanData) {
79161
+ const end = {
79162
+ output,
79163
+ attributes,
79164
+ outcome: "suspend",
79165
+ stopReason: info.reason === "approval" ? "approval_required" : null,
79166
+ stopReasonContext: info.reason === "approval" ? require_observability.compactStopReasonContext("approval_required", {
79167
+ toolCallId: info.toolCallId,
79168
+ toolName: info.toolName
79169
+ }) : null
79170
+ };
79171
+ const modelSpan = obs.rebuildSpan(modelSpanData);
79172
+ if (modelSpan?.isInternal) modelSpan.parent ??= agentSpan;
79173
+ if (usage) {
79174
+ const servedBy = typedInput.response?.servedBy;
79175
+ const servedName = servedBy && `llm: '${servedBy.modelId}'`;
79176
+ if (servedName && modelSpan && modelSpan.name !== servedName) modelSpan.update({ name: servedName });
79177
+ const costs = initData.reportedCosts?.slice(initData.generationReportedSteps ?? 0) ?? [];
79178
+ modelSpan?.createTracker()?.endGeneration({
79179
+ ...end,
79180
+ attributes: {
79181
+ ...attributes,
79182
+ ...servedBy ? {
79183
+ model: servedBy.modelId,
79184
+ provider: servedBy.provider
79185
+ } : {}
79186
+ },
79187
+ usage,
79188
+ stepProviderMetadata: [...costs, typedInput.response?.reportedCost].map((cost) => cost ?? void 0)
79189
+ });
79190
+ } else modelSpan?.end(end);
79191
+ }
79192
+ agentSpan?.end({
78322
79193
  output,
78323
79194
  attributes,
78324
79195
  outcome: "suspend",
@@ -78509,7 +79380,7 @@ function createDurableToolCallStep() {
78509
79380
  }).add(invocation, "memory");
78510
79381
  }
78511
79382
  if (saveQueueManager && messagesToFlush && memory && state?.threadId && state.resourceId && !state.memoryConfig?.readOnly) {
78512
- const authorizationRequestContext = registryEntry?.requestContext ?? restoreRequestContext$1(initData.requestContextEntries, requestContext);
79383
+ const authorizationRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext);
78513
79384
  const authorizeMemory = (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
78514
79385
  mastra,
78515
79386
  user: authorizationRequestContext.get("user"),
@@ -78553,7 +79424,7 @@ function createDurableToolCallStep() {
78553
79424
  };
78554
79425
  const registryRequireToolApproval = registryEntry?.requireToolApproval;
78555
79426
  const effectiveRequireToolApproval = registryRequireToolApproval !== void 0 ? registryRequireToolApproval : agentOptions.requireToolApproval;
78556
- const approvalRequestContext = registryEntry?.requestContext ?? restoreRequestContext$1(initData.requestContextEntries, requestContext);
79427
+ const approvalRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext);
78557
79428
  const requiresApproval = await toolRequiresApproval(tool, effectiveRequireToolApproval, args, {
78558
79429
  toolName,
78559
79430
  requestContext: Object.fromEntries([...approvalRequestContext.entries()].filter(([key]) => !INTERNAL_APPROVAL_KEYS.has(key))),
@@ -78786,7 +79657,7 @@ function createDurableToolCallStep() {
78786
79657
  type: "approval",
78787
79658
  resumeSchema: approvalResumeSchema
78788
79659
  }));
78789
- endSpansAsSuspended({
79660
+ await endSpansAsSuspended({
78790
79661
  toolCallId,
78791
79662
  toolName,
78792
79663
  reason: "approval"
@@ -79008,7 +79879,7 @@ function createDurableToolCallStep() {
79008
79879
  type: "approval",
79009
79880
  resumeSchema: approvalResumeSchema
79010
79881
  }));
79011
- endSpansAsSuspended({
79882
+ await endSpansAsSuspended({
79012
79883
  toolCallId,
79013
79884
  toolName: approvalToolName,
79014
79885
  reason: "approval"
@@ -79063,7 +79934,7 @@ function createDurableToolCallStep() {
79063
79934
  await publishAfterPersist(() => emitChunkEvent(pubsub, runId, suspensionChunk));
79064
79935
  await publishAfterPersist(() => emitSuspendedEvent(pubsub, runId, suspendedEventData));
79065
79936
  }
79066
- endSpansAsSuspended({
79937
+ await endSpansAsSuspended({
79067
79938
  toolCallId,
79068
79939
  toolName,
79069
79940
  reason: "suspension"
@@ -79278,7 +80149,7 @@ function createDurableToolCallStep() {
79278
80149
  toolCallId: params.toolCallId,
79279
80150
  toolName: params.toolName,
79280
80151
  status: params.status === "failed" ? "failed" : "completed",
79281
- requestContext: registryEntry?.requestContext ?? restoreRequestContext$1(initData.requestContextEntries, requestContext)
80152
+ requestContext: restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext)
79282
80153
  });
79283
80154
  } catch (error) {
79284
80155
  resolveReconciliation({ error });
@@ -79819,7 +80690,8 @@ const durableLLMMappingOutputSchema = zod.z.object({
79819
80690
  deferredStepFinishChunk: zod.z.any().optional(),
79820
80691
  completionStartTime: zod.z.coerce.date().optional(),
79821
80692
  timeToFirstTokenMs: zod.z.number().optional(),
79822
- response: responseRecordSchema.optional()
80693
+ response: responseRecordSchema.optional(),
80694
+ suspensionReportedUsage: zod.z.boolean().optional()
79823
80695
  });
79824
80696
  /**
79825
80697
  * Create a durable LLM mapping step.
@@ -79890,8 +80762,19 @@ function createDurableLLMMappingStep() {
79890
80762
  const isPendingClientCall = (toolResult) => toolResult.result === void 0 && !toolResult.error && !toolResult.aborted && !toolResult.resultBlocked && !toolResult.providerExecuted && !isDeniedApproval(toolResult);
79891
80763
  const registryTools = registryEntry?.tools;
79892
80764
  let stepSpan;
80765
+ let suspensionReportedUsage = false;
79893
80766
  if (llmOutput.stepSpanData) try {
79894
- if (segmentOwnsStep(segmentSpanData(requestContext, _runId, getInitData(), getRunRegistryEntry(_runId, mastra)), llmOutput.stepSpanData)) stepSpan = (mastra?.observability?.getSelectedInstance({ requestContext }))?.rebuildSpan(llmOutput.stepSpanData);
80767
+ const initData = getInitData();
80768
+ const reg = getRunRegistryEntry(_runId, mastra);
80769
+ if (segmentOwnsStep(segmentSpanData(requestContext, _runId, initData, reg), llmOutput.stepSpanData)) {
80770
+ const observability = mastra?.observability?.getSelectedInstance({ requestContext });
80771
+ const stepSpanData = llmOutput.stepSpanData;
80772
+ stepSpan = liveSegmentSpan(stepSpanData, reg?.openStepSpan) ?? observability?.rebuildSpan(stepSpanData);
80773
+ } else suspensionReportedUsage = !toolCallsRunSideBySide({
80774
+ options: initData.options,
80775
+ toolsMetadata: initData.toolsMetadata,
80776
+ toolCalls: llmOutput.toolCalls
80777
+ });
79895
80778
  } catch {}
79896
80779
  if (toolResults.length > 0) {
79897
80780
  const runStopped = toolResults.some((result) => result.deadlineTimeout || result.runAborted);
@@ -80026,6 +80909,7 @@ function createDurableLLMMappingStep() {
80026
80909
  delegationBailed,
80027
80910
  tracingDelegationFailure,
80028
80911
  tracingTermination: llmOutput.tracingTermination,
80912
+ ...suspensionReportedUsage ? { suspensionReportedUsage } : {},
80029
80913
  ...deadlineTimeout ? { deadlineTimeout } : {},
80030
80914
  ...runAborted ? { runAborted } : {},
80031
80915
  deferredStepFinishChunk,
@@ -80329,7 +81213,7 @@ function createDurableIsTaskCompleteStep(defaultMaxSteps = DurableAgentDefaults.
80329
81213
  const restored = await restoreCompletionPolicy({
80330
81214
  agent,
80331
81215
  persisted: initData.options.isTaskComplete,
80332
- requestContext: restoreRequestContext$1(initData.requestContextEntries, registryEntry?.requestContext),
81216
+ requestContext: restoreRequestContext(initData.requestContextEntries, registryEntry?.requestContext, getLiveRunRequestContext(registryEntry)),
80333
81217
  runId: state.runId,
80334
81218
  logger: mastra?.getLogger?.()
80335
81219
  });
@@ -80413,9 +81297,10 @@ function createDurableGoalStep() {
80413
81297
  const registryEntry = getRunRegistryEntry(state.runId, mastra);
80414
81298
  let goalConfig = registryEntry?.goal;
80415
81299
  if (!goalConfig && initData.agentId) goalConfig = mastra?.getAgentById?.(initData.agentId)?.__getGoalConfig?.();
80416
- const liveRequestContext = registryEntry?.requestContext ?? params.requestContext;
80417
- const requestContext = restoreRequestContext$1(initData.requestContextEntries, liveRequestContext);
80418
- const customContext = restoreCustomContext(initData.requestContextEntries, liveRequestContext);
81300
+ const liveRunContext = getLiveRunRequestContext(registryEntry);
81301
+ const currentRequestContext = liveRunContext ?? params.requestContext;
81302
+ const requestContext = restoreRequestContext(initData.requestContextEntries, params.requestContext, liveRunContext);
81303
+ const customContext = restoreCustomContext(initData.requestContextEntries, currentRequestContext);
80419
81304
  if (!goalConfig) return state;
80420
81305
  const messageListState = await readMessageListState(params, state);
80421
81306
  let messageList;
@@ -80486,7 +81371,6 @@ function withParams(params, overrides) {
80486
81371
  };
80487
81372
  return Object.defineProperties({}, descriptors);
80488
81373
  }
80489
- const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
80490
81374
  /**
80491
81375
  * Historical default persistence policy for durable agent workflows.
80492
81376
  *
@@ -80838,14 +81722,22 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80838
81722
  completionStartTime: state.completionStartTime,
80839
81723
  timeToFirstTokenMs: state.timeToFirstTokenMs
80840
81724
  };
80841
- }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData }) => {
81725
+ }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData, getInitData }) => {
80842
81726
  const llmOutput = inputData;
81727
+ const state = getInitData();
81728
+ const sideBySide = toolCallsRunSideBySide({
81729
+ options: state?.options,
81730
+ toolsMetadata: state?.toolsMetadata,
81731
+ toolCalls: llmOutput.toolCalls
81732
+ });
80843
81733
  return (llmOutput.toolCalls ?? []).map((toolCall) => ({
80844
81734
  ...toolCall,
80845
81735
  stepSpanData: llmOutput.stepSpanData,
80846
81736
  completionStartTime: llmOutput.completionStartTime,
80847
81737
  timeToFirstTokenMs: llmOutput.timeToFirstTokenMs,
80848
- stepUsage: llmOutput.stepResult?.totalUsage
81738
+ stepUsage: llmOutput.stepResult?.totalUsage,
81739
+ response: llmOutput.response,
81740
+ ...sideBySide ? { sideBySide } : {}
80849
81741
  }));
80850
81742
  }, { id: "extract-tool-calls" }).foreach(toolCallStep, { concurrency: ({ inputData, getInitData }) => {
80851
81743
  const state = getInitData();
@@ -81131,6 +82023,11 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81131
82023
  totalTokens: 0
81132
82024
  },
81133
82025
  usageAggregationVersion: 1,
82026
+ generationReportedUsage: {
82027
+ inputTokens: 0,
82028
+ outputTokens: 0,
82029
+ totalTokens: 0
82030
+ },
81134
82031
  lastStepResult: void 0
81135
82032
  };
81136
82033
  }, { id: "init-iteration-state" }).dowhile(this.buildIterationWorkflow(), markFrameworkCondition(this.buildContinuationPredicate())).map(async (params) => {
@@ -81156,13 +82053,24 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81156
82053
  user: finalMessageList.get.input.aiV5.model(),
81157
82054
  nonUser: finalMessageList.get.response.aiV5.model()
81158
82055
  };
82056
+ const reg = getRunRegistryEntry(initData.runId, mastra);
82057
+ let observability;
82058
+ let segment;
82059
+ let agentSpan;
82060
+ try {
82061
+ observability = mastra?.observability?.getSelectedInstance({ requestContext });
82062
+ segment = segmentSpanData(requestContext, initData.runId, initData, reg);
82063
+ agentSpan = liveOrRebuiltAgentSpan(segment.agentSpanData, reg, observability);
82064
+ } catch (error) {
82065
+ logger?.warn?.(`[DurableAgent] Error resolving the run span: ${error}`);
82066
+ }
81159
82067
  const finishResult = await runDurableFinishSideEffects({
81160
82068
  runId: state.runId,
81161
82069
  initData,
81162
82070
  messageListState,
81163
82071
  mastra,
81164
82072
  requestContext,
81165
- tracingContext,
82073
+ tracingContext: agentSpan ? { currentSpan: agentSpan } : tracingContext,
81166
82074
  logger,
81167
82075
  messageId: state.messageId,
81168
82076
  outputResult: {
@@ -81236,7 +82144,6 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81236
82144
  },
81237
82145
  state: state.state
81238
82146
  };
81239
- const reg = getRunRegistryEntry(initData.runId, mastra);
81240
82147
  const stopCause = state.tracingStopCause ?? reg?.tracingStopCause;
81241
82148
  if (pubsub) await emitFinishEvent(pubsub, state.runId, {
81242
82149
  output: finalOutput.output,
@@ -81249,30 +82156,35 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81249
82156
  const finishReason = finalOutput.stepResult?.reason;
81250
82157
  const recordedTermination = state.tracingTermination ?? reg?.tracingTermination;
81251
82158
  if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) logger?.warn?.(`[DurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
82159
+ const runTripwire = tripwire ?? state.lastStepResult?.tripwire ?? initData.inputTripwire;
81252
82160
  const termination = ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : require_observability.agentLoopTermination({
81253
82161
  stopCause,
81254
82162
  delegationFailure: state.tracingDelegationFailure ?? reg?.tracingDelegationFailure,
81255
82163
  finishReason,
81256
- tripwire: tripwire ?? state.lastStepResult?.tripwire,
82164
+ tripwire: runTripwire,
81257
82165
  maxSteps: initData.options?.maxSteps
81258
82166
  });
81259
82167
  try {
81260
- const observability = mastra?.observability?.getSelectedInstance({ requestContext });
81261
- const { agentSpanData, modelSpanData, carried } = segmentSpanData(requestContext, initData.runId, initData, reg);
81262
- const clocks = carriedSpanClocks(reg, state, carried);
82168
+ const clocks = carriedSpanClocks(reg, state, segment?.carried);
81263
82169
  if (observability) {
82170
+ const modelSpanData = segment?.modelSpanData;
81264
82171
  if (modelSpanData) {
81265
82172
  const modelSpan = liveSegmentSpan(modelSpanData, reg?.resumeModelSpan, reg?.modelSpan) ?? observability.rebuildSpan(modelSpanData);
82173
+ if (modelSpan?.isInternal) modelSpan.parent ??= agentSpan;
81266
82174
  const toolCalls = steps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
81267
82175
  toolCallId: tc.toolCallId,
81268
82176
  toolName: tc.toolName,
81269
82177
  args: tc.args
81270
82178
  })));
81271
82179
  const usageIncomplete = require_observability.isUsageIncomplete(state.accumulatedUsage);
82180
+ const servedBy = state.lastResponse?.servedBy;
82181
+ const servedName = servedBy && `llm: '${servedBy.modelId}'`;
82182
+ if (servedName && modelSpan && modelSpan.name !== servedName) modelSpan.update({ name: servedName });
81272
82183
  modelSpan?.createTracker()?.endGeneration({
81273
82184
  ...termination,
81274
82185
  output: {
81275
82186
  text: finalText,
82187
+ object: finishResult.object,
81276
82188
  toolCalls: toolCalls.length ? toolCalls : void 0
81277
82189
  },
81278
82190
  attributes: {
@@ -81280,15 +82192,32 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
81280
82192
  ...usageIncomplete ? { usageIncomplete: true } : {},
81281
82193
  ...clocks,
81282
82194
  responseId: state.lastResponse?.id,
81283
- responseModel: state.lastResponse?.modelId
82195
+ responseModel: state.lastResponse?.modelId,
82196
+ ...servedBy ? {
82197
+ model: servedBy.modelId,
82198
+ provider: servedBy.provider
82199
+ } : {}
81284
82200
  },
81285
- usage: usageIncomplete ? require_observability.calculateObservedUsage(steps) : state.accumulatedUsage
82201
+ usage: require_observability.subtractReportedUsage(usageIncomplete ? require_observability.calculateObservedUsage(steps) : state.accumulatedUsage, state.generationReportedUsage),
82202
+ stepProviderMetadata: state.reportedCosts?.slice(state.generationReportedSteps ?? 0).map((cost) => cost ?? void 0)
81286
82203
  });
81287
82204
  }
81288
- liveOrRebuiltAgentSpan(agentSpanData, reg, observability)?.end({
82205
+ agentSpan?.end({
81289
82206
  ...termination,
81290
- output: { text: finalText },
81291
- ...clocks ? { attributes: clocks } : {}
82207
+ output: {
82208
+ text: finalText,
82209
+ object: finishResult.object,
82210
+ ...runTripwire ? { tripwire: runTripwire } : {}
82211
+ },
82212
+ attributes: {
82213
+ ...clocks,
82214
+ ...runTripwire ? { tripwireAbort: {
82215
+ reason: runTripwire.reason,
82216
+ processorId: runTripwire.processorId,
82217
+ retry: runTripwire.retry,
82218
+ metadata: runTripwire.metadata
82219
+ } } : {}
82220
+ }
81292
82221
  });
81293
82222
  }
81294
82223
  } catch (error) {
@@ -81387,19 +82316,20 @@ var DefaultAgentExecutionEngine = class {
81387
82316
  keepReplayEvent,
81388
82317
  attachedAtLogIndex
81389
82318
  };
81390
- const skipped = history.slice(0, offset);
81391
- if (skipped.length === offset) {
81392
- let floor;
81393
- for (const event of skipped) {
81394
- const generation = event.generation;
81395
- if (typeof generation === "number" && (floor === void 0 || generation > floor)) floor = generation;
81396
- }
81397
- return {
81398
- minGeneration: floor,
81399
- keepReplayEvent,
81400
- attachedAtLogIndex
81401
- };
81402
- }
82319
+ let first;
82320
+ let floor;
82321
+ for (const event of history) {
82322
+ const index = event.index;
82323
+ if (typeof index !== "number" || index >= offset) continue;
82324
+ if (first === void 0 || index < first) first = index;
82325
+ const generation = event.generation;
82326
+ if (typeof generation === "number" && (floor === void 0 || generation > floor)) floor = generation;
82327
+ }
82328
+ if (first !== void 0) return {
82329
+ minGeneration: floor,
82330
+ keepReplayEvent,
82331
+ attachedAtLogIndex
82332
+ };
81403
82333
  return {
81404
82334
  minGeneration: await readRunGeneration(this.mastra, runId),
81405
82335
  keepReplayEvent,
@@ -81438,7 +82368,13 @@ var DefaultAgentExecutionEngine = class {
81438
82368
  if (typeof historyPubsub.getHistory !== "function") return "latest";
81439
82369
  try {
81440
82370
  const history = await historyPubsub.getHistory(AGENT_STREAM_TOPIC(runId));
81441
- return Array.isArray(history) && history.length > 0 ? history.length : "latest";
82371
+ if (!Array.isArray(history) || history.length === 0) return "latest";
82372
+ let newest = -1;
82373
+ for (const event of history) {
82374
+ const index = event?.index;
82375
+ if (typeof index === "number" && index > newest) newest = index;
82376
+ }
82377
+ return newest >= 0 ? newest + 1 : "latest";
81442
82378
  } catch {
81443
82379
  return "latest";
81444
82380
  }
@@ -81964,12 +82900,15 @@ var DefaultAgentExecutionEngine = class {
81964
82900
  }
81965
82901
  });
81966
82902
  const finishPublishedBeforeCrash = snapshot.context?.[MAP_FINAL_OUTPUT_STEP_ID]?.status === "success";
81967
- const resumed = Object.values(snapshot.context ?? {}).some((result) => result && typeof result === "object" && "resumedAt" in result && result.resumedAt != null);
82903
+ const results = Object.values(snapshot.context ?? {});
82904
+ const stepSuspended = results.some((result) => result?.status === "suspended");
82905
+ const resumed = stepSuspended || results.some((result) => result?.resumedAt != null);
81968
82906
  return {
81969
82907
  snapshot,
81970
82908
  workflowInput,
81971
82909
  finishPublishedBeforeCrash,
81972
- originalSpansEnded: finishPublishedBeforeCrash || resumed
82910
+ originalSpansEnded: finishPublishedBeforeCrash || resumed,
82911
+ openStepsOf: stepSuspended ? [] : openStepsOfCrashedSegment(snapshot.requestContext, runId)
81973
82912
  };
81974
82913
  }
81975
82914
  async loadSuspendedRequestContextValue(workflowsStore, runId, agent, key) {
@@ -82494,7 +83433,7 @@ async function prepareForDurableExecution(options) {
82494
83433
  });
82495
83434
  let tripwireData;
82496
83435
  if (inputProcessors.length > 0) try {
82497
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-BIXX67WE.cjs")).then((n) => n.runner_exports);
83436
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-DH7Qgz8l.cjs")).then((n) => n.runner_exports);
82498
83437
  await new ProcessorRunner({
82499
83438
  inputProcessors,
82500
83439
  outputProcessors,
@@ -82569,6 +83508,8 @@ async function prepareForDurableExecution(options) {
82569
83508
  } catch (error) {
82570
83509
  logger?.warn?.(`[DurableAgent] Error converting tools: ${error}`);
82571
83510
  }
83511
+ const toolNames = Object.keys(tools);
83512
+ if (!resumedSpans && toolNames.length > 0) agentSpan?.update({ attributes: { availableTools: toolNames } });
82572
83513
  if (!tripwireData) {
82573
83514
  await fireClientToolOutputHooks({
82574
83515
  messages,
@@ -82629,18 +83570,36 @@ async function prepareForDurableExecution(options) {
82629
83570
  type: "model_generation",
82630
83571
  outcome: null,
82631
83572
  name: `llm: '${model.modelId}'`,
83573
+ input: { messages: [...messageList.getAllSystemMessages(), ...messageList.get.all.aiV5.model()] },
82632
83574
  attributes: {
82633
83575
  model: model.modelId,
82634
83576
  provider: model.provider,
82635
- streaming: true
83577
+ streaming: true,
83578
+ parameters: serializeModelSettings(execOptions?.modelSettings),
83579
+ tools: agentSpan?.isValid ? getToolDefinitionsForTracing({
83580
+ tools,
83581
+ toolChoice: execOptions?.toolChoice,
83582
+ activeTools: execOptions?.activeTools,
83583
+ stripToolsWhenNone: sendsNativeResponseFormat(execOptions?.structuredOutput, model)
83584
+ }) : void 0
82636
83585
  },
82637
83586
  metadata: {
82638
83587
  runId,
82639
83588
  threadId,
82640
83589
  resourceId
82641
83590
  },
83591
+ tracingPolicy: agentTracingPolicy,
82642
83592
  requestContext
82643
83593
  });
83594
+ const modelSnapshot = modelSpan?.snapshot?.() ?? modelSpan?.exportSpan();
83595
+ const modelSnapshotWithoutPromptOrTools = modelSnapshot && {
83596
+ ...modelSnapshot,
83597
+ input: void 0,
83598
+ attributes: {
83599
+ ...modelSnapshot.attributes,
83600
+ tools: void 0
83601
+ }
83602
+ };
82644
83603
  return {
82645
83604
  runId,
82646
83605
  messageId,
@@ -82706,7 +83665,7 @@ async function prepareForDurableExecution(options) {
82706
83665
  },
82707
83666
  messageId,
82708
83667
  agentSpanData: agentSpan?.snapshot?.() ?? agentSpan?.exportSpan(),
82709
- modelSpanData: modelSpan?.snapshot?.() ?? modelSpan?.exportSpan(),
83668
+ modelSpanData: modelSnapshotWithoutPromptOrTools,
82710
83669
  requestContextEntries: requestContextEntriesSnapshot,
82711
83670
  inputTripwire: tripwireData
82712
83671
  }),
@@ -92042,11 +93001,14 @@ var Agent = class Agent extends require_base.MastraBase {
92042
93001
  if (generation !== executionFence.generation || !executionFence.ownsRunTopics()) return;
92043
93002
  const currentFence = getRunRegistryEntry(runId, this.#mastra)?.executionFence;
92044
93003
  if (currentFence && currentFence !== executionFence) return;
93004
+ if (executionFence.detached) return;
92045
93005
  try {
92046
93006
  await publisher?.settle(status);
92047
93007
  } catch (error) {
92048
- if (!(error instanceof DurableExecutionFenceError) || error.id !== "DURABLE_AGENT_EXECUTION_UNVERIFIED") throw error;
92049
- this.#unverifiedReaderFences.add(executionFence);
93008
+ const unverified = error instanceof DurableExecutionFenceError && error.id === "DURABLE_AGENT_EXECUTION_UNVERIFIED";
93009
+ if (unverified) this.#unverifiedReaderFences.add(executionFence);
93010
+ if (executionFence.detached) return;
93011
+ if (!unverified) throw error;
92050
93012
  this.logger.warn(`[DurableAgent:${this.id}] run ${runId}: terminal ownership could not be verified`, { error });
92051
93013
  }
92052
93014
  };
@@ -92237,7 +93199,7 @@ var Agent = class Agent extends require_base.MastraBase {
92237
93199
  }
92238
93200
  }
92239
93201
  /** Rebuilds process-local recovery state from the persisted durable workflow input. */
92240
- async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, latestMessageListState }) {
93202
+ async #rehydrateRecoveryState({ runId, workflowInput, abortController, executionFence, originalSpansEnded, openStepsOf, latestMessageListState }) {
92241
93203
  const requestContext = workflowInput.requestContextEntries ? new require_request_context.RequestContext(Object.entries(workflowInput.requestContextEntries)) : new require_request_context.RequestContext();
92242
93204
  restoreRunAgentScopes(requestContext);
92243
93205
  const messageListMemoryInfo = workflowInput.messageListState?.memoryInfo;
@@ -92391,6 +93353,7 @@ var Agent = class Agent extends require_base.MastraBase {
92391
93353
  provider: model?.provider,
92392
93354
  streaming: true
92393
93355
  },
93356
+ tracingPolicy: agentTracingPolicy,
92394
93357
  metadata: {
92395
93358
  runId,
92396
93359
  recovered: true
@@ -92404,7 +93367,7 @@ var Agent = class Agent extends require_base.MastraBase {
92404
93367
  carrySegmentSpans(requestContext, runId, recoverAgentSpan ? {
92405
93368
  ...openedSegment(recoverAgentSpan, recoverModelSpan),
92406
93369
  adoptsOpenSteps: true,
92407
- ...originalSpansEnded && origModelSpanData?.id ? { endedStepsOf: origModelSpanData.id } : {}
93370
+ ...openStepsOf ? { openStepsOf } : originalSpansEnded && origModelSpanData?.id ? { endedStepsOf: origModelSpanData.id } : {}
92408
93371
  } : null);
92409
93372
  executionFence.throwIfLost();
92410
93373
  const registryEntry = {
@@ -92474,7 +93437,9 @@ var Agent = class Agent extends require_base.MastraBase {
92474
93437
  * @internal
92475
93438
  */
92476
93439
  async emitError(runId, error, generation) {
92477
- endRunSpansWithError(runId, error);
93440
+ const evented = this.executionEngine.resolveWorkflowEngine(this.workflowEngine, this.logger) === "evented";
93441
+ const bus = this.#mastra?.pubsub ?? this.getPubSub();
93442
+ endRunSpansWithError(runId, error, { endStep: !evented || !bus || !reachesOtherProcesses(bus) });
92478
93443
  await runOutsideRunFenceScope(() => emitErrorEvent(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId, error, generation, shouldRejectStream(error) ? "reject" : void 0));
92479
93444
  }
92480
93445
  /**
@@ -92751,6 +93716,7 @@ var Agent = class Agent extends require_base.MastraBase {
92751
93716
  abortController,
92752
93717
  executionFence,
92753
93718
  originalSpansEnded: loaded.originalSpansEnded,
93719
+ openStepsOf: loaded.openStepsOf,
92754
93720
  latestMessageListState: await this.loadLatestMessageListState(workflowsStore, runId, loaded.snapshot)
92755
93721
  });
92756
93722
  await this.coverMemory(executionFence, recoveryState.requestContext, true);
@@ -93104,6 +94070,15 @@ var Agent = class Agent extends require_base.MastraBase {
93104
94070
  const resourceId = workflowInput.state?.resourceId ?? memoryInfo?.resourceId;
93105
94071
  if (sharedExecution && pubsub && entry?.requestContext && executionFence && threadId) {
93106
94072
  await agentThreadStreamRuntime.claimDurableThreadLease(pubsub, runId, threadId, resourceId, executionFence.generation, executionFence.executionId);
94073
+ try {
94074
+ await executionFence.verify();
94075
+ } catch (error) {
94076
+ 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", {
94077
+ runId,
94078
+ error: releaseError
94079
+ }));
94080
+ throw error;
94081
+ }
93107
94082
  setExecutionClaim(entry.requestContext, runId, {
93108
94083
  ...executionFence.claim,
93109
94084
  threadId,
@@ -93707,9 +94682,6 @@ var Agent = class Agent extends require_base.MastraBase {
93707
94682
  requestContextKeys
93708
94683
  };
93709
94684
  resumeRequestContext = resolvedOptions.requestContext ?? resumeRequestContext;
93710
- entry.requestContext = resumeRequestContext;
93711
- const globalEntryForContext = getRunRegistryEntry(runId, this.#mastra);
93712
- if (globalEntryForContext) globalEntryForContext.requestContext = resumeRequestContext;
93713
94685
  if (resolvedOptions.untilIdle) {
93714
94686
  const { untilIdle, ...rest } = resolvedOptions;
93715
94687
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
@@ -93740,41 +94712,6 @@ var Agent = class Agent extends require_base.MastraBase {
93740
94712
  });
93741
94713
  const priorExecution = getRunRegistryEntry(runId, this.#mastra)?.workflowExecution;
93742
94714
  await priorExecution?.catch(() => {});
93743
- if (!coldSnapshot && (options?.requestContext || options?.delegation || options?.hooks || droppedStartingUser)) try {
93744
- const requestTools = await this.agentForExecution.getToolsForExecution({
93745
- toolsets: resolvedOptions.toolsets,
93746
- clientTools: resolvedOptions.clientTools,
93747
- threadId: memoryInfo?.threadId,
93748
- resourceId: memoryInfo?.resourceId,
93749
- runId,
93750
- requestContext: resumeRequestContext,
93751
- memoryConfig: resolvedOptions.memory?.options,
93752
- autoResumeSuspendedTools: resolvedOptions.autoResumeSuspendedTools,
93753
- delegation: options?.delegation ? resolvedOptions.delegation : entry.delegation ?? resolvedOptions.delegation,
93754
- hooks: resolvedOptions.hooks,
93755
- methodType: entry.methodType ?? "stream",
93756
- backgroundTaskEnabled: Boolean(entry.backgroundTaskManager),
93757
- backgroundTaskPolicy: resolvedOptions.backgroundTaskPolicy,
93758
- model: entry.model
93759
- });
93760
- const refresh = (current, previous) => {
93761
- const next = { ...current };
93762
- for (const [name, tool] of Object.entries(requestTools)) if (name in current ? current[name] === previous?.[name] : !previous || !(name in previous)) next[name] = tool;
93763
- return next;
93764
- };
93765
- for (const reg of /* @__PURE__ */ new Set([entry, getRunRegistryEntry(runId, this.#mastra)])) {
93766
- if (!reg) continue;
93767
- reg.tools = require_utils$1.rebindProcessorTools(refresh(reg.tools ?? {}, reg.requestTools), resumeRequestContext);
93768
- if (reg.baseTools) reg.baseTools = require_utils$1.rebindProcessorTools(refresh(reg.baseTools, reg.requestTools), resumeRequestContext);
93769
- reg.requestTools = {
93770
- ...reg.requestTools,
93771
- ...requestTools
93772
- };
93773
- if (options?.delegation) reg.delegation = resolvedOptions.delegation;
93774
- }
93775
- } catch (error) {
93776
- this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] resume(${runId}) tool resolution failed: ${error}`);
93777
- }
93778
94715
  const executionFence = await this.#claimExecution(runId, "acquire");
93779
94716
  let initialToolCalls;
93780
94717
  let resumedText;
@@ -93813,16 +94750,58 @@ var Agent = class Agent extends require_base.MastraBase {
93813
94750
  }
93814
94751
  });
93815
94752
  if (resumeRequestContext) await this.coverMemory(executionFence, resumeRequestContext);
93816
- await this.loadRecalledMessages(runId, coldSnapshot, resumeRequestContext);
93817
94753
  ({toolCalls: initialToolCalls, resumedText} = await this.#loadSuspendedIteration(runId));
93818
94754
  resumeOffset = await this.executionEngine.getPubsubOffset(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, runId);
93819
94755
  persistedInput = current?.context?.input;
93820
94756
  suspendedToolCallIds = Object.keys(current?.resumeLabels ?? {});
93821
94757
  await agentThreadStreamRuntime.reacquireParkedRunLease(runId, this.getPubSub());
94758
+ entry.requestContext = resumeRequestContext;
94759
+ entry.requestContextRebuilt = false;
94760
+ const globalEntryForContext = getRunRegistryEntry(runId, this.#mastra);
94761
+ if (globalEntryForContext) {
94762
+ globalEntryForContext.requestContext = resumeRequestContext;
94763
+ globalEntryForContext.requestContextRebuilt = false;
94764
+ }
94765
+ await this.loadRecalledMessages(runId, coldSnapshot, resumeRequestContext);
93822
94766
  } catch (error) {
93823
94767
  await executionFence.settle(async () => {});
93824
94768
  throw error;
93825
94769
  }
94770
+ if (!coldSnapshot && (options?.requestContext || options?.delegation || options?.hooks || droppedStartingUser)) try {
94771
+ const requestTools = await this.agentForExecution.getToolsForExecution({
94772
+ toolsets: resolvedOptions.toolsets,
94773
+ clientTools: resolvedOptions.clientTools,
94774
+ threadId: memoryInfo?.threadId,
94775
+ resourceId: memoryInfo?.resourceId,
94776
+ runId,
94777
+ requestContext: resumeRequestContext,
94778
+ memoryConfig: resolvedOptions.memory?.options,
94779
+ autoResumeSuspendedTools: resolvedOptions.autoResumeSuspendedTools,
94780
+ delegation: options?.delegation ? resolvedOptions.delegation : entry.delegation ?? resolvedOptions.delegation,
94781
+ hooks: resolvedOptions.hooks,
94782
+ methodType: entry.methodType ?? "stream",
94783
+ backgroundTaskEnabled: Boolean(entry.backgroundTaskManager),
94784
+ backgroundTaskPolicy: resolvedOptions.backgroundTaskPolicy,
94785
+ model: entry.model
94786
+ });
94787
+ const refresh = (current, previous) => {
94788
+ const next = { ...current };
94789
+ for (const [name, tool] of Object.entries(requestTools)) if (name in current ? current[name] === previous?.[name] : !previous || !(name in previous)) next[name] = tool;
94790
+ return next;
94791
+ };
94792
+ for (const reg of /* @__PURE__ */ new Set([entry, getRunRegistryEntry(runId, this.#mastra)])) {
94793
+ if (!reg) continue;
94794
+ reg.tools = require_utils$1.rebindProcessorTools(refresh(reg.tools ?? {}, reg.requestTools), resumeRequestContext);
94795
+ if (reg.baseTools) reg.baseTools = require_utils$1.rebindProcessorTools(refresh(reg.baseTools, reg.requestTools), resumeRequestContext);
94796
+ reg.requestTools = {
94797
+ ...reg.requestTools,
94798
+ ...requestTools
94799
+ };
94800
+ if (options?.delegation) reg.delegation = resolvedOptions.delegation;
94801
+ }
94802
+ } catch (error) {
94803
+ this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] resume(${runId}) tool resolution failed: ${error}`);
94804
+ }
93826
94805
  setExecutionClaim(resumeRequestContext, runId, executionFence.claim);
93827
94806
  for (const reg of [entry, getRunRegistryEntry(runId, this.#mastra)]) {
93828
94807
  if (!reg) continue;
@@ -93911,6 +94890,7 @@ var Agent = class Agent extends require_base.MastraBase {
93911
94890
  provider: resumeModel?.provider,
93912
94891
  streaming: true
93913
94892
  },
94893
+ tracingPolicy: agentTracingPolicy,
93914
94894
  metadata: {
93915
94895
  runId,
93916
94896
  resumed: true
@@ -99196,6 +100176,21 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
99196
100176
  let currentIteration = 0;
99197
100177
  let eagerAbortListenerRegistered = false;
99198
100178
  const transcriptSteps = [];
100179
+ const apiErrorRows = [];
100180
+ const restoreApiErrorRows = (messageId) => {
100181
+ const parts = messageList.get.all.db().find((message) => message.id === messageId)?.content.parts ?? [];
100182
+ const missing = apiErrorRows.filter((row) => row.messageId === messageId).filter((row) => !parts.some((part) => part.type === row.part.type && require_deep_equal.deepEqual(part.data, row.part.data))).map((row) => row.part);
100183
+ if (missing.length === 0) return;
100184
+ messageList.add({
100185
+ id: messageId,
100186
+ role: "assistant",
100187
+ content: {
100188
+ format: 2,
100189
+ parts: missing
100190
+ },
100191
+ createdAt: /* @__PURE__ */ new Date()
100192
+ }, "response");
100193
+ };
99199
100194
  const pendingProviderToolCallsByToolCallId = /* @__PURE__ */ new Map();
99200
100195
  const cleanupProviderToolSpans = (terminal) => {
99201
100196
  if (!terminal) return;
@@ -99414,6 +100409,19 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
99414
100409
  start: messageList.get.response.aiV5.ui().find((message) => message.id === currentMessageId)?.parts.length ?? 0,
99415
100410
  end: 0
99416
100411
  };
100412
+ const apiErrorWriter = outputWriter ? { custom: async (data, options) => {
100413
+ if (require_llm.isDataChunk(data) && !data.transient) apiErrorRows.push({
100414
+ messageId: currentMessageId,
100415
+ part: {
100416
+ type: data.type,
100417
+ data: data.data
100418
+ }
100419
+ });
100420
+ return outputWriter(data, {
100421
+ ...options,
100422
+ messageId: currentMessageId
100423
+ });
100424
+ } } : void 0;
99417
100425
  modelSpanTracker?.startStep();
99418
100426
  let modelResult;
99419
100427
  let warnings;
@@ -100141,10 +101149,6 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100141
101149
  });
100142
101150
  const currentRetryCount = inputData.processorRetryCount || 0;
100143
101151
  const canRetryError = maxErrorProcessorRetries !== void 0 && currentRetryCount < maxErrorProcessorRetries;
100144
- const apiErrorWriter = outputWriter ? { custom: async (data, options) => outputWriter(data, {
100145
- ...options,
100146
- messageId: currentMessageId
100147
- }) } : void 0;
100148
101152
  const errorResult = await processorRunner.runProcessAPIError({
100149
101153
  error,
100150
101154
  messages: messageList.get.all.db(),
@@ -100389,7 +101393,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100389
101393
  }
100390
101394
  const currentRetryCount = inputData.processorRetryCount || 0;
100391
101395
  const canRetryError = maxErrorProcessorRetries !== void 0 && currentRetryCount < maxErrorProcessorRetries && !eagerCoordinator?.hasSuspendedHandback;
100392
- const processorRunner = new require_stream.ProcessorRunner({
101396
+ const errorResult = await new require_stream.ProcessorRunner({
100393
101397
  inputProcessors: inputProcessors || [],
100394
101398
  outputProcessors: outputProcessors || [],
100395
101399
  errorProcessors: errorProcessors || [],
@@ -100397,12 +101401,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100397
101401
  agentName: agentId || "unknown",
100398
101402
  agent,
100399
101403
  processorStates
100400
- });
100401
- const apiErrorWriter2 = outputWriter ? { custom: async (data, options) => outputWriter(data, {
100402
- ...options,
100403
- messageId: currentMessageId
100404
- }) } : void 0;
100405
- const errorResult = await processorRunner.runProcessAPIError({
101404
+ }).runProcessAPIError({
100406
101405
  error: runState.state.apiError,
100407
101406
  messages: messageList.get.all.db(),
100408
101407
  messageList,
@@ -100411,7 +101410,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100411
101410
  retryCount: currentRetryCount,
100412
101411
  requestContext,
100413
101412
  tracingContext: modelSpanTracker?.getTracingContext() ?? tracingContext,
100414
- writer: apiErrorWriter2,
101413
+ writer: apiErrorWriter,
100415
101414
  abortSignal: options?.abortSignal,
100416
101415
  messageId: currentMessageId,
100417
101416
  rotateResponseMessageId: () => {
@@ -100481,6 +101480,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
100481
101480
  cleanupProviderToolSpans(true);
100482
101481
  eagerCoordinator?.recarryCommittedWork(transcriptStep.messageId);
100483
101482
  messageList.rollbackToStepBoundary(transcriptStep.messageId, iterationBoundary);
101483
+ restoreApiErrorRows(transcriptStep.messageId);
100484
101484
  await discardAttemptEagerWork();
100485
101485
  if (runAbortSignal?.aborted) {
100486
101486
  await options?.onAbort?.({
@@ -102886,6 +103886,8 @@ function isStaleRequest(expiresAt) {
102886
103886
  /** Thread lease TTL and renew interval; shared with the durable execution lease. */
102887
103887
  const AGENT_THREAD_LEASE_TTL_MS = AGENT_LEASE_TTL_MS;
102888
103888
  const AGENT_THREAD_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS;
103889
+ const DURABLE_THREAD_CLAIM_WAIT_MS = 5e3;
103890
+ const DURABLE_THREAD_CLAIM_POLL_MS = 100;
102889
103891
  /**
102890
103892
  * TTL for a suspended run's warm in-memory state — the parked thread-run record
102891
103893
  * (swept by #sweepStaleSuspendedRecords). The Mastra internal-workflow registry
@@ -103245,11 +104247,24 @@ var AgentThreadStreamRuntime = class {
103245
104247
  }
103246
104248
  /** @internal Qualify a shared thread lease before dispatching this execution. */
103247
104249
  async claimDurableThreadLease(pubsub, runId, threadId, resourceId, generation, executionId) {
103248
- const lease = await this.#acquireThreadLease(pubsub, this.#threadKey(resourceId, threadId), runId, threadLeaseOwner(runId, generation, executionId));
104250
+ const key = this.#threadKey(resourceId, threadId);
104251
+ const owner = threadLeaseOwner(runId, generation, executionId);
104252
+ let lease = await this.#acquireThreadLease(pubsub, key, runId, owner);
104253
+ const previousOwner = parseThreadLeaseOwner(lease.owner);
104254
+ if (!lease.acquired && (lease.owner === void 0 || previousOwner && previousOwner[0] !== runId && (previousOwner[1] === "generation" || previousOwner[1] === "execution"))) {
104255
+ const blockingOwner = lease.owner;
104256
+ const deadline = Date.now() + DURABLE_THREAD_CLAIM_WAIT_MS;
104257
+ while (!lease.acquired && (lease.owner === void 0 || lease.owner === blockingOwner)) {
104258
+ const remaining = deadline - Date.now();
104259
+ if (remaining <= 0) break;
104260
+ await new Promise((resolve) => setTimeout(resolve, Math.min(remaining, DURABLE_THREAD_CLAIM_POLL_MS)));
104261
+ lease = await this.#acquireThreadLease(pubsub, key, runId, owner);
104262
+ }
104263
+ }
103249
104264
  if (!lease.acquired) throw new AgentThreadLeaseConflictError(runId, lease.owner ?? "another owner");
103250
104265
  if (this.#getState(pubsub).leaseRenewalTimers.has(runId)) {
103251
104266
  this.#stopLeaseRenewal(pubsub, runId);
103252
- this.#startLeaseRenewal(pubsub, this.#threadKey(resourceId, threadId), runId, threadLeaseOwner(runId, generation, executionId));
104267
+ this.#startLeaseRenewal(pubsub, key, runId, owner);
103253
104268
  }
103254
104269
  }
103255
104270
  /** @internal Renew only the captured execution's thread lease; never acquire or transfer it. */
@@ -103553,6 +104568,7 @@ var AgentThreadStreamRuntime = class {
103553
104568
  this.#stopLeaseRenewal(pubsub, runId, timer);
103554
104569
  this.#abortLeaseLostRun(state, runId);
103555
104570
  }
104571
+ if (state.threadRunsById.get(runId)?.lifecycle === "suspended" && typeof owner === "string" && threadLeaseRunId(owner) === runId) return;
103556
104572
  throw new AgentThreadLeaseLostError(runId);
103557
104573
  };
103558
104574
  }
@@ -104605,7 +105621,7 @@ var AgentThreadStreamRuntime = class {
104605
105621
  releaseMessageIdentity(require_error.getErrorFromUnknown(error));
104606
105622
  throw error;
104607
105623
  }
104608
- const callerRequestContext = remoteRequestContextEntries ? restoreRequestContext$1(remoteRequestContextEntries, ownerStreamOptions?.requestContext) : incomingStreamOptions?.requestContext;
105624
+ const callerRequestContext = remoteRequestContextEntries ? restoreRequestContext(remoteRequestContextEntries, ownerStreamOptions?.requestContext) : incomingStreamOptions?.requestContext;
104609
105625
  const incomingRequestContext = callerRequestContext && claimedOwnerRequestContext(callerRequestContext, ownerStreamOptions?.requestContext);
104610
105626
  streamOptions = incomingRequestContext === void 0 ? ownerStreamOptions : {
104611
105627
  ...ownerStreamOptions,
@@ -108523,6 +109539,7 @@ async function participateInDurableExecution(mastra, event, execute) {
108523
109539
  const fence = await participant.fence;
108524
109540
  if (!fence) return await execute();
108525
109541
  await fence.verify();
109542
+ await carryEndedSegment(mastra, event);
108526
109543
  let parentRunId = runId;
108527
109544
  for (const nestedRunId of nestedRunIds) {
108528
109545
  fence.coverNestedRun(parentRunId, nestedRunId);
@@ -108561,6 +109578,51 @@ async function retrySettledDurableExecution(mastra, event) {
108561
109578
  await settleEventedDurableExecution(mastra, event);
108562
109579
  return true;
108563
109580
  }
109581
+ /**
109582
+ * When a suspension beside the failed tool call ends the segment's spans, tell this failure and the run's own, through
109583
+ * the request context they inherit. Called before the delivery passes that context on.
109584
+ */
109585
+ async function carryEndedSegment(mastra, event) {
109586
+ const { workflowId, stepResults, requestContext } = event.data ?? {};
109587
+ const state = stepResults?.input;
109588
+ const calls = stepResults?.[DurableStepIds.TOOL_CALL];
109589
+ if (event.type !== "workflow.fail" || workflowId !== DurableStepIds.AGENTIC_EXECUTION || !state?.runId) return;
109590
+ if (calls?.status !== "failed" || Array.isArray(calls.payload) && !calls.payload[0]?.sideBySide) return;
109591
+ const context = new require_request_context.RequestContext(Object.entries(requestContext ?? {}));
109592
+ const segment = segmentSpanData(context, state.runId, state);
109593
+ if (segment.carried) return;
109594
+ const { runId, iterationCount } = state;
109595
+ if (await claimSegmentEnd({
109596
+ mastra,
109597
+ requestContext: context,
109598
+ runId,
109599
+ iterationCount,
109600
+ outcome: "fail"
109601
+ }) ?? !segmentEndedBySuspension(segment, stepResults)) return;
109602
+ event.data.requestContext = { ...requestContext };
109603
+ carrySegmentSpans(event.data.requestContext, runId, null);
109604
+ }
109605
+ function endFailedSpans(mastra, event) {
109606
+ const { stepResults, prevResult, requestContext } = event.data ?? {};
109607
+ const runId = stepResults?.input?.runId;
109608
+ if (!runId || isExecutionFenceError(prevResult?.error)) return;
109609
+ endFailedSegmentSpans({
109610
+ mastra,
109611
+ requestContext: new require_request_context.RequestContext(Object.entries(requestContext ?? {})),
109612
+ runId,
109613
+ state: stepResults.input,
109614
+ steps: stepResults,
109615
+ error: require_error.getErrorFromUnknown(prevResult?.error ?? "Workflow execution failed"),
109616
+ live: getRunRegistryEntry(runId, mastra),
109617
+ firstPairOnly: true
109618
+ });
109619
+ }
109620
+ /** End the MODEL_STEP of a failed iteration. Only the iteration's own event still carries it. */
109621
+ function endFailedIteration(mastra, event) {
109622
+ if (event.type !== "workflow.fail" || event.data?.workflowId !== DurableStepIds.AGENTIC_EXECUTION) return;
109623
+ if (isWorkflowStepConflictError(event.data.prevResult?.error)) return;
109624
+ endFailedSpans(mastra, event);
109625
+ }
108564
109626
  /** Called only after the root terminal handler has persisted and published its outcome. */
108565
109627
  async function settleEventedDurableExecution(mastra, event) {
108566
109628
  if (!isRootTerminal(event)) return;
@@ -108597,6 +109659,7 @@ async function settleEventedDurableExecution(mastra, event) {
108597
109659
  fence
108598
109660
  });
108599
109661
  await ExecutionFence.releaseSharedClaim(mastra, event.runId, claim, "settled");
109662
+ if (event.type === "workflow.fail" && !released) endFailedSpans(mastra, event);
108600
109663
  if (claim.threadId && event.type !== "workflow.suspend") await agentThreadStreamRuntime.releaseDurableThreadLease(mastra.pubsub, event.runId, claim.threadId, claim.resourceId, claim.generation, claim.executionId);
108601
109664
  if (claim.memoryFenced && fence) await (await mastra.getStorage()?.getStore("memory"))?.retireRunFence(fence);
108602
109665
  await mastra.__getRunScope(event.runId)?.get(PARTICIPANTS)?.get(claim.executionId)?.stop();
@@ -108654,6 +109717,9 @@ function getRunRegistryEntry(runId, mastra) {
108654
109717
  }
108655
109718
  return require_observability.unwrapMastraTracingProxy(entry.mastra) === require_observability.unwrapMastraTracingProxy(mastra) ? entry : void 0;
108656
109719
  }
109720
+ function getLiveRunRequestContext(entry) {
109721
+ return entry?.requestContextRebuilt ? void 0 : entry?.requestContext;
109722
+ }
108657
109723
  /**
108658
109724
  * Publish an entry for `runId`, owned by `mastra`, unless the slot holds
108659
109725
  * another Mastra instance's live run. Returns whether the entry was stored.
@@ -108811,6 +109877,11 @@ async function abandonDurableAgentExecutions(mastra) {
108811
109877
  function endRunSpansWithError(runId, error, options = {}) {
108812
109878
  try {
108813
109879
  const entry = globalRunRegistry.has(runId) ? globalRunRegistry.get(runId) : void 0;
109880
+ if (options.endStep ?? options.endSpan ?? true) entry?.openStepSpan?.error(stepFailure({
109881
+ error,
109882
+ ...require_observability.executionFailureTermination(error),
109883
+ endSpan: true
109884
+ }));
108814
109885
  (entry?.resumeModelSpan ?? entry?.modelSpan)?.error({
108815
109886
  error,
108816
109887
  ...require_observability.executionFailureTermination(error),
@@ -109067,6 +110138,18 @@ Object.defineProperty(exports, "CHAT_CHANNEL_RENDER_CONTEXT_KEY", {
109067
110138
  return CHAT_CHANNEL_RENDER_CONTEXT_KEY;
109068
110139
  }
109069
110140
  });
110141
+ Object.defineProperty(exports, "CONTINUE_RUN_ACTION_ID", {
110142
+ enumerable: true,
110143
+ get: function() {
110144
+ return CONTINUE_RUN_ACTION_ID;
110145
+ }
110146
+ });
110147
+ Object.defineProperty(exports, "CONTINUE_RUN_MESSAGE", {
110148
+ enumerable: true,
110149
+ get: function() {
110150
+ return CONTINUE_RUN_MESSAGE;
110151
+ }
110152
+ });
109070
110153
  Object.defineProperty(exports, "ChannelSessionRejectedError", {
109071
110154
  enumerable: true,
109072
110155
  get: function() {
@@ -110837,6 +111920,12 @@ Object.defineProperty(exports, "encodeTraceQueryDeltaCursor", {
110837
111920
  return encodeTraceQueryDeltaCursor;
110838
111921
  }
110839
111922
  });
111923
+ Object.defineProperty(exports, "endFailedSegmentSpans", {
111924
+ enumerable: true,
111925
+ get: function() {
111926
+ return endFailedSegmentSpans;
111927
+ }
111928
+ });
110840
111929
  Object.defineProperty(exports, "endRunSpansWithError", {
110841
111930
  enumerable: true,
110842
111931
  get: function() {
@@ -111821,6 +112910,12 @@ Object.defineProperty(exports, "runEvals", {
111821
112910
  return runEvals;
111822
112911
  }
111823
112912
  });
112913
+ Object.defineProperty(exports, "runFenceConflictOf", {
112914
+ enumerable: true,
112915
+ get: function() {
112916
+ return runFenceConflictOf;
112917
+ }
112918
+ });
111824
112919
  Object.defineProperty(exports, "runFencingNotSupportedError", {
111825
112920
  enumerable: true,
111826
112921
  get: function() {
@@ -111869,6 +112964,12 @@ Object.defineProperty(exports, "safelyParseJSON", {
111869
112964
  return safelyParseJSON;
111870
112965
  }
111871
112966
  });
112967
+ Object.defineProperty(exports, "segmentEndedBySuspension", {
112968
+ enumerable: true,
112969
+ get: function() {
112970
+ return segmentEndedBySuspension;
112971
+ }
112972
+ });
111872
112973
  Object.defineProperty(exports, "segmentSpanData", {
111873
112974
  enumerable: true,
111874
112975
  get: function() {