@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
@@ -17,6 +17,7 @@ const TOPIC_RESULT = "background-tasks-result";
17
17
  const WORKER_GROUP = "background-task-workers";
18
18
  const SHUTDOWN_GRACE_PERIOD_MS = 5e3;
19
19
  const SHUTDOWN_ABORT_MESSAGE = "Background task manager is shutting down";
20
+ const WORKER_TERMINATED_MESSAGE = "Worker process terminated before task completed";
20
21
  const TASK_OWNERSHIP_LOST_MESSAGE = "Background task execution ownership was taken over by another worker";
21
22
  function workflowRunError(result) {
22
23
  if (result.error !== void 0) return result.error;
@@ -35,6 +36,7 @@ function toTaskError(err) {
35
36
  }
36
37
  /** Pending rows each lapsed-pin sweep reads; later pages are read on later ticks. */
37
38
  const PIN_SWEEP_PAGE_SIZE = 100;
39
+ const RUNNING_SWEEP_MAX_PAGE_SIZE = 1e3;
38
40
  /** Test-only lower lease minimum; only ever lowers the default 3s. Read per manager, not at import. */
39
41
  function minLeaseOverride() {
40
42
  const value = Number(process.env.MASTRA_BACKGROUND_TASKS_MIN_LEASE_MS);
@@ -57,7 +59,9 @@ function minLeaseOverride() {
57
59
  * - Expiry and adoption: `recoverStaleTasks` only reclaims a `running` task
58
60
  * once its lease has expired (or was released on shutdown), fenced on the
59
61
  * owner/lease it read so one manager wins. It re-runs when the earliest live
60
- * lease lapses. `restart()` is the one deliberate takeover of a live lease.
62
+ * lease lapses, and the periodic sweep in `#sweepLapsedPins` reclaims rows
63
+ * whose owner died later. `restart()` is the one deliberate takeover of a
64
+ * live lease.
61
65
  * - Loss: a failed renewal aborts the local run's signal when another owner
62
66
  * holds the task or it was cancelled.
63
67
  *
@@ -94,6 +98,7 @@ var BackgroundTaskManager = class {
94
98
  pinSweepInterval;
95
99
  sweepingPins = false;
96
100
  pinSweepPage = 0;
101
+ runningSweepPage = 0;
97
102
  #settlingRuns = /* @__PURE__ */ new Set();
98
103
  workerCallback;
99
104
  resultCallback;
@@ -149,7 +154,9 @@ var BackgroundTaskManager = class {
149
154
  this.resultCallback = async (event, ack) => {
150
155
  if (event.type === "task.completed" || event.type === "task.failed") {
151
156
  try {
152
- await this.handleResult(event);
157
+ const handling = this.handleResult(event);
158
+ this.#trackSettlingRun(handling.catch(() => {}));
159
+ await handling;
153
160
  } finally {
154
161
  await ack?.();
155
162
  }
@@ -178,7 +185,7 @@ var BackgroundTaskManager = class {
178
185
  if (handled) await ack?.();
179
186
  };
180
187
  if (this.#mastra) {
181
- const { buildBackgroundTaskWorkflow } = await Promise.resolve().then(() => require("./workflow-zvQGBMCM.cjs"));
188
+ const { buildBackgroundTaskWorkflow } = await Promise.resolve().then(() => require("./workflow-D5Fc5ieC.cjs"));
182
189
  const workflow = buildBackgroundTaskWorkflow(this);
183
190
  if (!this.#mastra.__hasInternalWorkflow("__background-task")) this.#mastra.__registerInternalWorkflow(workflow);
184
191
  }
@@ -188,10 +195,6 @@ var BackgroundTaskManager = class {
188
195
  await this.#releaseLateInitSubscriptions([[TOPIC_DISPATCH, this.workerCallback], [this.processAffineDispatchTopic, this.workerCallback]]);
189
196
  return;
190
197
  }
191
- if (this.config.recoverStaleTasksOnStart) {
192
- await this.recoverStaleTasks();
193
- this.#startPinSweep();
194
- }
195
198
  }
196
199
  await this.pubsub.subscribe(TOPIC_RESULT, this.resultCallback);
197
200
  if (this.shuttingDown) {
@@ -204,6 +207,10 @@ var BackgroundTaskManager = class {
204
207
  await this.#releaseLateInitSubscriptions(lateSubscriptions);
205
208
  return;
206
209
  }
210
+ if (!isProducerOnly && this.config.recoverStaleTasksOnStart) {
211
+ await this.recoverStaleTasks();
212
+ this.#startPinSweep();
213
+ }
207
214
  const cleanupConfig = this.config.cleanup;
208
215
  if (cleanupConfig && !this.shuttingDown) {
209
216
  const intervalMs = cleanupConfig.cleanupIntervalMs ?? 6e4;
@@ -274,6 +281,7 @@ var BackgroundTaskManager = class {
274
281
  if (this.shuttingDown) throw new Error("BackgroundTaskManager is shutting down, cannot enqueue new tasks");
275
282
  const pinned = options?.pinToWorker === true;
276
283
  if (pinned && !context) throw new Error("pinToWorker requires a task context");
284
+ if (context) this.#assertCanRunLocalTasks("enqueue");
277
285
  if (this.initPromise) await this.initPromise;
278
286
  const createdAt = /* @__PURE__ */ new Date();
279
287
  const task = {
@@ -375,13 +383,7 @@ var BackgroundTaskManager = class {
375
383
  this.activeAbortControllers.delete(taskId);
376
384
  }
377
385
  }
378
- if (previousStatus === "running" || previousStatus === "suspended") {
379
- if (this.#mastra) try {
380
- await (await this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID).createRun({ runId: taskId })).cancel();
381
- } catch (err) {
382
- this.#mastra?.getLogger?.()?.warn(`background-task workflow cancel failed for ${taskId}:`, err);
383
- }
384
- }
386
+ if (previousStatus === "running" || previousStatus === "suspended") await this.#cancelWorkflowRun(taskId);
385
387
  const cancelledTask = await storage.getTask(taskId);
386
388
  if (cancelledTask) {
387
389
  await this.publishLifecycleEvent("task.cancelled", cancelledTask);
@@ -422,6 +424,7 @@ var BackgroundTaskManager = class {
422
424
  if (task.status !== "suspended") throw new Error(`Cannot resume task in status '${task.status}' (expected 'suspended')`);
423
425
  if (options?.suspendedAt !== void 0 && new Date(options.suspendedAt).getTime() !== suspensionToken(task)) throw new Error(`Cannot resume task "${taskId}": its suspension has changed since it was read`);
424
426
  const isProcessAffine = this.taskContexts.has(taskId);
427
+ if (isProcessAffine) this.#assertCanRunLocalTasks("resume");
425
428
  if (!(isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId))) {
426
429
  if (options?.onNoSlot === "queue") {
427
430
  this.localPendingResumes.set(taskId, {
@@ -483,6 +486,7 @@ var BackgroundTaskManager = class {
483
486
  if (!task) throw new Error(`Task not found: ${taskId}`);
484
487
  if (task.status !== "pending" && task.status !== "running") throw new Error(`Cannot restart task in status '${task.status}' (expected 'pending' or 'running')`);
485
488
  const isRestart = task.status === "running";
489
+ if (context || this.taskContexts.has(taskId)) this.#assertCanRunLocalTasks("restart");
486
490
  if (context) this.registerTaskContext(task.id, context);
487
491
  const isProcessAffine = this.taskContexts.has(taskId);
488
492
  if (!(isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId))) throw new Error(`Concurrency limit reached, cannot restart task "${taskId}" \u2014 retry once a slot is available`);
@@ -852,9 +856,33 @@ var BackgroundTaskManager = class {
852
856
  if (this.initPromise) await this.#waitForShutdownStep("background task pubsub flush", this.pubsub.flush());
853
857
  }
854
858
  async #cancelTaskForShutdown(taskId) {
855
- const task = await (await this.getStorage()).getTask(taskId);
856
- if (task?.status === "running" && task.maxRetries > 0) return;
857
- await this.cancel(taskId);
859
+ const storage = await this.getStorage();
860
+ const task = await storage.getTask(taskId);
861
+ if (task?.status !== "running") {
862
+ await this.cancel(taskId);
863
+ return;
864
+ }
865
+ if (task.maxRetries > 0) return;
866
+ const fence = {
867
+ expectedStatus: "running",
868
+ expectedOwnerId: this.workerId
869
+ };
870
+ if (await this.#failTerminated(storage, taskId, fence, { runLocalHooks: true })) {
871
+ this.ownedLeases.delete(taskId);
872
+ await this.#cancelWorkflowRun(taskId);
873
+ }
874
+ }
875
+ /**
876
+ * Cancels a task's background-task workflow run, so workflow storage
877
+ * reflects the task's end and any stored suspended snapshot is cleaned up.
878
+ */
879
+ async #cancelWorkflowRun(taskId) {
880
+ if (!this.#mastra) return;
881
+ try {
882
+ await (await this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID).createRun({ runId: taskId })).cancel();
883
+ } catch (err) {
884
+ this.#mastra?.getLogger?.()?.warn(`background-task workflow cancel failed for ${taskId}:`, err);
885
+ }
858
886
  }
859
887
  #abortActiveControllers() {
860
888
  for (const controller of this.activeAbortControllers.values()) controller.abort(/* @__PURE__ */ new Error(SHUTDOWN_ABORT_MESSAGE));
@@ -904,6 +932,17 @@ var BackgroundTaskManager = class {
904
932
  });
905
933
  }
906
934
  /**
935
+ * A task with a registered context runs from this process's closures, so it
936
+ * is published to this process's own dispatch topic. A producer-mode manager
937
+ * never consumes that topic, and no other process can run those closures, so
938
+ * the task would sit unclaimed (#31089). Refuse before anything is persisted
939
+ * or published; agent runs then execute the tool without a background task.
940
+ */
941
+ #assertCanRunLocalTasks(action) {
942
+ if (this.config.mode !== "producer") return;
943
+ throw new Error(`Cannot ${action} a background task with an in-process executor: this process doesn't run background tasks (workers are disabled or MASTRA_WORKERS excludes backgroundTasks), and other processes can't run its executor. Run the backgroundTasks worker on this process, or pass \`disableBackgroundTasks: true\` to agent runs here so their tools run inline. Tasks enqueued directly can omit the task context to let a dedicated worker run the tool by name.`);
944
+ }
945
+ /**
907
946
  * Lazily start Mastra's execution workers before publishing. In "library
908
947
  * mode" nothing ever calls `mastra.startWorkers()`, so the evented
909
948
  * `__background-task` workflow started by `handleDispatch` would publish
@@ -1592,31 +1631,12 @@ var BackgroundTaskManager = class {
1592
1631
  const { tasks: staleTasks } = await storage.listTasks({ status: "running" });
1593
1632
  let nextSweepAt;
1594
1633
  for (const task of staleTasks) {
1595
- if (task.ownerId && task.leaseExpiresAt && task.leaseExpiresAt.getTime() > now) {
1634
+ if (isLiveRunning(task, now)) {
1596
1635
  const leaseExpiry = task.leaseExpiresAt.getTime();
1597
1636
  nextSweepAt = nextSweepAt === void 0 ? leaseExpiry : Math.min(nextSweepAt, leaseExpiry);
1598
1637
  continue;
1599
1638
  }
1600
- const fence = {
1601
- expectedStatus: "running",
1602
- expectedOwnerId: task.ownerId ?? null,
1603
- expectedLeaseExpiresAt: task.leaseExpiresAt ?? null
1604
- };
1605
- const handedBack = !task.ownerId && task.maxRetries > 0;
1606
- if (handedBack || task.retryCount < task.maxRetries) await storage.updateTask(task.id, {
1607
- status: "pending",
1608
- retryCount: handedBack ? task.retryCount : task.retryCount + 1,
1609
- startedAt: void 0,
1610
- ownerId: void 0,
1611
- leaseExpiresAt: void 0
1612
- }, fence);
1613
- else await storage.updateTask(task.id, {
1614
- status: "failed",
1615
- error: { message: "Worker process terminated before task completed" },
1616
- completedAt: /* @__PURE__ */ new Date(),
1617
- ownerId: void 0,
1618
- leaseExpiresAt: void 0
1619
- }, fence);
1639
+ await this.#reclaimLapsedRunning(storage, task);
1620
1640
  }
1621
1641
  const { tasks: pendingTasks } = await storage.listTasks({
1622
1642
  status: "pending",
@@ -1639,6 +1659,59 @@ var BackgroundTaskManager = class {
1639
1659
  }
1640
1660
  }
1641
1661
  /**
1662
+ * Reclaims a `running` row whose lease lapsed: re-pends it, or fails it once
1663
+ * it is out of retries. Returns `true` when the row was re-pended and should
1664
+ * be dispatched; `false` when it was failed or another worker got to it first.
1665
+ */
1666
+ async #reclaimLapsedRunning(storage, task) {
1667
+ const fence = {
1668
+ expectedStatus: "running",
1669
+ expectedOwnerId: task.ownerId ?? null,
1670
+ expectedLeaseExpiresAt: task.leaseExpiresAt ?? null
1671
+ };
1672
+ const handedBack = !task.ownerId && task.maxRetries > 0;
1673
+ if (handedBack || task.retryCount < task.maxRetries) {
1674
+ const requeued = await storage.updateTask(task.id, {
1675
+ status: "pending",
1676
+ retryCount: handedBack ? task.retryCount : task.retryCount + 1,
1677
+ startedAt: void 0,
1678
+ ownerId: void 0,
1679
+ leaseExpiresAt: void 0
1680
+ }, fence);
1681
+ return Boolean(requeued);
1682
+ }
1683
+ await this.#failTerminated(storage, task.id, fence);
1684
+ return false;
1685
+ }
1686
+ /**
1687
+ * Fails a task whose worker is gone and reports it with `task.failed`, so
1688
+ * `onTaskFailed` and stream subscribers hear about it like any other failure.
1689
+ * Only the caller whose fenced write lands publishes, so peers racing on the
1690
+ * same row stay quiet. A failed publish is logged, not thrown, so a sweep
1691
+ * still reaches the rows after this one. Returns whether the write landed.
1692
+ * Pass `runLocalHooks` when this process may still hold the task's per-task
1693
+ * hooks, so they run, isolated, before the event, as for any other failure.
1694
+ */
1695
+ async #failTerminated(storage, taskId, fence, { runLocalHooks = false } = {}) {
1696
+ if (!await storage.updateTask(taskId, {
1697
+ status: "failed",
1698
+ error: { message: WORKER_TERMINATED_MESSAGE },
1699
+ completedAt: /* @__PURE__ */ new Date(),
1700
+ ownerId: void 0,
1701
+ leaseExpiresAt: void 0
1702
+ }, fence)) return false;
1703
+ try {
1704
+ const failedTask = await storage.getTask(taskId);
1705
+ if (failedTask?.status === "failed") {
1706
+ if (runLocalHooks) await this.runLocalCompletionHooks(failedTask, "failed", { error: failedTask.error });
1707
+ await this.publishLifecycleEvent("task.failed", failedTask);
1708
+ }
1709
+ } catch (error) {
1710
+ this.#mastra?.getLogger?.()?.warn(`Failed to report background task ${taskId} as failed:`, error);
1711
+ }
1712
+ return true;
1713
+ }
1714
+ /**
1642
1715
  * Accounts for a `pinToWorker` row whose owner stopped renewing its lease.
1643
1716
  * A pin means work for the row was in flight on its owner, so a lapsed pin
1644
1717
  * is a lost attempt, handled like a `running` row whose lease lapsed: it
@@ -1658,13 +1731,7 @@ var BackgroundTaskManager = class {
1658
1731
  retryCount: task.retryCount + 1,
1659
1732
  ownerId: void 0,
1660
1733
  leaseExpiresAt: void 0
1661
- }, fence) : await storage.updateTask(task.id, {
1662
- status: "failed",
1663
- error: { message: "Worker process terminated before task completed" },
1664
- completedAt: /* @__PURE__ */ new Date(),
1665
- ownerId: void 0,
1666
- leaseExpiresAt: void 0
1667
- }, fence);
1734
+ }, fence) : await this.#failTerminated(storage, task.id, fence);
1668
1735
  if (recovered) this.#mastra?.getLogger()?.warn(`Background task ${task.id} lost its pin: worker ${task.ownerId} stopped renewing its lease. ${retry ? "Retrying it on another worker." : "Marking it failed."}`);
1669
1736
  return retry && recovered;
1670
1737
  }
@@ -1693,19 +1760,33 @@ var BackgroundTaskManager = class {
1693
1760
  }
1694
1761
  }
1695
1762
  /**
1696
- * Periodically recovers lapsed `pinToWorker` rows. The startup scan only
1697
- * sees rows that existed when this worker started, so without this a pin
1698
- * enqueued later by a worker that then died would wait for a restart.
1699
- * Unpinned pending rows are left alone: they are dispatched by their own
1700
- * worker and by startup recovery, as before.
1763
+ * Periodically recovers `running` rows and `pinToWorker` rows whose owner
1764
+ * stopped renewing its lease. The startup scan only sees rows that existed
1765
+ * when this worker started, so without this a task whose worker died later
1766
+ * would wait for a restart. Unpinned pending rows are left alone: they are
1767
+ * dispatched by their own worker and by startup recovery, as before.
1701
1768
  */
1702
1769
  async #sweepLapsedPins() {
1703
1770
  if (this.shuttingDown || this.sweepingPins) return;
1704
1771
  this.sweepingPins = true;
1705
1772
  try {
1706
- if (this.localPendingTaskIds.size > 0) await this.drainPending();
1707
1773
  const storage = await this.getStorage();
1708
1774
  const now = Date.now();
1775
+ const runningPageSize = Math.min(Math.max(PIN_SWEEP_PAGE_SIZE, this.config.globalConcurrency), RUNNING_SWEEP_MAX_PAGE_SIZE);
1776
+ const { tasks: running, total: runningTotal } = await storage.listTasks({
1777
+ status: "running",
1778
+ orderBy: "createdAt",
1779
+ orderDirection: "asc",
1780
+ page: this.runningSweepPage,
1781
+ perPage: runningPageSize
1782
+ });
1783
+ this.runningSweepPage = (this.runningSweepPage + 1) * runningPageSize < runningTotal ? this.runningSweepPage + 1 : 0;
1784
+ for (const task of running) {
1785
+ if (this.shuttingDown) return;
1786
+ if (isLiveRunning(task, now)) continue;
1787
+ if (await this.#reclaimLapsedRunning(storage, task)) this.localPendingTaskIds.add(task.id);
1788
+ }
1789
+ if (this.localPendingTaskIds.size > 0) await this.drainPending();
1709
1790
  const { tasks } = await storage.listTasks({
1710
1791
  status: "pending",
1711
1792
  orderBy: "createdAt",
@@ -1749,6 +1830,13 @@ var BackgroundTaskManager = class {
1749
1830
  this.staleRecoveryTimeout.unref?.();
1750
1831
  }
1751
1832
  };
1833
+ /**
1834
+ * A still-valid lease proves a `running` row's owner is alive. This is what
1835
+ * stops a second worker from taking over a task another process is running.
1836
+ */
1837
+ function isLiveRunning(task, now) {
1838
+ return Boolean(task.ownerId && task.leaseExpiresAt && task.leaseExpiresAt.getTime() > now);
1839
+ }
1752
1840
  function suspensionToken(task) {
1753
1841
  return task.suspendedAt?.getTime() ?? null;
1754
1842
  }
@@ -17,6 +17,7 @@ const TOPIC_RESULT = "background-tasks-result";
17
17
  const WORKER_GROUP = "background-task-workers";
18
18
  const SHUTDOWN_GRACE_PERIOD_MS = 5e3;
19
19
  const SHUTDOWN_ABORT_MESSAGE = "Background task manager is shutting down";
20
+ const WORKER_TERMINATED_MESSAGE = "Worker process terminated before task completed";
20
21
  const TASK_OWNERSHIP_LOST_MESSAGE = "Background task execution ownership was taken over by another worker";
21
22
  function workflowRunError(result) {
22
23
  if (result.error !== void 0) return result.error;
@@ -35,6 +36,7 @@ function toTaskError(err) {
35
36
  }
36
37
  /** Pending rows each lapsed-pin sweep reads; later pages are read on later ticks. */
37
38
  const PIN_SWEEP_PAGE_SIZE = 100;
39
+ const RUNNING_SWEEP_MAX_PAGE_SIZE = 1e3;
38
40
  /** Test-only lower lease minimum; only ever lowers the default 3s. Read per manager, not at import. */
39
41
  function minLeaseOverride() {
40
42
  const value = Number(process.env.MASTRA_BACKGROUND_TASKS_MIN_LEASE_MS);
@@ -57,7 +59,9 @@ function minLeaseOverride() {
57
59
  * - Expiry and adoption: `recoverStaleTasks` only reclaims a `running` task
58
60
  * once its lease has expired (or was released on shutdown), fenced on the
59
61
  * owner/lease it read so one manager wins. It re-runs when the earliest live
60
- * lease lapses. `restart()` is the one deliberate takeover of a live lease.
62
+ * lease lapses, and the periodic sweep in `#sweepLapsedPins` reclaims rows
63
+ * whose owner died later. `restart()` is the one deliberate takeover of a
64
+ * live lease.
61
65
  * - Loss: a failed renewal aborts the local run's signal when another owner
62
66
  * holds the task or it was cancelled.
63
67
  *
@@ -94,6 +98,7 @@ var BackgroundTaskManager = class {
94
98
  pinSweepInterval;
95
99
  sweepingPins = false;
96
100
  pinSweepPage = 0;
101
+ runningSweepPage = 0;
97
102
  #settlingRuns = /* @__PURE__ */ new Set();
98
103
  workerCallback;
99
104
  resultCallback;
@@ -149,7 +154,9 @@ var BackgroundTaskManager = class {
149
154
  this.resultCallback = async (event, ack) => {
150
155
  if (event.type === "task.completed" || event.type === "task.failed") {
151
156
  try {
152
- await this.handleResult(event);
157
+ const handling = this.handleResult(event);
158
+ this.#trackSettlingRun(handling.catch(() => {}));
159
+ await handling;
153
160
  } finally {
154
161
  await ack?.();
155
162
  }
@@ -178,7 +185,7 @@ var BackgroundTaskManager = class {
178
185
  if (handled) await ack?.();
179
186
  };
180
187
  if (this.#mastra) {
181
- const { buildBackgroundTaskWorkflow } = await import("./workflow-BSLS7_vB.js");
188
+ const { buildBackgroundTaskWorkflow } = await import("./workflow-wXOf72fO.js");
182
189
  const workflow = buildBackgroundTaskWorkflow(this);
183
190
  if (!this.#mastra.__hasInternalWorkflow("__background-task")) this.#mastra.__registerInternalWorkflow(workflow);
184
191
  }
@@ -188,10 +195,6 @@ var BackgroundTaskManager = class {
188
195
  await this.#releaseLateInitSubscriptions([[TOPIC_DISPATCH, this.workerCallback], [this.processAffineDispatchTopic, this.workerCallback]]);
189
196
  return;
190
197
  }
191
- if (this.config.recoverStaleTasksOnStart) {
192
- await this.recoverStaleTasks();
193
- this.#startPinSweep();
194
- }
195
198
  }
196
199
  await this.pubsub.subscribe(TOPIC_RESULT, this.resultCallback);
197
200
  if (this.shuttingDown) {
@@ -204,6 +207,10 @@ var BackgroundTaskManager = class {
204
207
  await this.#releaseLateInitSubscriptions(lateSubscriptions);
205
208
  return;
206
209
  }
210
+ if (!isProducerOnly && this.config.recoverStaleTasksOnStart) {
211
+ await this.recoverStaleTasks();
212
+ this.#startPinSweep();
213
+ }
207
214
  const cleanupConfig = this.config.cleanup;
208
215
  if (cleanupConfig && !this.shuttingDown) {
209
216
  const intervalMs = cleanupConfig.cleanupIntervalMs ?? 6e4;
@@ -274,6 +281,7 @@ var BackgroundTaskManager = class {
274
281
  if (this.shuttingDown) throw new Error("BackgroundTaskManager is shutting down, cannot enqueue new tasks");
275
282
  const pinned = options?.pinToWorker === true;
276
283
  if (pinned && !context) throw new Error("pinToWorker requires a task context");
284
+ if (context) this.#assertCanRunLocalTasks("enqueue");
277
285
  if (this.initPromise) await this.initPromise;
278
286
  const createdAt = /* @__PURE__ */ new Date();
279
287
  const task = {
@@ -375,13 +383,7 @@ var BackgroundTaskManager = class {
375
383
  this.activeAbortControllers.delete(taskId);
376
384
  }
377
385
  }
378
- if (previousStatus === "running" || previousStatus === "suspended") {
379
- if (this.#mastra) try {
380
- await (await this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID).createRun({ runId: taskId })).cancel();
381
- } catch (err) {
382
- this.#mastra?.getLogger?.()?.warn(`background-task workflow cancel failed for ${taskId}:`, err);
383
- }
384
- }
386
+ if (previousStatus === "running" || previousStatus === "suspended") await this.#cancelWorkflowRun(taskId);
385
387
  const cancelledTask = await storage.getTask(taskId);
386
388
  if (cancelledTask) {
387
389
  await this.publishLifecycleEvent("task.cancelled", cancelledTask);
@@ -422,6 +424,7 @@ var BackgroundTaskManager = class {
422
424
  if (task.status !== "suspended") throw new Error(`Cannot resume task in status '${task.status}' (expected 'suspended')`);
423
425
  if (options?.suspendedAt !== void 0 && new Date(options.suspendedAt).getTime() !== suspensionToken(task)) throw new Error(`Cannot resume task "${taskId}": its suspension has changed since it was read`);
424
426
  const isProcessAffine = this.taskContexts.has(taskId);
427
+ if (isProcessAffine) this.#assertCanRunLocalTasks("resume");
425
428
  if (!(isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId))) {
426
429
  if (options?.onNoSlot === "queue") {
427
430
  this.localPendingResumes.set(taskId, {
@@ -483,6 +486,7 @@ var BackgroundTaskManager = class {
483
486
  if (!task) throw new Error(`Task not found: ${taskId}`);
484
487
  if (task.status !== "pending" && task.status !== "running") throw new Error(`Cannot restart task in status '${task.status}' (expected 'pending' or 'running')`);
485
488
  const isRestart = task.status === "running";
489
+ if (context || this.taskContexts.has(taskId)) this.#assertCanRunLocalTasks("restart");
486
490
  if (context) this.registerTaskContext(task.id, context);
487
491
  const isProcessAffine = this.taskContexts.has(taskId);
488
492
  if (!(isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId))) throw new Error(`Concurrency limit reached, cannot restart task "${taskId}" \u2014 retry once a slot is available`);
@@ -852,9 +856,33 @@ var BackgroundTaskManager = class {
852
856
  if (this.initPromise) await this.#waitForShutdownStep("background task pubsub flush", this.pubsub.flush());
853
857
  }
854
858
  async #cancelTaskForShutdown(taskId) {
855
- const task = await (await this.getStorage()).getTask(taskId);
856
- if (task?.status === "running" && task.maxRetries > 0) return;
857
- await this.cancel(taskId);
859
+ const storage = await this.getStorage();
860
+ const task = await storage.getTask(taskId);
861
+ if (task?.status !== "running") {
862
+ await this.cancel(taskId);
863
+ return;
864
+ }
865
+ if (task.maxRetries > 0) return;
866
+ const fence = {
867
+ expectedStatus: "running",
868
+ expectedOwnerId: this.workerId
869
+ };
870
+ if (await this.#failTerminated(storage, taskId, fence, { runLocalHooks: true })) {
871
+ this.ownedLeases.delete(taskId);
872
+ await this.#cancelWorkflowRun(taskId);
873
+ }
874
+ }
875
+ /**
876
+ * Cancels a task's background-task workflow run, so workflow storage
877
+ * reflects the task's end and any stored suspended snapshot is cleaned up.
878
+ */
879
+ async #cancelWorkflowRun(taskId) {
880
+ if (!this.#mastra) return;
881
+ try {
882
+ await (await this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID).createRun({ runId: taskId })).cancel();
883
+ } catch (err) {
884
+ this.#mastra?.getLogger?.()?.warn(`background-task workflow cancel failed for ${taskId}:`, err);
885
+ }
858
886
  }
859
887
  #abortActiveControllers() {
860
888
  for (const controller of this.activeAbortControllers.values()) controller.abort(/* @__PURE__ */ new Error(SHUTDOWN_ABORT_MESSAGE));
@@ -904,6 +932,17 @@ var BackgroundTaskManager = class {
904
932
  });
905
933
  }
906
934
  /**
935
+ * A task with a registered context runs from this process's closures, so it
936
+ * is published to this process's own dispatch topic. A producer-mode manager
937
+ * never consumes that topic, and no other process can run those closures, so
938
+ * the task would sit unclaimed (#31089). Refuse before anything is persisted
939
+ * or published; agent runs then execute the tool without a background task.
940
+ */
941
+ #assertCanRunLocalTasks(action) {
942
+ if (this.config.mode !== "producer") return;
943
+ throw new Error(`Cannot ${action} a background task with an in-process executor: this process doesn't run background tasks (workers are disabled or MASTRA_WORKERS excludes backgroundTasks), and other processes can't run its executor. Run the backgroundTasks worker on this process, or pass \`disableBackgroundTasks: true\` to agent runs here so their tools run inline. Tasks enqueued directly can omit the task context to let a dedicated worker run the tool by name.`);
944
+ }
945
+ /**
907
946
  * Lazily start Mastra's execution workers before publishing. In "library
908
947
  * mode" nothing ever calls `mastra.startWorkers()`, so the evented
909
948
  * `__background-task` workflow started by `handleDispatch` would publish
@@ -1592,31 +1631,12 @@ var BackgroundTaskManager = class {
1592
1631
  const { tasks: staleTasks } = await storage.listTasks({ status: "running" });
1593
1632
  let nextSweepAt;
1594
1633
  for (const task of staleTasks) {
1595
- if (task.ownerId && task.leaseExpiresAt && task.leaseExpiresAt.getTime() > now) {
1634
+ if (isLiveRunning(task, now)) {
1596
1635
  const leaseExpiry = task.leaseExpiresAt.getTime();
1597
1636
  nextSweepAt = nextSweepAt === void 0 ? leaseExpiry : Math.min(nextSweepAt, leaseExpiry);
1598
1637
  continue;
1599
1638
  }
1600
- const fence = {
1601
- expectedStatus: "running",
1602
- expectedOwnerId: task.ownerId ?? null,
1603
- expectedLeaseExpiresAt: task.leaseExpiresAt ?? null
1604
- };
1605
- const handedBack = !task.ownerId && task.maxRetries > 0;
1606
- if (handedBack || task.retryCount < task.maxRetries) await storage.updateTask(task.id, {
1607
- status: "pending",
1608
- retryCount: handedBack ? task.retryCount : task.retryCount + 1,
1609
- startedAt: void 0,
1610
- ownerId: void 0,
1611
- leaseExpiresAt: void 0
1612
- }, fence);
1613
- else await storage.updateTask(task.id, {
1614
- status: "failed",
1615
- error: { message: "Worker process terminated before task completed" },
1616
- completedAt: /* @__PURE__ */ new Date(),
1617
- ownerId: void 0,
1618
- leaseExpiresAt: void 0
1619
- }, fence);
1639
+ await this.#reclaimLapsedRunning(storage, task);
1620
1640
  }
1621
1641
  const { tasks: pendingTasks } = await storage.listTasks({
1622
1642
  status: "pending",
@@ -1639,6 +1659,59 @@ var BackgroundTaskManager = class {
1639
1659
  }
1640
1660
  }
1641
1661
  /**
1662
+ * Reclaims a `running` row whose lease lapsed: re-pends it, or fails it once
1663
+ * it is out of retries. Returns `true` when the row was re-pended and should
1664
+ * be dispatched; `false` when it was failed or another worker got to it first.
1665
+ */
1666
+ async #reclaimLapsedRunning(storage, task) {
1667
+ const fence = {
1668
+ expectedStatus: "running",
1669
+ expectedOwnerId: task.ownerId ?? null,
1670
+ expectedLeaseExpiresAt: task.leaseExpiresAt ?? null
1671
+ };
1672
+ const handedBack = !task.ownerId && task.maxRetries > 0;
1673
+ if (handedBack || task.retryCount < task.maxRetries) {
1674
+ const requeued = await storage.updateTask(task.id, {
1675
+ status: "pending",
1676
+ retryCount: handedBack ? task.retryCount : task.retryCount + 1,
1677
+ startedAt: void 0,
1678
+ ownerId: void 0,
1679
+ leaseExpiresAt: void 0
1680
+ }, fence);
1681
+ return Boolean(requeued);
1682
+ }
1683
+ await this.#failTerminated(storage, task.id, fence);
1684
+ return false;
1685
+ }
1686
+ /**
1687
+ * Fails a task whose worker is gone and reports it with `task.failed`, so
1688
+ * `onTaskFailed` and stream subscribers hear about it like any other failure.
1689
+ * Only the caller whose fenced write lands publishes, so peers racing on the
1690
+ * same row stay quiet. A failed publish is logged, not thrown, so a sweep
1691
+ * still reaches the rows after this one. Returns whether the write landed.
1692
+ * Pass `runLocalHooks` when this process may still hold the task's per-task
1693
+ * hooks, so they run, isolated, before the event, as for any other failure.
1694
+ */
1695
+ async #failTerminated(storage, taskId, fence, { runLocalHooks = false } = {}) {
1696
+ if (!await storage.updateTask(taskId, {
1697
+ status: "failed",
1698
+ error: { message: WORKER_TERMINATED_MESSAGE },
1699
+ completedAt: /* @__PURE__ */ new Date(),
1700
+ ownerId: void 0,
1701
+ leaseExpiresAt: void 0
1702
+ }, fence)) return false;
1703
+ try {
1704
+ const failedTask = await storage.getTask(taskId);
1705
+ if (failedTask?.status === "failed") {
1706
+ if (runLocalHooks) await this.runLocalCompletionHooks(failedTask, "failed", { error: failedTask.error });
1707
+ await this.publishLifecycleEvent("task.failed", failedTask);
1708
+ }
1709
+ } catch (error) {
1710
+ this.#mastra?.getLogger?.()?.warn(`Failed to report background task ${taskId} as failed:`, error);
1711
+ }
1712
+ return true;
1713
+ }
1714
+ /**
1642
1715
  * Accounts for a `pinToWorker` row whose owner stopped renewing its lease.
1643
1716
  * A pin means work for the row was in flight on its owner, so a lapsed pin
1644
1717
  * is a lost attempt, handled like a `running` row whose lease lapsed: it
@@ -1658,13 +1731,7 @@ var BackgroundTaskManager = class {
1658
1731
  retryCount: task.retryCount + 1,
1659
1732
  ownerId: void 0,
1660
1733
  leaseExpiresAt: void 0
1661
- }, fence) : await storage.updateTask(task.id, {
1662
- status: "failed",
1663
- error: { message: "Worker process terminated before task completed" },
1664
- completedAt: /* @__PURE__ */ new Date(),
1665
- ownerId: void 0,
1666
- leaseExpiresAt: void 0
1667
- }, fence);
1734
+ }, fence) : await this.#failTerminated(storage, task.id, fence);
1668
1735
  if (recovered) this.#mastra?.getLogger()?.warn(`Background task ${task.id} lost its pin: worker ${task.ownerId} stopped renewing its lease. ${retry ? "Retrying it on another worker." : "Marking it failed."}`);
1669
1736
  return retry && recovered;
1670
1737
  }
@@ -1693,19 +1760,33 @@ var BackgroundTaskManager = class {
1693
1760
  }
1694
1761
  }
1695
1762
  /**
1696
- * Periodically recovers lapsed `pinToWorker` rows. The startup scan only
1697
- * sees rows that existed when this worker started, so without this a pin
1698
- * enqueued later by a worker that then died would wait for a restart.
1699
- * Unpinned pending rows are left alone: they are dispatched by their own
1700
- * worker and by startup recovery, as before.
1763
+ * Periodically recovers `running` rows and `pinToWorker` rows whose owner
1764
+ * stopped renewing its lease. The startup scan only sees rows that existed
1765
+ * when this worker started, so without this a task whose worker died later
1766
+ * would wait for a restart. Unpinned pending rows are left alone: they are
1767
+ * dispatched by their own worker and by startup recovery, as before.
1701
1768
  */
1702
1769
  async #sweepLapsedPins() {
1703
1770
  if (this.shuttingDown || this.sweepingPins) return;
1704
1771
  this.sweepingPins = true;
1705
1772
  try {
1706
- if (this.localPendingTaskIds.size > 0) await this.drainPending();
1707
1773
  const storage = await this.getStorage();
1708
1774
  const now = Date.now();
1775
+ const runningPageSize = Math.min(Math.max(PIN_SWEEP_PAGE_SIZE, this.config.globalConcurrency), RUNNING_SWEEP_MAX_PAGE_SIZE);
1776
+ const { tasks: running, total: runningTotal } = await storage.listTasks({
1777
+ status: "running",
1778
+ orderBy: "createdAt",
1779
+ orderDirection: "asc",
1780
+ page: this.runningSweepPage,
1781
+ perPage: runningPageSize
1782
+ });
1783
+ this.runningSweepPage = (this.runningSweepPage + 1) * runningPageSize < runningTotal ? this.runningSweepPage + 1 : 0;
1784
+ for (const task of running) {
1785
+ if (this.shuttingDown) return;
1786
+ if (isLiveRunning(task, now)) continue;
1787
+ if (await this.#reclaimLapsedRunning(storage, task)) this.localPendingTaskIds.add(task.id);
1788
+ }
1789
+ if (this.localPendingTaskIds.size > 0) await this.drainPending();
1709
1790
  const { tasks } = await storage.listTasks({
1710
1791
  status: "pending",
1711
1792
  orderBy: "createdAt",
@@ -1749,6 +1830,13 @@ var BackgroundTaskManager = class {
1749
1830
  this.staleRecoveryTimeout.unref?.();
1750
1831
  }
1751
1832
  };
1833
+ /**
1834
+ * A still-valid lease proves a `running` row's owner is alive. This is what
1835
+ * stops a second worker from taking over a task another process is running.
1836
+ */
1837
+ function isLiveRunning(task, now) {
1838
+ return Boolean(task.ownerId && task.leaseExpiresAt && task.leaseExpiresAt.getTime() > now);
1839
+ }
1752
1840
  function suspensionToken(task) {
1753
1841
  return task.suspendedAt?.getTime() ?? null;
1754
1842
  }
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_base = require("../base-BIzR1D3_.cjs");
3
3
  const require_logger = require("../logger-CvzZYuJd.cjs");
4
- const require_stream = require("../stream-BIXX67WE.cjs");
4
+ const require_stream = require("../stream-DH7Qgz8l.cjs");
5
5
  const require_tool = require("../tool-CYlT2UA-.cjs");
6
6
  const require_workspace = require("../workspace-X2RHJZU9.cjs");
7
7
  let events = require("events");