@mastra/core 1.87.0 → 1.88.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 (404) hide show
  1. package/dist/_types/@internal_ai-v6@0.0.100/dist/index.d.ts +97 -2049
  2. package/dist/agent/agent.d.ts +10 -2
  3. package/dist/agent/durable/create-evented-agent.d.ts +2 -1
  4. package/dist/agent/durable/execution-engine.d.ts +4 -2
  5. package/dist/agent/durable/index.cjs +3 -2
  6. package/dist/agent/durable/index.js +3 -2
  7. package/dist/agent/durable/segment-spans.d.ts +7 -0
  8. package/dist/agent/durable/stored-signal-drain.d.ts +1 -1
  9. package/dist/agent/durable/types.d.ts +6 -0
  10. package/dist/agent/index.cjs +2 -2
  11. package/dist/agent/index.js +2 -2
  12. package/dist/agent/request-context-snapshot.d.ts +5 -0
  13. package/dist/agent/thread-stream-runtime.d.ts +26 -4
  14. package/dist/agent-builder/ee/index.cjs +1 -1
  15. package/dist/agent-builder/ee/index.js +1 -1
  16. package/dist/agent-controller/index.cjs +1 -1
  17. package/dist/agent-controller/index.js +1 -1
  18. package/dist/{agent-controller-vUU_atR-.js → agent-controller-CQDCmsFD.js} +15 -9
  19. package/dist/{agent-controller-DckvJ7bq.cjs → agent-controller-NQKYmY0W.cjs} +15 -9
  20. package/dist/background-tasks/index.cjs +1 -1
  21. package/dist/background-tasks/index.js +1 -1
  22. package/dist/{background-tasks-HAzB0JtC.js → background-tasks-B7UygDdO.js} +1 -1
  23. package/dist/{background-tasks-By_1e9Gf.cjs → background-tasks-CeARf1DK.cjs} +1 -1
  24. package/dist/browser/index.cjs +1 -1
  25. package/dist/browser/index.js +1 -1
  26. package/dist/{builder-CmtDqFLe.js → builder-CpAEmMdR.js} +2 -2
  27. package/dist/{builder-Dx8GMhFn.cjs → builder-Dmf04g9P.cjs} +2 -2
  28. package/dist/capabilities/302ai.json +196 -196
  29. package/dist/capabilities/abliteratedllm.json +33 -33
  30. package/dist/capabilities/abliteration-ai.json +9 -9
  31. package/dist/capabilities/above.json +13 -13
  32. package/dist/capabilities/adaption.json +7 -7
  33. package/dist/capabilities/adzuki.json +20 -20
  34. package/dist/capabilities/agentrouter.json +10 -10
  35. package/dist/capabilities/agnes.json +2 -2
  36. package/dist/capabilities/ai-router.json +6 -6
  37. package/dist/capabilities/aiand.json +27 -18
  38. package/dist/capabilities/aigrow.json +14 -14
  39. package/dist/capabilities/aimlapi.json +146 -146
  40. package/dist/capabilities/aipg.json +2 -2
  41. package/dist/capabilities/aixy.json +17 -17
  42. package/dist/capabilities/aki-io.json +14 -14
  43. package/dist/capabilities/alibaba-cn.json +94 -94
  44. package/dist/capabilities/alibaba-coding-plan-cn.json +5 -5
  45. package/dist/capabilities/alibaba-coding-plan.json +5 -5
  46. package/dist/capabilities/alibaba-token-plan-cn.json +50 -50
  47. package/dist/capabilities/alibaba-token-plan.json +53 -53
  48. package/dist/capabilities/alibaba.json +71 -71
  49. package/dist/capabilities/ambient.json +8 -8
  50. package/dist/capabilities/amd-tokenlab.json +4 -4
  51. package/dist/capabilities/amd.json +11 -11
  52. package/dist/capabilities/anthropic.json +36 -36
  53. package/dist/capabilities/anyapi.json +18 -18
  54. package/dist/capabilities/apiko.json +2 -2
  55. package/dist/capabilities/arcee.json +9 -9
  56. package/dist/capabilities/augure.json +5 -5
  57. package/dist/capabilities/auriko.json +23 -23
  58. package/dist/capabilities/bailing.json +5 -5
  59. package/dist/capabilities/baseten.json +47 -38
  60. package/dist/capabilities/bee.json +5 -5
  61. package/dist/capabilities/bothub.json +14 -14
  62. package/dist/capabilities/boundless.json +37 -37
  63. package/dist/capabilities/bumo.json +40 -40
  64. package/dist/capabilities/byteplus.json +22 -22
  65. package/dist/capabilities/cerebras.json +4 -4
  66. package/dist/capabilities/cheapaimodel.json +10 -10
  67. package/dist/capabilities/cheapest-token.json +25 -25
  68. package/dist/capabilities/chutes.json +34 -32
  69. package/dist/capabilities/cline-pass.json +29 -29
  70. package/dist/capabilities/cloudcode.json +7 -7
  71. package/dist/capabilities/cloudflare-workers-ai.json +15 -15
  72. package/dist/capabilities/commandcode.json +146 -146
  73. package/dist/capabilities/concentrate.json +286 -277
  74. package/dist/capabilities/cortecs.json +109 -109
  75. package/dist/capabilities/crossmodel.json +194 -194
  76. package/dist/capabilities/crusoe.json +13 -13
  77. package/dist/capabilities/daoxe.json +7 -7
  78. package/dist/capabilities/databricks.json +128 -120
  79. package/dist/capabilities/deepinfra.json +102 -102
  80. package/dist/capabilities/deepseek.json +4 -4
  81. package/dist/capabilities/digitalocean.json +113 -114
  82. package/dist/capabilities/dothoosh.json +29 -29
  83. package/dist/capabilities/doubleword.json +26 -26
  84. package/dist/capabilities/edenai.json +287 -278
  85. package/dist/capabilities/empiriolabs.json +169 -169
  86. package/dist/capabilities/engy.json +24 -18
  87. package/dist/capabilities/entrim.json +6 -6
  88. package/dist/capabilities/evroc.json +13 -13
  89. package/dist/capabilities/ezkielyna.json +9 -9
  90. package/dist/capabilities/fastrouter.json +79 -79
  91. package/dist/capabilities/fireworks-ai.json +92 -92
  92. package/dist/capabilities/freemodel.json +10 -10
  93. package/dist/capabilities/friendli.json +26 -5
  94. package/dist/capabilities/frogbot.json +97 -97
  95. package/dist/capabilities/gisoo.json +19 -19
  96. package/dist/capabilities/gmicloud.json +7 -7
  97. package/dist/capabilities/google.json +53 -53
  98. package/dist/capabilities/graphn.json +14 -14
  99. package/dist/capabilities/greenpt.json +34 -34
  100. package/dist/capabilities/groq.json +4 -4
  101. package/dist/capabilities/helicone.json +88 -88
  102. package/dist/capabilities/hetzner.json +4 -4
  103. package/dist/capabilities/hostinger-router.json +10 -10
  104. package/dist/capabilities/hpc-ai.json +2 -2
  105. package/dist/capabilities/huawei-maas.json +15 -15
  106. package/dist/capabilities/hubris.json +28 -28
  107. package/dist/capabilities/huggingface.json +87 -85
  108. package/dist/capabilities/hyper.json +24 -24
  109. package/dist/capabilities/impossibl.json +114 -114
  110. package/dist/capabilities/inception.json +3 -3
  111. package/dist/capabilities/inceptron.json +8 -8
  112. package/dist/capabilities/inco.json +2 -2
  113. package/dist/capabilities/infer.json +17 -17
  114. package/dist/capabilities/inferall.json +5 -5
  115. package/dist/capabilities/inference-coop.json +2 -2
  116. package/dist/capabilities/inferenceapis.json +27 -27
  117. package/dist/capabilities/inferris.json +3 -3
  118. package/dist/capabilities/infersia.json +11 -11
  119. package/dist/capabilities/infomaniak.json +2 -2
  120. package/dist/capabilities/io-net.json +2 -2
  121. package/dist/capabilities/iteracompute.json +38 -38
  122. package/dist/capabilities/jalapeno.json +10 -10
  123. package/dist/capabilities/jiekou.json +34 -34
  124. package/dist/capabilities/joingonka.json +4 -4
  125. package/dist/capabilities/jzstoken.json +49 -49
  126. package/dist/capabilities/keln.json +24 -24
  127. package/dist/capabilities/kenari.json +122 -137
  128. package/dist/capabilities/kilo.json +615 -614
  129. package/dist/capabilities/kimchi.json +14 -14
  130. package/dist/capabilities/kimi-code-plan-cn.json +9 -9
  131. package/dist/capabilities/kimi-code-plan-global.json +9 -9
  132. package/dist/capabilities/kitani.json +6 -6
  133. package/dist/capabilities/klavo.json +20 -20
  134. package/dist/capabilities/korouter.json +35 -35
  135. package/dist/capabilities/kunavo.json +10 -10
  136. package/dist/capabilities/liquid.json +9 -9
  137. package/dist/capabilities/lithosai.json +2 -2
  138. package/dist/capabilities/llmgateway-providers.json +959 -923
  139. package/dist/capabilities/llmgateway.json +349 -340
  140. package/dist/capabilities/llmtr.json +29 -29
  141. package/dist/capabilities/logits.json +2 -2
  142. package/dist/capabilities/lowrouter.json +53 -53
  143. package/dist/capabilities/lyceum.json +12 -12
  144. package/dist/capabilities/melious.json +9 -9
  145. package/dist/capabilities/merge-gateway.json +271 -263
  146. package/dist/capabilities/meta.json +11 -11
  147. package/dist/capabilities/minimax-cn-coding-plan.json +5 -5
  148. package/dist/capabilities/minimax-cn.json +5 -5
  149. package/dist/capabilities/minimax-coding-plan.json +5 -5
  150. package/dist/capabilities/minimax.json +5 -5
  151. package/dist/capabilities/mistral.json +16 -16
  152. package/dist/capabilities/mixlayer.json +4 -4
  153. package/dist/capabilities/modal.json +11 -11
  154. package/dist/capabilities/model-oracle-ai.json +19 -19
  155. package/dist/capabilities/modelis.json +16 -16
  156. package/dist/capabilities/modular.json +5 -5
  157. package/dist/capabilities/moneo.json +10 -10
  158. package/dist/capabilities/moonshotai-cn.json +6 -6
  159. package/dist/capabilities/moonshotai.json +6 -6
  160. package/dist/capabilities/morph.json +18 -18
  161. package/dist/capabilities/munito-eu.json +8 -8
  162. package/dist/capabilities/munito.json +10 -10
  163. package/dist/capabilities/nan.json +33 -33
  164. package/dist/capabilities/nano-gpt.json +557 -567
  165. package/dist/capabilities/nearai.json +77 -77
  166. package/dist/capabilities/nebius.json +42 -34
  167. package/dist/capabilities/neon.json +127 -127
  168. package/dist/capabilities/neuralwatt.json +37 -37
  169. package/dist/capabilities/nokeep.json +4 -4
  170. package/dist/capabilities/novita-ai.json +115 -115
  171. package/dist/capabilities/nvidia.json +17 -17
  172. package/dist/capabilities/oathbreaker.json +5 -5
  173. package/dist/capabilities/obscurify.json +29 -29
  174. package/dist/capabilities/oci.json +6 -6
  175. package/dist/capabilities/ofox.json +265 -265
  176. package/dist/capabilities/ollama-cloud.json +52 -52
  177. package/dist/capabilities/openai.json +58 -61
  178. package/dist/capabilities/opencode-go.json +90 -90
  179. package/dist/capabilities/openreason.json +6 -6
  180. package/dist/capabilities/openrouter.json +550 -548
  181. package/dist/capabilities/opper.json +26 -26
  182. package/dist/capabilities/orcarouter.json +310 -294
  183. package/dist/capabilities/outerlabs.json +29 -29
  184. package/dist/capabilities/ovhcloud.json +22 -22
  185. package/dist/capabilities/pareto.json +4 -4
  186. package/dist/capabilities/perplexity-agent.json +69 -69
  187. package/dist/capabilities/perplexity.json +2 -2
  188. package/dist/capabilities/phala.json +30 -30
  189. package/dist/capabilities/poe.json +111 -111
  190. package/dist/capabilities/poolside.json +2 -2
  191. package/dist/capabilities/powerspring.json +9 -9
  192. package/dist/capabilities/primalabs.json +11 -11
  193. package/dist/capabilities/prime.json +127 -119
  194. package/dist/capabilities/privatemode-ai.json +6 -6
  195. package/dist/capabilities/proxystacks.json +3 -3
  196. package/dist/capabilities/qiniu-ai.json +13 -13
  197. package/dist/capabilities/refuseless.json +5 -5
  198. package/dist/capabilities/regolo-ai.json +10 -10
  199. package/dist/capabilities/requesty.json +200 -200
  200. package/dist/capabilities/ruapi.json +20 -20
  201. package/dist/capabilities/runcrate.json +13 -13
  202. package/dist/capabilities/runinfra.json +19 -19
  203. package/dist/capabilities/sakana.json +5 -5
  204. package/dist/capabilities/sambanova.json +9 -9
  205. package/dist/capabilities/sandbase.json +22 -22
  206. package/dist/capabilities/sarvam.json +14 -14
  207. package/dist/capabilities/scaleway.json +17 -17
  208. package/dist/capabilities/scnet-token-plan.json +8 -8
  209. package/dist/capabilities/scx-ai.json +22 -22
  210. package/dist/capabilities/sensenova.json +11 -11
  211. package/dist/capabilities/siliconflow-cn.json +59 -59
  212. package/dist/capabilities/siliconflow.json +57 -57
  213. package/dist/capabilities/snowflake-cortex.json +19 -19
  214. package/dist/capabilities/sokkan.json +10 -10
  215. package/dist/capabilities/sparrowcodes.json +20 -20
  216. package/dist/capabilities/standardcompute.json +85 -85
  217. package/dist/capabilities/steadyrouter.json +40 -40
  218. package/dist/capabilities/stepfun-ai-step-plan.json +5 -5
  219. package/dist/capabilities/stepfun-ai.json +5 -5
  220. package/dist/capabilities/stepfun-step-plan.json +5 -5
  221. package/dist/capabilities/stepfun.json +5 -5
  222. package/dist/capabilities/stepping-stone.json +18 -18
  223. package/dist/capabilities/superbot-gg.json +4 -4
  224. package/dist/capabilities/synthetic.json +12 -12
  225. package/dist/capabilities/synthorai.json +21 -21
  226. package/dist/capabilities/teamorouter.json +17 -17
  227. package/dist/capabilities/teapot-router.json +13 -13
  228. package/dist/capabilities/tencent-token-plan-intl.json +22 -22
  229. package/dist/capabilities/tencent-token-plan.json +42 -42
  230. package/dist/capabilities/tencent-tokenhub.json +44 -44
  231. package/dist/capabilities/tensorx.json +43 -43
  232. package/dist/capabilities/tenstorrent.json +2 -2
  233. package/dist/capabilities/the-grid-ai.json +30 -30
  234. package/dist/capabilities/thinkingmachines.json +78 -78
  235. package/dist/capabilities/tinfoil.json +13 -13
  236. package/dist/capabilities/toapis.json +2 -2
  237. package/dist/capabilities/togetherai.json +54 -54
  238. package/dist/capabilities/tokengo.json +23 -23
  239. package/dist/capabilities/tokenharbor.json +217 -217
  240. package/dist/capabilities/tokenify.json +9 -9
  241. package/dist/capabilities/trustedrouter.json +6 -6
  242. package/dist/capabilities/trustedtokens.json +12 -12
  243. package/dist/capabilities/umans-ai-coding-plan.json +17 -17
  244. package/dist/capabilities/umans-ai.json +11 -11
  245. package/dist/capabilities/uncensuredai.json +5 -5
  246. package/dist/capabilities/unrestricted.json +4 -4
  247. package/dist/capabilities/uplinkswitch.json +20 -20
  248. package/dist/capabilities/upstage.json +2 -2
  249. package/dist/capabilities/vancine.json +20 -20
  250. package/dist/capabilities/vercel.json +580 -571
  251. package/dist/capabilities/vivgrid.json +61 -61
  252. package/dist/capabilities/volcengine-coding-plan.json +26 -26
  253. package/dist/capabilities/volcengine.json +24 -24
  254. package/dist/capabilities/vultr.json +15 -15
  255. package/dist/capabilities/wafer.ai.json +19 -19
  256. package/dist/capabilities/wallaby.json +5 -5
  257. package/dist/capabilities/wally.json +11 -11
  258. package/dist/capabilities/wandb.json +21 -21
  259. package/dist/capabilities/watt.json +19 -19
  260. package/dist/capabilities/xai.json +2 -2
  261. package/dist/capabilities/xpersona.json +13 -13
  262. package/dist/capabilities/xxapi.json +27 -27
  263. package/dist/capabilities/zai-coding-plan.json +11 -11
  264. package/dist/capabilities/zai.json +32 -32
  265. package/dist/capabilities/zenifra.json +27 -27
  266. package/dist/capabilities/zenmux.json +178 -178
  267. package/dist/capabilities/zerogpu.json +12 -12
  268. package/dist/capabilities/zhipuai-coding-plan.json +3 -3
  269. package/dist/capabilities/zhipuai.json +28 -28
  270. package/dist/capabilities/zro.json +7 -7
  271. package/dist/channels/index.cjs +2 -2
  272. package/dist/channels/index.js +2 -2
  273. package/dist/{channels-DChC1kXm.js → channels-BQ--aLCA.js} +1 -1
  274. package/dist/{channels-BamLzaJG.cjs → channels-CTCBsS5M.cjs} +1 -1
  275. package/dist/coding-agent/index.cjs +1 -1
  276. package/dist/coding-agent/index.js +1 -1
  277. package/dist/datasets/index.cjs +2 -2
  278. package/dist/datasets/index.js +2 -2
  279. package/dist/docs/SKILL.md +1 -1
  280. package/dist/docs/assets/SOURCE_MAP.json +804 -804
  281. package/dist/docs/references/docs-agents-human-in-the-loop.md +1 -1
  282. package/dist/docs/references/docs-agents-resumable-streams.md +3 -3
  283. package/dist/docs/references/docs-channels.md +8 -2
  284. package/dist/docs/references/docs-deployment-workers.md +10 -4
  285. package/dist/docs/references/docs-harness-durable-agents.md +17 -15
  286. package/dist/docs/references/docs-server-mcp.md +68 -0
  287. package/dist/docs/references/docs-server-pubsub.md +25 -16
  288. package/dist/docs/references/docs-signals-running-across-processes.md +9 -3
  289. package/dist/docs/references/docs-signals-sending-signals.md +1 -1
  290. package/dist/docs/references/docs-workflows-overview.md +3 -3
  291. package/dist/docs/references/reference-agents-agent.md +3 -1
  292. package/dist/docs/references/reference-agents-durable-agent.md +3 -3
  293. package/dist/docs/references/reference-configuration.md +60 -0
  294. package/dist/docs/references/reference-pubsub-base.md +1 -1
  295. package/dist/docs/references/reference-pubsub-caching-pubsub.md +1 -1
  296. package/dist/docs/references/reference-pubsub-google-cloud-pubsub.md +13 -7
  297. package/dist/docs/references/reference-pubsub-lease-provider.md +4 -0
  298. package/dist/docs/references/reference-pubsub-redis-streams.md +18 -9
  299. package/dist/docs/references/reference-pubsub-valkey-streams.md +25 -7
  300. package/dist/evals/index.cjs +1 -1
  301. package/dist/evals/index.js +1 -1
  302. package/dist/evals/scoreTraces/index.cjs +1 -1
  303. package/dist/evals/scoreTraces/index.js +1 -1
  304. package/dist/events/caching-pubsub.d.ts +3 -11
  305. package/dist/events/index.cjs +1 -1
  306. package/dist/events/index.js +1 -1
  307. package/dist/events/pubsub.d.ts +2 -1
  308. package/dist/{execution-fence-BBKnrhWR.cjs → execution-fence-C8Q0wWkG.cjs} +841 -219
  309. package/dist/{execution-fence--VdnD7p4.js → execution-fence-DGFyUV5h.js} +841 -219
  310. package/dist/harness/index.cjs +1 -1
  311. package/dist/harness/index.js +1 -1
  312. package/dist/index.cjs +1 -1
  313. package/dist/index.js +1 -1
  314. package/dist/knowledge/index.cjs +1 -1
  315. package/dist/knowledge/index.js +1 -1
  316. package/dist/llm/index.cjs +3 -3
  317. package/dist/llm/index.js +3 -3
  318. package/dist/llm/model/provider-types.generated.d.ts +7689 -7673
  319. package/dist/llm/reasoning/account-switch.d.ts +50 -0
  320. package/dist/llm/reasoning/index.cjs +65 -0
  321. package/dist/llm/reasoning/index.d.ts +1 -0
  322. package/dist/llm/reasoning/index.js +61 -1
  323. package/dist/{llm-DknPJDW6.cjs → llm-RIAYOAtD.cjs} +2 -2
  324. package/dist/{llm-ccA_1Q-H.js → llm-YNjDFSui.js} +2 -2
  325. package/dist/loop/index.cjs +2 -2
  326. package/dist/loop/index.js +2 -2
  327. package/dist/loop/suspended-run-auto-resume.d.ts +15 -0
  328. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +1 -1
  329. package/dist/{manager-DWX6-Cx4.js → manager-DZhtdV6Q.js} +2 -2
  330. package/dist/{manager-D9F0i7O2.cjs → manager-Y-jYcS7T.cjs} +2 -2
  331. package/dist/mastra/index.cjs +1 -1
  332. package/dist/mastra/index.d.ts +35 -11
  333. package/dist/mastra/index.js +1 -1
  334. package/dist/{mastra-BzWL4xI8.cjs → mastra-B2-HBq1-.cjs} +108 -20
  335. package/dist/{mastra-oUDN81l8.js → mastra-BJ54VxOO.js} +108 -20
  336. package/dist/memory/index.cjs +2 -2
  337. package/dist/memory/index.js +2 -2
  338. package/dist/{model-BwxfS6T_.js → model-cS3d5rmF.js} +1 -1
  339. package/dist/{model-BnD7SPlA.cjs → model-lzZPXaEV.cjs} +1 -1
  340. package/dist/{netlify-CS0VDbb9.cjs → netlify-1lti1j4Z.cjs} +1 -1
  341. package/dist/{netlify-DcY9gHCJ.js → netlify-ClBjc0Xg.js} +1 -1
  342. package/dist/notifications/index.cjs +1 -1
  343. package/dist/notifications/index.js +1 -1
  344. package/dist/{output-helpers-k2-48ssH.js → output-helpers-D-qplq22.js} +13 -15
  345. package/dist/{output-helpers-By5FbLpp.cjs → output-helpers-D4O_oFne.cjs} +12 -14
  346. package/dist/processor-provider/index.cjs +1 -1
  347. package/dist/processor-provider/index.js +1 -1
  348. package/dist/processors/index.cjs +2 -2
  349. package/dist/processors/index.js +2 -2
  350. package/dist/{provider-registry-OggbU6OE.cjs → provider-registry-C6jd3Uxi.cjs} +21565 -21544
  351. package/dist/{provider-registry-BvbEoScB.js → provider-registry-C_XQJvu2.js} +21565 -21544
  352. package/dist/provider-registry.json +22006 -21980
  353. package/dist/{registry-generator-CDaf48a6.cjs → registry-generator-BYdAlox6.cjs} +1 -1
  354. package/dist/{registry-generator-BFOQQHyt.js → registry-generator-DBrTbThj.js} +1 -1
  355. package/dist/{rehydrate-CFoKaNlm.js → rehydrate-4xHubfOY.js} +2 -2
  356. package/dist/{rehydrate-QeS0NjGw.cjs → rehydrate-BtwY0ima.cjs} +2 -2
  357. package/dist/relevance/index.cjs +2 -2
  358. package/dist/relevance/index.js +2 -2
  359. package/dist/{scheduler-0ShtMM1I.js → scheduler-D1qdie5k.js} +4 -2
  360. package/dist/{scheduler-CMjK0LoQ.cjs → scheduler-DE5lcHJA.cjs} +4 -2
  361. package/dist/server/index.d.ts +1 -1
  362. package/dist/server/types.d.ts +57 -0
  363. package/dist/storage/domains/memory/base.d.ts +6 -1
  364. package/dist/storage/index.cjs +2 -2
  365. package/dist/storage/index.js +2 -2
  366. package/dist/stream/index.cjs +2 -2
  367. package/dist/stream/index.js +2 -2
  368. package/dist/{stream-CNqAlDJF.cjs → stream-DqKDB3nL.cjs} +1 -1
  369. package/dist/{stream-D2rv1Ut1.js → stream-H_wVxqdK.js} +1 -1
  370. package/dist/test-utils/llm-mock.cjs +1 -1
  371. package/dist/test-utils/llm-mock.js +1 -1
  372. package/dist/tool-loop-agent/index.cjs +1 -1
  373. package/dist/tool-loop-agent/index.js +1 -1
  374. package/dist/{tool-loop-agent-Dusqj7-j.cjs → tool-loop-agent-D4gSdYuN.cjs} +3 -3
  375. package/dist/{tool-loop-agent-CFsOjueT.js → tool-loop-agent-DvZcOxWe.js} +3 -3
  376. package/dist/{utils-CIuOHPoS.cjs → utils-Dd4m7z13.cjs} +1 -1
  377. package/dist/{utils-DLnCt6E9.js → utils-h5k_ChdS.js} +1 -1
  378. package/dist/utils.cjs +1 -1
  379. package/dist/utils.js +1 -1
  380. package/dist/{validate-ShLcQTA5.js → validate-DQB9spZ1.js} +1 -1
  381. package/dist/{validate-1zReLtWc.cjs → validate-u6_TUYSo.cjs} +1 -1
  382. package/dist/vector/index.cjs +1 -1
  383. package/dist/vector/index.js +1 -1
  384. package/dist/worker/index.cjs +1 -1
  385. package/dist/worker/index.d.ts +1 -1
  386. package/dist/worker/index.js +1 -1
  387. package/dist/worker/workers/orchestration-worker.d.ts +13 -0
  388. package/dist/{worker-CQ8rTJwQ.cjs → worker-0F7Nukyf.cjs} +2 -2
  389. package/dist/{worker-BPNrwCFs.cjs → worker-D-cq8McN.cjs} +117 -32
  390. package/dist/{worker-ngt-F1Iv.js → worker-DWOK2M_5.js} +117 -32
  391. package/dist/{worker-CKcQcPl8.js → worker-DmUkyJY_.js} +2 -2
  392. package/dist/{workflow-B_e5wMmz.cjs → workflow-DXE15e-w.cjs} +4 -4
  393. package/dist/{workflow-XDIVRsu4.js → workflow-DamOke3z.js} +4 -4
  394. package/dist/workflows/builder/index.cjs +1 -1
  395. package/dist/workflows/builder/index.js +1 -1
  396. package/dist/workflows/evented/index.cjs +1 -1
  397. package/dist/workflows/evented/index.js +1 -1
  398. package/dist/workflows/evented/setup-warning.d.ts +20 -0
  399. package/dist/workflows/index.cjs +5 -5
  400. package/dist/workflows/index.js +5 -5
  401. package/dist/workflows/scheduler/types.d.ts +3 -0
  402. package/dist/workspace/tools/media.d.ts +2 -2
  403. package/package.json +7 -7
  404. package/src/llm/model/provider-types.generated.d.ts +7689 -7673
@@ -3,8 +3,8 @@ const require_logger = require("./logger-CvzZYuJd.cjs");
3
3
  const require_base = require("./base-BIzR1D3_.cjs");
4
4
  const require_error = require("./error-D90lJ6M7.cjs");
5
5
  const require_error$1 = require("./error-L1V4uUbd.cjs");
6
- const require_output_helpers = require("./output-helpers-By5FbLpp.cjs");
7
- const require_stream = require("./stream-CNqAlDJF.cjs");
6
+ const require_output_helpers = require("./output-helpers-D4O_oFne.cjs");
7
+ const require_stream = require("./stream-DqKDB3nL.cjs");
8
8
  const require_workflows_constants = require("./workflows/constants.cjs");
9
9
  const require_request_context = require("./request-context-D9RXYCy8.cjs");
10
10
  const require_observability = require("./observability-VaoaeadK.cjs");
@@ -12,9 +12,9 @@ const require_storage = require("./storage-CfG0I2aF.cjs");
12
12
  const require_utils = require("./utils-D-eNsgDM.cjs");
13
13
  const require_tool = require("./tool-Dn9WSDVn.cjs");
14
14
  const require_error_count = require("./error-count-DeDpeWU2.cjs");
15
- const require_utils$1 = require("./utils-CIuOHPoS.cjs");
15
+ const require_utils$1 = require("./utils-Dd4m7z13.cjs");
16
16
  const require_ee_iTj2bRDt = require("./ee-iTj2bRDt-D3-QLGDF.cjs");
17
- const require_background_tasks = require("./background-tasks-By_1e9Gf.cjs");
17
+ const require_background_tasks = require("./background-tasks-CeARf1DK.cjs");
18
18
  const require_toolchecks = require("./toolchecks-DbBsQGHW.cjs");
19
19
  const require_stream$1 = require("./stream-BGbj9jAU.cjs");
20
20
  const require_fetchWithRetry = require("./fetchWithRetry-f5k4p7_1.cjs");
@@ -22,16 +22,16 @@ const require_utils_safe_stringify = require("./utils/safe-stringify.cjs");
22
22
  const require_deep_equal = require("./deep-equal-TMDmByBC.cjs");
23
23
  const require_dynamic_argument = require("./dynamic-argument-CUc1BBOS.cjs");
24
24
  const require_message_list = require("./message-list-C0F2sDNC.cjs");
25
- const require_llm = require("./llm-DknPJDW6.cjs");
25
+ const require_llm = require("./llm-RIAYOAtD.cjs");
26
26
  const require_payload_transform = require("./payload-transform-CWgnsO9w.cjs");
27
27
  const require_signals = require("./signals-CWxAMEmE.cjs");
28
28
  const require_to_prompt = require("./to-prompt-CG-LyaBY.cjs");
29
29
  const require_dist = require("./dist-P2rjrlmj.cjs");
30
30
  const require_dist$1 = require("./dist-CXeCeeW7.cjs");
31
31
  const require_model = require("./model-jBymoqGa.cjs");
32
- const require_provider_registry = require("./provider-registry-OggbU6OE.cjs");
32
+ const require_provider_registry = require("./provider-registry-C6jd3Uxi.cjs");
33
33
  const require_inmemory = require("./inmemory-Dc86VWGB.cjs");
34
- const require_model$1 = require("./model-BnD7SPlA.cjs");
34
+ const require_model$1 = require("./model-lzZPXaEV.cjs");
35
35
  const require_predicate_index = require("./predicate/index.cjs");
36
36
  const require_classifier_index = require("./classifier/index.cjs");
37
37
  const require_observability_context_storage = require("./observability/context-storage.cjs");
@@ -57,6 +57,7 @@ const require_filesystem$4 = require("./filesystem-BP5yz5LG.cjs");
57
57
  const require_filesystem$5 = require("./filesystem-Fpsu7e24.cjs");
58
58
  const require_agent_skills_resolver = require("./agent-skills-resolver-2d8k7ioj.cjs");
59
59
  const require_voice = require("./voice-Cuev6Md3.cjs");
60
+ let _isaacs_ttlcache = require("@isaacs/ttlcache");
60
61
  let zod_v4 = require("zod/v4");
61
62
  let crypto$1 = require("crypto");
62
63
  let _mastra_schema_compat_json_to_zod = require("@mastra/schema-compat/json-to-zod");
@@ -71,7 +72,6 @@ let zod_v4_locales_en_js = require("zod/v4/locales/en.js");
71
72
  zod_v4_locales_en_js = require_rolldown_runtime.__toESM(zod_v4_locales_en_js, 1);
72
73
  let fs = require("fs");
73
74
  let path = require("path");
74
- let _isaacs_ttlcache = require("@isaacs/ttlcache");
75
75
  let async_hooks = require("async_hooks");
76
76
  let fastq = require("fastq");
77
77
  fastq = require_rolldown_runtime.__toESM(fastq, 1);
@@ -506,6 +506,11 @@ const MASTRA_DURABLE_EXECUTIONS_KEY = "mastra__durableExecutions";
506
506
  */
507
507
  const MASTRA_DURABLE_SEGMENTS_KEY = "mastra__durableSegments";
508
508
  /**
509
+ * Reserved request-context key carrying `Record<runId, boolean>`: the `autoResumeSuspendedTools` a resumed execution
510
+ * runs with, so a step that suspends persists it on whichever worker runs the step. (#30190)
511
+ */
512
+ const MASTRA_DURABLE_AUTO_RESUME_KEY = "mastra__durableAutoResume";
513
+ /**
509
514
  * JSON-safe snapshot of `requestContext.entries()`, for a run that continues
510
515
  * somewhere the live context can't follow: a durable step, or a claimed
511
516
  * thread owner in another process. Best-effort: entries that fail a JSON
@@ -523,6 +528,7 @@ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
523
528
  if (key === "mastra__versions") continue;
524
529
  if (key === "mastra__durableExecutions") continue;
525
530
  if (key === "mastra__durableSegments") continue;
531
+ if (key === "mastra__durableAutoResume") continue;
526
532
  if (key === "__mastra_chat_channel_render") continue;
527
533
  const json = require_utils_safe_stringify.boundedStringify(value);
528
534
  if (json === void 0) {
@@ -12325,6 +12331,15 @@ var EventedExecutionEngine = class extends ExecutionEngine {
12325
12331
  const DOCS_URL = "https://mastra.ai/docs/server/pubsub#evented-workflows-and-agents";
12326
12332
  const warnedHosts = /* @__PURE__ */ new WeakSet();
12327
12333
  const warnedSignalHosts = /* @__PURE__ */ new WeakSet();
12334
+ const warnedCacheHosts = /* @__PURE__ */ new WeakSet();
12335
+ /**
12336
+ * Whether each process keeps its own copy of the run logs `cache` holds while
12337
+ * `pubsub` carries the runs to other processes. Only `InMemoryServerCache` is
12338
+ * known to be process-local; any other cache is assumed to be shared.
12339
+ */
12340
+ function keepsRunLogsInProcess(pubsub, cache) {
12341
+ return cache instanceof require_inmemory.InMemoryServerCache && reachesOtherProcesses(pubsub);
12342
+ }
12328
12343
  /**
12329
12344
  * Evented runs spread over several processes need a pubsub that hands a stopped
12330
12345
  * worker's event to another worker, and a store whose step guards let one
@@ -12370,6 +12385,26 @@ function warnUnsharedAgentSignals(mastra, reason) {
12370
12385
  warnedSignalHosts.add(mastra);
12371
12386
  mastra.getLogger()?.warn(`Signals sent to running evented agents aren't supported on several processes with this setup: ${missing}. See ${DOCS_URL}`);
12372
12387
  }
12388
+ /**
12389
+ * An evented agent's steps append their stream frames to the run's log in the
12390
+ * server cache, which also holds the run's ownership record. With a cache each
12391
+ * process keeps to itself, a step in another process publishes its frames
12392
+ * unnumbered, so `observe(runId, { offset })` can't skip them, and another
12393
+ * process can't observe or stop the run. Logs once per Mastra instance, apart
12394
+ * from {@link warnUnsupportedEventedSetup} so that one does not hide this.
12395
+ *
12396
+ * Called when an evented agent is registered, in every process that can run
12397
+ * its steps, including dedicated workers that never start a run.
12398
+ */
12399
+ function warnProcessLocalServerCache(mastra) {
12400
+ if (warnedCacheHosts.has(mastra) || process.env.MASTRA_DISABLE_EVENTED_SETUP_WARNING === "true") return;
12401
+ const pubsub = mastra.pubsub;
12402
+ const wrapped = pubsub instanceof require_output_helpers.CachingPubSub;
12403
+ if (!keepsRunLogsInProcess(pubsub, wrapped ? pubsub.getCache() : mastra.serverCache)) return;
12404
+ const problem = wrapped ? `the configured CachingPubSub keeps run logs in an InMemoryServerCache, which only this process reads. Give that CachingPubSub a server cache every process shares` : `the server cache is an InMemoryServerCache, which only this process reads. Set \`cache\` on Mastra to a server cache every process shares`;
12405
+ warnedCacheHosts.add(mastra);
12406
+ mastra.getLogger()?.warn(`Evented agents aren't supported on several processes with this setup: ${problem}, such as RedisServerCache. See ${DOCS_URL}`);
12407
+ }
12373
12408
  // src/storage/workflow-step-guard.ts
12374
12409
  var WorkflowStepConflictError = class extends Error {
12375
12410
  reason;
@@ -12575,6 +12610,23 @@ function carrySegmentSpans(target, runId, segment) {
12575
12610
  else target[MASTRA_DURABLE_SEGMENTS_KEY] = next;
12576
12611
  }
12577
12612
  /**
12613
+ * Record the `autoResumeSuspendedTools` a resumed execution of `runId` runs with on the request context it hands the
12614
+ * engine, which carries it to every step of the segment wherever it runs. (#30190)
12615
+ */
12616
+ function carrySegmentAutoResume(requestContext, runId, value) {
12617
+ const current = requestContext.getRaw(MASTRA_DURABLE_AUTO_RESUME_KEY);
12618
+ requestContext.setRaw(MASTRA_DURABLE_AUTO_RESUME_KEY, {
12619
+ ...current && typeof current === "object" ? current : {},
12620
+ [runId]: value
12621
+ });
12622
+ }
12623
+ /** The `autoResumeSuspendedTools` a resume carried for the current execution of `runId`, if any. */
12624
+ function segmentAutoResume(requestContext, runId) {
12625
+ const all = requestContext?.getRaw?.(MASTRA_DURABLE_AUTO_RESUME_KEY);
12626
+ const value = all && typeof all === "object" ? all[runId] : void 0;
12627
+ return typeof value === "boolean" ? value : void 0;
12628
+ }
12629
+ /**
12578
12630
  * The pair the current execution reports under: the one a resume or recovery carried for `runId`,
12579
12631
  * else the run's first pair from `state` (the workflow input or the loop state). A carried `null`
12580
12632
  * means the execution opened no spans, so its steps end none. `carried` tells the two apart.
@@ -14466,7 +14518,7 @@ function closeStoredSignalRun({ mastra, runId, input, requestContext, state, dea
14466
14518
  agentId: input?.agentId,
14467
14519
  threadId: input?.state?.threadId
14468
14520
  });
14469
- return;
14521
+ return false;
14470
14522
  }
14471
14523
  const saved = typeof state === "function" ? await state() : state;
14472
14524
  await queue.store.closeSignalRun({
@@ -14474,11 +14526,13 @@ function closeStoredSignalRun({ mastra, runId, input, requestContext, state, dea
14474
14526
  runId,
14475
14527
  consumedIds: readConsumedSignalIds(saved)
14476
14528
  });
14529
+ return true;
14477
14530
  } catch (error) {
14478
14531
  mastra?.getLogger?.()?.warn?.("Could not close the stored signals of an ended run", {
14479
14532
  runId,
14480
14533
  error
14481
14534
  });
14535
+ return false;
14482
14536
  }
14483
14537
  })();
14484
14538
  }
@@ -15772,7 +15826,7 @@ function createDurableAgentStream(options) {
15772
15826
  armIdleTimer();
15773
15827
  resolveReady();
15774
15828
  releaseTerminalSubscription();
15775
- }).catch((error) => {
15829
+ }).catch(async (error) => {
15776
15830
  pubsub.unsubscribe(topic, subscribedCallback).catch((unsubscribeError) => {
15777
15831
  logError(`[DurableAgentStream] Failed to unsubscribe from ${topic}:`, unsubscribeError);
15778
15832
  });
@@ -15782,6 +15836,11 @@ function createDurableAgentStream(options) {
15782
15836
  markTerminated();
15783
15837
  if ((ctrl.desiredSize ?? 0) > 0) require_stream.safeError(ctrl, error);
15784
15838
  else pendingRejection = error;
15839
+ try {
15840
+ await onError?.({ error });
15841
+ } catch (callbackError) {
15842
+ logError(`[DurableAgentStream] onError callback error:`, callbackError);
15843
+ }
15785
15844
  });
15786
15845
  },
15787
15846
  pull(ctrl) {
@@ -16322,7 +16381,6 @@ function scopedRunStorage(runId, runStorage) {
16322
16381
  var StepExecutor = class extends require_base.MastraBase {
16323
16382
  mastra;
16324
16383
  #stepPubsub;
16325
- #warnedUnnumbered = false;
16326
16384
  constructor({ mastra }) {
16327
16385
  super({
16328
16386
  name: "StepExecutor",
@@ -16355,31 +16413,24 @@ var StepExecutor = class extends require_base.MastraBase {
16355
16413
  * numbering the same run from 0 in its own cache would have observers drop
16356
16414
  * its frames as late duplicates. So with a process-local cache behind a
16357
16415
  * cross-process transport, steps only append to logs this process already
16358
- * holds — the caller writes the run's `start` frame before any step runs, so
16416
+ * holds. The caller writes the run's `start` frame before any step runs, so
16359
16417
  * steps in the caller's process are numbered (#28324) and steps on other
16360
- * workers publish unnumbered (live-only).
16418
+ * workers publish unnumbered (live-only). Mastra warns about that setup when
16419
+ * the evented agent is registered (`warnProcessLocalServerCache`).
16361
16420
  */
16362
16421
  #getStepPubsub() {
16363
16422
  if (this.#stepPubsub) return this.#stepPubsub;
16364
16423
  const inner = this.mastra.pubsub;
16365
16424
  const cache = this.mastra?.serverCache;
16366
16425
  if (inner instanceof require_output_helpers.CachingPubSub) this.#stepPubsub = inner;
16367
- else if (cache) {
16368
- const processLocalLogs = cache instanceof require_inmemory.InMemoryServerCache && reachesOtherProcesses(inner);
16369
- this.#stepPubsub = new require_output_helpers.CachingPubSub(inner, cache, {
16370
- shouldCache: (topic) => !require_output_helpers.isRunLocalTopic(topic),
16371
- extendExistingLogsOnly: processLocalLogs,
16372
- onUnlogged: (topic) => this.#warnUnnumberedAgentStream(topic),
16373
- logger: this.logger
16374
- });
16375
- } else this.#stepPubsub = inner;
16426
+ else if (cache) this.#stepPubsub = new require_output_helpers.CachingPubSub(inner, cache, {
16427
+ shouldCache: (topic) => !require_output_helpers.isRunLocalTopic(topic),
16428
+ extendExistingLogsOnly: keepsRunLogsInProcess(inner, cache),
16429
+ logger: this.logger
16430
+ });
16431
+ else this.#stepPubsub = inner;
16376
16432
  return this.#stepPubsub;
16377
16433
  }
16378
- #warnUnnumberedAgentStream(topic) {
16379
- if (this.#warnedUnnumbered || !topic.startsWith(AGENT_STREAM_TOPIC(""))) return;
16380
- this.#warnedUnnumbered = true;
16381
- this.logger.warn(`Agent stream frames published from this process are not numbered: the run started in another process and the in-memory server cache is process-local, so observe(runId, { offset }) cannot skip these frames. Configure a shared server cache (e.g. RedisServerCache) on Mastra.`, { topic });
16382
- }
16383
16434
  /**
16384
16435
  * Creates an output writer function that publishes chunks to the workflow event stream.
16385
16436
  * @param runId - The workflow run ID
@@ -25019,7 +25070,7 @@ const RETRYABLE_FAILURE_KINDS = /* @__PURE__ */ new Set([
25019
25070
  const ACCOUNT_REFUSALS = /* @__PURE__ */ new Set(["auth", "quota"]);
25020
25071
  const OPENAI_RETRY_MESSAGE_PATTERN = /you can retry your request/i;
25021
25072
  const DEFAULT_MATCHERS = [isRetryableOpenAIResponsesStreamError];
25022
- function isRecord$7(value) {
25073
+ function isRecord$8(value) {
25023
25074
  return typeof value === "object" && value !== null;
25024
25075
  }
25025
25076
  function getStringProperty(value, key) {
@@ -25028,15 +25079,15 @@ function getStringProperty(value, key) {
25028
25079
  }
25029
25080
  function getObjectCause(error) {
25030
25081
  if (error instanceof Error) return error.cause;
25031
- if (!isRecord$7(error)) return;
25082
+ if (!isRecord$8(error)) return;
25032
25083
  return error.cause;
25033
25084
  }
25034
25085
  function getOpenAIErrorPayload(error) {
25035
- if (!isRecord$7(error)) return;
25036
- if (error.type === "error" && isRecord$7(error.error)) return error.error;
25037
- if (error.type === "response.failed" && isRecord$7(error.response)) {
25086
+ if (!isRecord$8(error)) return;
25087
+ if (error.type === "error" && isRecord$8(error.error)) return error.error;
25088
+ if (error.type === "response.failed" && isRecord$8(error.response)) {
25038
25089
  const responseError = error.response.error;
25039
- return isRecord$7(responseError) ? responseError : void 0;
25090
+ return isRecord$8(responseError) ? responseError : void 0;
25040
25091
  }
25041
25092
  }
25042
25093
  function hasExplicitRetryMessage(payload) {
@@ -25068,12 +25119,12 @@ function isBadRequestError(error) {
25068
25119
  return false;
25069
25120
  }
25070
25121
  function isRetryableProviderMetadata(error) {
25071
- return (require_dist.APICallError.isInstance(error) ? error.isRetryable : isRecord$7(error) && typeof error.isRetryable === "boolean" ? error.isRetryable : void 0) === true;
25122
+ return (require_dist.APICallError.isInstance(error) ? error.isRetryable : isRecord$8(error) && typeof error.isRetryable === "boolean" ? error.isRetryable : void 0) === true;
25072
25123
  }
25073
25124
  function hasDeniedHttpStatus(error) {
25074
25125
  const visited = /* @__PURE__ */ new WeakSet();
25075
25126
  function visit(candidate) {
25076
- if (!isRecord$7(candidate) || visited.has(candidate)) return false;
25127
+ if (!isRecord$8(candidate) || visited.has(candidate)) return false;
25077
25128
  visited.add(candidate);
25078
25129
  if (candidate.status === 401 || candidate.status === 403) return true;
25079
25130
  return visit(candidate.error) || visit(candidate.data) || visit(candidate.cause);
@@ -25095,7 +25146,7 @@ function normalizeEntry(entry) {
25095
25146
  function findMatchingPolicy(error, entries) {
25096
25147
  const visited = /* @__PURE__ */ new WeakSet();
25097
25148
  function visit(candidate) {
25098
- if (isRecord$7(candidate)) {
25149
+ if (isRecord$8(candidate)) {
25099
25150
  if (visited.has(candidate)) return void 0;
25100
25151
  visited.add(candidate);
25101
25152
  }
@@ -30718,7 +30769,7 @@ async function localPathIdentity(path) {
30718
30769
  return toAbsolutePath(path);
30719
30770
  }
30720
30771
  }
30721
- function isRecord$6(value) {
30772
+ function isRecord$7(value) {
30722
30773
  return typeof value === "object" && value !== null;
30723
30774
  }
30724
30775
  function isInstructionFileName(name) {
@@ -30777,9 +30828,9 @@ async function findInstructionFileForPath(candidatePath, pathExists, isDirectory
30777
30828
  }
30778
30829
  }
30779
30830
  function getMessageText(message) {
30780
- const parts = isRecord$6(message.content) ? message.content.parts : void 0;
30831
+ const parts = isRecord$7(message.content) ? message.content.parts : void 0;
30781
30832
  if (!Array.isArray(parts)) return "";
30782
- return parts.filter((part) => isRecord$6(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
30833
+ return parts.filter((part) => isRecord$7(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
30783
30834
  }
30784
30835
  function decodeXmlEntities(value) {
30785
30836
  return value.replaceAll("&quot;", "\"").replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&amp;", "&");
@@ -30801,8 +30852,8 @@ function getReminderMetadata(instructionPath) {
30801
30852
  }
30802
30853
  function extractReminderPathFromMetadata(message) {
30803
30854
  const metadata = message.content.metadata;
30804
- if (!isRecord$6(metadata)) return;
30805
- const reminderMetadata = isRecord$6(metadata.systemReminder) ? metadata.systemReminder : isRecord$6(metadata[LEGACY_REMINDER_METADATA_KEY]) ? metadata[LEGACY_REMINDER_METADATA_KEY] : isRecord$6(metadata.signal) && isRecord$6(metadata.signal.attributes) ? metadata.signal.attributes : metadata;
30855
+ if (!isRecord$7(metadata)) return;
30856
+ const reminderMetadata = isRecord$7(metadata.systemReminder) ? metadata.systemReminder : isRecord$7(metadata[LEGACY_REMINDER_METADATA_KEY]) ? metadata[LEGACY_REMINDER_METADATA_KEY] : isRecord$7(metadata.signal) && isRecord$7(metadata.signal.attributes) ? metadata.signal.attributes : metadata;
30806
30857
  return typeof reminderMetadata.path === "string" ? reminderMetadata.path : void 0;
30807
30858
  }
30808
30859
  function getReminderMarkup(reminderText, instructionPath) {
@@ -30828,10 +30879,10 @@ function truncateToTokenLimit(content, maxTokens) {
30828
30879
  function getCompletedToolCalls(messages) {
30829
30880
  const completed = [];
30830
30881
  for (const message of [...messages].reverse()) {
30831
- const parts = isRecord$6(message.content) ? message.content.parts : void 0;
30882
+ const parts = isRecord$7(message.content) ? message.content.parts : void 0;
30832
30883
  if (!Array.isArray(parts)) continue;
30833
30884
  for (const part of [...parts].reverse()) {
30834
- if (!isRecord$6(part) || part.type !== "tool-invocation") continue;
30885
+ if (!isRecord$7(part) || part.type !== "tool-invocation") continue;
30835
30886
  const invocation = part.toolInvocation;
30836
30887
  if (!invocation || invocation.state !== "result" || typeof invocation.toolCallId !== "string") continue;
30837
30888
  completed.push({
@@ -30843,11 +30894,11 @@ function getCompletedToolCalls(messages) {
30843
30894
  return completed;
30844
30895
  }
30845
30896
  function parseInvocationArgs(args) {
30846
- if (isRecord$6(args)) return args;
30897
+ if (isRecord$7(args)) return args;
30847
30898
  if (typeof args !== "string") return;
30848
30899
  try {
30849
30900
  const parsed = JSON.parse(args);
30850
- return isRecord$6(parsed) ? parsed : void 0;
30901
+ return isRecord$7(parsed) ? parsed : void 0;
30851
30902
  } catch {
30852
30903
  return;
30853
30904
  }
@@ -30953,7 +31004,7 @@ var AgentsMDInjector = class {
30953
31004
  return this.reminderText?.trim() || void 0;
30954
31005
  }
30955
31006
  async *findInstructionPathsInInvocation(invocation, reader, basePath) {
30956
- if (!isRecord$6(invocation)) return;
31007
+ if (!isRecord$7(invocation)) return;
30957
31008
  const args = parseInvocationArgs(invocation.args);
30958
31009
  if (!args) return;
30959
31010
  for (const field of PATH_FIELDS) {
@@ -32493,7 +32544,7 @@ function hashBinary(value) {
32493
32544
  const CYBER_POLICY_ERROR_CODE = "cyber_policy";
32494
32545
  const CYBER_REFUSAL_MESSAGE = "this content was flagged for possible cybersecurity risk";
32495
32546
  const CYBER_STOP_CATEGORY = "cyber";
32496
- function isRecord$5(value) {
32547
+ function isRecord$6(value) {
32497
32548
  return typeof value === "object" && value !== null;
32498
32549
  }
32499
32550
  function parseJson(value) {
@@ -32516,7 +32567,7 @@ function parseJson(value) {
32516
32567
  function isCyberRefusalError(error) {
32517
32568
  const visited = /* @__PURE__ */ new WeakSet();
32518
32569
  function visit(candidate) {
32519
- if (!isRecord$5(candidate) || visited.has(candidate)) return false;
32570
+ if (!isRecord$6(candidate) || visited.has(candidate)) return false;
32520
32571
  visited.add(candidate);
32521
32572
  const { code, message, responseBody } = candidate;
32522
32573
  if (typeof code === "string" && code.toLowerCase() === CYBER_POLICY_ERROR_CODE) return true;
@@ -32536,10 +32587,10 @@ function isCyberRefusalError(error) {
32536
32587
  * still recognized when Claude is reached through another provider.
32537
32588
  */
32538
32589
  function isCyberStopRefusal(finishReason, providerMetadata) {
32539
- if (finishReason !== "content-filter" || !isRecord$5(providerMetadata)) return false;
32590
+ if (finishReason !== "content-filter" || !isRecord$6(providerMetadata)) return false;
32540
32591
  return Object.values(providerMetadata).some((namespace) => {
32541
- const stopDetails = isRecord$5(namespace) ? namespace.stopDetails : void 0;
32542
- return isRecord$5(stopDetails) && typeof stopDetails.category === "string" && stopDetails.category.toLowerCase() === CYBER_STOP_CATEGORY;
32592
+ const stopDetails = isRecord$6(namespace) ? namespace.stopDetails : void 0;
32593
+ return isRecord$6(stopDetails) && typeof stopDetails.category === "string" && stopDetails.category.toLowerCase() === CYBER_STOP_CATEGORY;
32543
32594
  });
32544
32595
  }
32545
32596
  /**
@@ -32805,18 +32856,18 @@ async function checkThreadFGA({ mastra, user, threadId, resourceId, agentId, req
32805
32856
  }
32806
32857
  // src/memory/system-reminders.ts
32807
32858
  const LEGACY_SYSTEM_REMINDER_METADATA_KEY = "dynamicAgentsMdReminder";
32808
- function isRecord$4(value) {
32859
+ function isRecord$5(value) {
32809
32860
  return typeof value === "object" && value !== null;
32810
32861
  }
32811
32862
  function isSystemReminderSignalType(type) {
32812
32863
  return type === "system-reminder" || type === "reactive";
32813
32864
  }
32814
32865
  function isSystemReminderMessage(message) {
32815
- if (!isRecord$4(message.content)) return false;
32866
+ if (!isRecord$5(message.content)) return false;
32816
32867
  const metadata = message.content.metadata;
32817
- if (message.role === "signal") return isRecord$4(metadata) && isRecord$4(metadata.signal) && isSystemReminderSignalType(metadata.signal.type);
32868
+ if (message.role === "signal") return isRecord$5(metadata) && isRecord$5(metadata.signal) && isSystemReminderSignalType(metadata.signal.type);
32818
32869
  if (message.role !== "user") return false;
32819
- if (isRecord$4(metadata) && (isRecord$4(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) return true;
32870
+ if (isRecord$5(metadata) && (isRecord$5(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) return true;
32820
32871
  const firstTextPart = message.content.parts.find((part) => part.type === "text");
32821
32872
  return typeof firstTextPart?.text === "string" && firstTextPart.text.startsWith("<system-reminder");
32822
32873
  }
@@ -32824,10 +32875,10 @@ function isRecallSignalType(type) {
32824
32875
  return type === "user" || type === "state" || type === "reactive" || type === "notification" || type === "user-message" || type === "system-reminder";
32825
32876
  }
32826
32877
  function getRecallSignalType(message) {
32827
- if (!isRecord$4(message.content)) return void 0;
32828
- for (const part of message.content.parts) if ((part.type === "data-signal" || part.type === "data-user-message") && isRecord$4(part.data) && isRecallSignalType(part.data.type)) return part.data.type;
32878
+ if (!isRecord$5(message.content)) return void 0;
32879
+ for (const part of message.content.parts) if ((part.type === "data-signal" || part.type === "data-user-message") && isRecord$5(part.data) && isRecallSignalType(part.data.type)) return part.data.type;
32829
32880
  const metadata = message.content.metadata;
32830
- if (message.role === "signal" && isRecord$4(metadata) && isRecord$4(metadata.signal)) {
32881
+ if (message.role === "signal" && isRecord$5(metadata) && isRecord$5(metadata.signal)) {
32831
32882
  if (isRecallSignalType(metadata.signal.type)) return metadata.signal.type;
32832
32883
  }
32833
32884
  return isSystemReminderMessage(message) ? "system-reminder" : void 0;
@@ -42685,7 +42736,12 @@ var MemoryStorage = class MemoryStorage extends require_filesystem_versioned.Sto
42685
42736
  throw pendingSignalsNotSupportedError(this.constructor.name);
42686
42737
  }
42687
42738
  /**
42688
- * Delete the thread's taken rows whose id is in `consumedIds`. Then, if the
42739
+ * Delete the thread's taken rows whose id is in `consumedIds`. A consumed
42740
+ * id never names a queued row: a run consumes a row by claiming it or by
42741
+ * starting with it, a claim never returns a queued row, and a run that
42742
+ * keeps its signals here named itself the signal run through
42743
+ * `setSignalRun` before it started, which made the thread's queued rows
42744
+ * pending. Then, if the
42689
42745
  * thread's signal run is still `runId`, move its other taken rows and its
42690
42746
  * queued rows to pending and clear the signal run. A close that comes after another run
42691
42747
  * became the signal run deletes only what it consumed and leaves the other
@@ -51274,11 +51330,10 @@ function claimFirstReplyLink(requestContext, link) {
51274
51330
  /** Live posts of `reply_in_thread` calls whose text is still streaming in, by tool call id. */
51275
51331
  const STREAMS_KEY = "mastra__channelReplyStreams";
51276
51332
  function replyStreams(requestContext) {
51277
- let streams = requestContext.get(STREAMS_KEY);
51278
- if (!streams) {
51279
- streams = /* @__PURE__ */ new Map();
51280
- requestContext.set(STREAMS_KEY, streams);
51281
- }
51333
+ const stored = requestContext.get(STREAMS_KEY);
51334
+ if (stored instanceof Map) return stored;
51335
+ const streams = /* @__PURE__ */ new Map();
51336
+ requestContext.set(STREAMS_KEY, streams);
51282
51337
  return streams;
51283
51338
  }
51284
51339
  /**
@@ -51290,7 +51345,7 @@ function openReplyStream({ chatThread, logger }) {
51290
51345
  let sent = "";
51291
51346
  let closed = false;
51292
51347
  let wake;
51293
- let done;
51348
+ let posted;
51294
51349
  async function* chunks() {
51295
51350
  while (true) {
51296
51351
  while (queue.length > 0) yield queue.shift();
@@ -51301,12 +51356,16 @@ function openReplyStream({ chatThread, logger }) {
51301
51356
  const push = (text) => {
51302
51357
  if (!text) return;
51303
51358
  queue.push(text);
51304
- done ??= chatThread.post(chunks()).then(() => true, (error) => {
51359
+ posted ??= chatThread.post(chunks()).then((message) => message, (error) => {
51305
51360
  logger?.warn("[channels] streamed reply failed; posting it whole", { error });
51306
- return false;
51307
51361
  });
51308
51362
  wake?.();
51309
51363
  };
51364
+ const end = async () => {
51365
+ closed = true;
51366
+ wake?.();
51367
+ return posted;
51368
+ };
51310
51369
  return {
51311
51370
  update(text) {
51312
51371
  const visible = text.trimStart();
@@ -51316,16 +51375,20 @@ function openReplyStream({ chatThread, logger }) {
51316
51375
  },
51317
51376
  async finish(text, suffix) {
51318
51377
  if (text.startsWith(sent)) push(text.slice(sent.length));
51319
- if (!done) return false;
51378
+ if (!posted) return false;
51320
51379
  push(suffix);
51321
- closed = true;
51322
- wake?.();
51323
- return done;
51380
+ return !!await end();
51324
51381
  },
51325
51382
  async close() {
51326
- closed = true;
51327
- wake?.();
51328
- return done ?? false;
51383
+ return !!await end();
51384
+ },
51385
+ async discard() {
51386
+ const message = await end();
51387
+ try {
51388
+ await message?.delete();
51389
+ } catch (error) {
51390
+ logger?.warn("[channels] could not delete a streamed reply preview", { error });
51391
+ }
51329
51392
  }
51330
51393
  };
51331
51394
  }
@@ -51352,6 +51415,7 @@ var ChannelReplyStreamProcessor = class {
51352
51415
  if (!requestContext) return part;
51353
51416
  await this.#postUnsentAnswer(part, state, requestContext);
51354
51417
  const args = state.args ??= {};
51418
+ const called = state.called ??= {};
51355
51419
  if (part.type === "tool-call-input-streaming-start" && part.payload.toolName === "reply_in_thread") {
51356
51420
  const render = await this.#resolveRender(requestContext);
51357
51421
  if (render?.textDisplay !== "hidden" || !render.streaming?.enabled) return part;
@@ -51362,10 +51426,19 @@ var ChannelReplyStreamProcessor = class {
51362
51426
  if (text !== void 0) replyStreams(requestContext).get(part.payload.toolCallId)?.update(text);
51363
51427
  } else if ((part.type === "tool-error" || part.type === "tool-result") && part.payload.toolCallId in args) {
51364
51428
  delete args[part.payload.toolCallId];
51365
- await closeStream(requestContext, part.payload.toolCallId);
51366
- } else if (RUN_END.has(part.type)) {
51367
- for (const toolCallId of Object.keys(args)) await closeStream(requestContext, toolCallId);
51429
+ delete called[part.payload.toolCallId];
51430
+ await discardStream(requestContext, part.payload.toolCallId);
51431
+ } else if (part.type === "tool-call" && part.payload.toolCallId in args) called[part.payload.toolCallId] = true;
51432
+ else if (part.type === "step-finish") for (const toolCallId of Object.keys(called)) {
51433
+ delete args[toolCallId];
51434
+ delete called[toolCallId];
51435
+ await discardStream(requestContext, toolCallId);
51436
+ }
51437
+ else if (RUN_END.has(part.type)) {
51438
+ for (const toolCallId of Object.keys(args)) if (called[toolCallId]) await discardStream(requestContext, toolCallId);
51439
+ else await closeStream(requestContext, toolCallId);
51368
51440
  state.args = {};
51441
+ state.called = {};
51369
51442
  }
51370
51443
  return part;
51371
51444
  }
@@ -51373,8 +51446,7 @@ var ChannelReplyStreamProcessor = class {
51373
51446
  * Models sometimes end a turn with a plain-text answer and never call
51374
51447
  * `reply_in_thread`, so the thread never hears back. When a run finishes
51375
51448
  * without having replied, post the text written after its last tool call.
51376
- * A reply counts once it posts: a call that fails validation doesn't, unless
51377
- * its streamed post already left text in the thread.
51449
+ * A reply counts once it posts; a failed call's streamed preview is deleted, so it doesn't.
51378
51450
  */
51379
51451
  async #postUnsentAnswer(part, state, requestContext) {
51380
51452
  const answer = state.answer ??= {
@@ -51388,10 +51460,7 @@ var ChannelReplyStreamProcessor = class {
51388
51460
  answer.tail = "";
51389
51461
  if (part.payload.toolName === "reply_in_thread") answer.calls.add(part.payload.toolCallId);
51390
51462
  } else if (part.type === "tool-result" && answer.calls.has(part.payload.toolCallId)) answer.replied = true;
51391
- else if (part.type === "tool-error" && answer.calls.has(part.payload.toolCallId)) {
51392
- const stream = replyStreams(requestContext).get(part.payload.toolCallId);
51393
- if (stream && await stream.close()) answer.replied = true;
51394
- } else if (part.type === "tool-call-approval" || part.type === "tool-call-suspended") answer.held = true;
51463
+ else if (part.type === "tool-call-approval" || part.type === "tool-call-suspended") answer.held = true;
51395
51464
  else if (RUN_END.has(part.type)) {
51396
51465
  state.answer = void 0;
51397
51466
  const text = answer.tail.trim();
@@ -51426,6 +51495,13 @@ async function closeStream(requestContext, toolCallId) {
51426
51495
  streams.delete(toolCallId);
51427
51496
  await stream.close();
51428
51497
  }
51498
+ /** Deletes a streamed post that is only a preview of a reply posted, or failed, elsewhere. */
51499
+ async function discardStream(requestContext, toolCallId) {
51500
+ const streams = replyStreams(requestContext);
51501
+ const stream = streams.get(toolCallId);
51502
+ streams.delete(toolCallId);
51503
+ await stream?.discard();
51504
+ }
51429
51505
  const ESCAPES = {
51430
51506
  "\"": "\"",
51431
51507
  "\\": "\\",
@@ -51895,11 +51971,11 @@ var MastraStateAdapter = class {
51895
51971
  * otherwise reach the agent as just the notification fallback.
51896
51972
  */
51897
51973
  function layoutBlockTexts(raw) {
51898
- const blocks = isRecord$3(raw) ? raw.blocks : void 0;
51974
+ const blocks = isRecord$4(raw) ? raw.blocks : void 0;
51899
51975
  if (!Array.isArray(blocks)) return [];
51900
51976
  const texts = [];
51901
51977
  for (const block of blocks) {
51902
- if (!isRecord$3(block) || typeof block.type !== "string") continue;
51978
+ if (!isRecord$4(block) || typeof block.type !== "string") continue;
51903
51979
  const parts = blockParts(block).map((part) => part.trim()).filter(Boolean);
51904
51980
  if (parts.length) texts.push(parts);
51905
51981
  }
@@ -51912,13 +51988,13 @@ function blockParts(block) {
51912
51988
  const fields = Array.isArray(block.fields) ? block.fields.map(textObject) : [];
51913
51989
  return [textObject(block.text), ...fields];
51914
51990
  }
51915
- case "context": return [(Array.isArray(block.elements) ? block.elements : []).filter((el) => isRecord$3(el) && (el.type === "mrkdwn" || el.type === "plain_text")).map(textObject).filter(Boolean).join(" ")];
51991
+ case "context": return [(Array.isArray(block.elements) ? block.elements : []).filter((el) => isRecord$4(el) && (el.type === "mrkdwn" || el.type === "plain_text")).map(textObject).filter(Boolean).join(" ")];
51916
51992
  case "markdown": return [typeof block.text === "string" ? block.text : ""];
51917
51993
  default: return [];
51918
51994
  }
51919
51995
  }
51920
51996
  function textObject(value) {
51921
- if (!isRecord$3(value) || typeof value.text !== "string") return "";
51997
+ if (!isRecord$4(value) || typeof value.text !== "string") return "";
51922
51998
  const text = value.text.trim();
51923
51999
  return value.type === "mrkdwn" ? slackLinksToMarkdown(text) : text;
51924
52000
  }
@@ -51930,7 +52006,7 @@ function slackLinksToMarkdown(text) {
51930
52006
  return `[${label.replace(/[\\[\]]/g, "\\$&")}](${destination})`;
51931
52007
  });
51932
52008
  }
51933
- function isRecord$3(value) {
52009
+ function isRecord$4(value) {
51934
52010
  return typeof value === "object" && value !== null;
51935
52011
  }
51936
52012
  /**
@@ -57070,7 +57146,7 @@ function isBuffer(value) {
57070
57146
  /**
57071
57147
  * Checks whether a value is a non-null, non-array object.
57072
57148
  */
57073
- function isRecord$2(value) {
57149
+ function isRecord$3(value) {
57074
57150
  return value != null && typeof value === "object" && !Array.isArray(value);
57075
57151
  }
57076
57152
  /**
@@ -59064,7 +59140,7 @@ function parseSpeechStreamPart(text) {
59064
59140
  } catch {
59065
59141
  return;
59066
59142
  }
59067
- if (!isRecord$2(value)) return;
59143
+ if (!isRecord$3(value)) return;
59068
59144
  const part = value;
59069
59145
  switch (part.type) {
59070
59146
  case "stream-start": {
@@ -59075,10 +59151,10 @@ function parseSpeechStreamPart(text) {
59075
59151
  warnings
59076
59152
  } : void 0;
59077
59153
  }
59078
- case "audio": return isString$1(part.audio) && isAudioFormat(part.audioFormat) && isOptional$1(part.id, isString$1) && isOptional$1(part.providerMetadata, isRecord$2) ? part : void 0;
59079
- case "finish": return isOptional$1(part.usage, isUsage) && isOptional$1(part.providerMetadata, isRecord$2) ? part : void 0;
59154
+ case "audio": return isString$1(part.audio) && isAudioFormat(part.audioFormat) && isOptional$1(part.id, isString$1) && isOptional$1(part.providerMetadata, isRecord$3) ? part : void 0;
59155
+ case "finish": return isOptional$1(part.usage, isUsage) && isOptional$1(part.providerMetadata, isRecord$3) ? part : void 0;
59080
59156
  case "response-metadata": {
59081
- if (!(isOptional$1(part.modelId, isString$1) && isOptional$1(part.headers, isRecord$2))) return;
59157
+ if (!(isOptional$1(part.modelId, isString$1) && isOptional$1(part.headers, isRecord$3))) return;
59082
59158
  const timestamp = part.timestamp;
59083
59159
  if (timestamp == null) return {
59084
59160
  ...part,
@@ -59109,10 +59185,10 @@ const knownWarningTypes = /* @__PURE__ */ new Set([
59109
59185
  "unsupported"
59110
59186
  ]);
59111
59187
  function isUnknownWarningType(value) {
59112
- return isRecord$2(value) && isString$1(value.type) && !knownWarningTypes.has(value.type);
59188
+ return isRecord$3(value) && isString$1(value.type) && !knownWarningTypes.has(value.type);
59113
59189
  }
59114
59190
  function isWarning$1(value) {
59115
- if (!isRecord$2(value)) return false;
59191
+ if (!isRecord$3(value)) return false;
59116
59192
  switch (value.type) {
59117
59193
  case "compatibility":
59118
59194
  case "unsupported": return isString$1(value.feature) && isOptional$1(value.details, isString$1);
@@ -59122,10 +59198,10 @@ function isWarning$1(value) {
59122
59198
  }
59123
59199
  }
59124
59200
  function isAudioFormat(value) {
59125
- return isRecord$2(value) && isString$1(value.type) && value.type.length > 0 && isOptional$1(value.rate, (rate) => typeof rate === "number" && Number.isFinite(rate) && rate > 0);
59201
+ return isRecord$3(value) && isString$1(value.type) && value.type.length > 0 && isOptional$1(value.rate, (rate) => typeof rate === "number" && Number.isFinite(rate) && rate > 0);
59126
59202
  }
59127
59203
  function isUsage(value) {
59128
- return isRecord$2(value) && [
59204
+ return isRecord$3(value) && [
59129
59205
  "inputCharacters",
59130
59206
  "inputTokens",
59131
59207
  "outputTokens"
@@ -59192,12 +59268,12 @@ function parseTranscriptionStreamPart(text) {
59192
59268
  const part = value;
59193
59269
  switch (part.type) {
59194
59270
  case "stream-start": return Array.isArray(part.warnings) && part.warnings.every(isWarning) ? part : void 0;
59195
- case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59196
- case "transcript-partial": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59197
- case "transcript-final": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.endSecond, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59198
- case "finish": return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.usage, isRecord$2) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59271
+ case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isRecord$3) ? part : void 0;
59272
+ case "transcript-partial": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord$3) ? part : void 0;
59273
+ case "transcript-final": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.endSecond, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord$3) ? part : void 0;
59274
+ case "finish": return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.usage, isRecord$3) && isOptional(part.providerMetadata, isRecord$3) ? part : void 0;
59199
59275
  case "response-metadata": {
59200
- if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isRecord$2))) return;
59276
+ if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isRecord$3))) return;
59201
59277
  const timestamp = part.timestamp;
59202
59278
  if (timestamp == null) return {
59203
59279
  ...part,
@@ -59225,10 +59301,10 @@ function isOptional(value, check) {
59225
59301
  return value === void 0 || check(value);
59226
59302
  }
59227
59303
  function isWarning(value) {
59228
- return isRecord$2(value) && isString(value.type);
59304
+ return isRecord$3(value) && isString(value.type);
59229
59305
  }
59230
59306
  function isSegment(value) {
59231
- return isRecord$2(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
59307
+ return isRecord$3(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
59232
59308
  }
59233
59309
  function withoutTrailingSlash(url) {
59234
59310
  return url?.replace(/\/$/, "");
@@ -72758,6 +72834,50 @@ async function runIdleLoop(agent, streamOptions, deps, firstTurn, streamForConti
72758
72834
  resourceId
72759
72835
  });
72760
72836
  }
72837
+ // src/loop/suspended-run-auto-resume.ts
72838
+ /**
72839
+ * The `autoResumeSuspendedTools` a suspended agentic-loop run executed its latest segment with: the value persisted
72840
+ * with its most recent suspension. A resume can override the run's setting, so a resume in another process (or after
72841
+ * a restart) that leaves the option out keeps the latest one, not the one the first parked tool call recorded.
72842
+ * (#30190)
72843
+ *
72844
+ * Each tool call that suspends persists the segment's value in its own suspend payload, with its `suspendedAt`.
72845
+ * Tool calls that suspend side by side keep one record each, under `__workflow_meta.foreachOutput` or as the step's
72846
+ * `output`. The step's own suspend payload mirrors only the first suspended call, so a step with per-call records is
72847
+ * read through those records. A per-call record is read through its own payload first: on the evented engine its
72848
+ * `output` can hold stale copies of its siblings' records from before it was resumed. A snapshot written before the
72849
+ * value was persisted has none, and this returns `undefined`.
72850
+ */
72851
+ function findLatestSuspendedAutoResume(snapshot) {
72852
+ let latest;
72853
+ /** Records the values persisted at or under `entry`; whether it found one. */
72854
+ const visit = (entry, isToolCall) => {
72855
+ if (!isRecord$2(entry) || entry.status !== "suspended") return false;
72856
+ const suspendPayload = isRecord$2(entry.suspendPayload) ? entry.suspendPayload : void 0;
72857
+ const value = suspendPayload?.__autoResumeSuspendedTools;
72858
+ const record = () => {
72859
+ if (typeof value !== "boolean") return false;
72860
+ const at = typeof entry.suspendedAt === "number" ? entry.suspendedAt : 0;
72861
+ if (!latest || at >= latest.at) latest = {
72862
+ at,
72863
+ value
72864
+ };
72865
+ return true;
72866
+ };
72867
+ if (isToolCall && record()) return true;
72868
+ const meta = isRecord$2(suspendPayload?.__workflow_meta) ? suspendPayload.__workflow_meta : void 0;
72869
+ const perCall = Array.isArray(meta?.foreachOutput) ? meta.foreachOutput : Array.isArray(entry.output) ? entry.output : void 0;
72870
+ let found = false;
72871
+ for (const call of perCall ?? []) found = visit(call, true) || found;
72872
+ return found || !isToolCall && record();
72873
+ };
72874
+ const context = isRecord$2(snapshot) && isRecord$2(snapshot.context) ? snapshot.context : void 0;
72875
+ for (const step of Object.values(context ?? {})) visit(step, false);
72876
+ return latest?.value;
72877
+ }
72878
+ function isRecord$2(value) {
72879
+ return typeof value === "object" && value !== null;
72880
+ }
72761
72881
  // src/tools/provider-tool-utils.ts
72762
72882
  /**
72763
72883
  * Find a provider-defined tool by its model-facing name.
@@ -81209,6 +81329,16 @@ async function processChunkThroughOutputProcessors(chunk, registryEntry, stepReq
81209
81329
  });
81210
81330
  }
81211
81331
  /**
81332
+ * The run's `autoResumeSuspendedTools` for its current segment, persisted with each suspension: a resume can override
81333
+ * the value the run started with, and a later resume in another process that leaves the option out reads the latest
81334
+ * one back from the snapshot. The resume carries its value on the segment's request context, which reaches a step on
81335
+ * any worker; this process's registry entry stands in when user code cleared it. (#30190)
81336
+ */
81337
+ function runAutoResumeSuspendPayload(carried, registryEntry, startOptions) {
81338
+ const value = carried ?? registryEntry?.autoResumeSuspendedTools ?? startOptions?.autoResumeSuspendedTools;
81339
+ return value === void 0 ? {} : { __autoResumeSuspendedTools: value };
81340
+ }
81341
+ /**
81212
81342
  * Create a durable tool call step.
81213
81343
  *
81214
81344
  * This step mirrors the base Agent's createToolCallStep pattern:
@@ -81822,7 +81952,8 @@ function createDurableToolCallStep() {
81822
81952
  type: "approval",
81823
81953
  toolCallId,
81824
81954
  toolName,
81825
- args
81955
+ args,
81956
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
81826
81957
  }, { resumeLabel: toolCallId });
81827
81958
  }
81828
81959
  const isResumableTool = toolName?.startsWith("agent-") || toolName?.startsWith("workflow-");
@@ -82047,7 +82178,8 @@ function createDurableToolCallStep() {
82047
82178
  toolName: approvalToolName,
82048
82179
  args: approvalArgs
82049
82180
  },
82050
- ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
82181
+ ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {},
82182
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
82051
82183
  }, { resumeLabel: toolCallId });
82052
82184
  }
82053
82185
  const suspendedEventData = {
@@ -82101,7 +82233,8 @@ function createDurableToolCallStep() {
82101
82233
  toolCallId,
82102
82234
  toolName,
82103
82235
  resumeLabel: suspendOptions?.resumeLabel,
82104
- ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
82236
+ ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {},
82237
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
82105
82238
  }, { resumeLabel: toolCallId });
82106
82239
  };
82107
82240
  const toolOptions = defineLazyWriter(toolOptionsWithoutWriter, () => new require_stream$1.ToolStream({
@@ -84776,6 +84909,8 @@ var DefaultAgentExecutionEngine = class {
84776
84909
  * Close the stored signals of a parked run that was aborted. Call it before
84777
84910
  * the snapshot is deleted and before the abort terminal is published.
84778
84911
  * Returns nothing to wait for when this engine's runs never store signals.
84912
+ * Resolves `false` when the run was left open: its committed state could not
84913
+ * be determined yet, or the close did not commit.
84779
84914
  */
84780
84915
  closeParkedRunSignals(_runId) {}
84781
84916
  /**
@@ -84912,7 +85047,10 @@ var DefaultAgentExecutionEngine = class {
84912
85047
  logger: this.mastra.getLogger(),
84913
85048
  storage: this.mastra.getStorage()
84914
85049
  });
84915
- if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === "evented") this.mastra.__registerInternalWorkflow(this.#workflow, void 0, { distributed: true });
85050
+ if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === "evented") {
85051
+ this.mastra.__registerInternalWorkflow(this.#workflow, void 0, { distributed: true });
85052
+ warnProcessLocalServerCache(this.mastra);
85053
+ }
84916
85054
  }
84917
85055
  }
84918
85056
  return this.#workflow;
@@ -85213,17 +85351,17 @@ var EventedAgentExecutionEngine = class extends DefaultAgentExecutionEngine {
85213
85351
  workflowName: DurableStepIds.AGENTIC_LOOP,
85214
85352
  runId
85215
85353
  }).catch(() => null);
85216
- if (!snapshot) return;
85354
+ if (!snapshot) return false;
85217
85355
  const context = snapshot.context;
85218
- if (!context?.input?.signalsStored) return;
85356
+ if (!context?.input?.signalsStored) return true;
85219
85357
  const committed = await this.#parkedRunState(workflowsStore, snapshot);
85220
- if (!committed) return;
85221
- await closeStoredSignalRun({
85358
+ if (!committed) return false;
85359
+ return await closeStoredSignalRun({
85222
85360
  mastra: this.mastra,
85223
85361
  runId,
85224
85362
  input: context.input,
85225
85363
  state: committed.state
85226
- });
85364
+ }) ?? false;
85227
85365
  }
85228
85366
  /**
85229
85367
  * The latest committed workflow state of a parked run, or `undefined` when
@@ -85726,7 +85864,7 @@ async function prepareForDurableExecution(options) {
85726
85864
  });
85727
85865
  let tripwireData;
85728
85866
  if (inputProcessors.length > 0) try {
85729
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-CNqAlDJF.cjs")).then((n) => n.runner_exports);
85867
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-DqKDB3nL.cjs")).then((n) => n.runner_exports);
85730
85868
  await new ProcessorRunner({
85731
85869
  inputProcessors,
85732
85870
  outputProcessors,
@@ -94235,9 +94373,30 @@ var Agent = class Agent extends require_base.MastraBase {
94235
94373
  if (!this.__usesSharedRunLog()) return void 0;
94236
94374
  return this.#resolveExecutionEngine()?.closeParkedRunSignals(runId);
94237
94375
  }
94238
- /** @internal Close the stored signals of a parked run that an abort requested by another process releases here. */
94239
- __closeParkedRunSignals(runId) {
94240
- return this.#closeParkedRunSignals(runId);
94376
+ /**
94377
+ * @internal Close the stored signals of a parked run that an abort requested by another process releases here.
94378
+ * With `exclusiveOfResume`, the close holds the run's execution claim from its snapshot read through its commit, as
94379
+ * a resume segment does. A resume that starts meanwhile waits for it, instead of consuming a signal that the close,
94380
+ * working from the snapshot it read before, would then return to pending. Resolves `false` while another
94381
+ * execution holds the run.
94382
+ */
94383
+ __closeParkedRunSignals(runId, options) {
94384
+ if (!options?.exclusiveOfResume || !this.__usesSharedRunLog() || !this.#resolveExecutionEngine()) return this.#closeParkedRunSignals(runId);
94385
+ return this.#closeParkedRunSignalsExclusively(runId);
94386
+ }
94387
+ async #closeParkedRunSignalsExclusively(runId) {
94388
+ let executionFence;
94389
+ try {
94390
+ executionFence = await this.#claimExecution(runId, "acquire");
94391
+ } catch (error) {
94392
+ if (error instanceof require_error.MastraError && error.id === "DURABLE_AGENT_EXECUTION_CONFLICT") return false;
94393
+ throw error;
94394
+ }
94395
+ let closed = false;
94396
+ await executionFence.settle(async () => {
94397
+ closed = await this.#closeParkedRunSignals(runId) ?? false;
94398
+ });
94399
+ return closed;
94241
94400
  }
94242
94401
  async #cancelAndCloseParkedRun(runId) {
94243
94402
  if (!await this.executionEngine.cancelParkedRun(runId)) return false;
@@ -94629,7 +94788,12 @@ var Agent = class Agent extends require_base.MastraBase {
94629
94788
  }
94630
94789
  async resumeStream(resumeData, streamOptions) {
94631
94790
  if (this.#resolveExecutionEngine()) return this.#resumeDurableStream(resumeData, streamOptions);
94632
- return this.#resumeStream(resumeData, streamOptions, false);
94791
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(streamOptions?.runId ?? "", this.getPubSub());
94792
+ try {
94793
+ return await this.#resumeStream(resumeData, streamOptions, false);
94794
+ } finally {
94795
+ releaseResumeHold();
94796
+ }
94633
94797
  }
94634
94798
  async #resumeDurableStream(resumeData, streamOptions) {
94635
94799
  const runId = streamOptions?.runId;
@@ -94659,7 +94823,10 @@ var Agent = class Agent extends require_base.MastraBase {
94659
94823
  const actor = mergedStreamOptions.actor;
94660
94824
  delete loopStreamOptions.actor;
94661
94825
  if (mergedStreamOptions.untilIdle) {
94662
- const { untilIdle, ...rest } = mergedStreamOptions ?? {};
94826
+ const { untilIdle, ...rest } = {
94827
+ ...mergedStreamOptions,
94828
+ autoResumeSuspendedTools: streamOptions?.autoResumeSuspendedTools
94829
+ };
94663
94830
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
94664
94831
  return runResumeStreamUntilIdle(this, resumeData, {
94665
94832
  ...rest,
@@ -94680,6 +94847,8 @@ var Agent = class Agent extends require_base.MastraBase {
94680
94847
  const snapshotMemoryInfo = this.#getSnapshotMemoryInfo(existingSnapshot);
94681
94848
  const persistedReturnScorerData = streamOptions?.returnScorerData === void 0 ? this.#getSnapshotReturnScorerData(existingSnapshot) : void 0;
94682
94849
  if (persistedReturnScorerData !== void 0) mergedStreamOptions.returnScorerData = loopStreamOptions.returnScorerData = persistedReturnScorerData;
94850
+ const runAutoResume = streamOptions?.autoResumeSuspendedTools ?? findLatestSuspendedAutoResume(existingSnapshot);
94851
+ if (runAutoResume !== void 0) mergedStreamOptions.autoResumeSuspendedTools = loopStreamOptions.autoResumeSuspendedTools = runAutoResume;
94683
94852
  if (snapshotMemoryInfo?.threadId) {
94684
94853
  mergedStreamOptions.memory = {
94685
94854
  ...mergedStreamOptions.memory ?? {},
@@ -94786,7 +94955,10 @@ var Agent = class Agent extends require_base.MastraBase {
94786
94955
  text: "An unknown error occurred while streaming"
94787
94956
  });
94788
94957
  }
94789
- await agentThreadStreamRuntime.registerRun(this, result.result, preparedOptions, threadStreamPubSub);
94958
+ await agentThreadStreamRuntime.registerRun(this, result.result, {
94959
+ ...preparedOptions,
94960
+ autoResumeSuspendedTools: runAutoResume
94961
+ }, threadStreamPubSub);
94790
94962
  return result.result;
94791
94963
  } catch (error) {
94792
94964
  await resumeClaim.release();
@@ -94815,6 +94987,17 @@ var Agent = class Agent extends require_base.MastraBase {
94815
94987
  async resumeGenerate(...args) {
94816
94988
  if (this.#resolveExecutionEngine()) return this.#resumeDurableGenerate(args);
94817
94989
  const [resumeData, options] = args;
94990
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(options?.runId ?? "", this.getPubSub());
94991
+ let completed = false;
94992
+ try {
94993
+ const output = await this.#resumePlainGenerate(resumeData, options);
94994
+ completed = output.finishReason !== "suspended";
94995
+ return output;
94996
+ } finally {
94997
+ releaseResumeHold({ startQueuedTurn: completed });
94998
+ }
94999
+ }
95000
+ async #resumePlainGenerate(resumeData, options) {
94818
95001
  const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });
94819
95002
  const mergedOptions = require_utils$1.deepMerge(withDefaultToolCallConcurrencyLimit(defaultOptions, options), withDefinedToolHooks(options) ?? {});
94820
95003
  validateModelTimeoutSettings(mergedOptions.modelSettings?.timeout);
@@ -94828,6 +95011,8 @@ var Agent = class Agent extends require_base.MastraBase {
94828
95011
  });
94829
95012
  const persistedReturnScorerData = options?.returnScorerData === void 0 ? this.#getSnapshotReturnScorerData(existingSnapshot) : void 0;
94830
95013
  if (persistedReturnScorerData !== void 0) mergedOptions.returnScorerData = loopOptions.returnScorerData = persistedReturnScorerData;
95014
+ const persistedAutoResume = options?.autoResumeSuspendedTools === void 0 ? findLatestSuspendedAutoResume(existingSnapshot) : void 0;
95015
+ if (persistedAutoResume !== void 0) mergedOptions.autoResumeSuspendedTools = loopOptions.autoResumeSuspendedTools = persistedAutoResume;
94831
95016
  const { options: scopedOptions, resolved: resolvedScopes } = await this.#resolveRunScopes(mergedOptions, {
94832
95017
  callScopes: options?.scopes,
94833
95018
  defaultScopes: defaultOptions?.scopes,
@@ -94961,7 +95146,12 @@ var Agent = class Agent extends require_base.MastraBase {
94961
95146
  runId: options.runId
94962
95147
  }
94963
95148
  });
94964
- return this.#resumeStream(void 0, options, true);
95149
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(options.runId, this.getPubSub());
95150
+ try {
95151
+ return await this.#resumeStream(void 0, options, true);
95152
+ } finally {
95153
+ releaseResumeHold();
95154
+ }
94965
95155
  }
94966
95156
  /**
94967
95157
  * Approves a pending tool call and resumes execution.
@@ -96202,10 +96392,11 @@ var Agent = class Agent extends require_base.MastraBase {
96202
96392
  if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, registryEntry);
96203
96393
  }
96204
96394
  };
96395
+ let cleanupOutput;
96205
96396
  const runCleanup = createRunCleanup({
96206
96397
  scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
96207
96398
  release: () => {
96208
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
96399
+ if (cleanupOutput) agentThreadStreamRuntime.closeRunContinuation(cleanupOutput, this.getPubSub());
96209
96400
  streamCleanup?.();
96210
96401
  cleanupOwnedRegistryState();
96211
96402
  }
@@ -96238,6 +96429,7 @@ var Agent = class Agent extends require_base.MastraBase {
96238
96429
  });
96239
96430
  const { output, cleanup: createdStreamCleanup, ready } = stream;
96240
96431
  streamCleanup = createdStreamCleanup;
96432
+ cleanupOutput = output;
96241
96433
  const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
96242
96434
  const workflowExecution = executionFence.run(() => this.executionEngine.raceFenceLoss(ready, executionFence).then(async () => {
96243
96435
  const result = await this.executionEngine.restartRun(workflow, executionFence, recoveryPubsub, this.workflowEngine, this.logger, resourceId, requestContext, require_observability.createObservabilityContext({ currentSpan: recoverAgentSpan }));
@@ -96954,12 +97146,15 @@ var Agent = class Agent extends require_base.MastraBase {
96954
97146
  });
96955
97147
  releaseResumeMarker = release;
96956
97148
  }
97149
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(runId, this.getPubSub());
96957
97150
  try {
96958
97151
  if (await this.#isRunCanceledInStorage(runId)) throw abortedRunError();
96959
97152
  return await this.#resumeRun(runId, resumeData, options, releaseResumeMarker);
96960
97153
  } catch (error) {
96961
97154
  releaseResumeMarker();
96962
97155
  throw error;
97156
+ } finally {
97157
+ releaseResumeHold();
96963
97158
  }
96964
97159
  }
96965
97160
  /**
@@ -97001,6 +97196,7 @@ var Agent = class Agent extends require_base.MastraBase {
97001
97196
  let entry = this.executionRunRegistry.get(runId);
97002
97197
  let rehydratedScopes;
97003
97198
  let coldSnapshot;
97199
+ let coldRunAutoResume;
97004
97200
  if (!entry) {
97005
97201
  const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
97006
97202
  const persisted = workflowsStore ? await this.executionEngine.loadPersistedRunSnapshot(workflowsStore, runId) : void 0;
@@ -97099,6 +97295,7 @@ var Agent = class Agent extends require_base.MastraBase {
97099
97295
  }
97100
97296
  });
97101
97297
  rehydratedScopes = persistedScopes;
97298
+ coldRunAutoResume = findLatestSuspendedAutoResume(snapshot) ?? workflowInput.options?.autoResumeSuspendedTools;
97102
97299
  const memory = threadId ? {
97103
97300
  ...options?.memory,
97104
97301
  thread: threadId,
@@ -97159,8 +97356,12 @@ var Agent = class Agent extends require_base.MastraBase {
97159
97356
  requestContextKeys
97160
97357
  };
97161
97358
  resumeRequestContext = resolvedOptions.requestContext ?? resumeRequestContext;
97359
+ const runAutoResume = options?.autoResumeSuspendedTools ?? (coldSnapshot ? coldRunAutoResume : entry.autoResumeSuspendedTools);
97162
97360
  if (resolvedOptions.untilIdle) {
97163
- const { untilIdle, ...rest } = resolvedOptions;
97361
+ const { untilIdle, ...rest } = {
97362
+ ...resolvedOptions,
97363
+ autoResumeSuspendedTools: runAutoResume
97364
+ };
97164
97365
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
97165
97366
  releaseResumeMarker();
97166
97367
  return runResumeDurableStreamUntilIdle({
@@ -97323,6 +97524,7 @@ var Agent = class Agent extends require_base.MastraBase {
97323
97524
  globalEntryForContext.requestContext = resumeRequestContext;
97324
97525
  globalEntryForContext.requestContextRebuilt = false;
97325
97526
  }
97527
+ for (const reg of /* @__PURE__ */ new Set([entry, globalEntryForContext])) if (reg && runAutoResume !== void 0) reg.autoResumeSuspendedTools = runAutoResume;
97326
97528
  } catch (error) {
97327
97529
  await executionFence.settle(async () => {});
97328
97530
  throw error;
@@ -97436,6 +97638,7 @@ var Agent = class Agent extends require_base.MastraBase {
97436
97638
  this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open resume spans: ${error}`);
97437
97639
  }
97438
97640
  carrySegmentSpans(resumeRequestContext, runId, resumeSegment);
97641
+ if (runAutoResume !== void 0) carrySegmentAutoResume(resumeRequestContext, runId, runAutoResume);
97439
97642
  const resumeSegmentSpan = entry.resumeAgentSpan ?? entry.agentSpan;
97440
97643
  const closeOnSuspend = resolvedOptions.closeOnSuspend ?? false;
97441
97644
  const { output, cleanup: createdStreamCleanup, detach: detachResumeStream, fail: failResumeStream, waitForEventDelivery, ready } = createDurableAgentStream({
@@ -97557,7 +97760,8 @@ var Agent = class Agent extends require_base.MastraBase {
97557
97760
  workflowExecution.then(releaseResumeMarker, releaseResumeMarker);
97558
97761
  const resumeStreamOptions = {
97559
97762
  ...resolvedOptions,
97560
- runId
97763
+ runId,
97764
+ autoResumeSuspendedTools: runAutoResume
97561
97765
  };
97562
97766
  if (!agentThreadStreamRuntime.continueRun(this, output, resumeStreamOptions, this.getPubSub(), {
97563
97767
  generation: executionFence.generation,
@@ -104776,7 +104980,7 @@ function createLLMMappingStep({ models, _internal, ...rest }, llmExecutionStep)
104776
104980
  });
104777
104981
  }
104778
104982
  // src/loop/workflows/agentic-execution/tool-call-step.ts
104779
- function createToolCallStep({ tools, messageList, options, outputWriter, controller, runId, streamState, modelSpanTracker, _internal, logger, agentId, agentVersionId, resolvedScopes, returnScorerData, mastra, requireToolApproval: requireToolApprovalFromFactory, actor, mcp, agent }) {
104983
+ function createToolCallStep({ tools, messageList, options, outputWriter, controller, runId, streamState, modelSpanTracker, _internal, logger, agentId, agentVersionId, resolvedScopes, returnScorerData, autoResumeSuspendedTools, mastra, requireToolApproval: requireToolApprovalFromFactory, actor, mcp, agent }) {
104780
104984
  const memoryMessageRefs = new MemoryMessageRefs();
104781
104985
  return createStep$1({
104782
104986
  id: "toolCallStep",
@@ -105124,6 +105328,7 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105124
105328
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105125
105329
  __resolvedScopes: resolvedScopes ?? [],
105126
105330
  ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105331
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {},
105127
105332
  suspendedToolRunId: options.runId
105128
105333
  }, { resumeLabel: inputData.toolCallId });
105129
105334
  }
@@ -105164,6 +105369,7 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105164
105369
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105165
105370
  __resolvedScopes: resolvedScopes ?? [],
105166
105371
  ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105372
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {},
105167
105373
  toolCallId: inputData.toolCallId,
105168
105374
  toolName: inputData.toolName,
105169
105375
  resumeLabel: options?.resumeLabel,
@@ -105237,7 +105443,8 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105237
105443
  __agentId: agentId,
105238
105444
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105239
105445
  __resolvedScopes: resolvedScopes ?? [],
105240
- ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {}
105446
+ ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105447
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {}
105241
105448
  }, { resumeLabel: inputData.toolCallId });
105242
105449
  }
105243
105450
  const clearedApproval = await removeToolMetadata({
@@ -106680,6 +106887,15 @@ const AGENT_THREAD_WAKE_OWNER_DISCOVERY_DEADLINE_MS = require_utils$1.readPositi
106680
106887
  const AGENT_THREAD_CLAIM_LEASE_PREFIX = "thread-claim:";
106681
106888
  const AGENT_THREAD_OWNER_ACCEPTANCE_TIMEOUT_MS = 5e3;
106682
106889
  const UNSAVED_RUN_TRIM_DELAY_MS = 3e4;
106890
+ /** Waits before a parked storage-backed run tries again to let go of its thread for queued input (#30190). */
106891
+ const PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS = [
106892
+ 100,
106893
+ 200,
106894
+ 400,
106895
+ 800,
106896
+ 1600,
106897
+ 3200
106898
+ ];
106683
106899
  const AGENT_THREAD_PEER_DISCOVERY_TOPIC = "agent.thread-peer-discovery";
106684
106900
  const AGENT_THREAD_PEER_DISCOVERY_TIMEOUT_MS = 100;
106685
106901
  const THREAD_LEASE_OWNER_PREFIX = "mastra:thread-lease:";
@@ -106968,6 +107184,38 @@ function withThreadMemory(memory, resourceId, threadId) {
106968
107184
  thread: memory?.thread ?? threadId
106969
107185
  };
106970
107186
  }
107187
+ /**
107188
+ * The memory a resume that names no thread continues its run with: the run's thread and resource, the run's
107189
+ * settings, and on top of those every setting the resume passes itself (`options` merged key by key, so a resume
107190
+ * that sets only `lastMessages` or `readOnly` keeps the rest).
107191
+ */
107192
+ function resumeMemoryOnOwnThread({ run, resume, threadId, resourceId }) {
107193
+ const options = run?.options || resume?.options ? {
107194
+ ...run?.options,
107195
+ ...resume?.options
107196
+ } : void 0;
107197
+ return {
107198
+ ...run,
107199
+ ...resume,
107200
+ thread: run?.thread ?? threadId,
107201
+ resource: run?.resource ?? resourceId,
107202
+ ...options ? { options } : {}
107203
+ };
107204
+ }
107205
+ /**
107206
+ * The options a resume leaves on its run's record. Resume callers hand over the resume's own
107207
+ * `autoResumeSuspendedTools`, not the agent default merged in, so `undefined` means the resume left it out. The run
107208
+ * then keeps the value it started with: a run that turned auto-resume off keeps holding a queued message for an
107209
+ * explicit resume after it parks again. Callers that resume a run rebuilt from storage pass the run's persisted value
107210
+ * instead, since this process has no record of it. (#30190)
107211
+ */
107212
+ function keepRunAutoResume(resume, run) {
107213
+ if (resume.autoResumeSuspendedTools !== void 0 || run?.autoResumeSuspendedTools === void 0) return resume;
107214
+ return {
107215
+ ...resume,
107216
+ autoResumeSuspendedTools: run.autoResumeSuspendedTools
107217
+ };
107218
+ }
106971
107219
  const CANCELLED_BEFORE_RUN = "The accepted message was cancelled before it ran";
106972
107220
  function toPublicThreadPeer(peer) {
106973
107221
  const { unsubscribe: _unsubscribe, ...publicPeer } = peer;
@@ -106998,6 +107246,7 @@ function createRuntimeState() {
106998
107246
  suspensionMetadataByRunId: /* @__PURE__ */ new Map(),
106999
107247
  signalQueues: createActiveRunSignalQueues(),
107000
107248
  locallyQueuedSignalIdsByThread: /* @__PURE__ */ new Map(),
107249
+ startedSignalIdsByThread: /* @__PURE__ */ new Map(),
107001
107250
  pendingSignalListenersByRunId: /* @__PURE__ */ new Map(),
107002
107251
  lostRunsByThread: /* @__PURE__ */ new Map(),
107003
107252
  pendingIdleSignalsByThread: /* @__PURE__ */ new Map(),
@@ -107045,6 +107294,11 @@ var AgentThreadStreamRuntime = class {
107045
107294
  #stalledLeaseReads = /* @__PURE__ */ new WeakMap();
107046
107295
  /** Per run, the resolution of its signals store in flight (see `#signalsStoreOf`). */
107047
107296
  #storeResolutions = /* @__PURE__ */ new WeakMap();
107297
+ /**
107298
+ * Parked storage-backed runs letting go of their thread for queued input, one release at a time per run. `again`
107299
+ * records a trigger that arrived meanwhile, which checks the run again unless the release let go of the thread.
107300
+ */
107301
+ #releasingParkedStoredRuns = /* @__PURE__ */ new WeakMap();
107048
107302
  #threadlessRunFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(({ state, runId, token }) => {
107049
107303
  if (state.preparedRunsById.get(runId)?.finalizerToken !== token) return;
107050
107304
  this.#cleanupPreparedRun(state, runId);
@@ -107279,7 +107533,7 @@ var AgentThreadStreamRuntime = class {
107279
107533
  }
107280
107534
  const preparedRun = state.preparedRunsById.get(runId);
107281
107535
  const controller = preparedRun?.abortController ?? record.segmentAbortController;
107282
- const stepOwners = [controller?.signal, record.stepOwner?.()].filter((owner) => owner !== void 0);
107536
+ const stepOwners = this.#runStepOwners(state, record);
107283
107537
  const executing = !!preparedRun && record.lifecycle !== "suspended" || stepOwners.some((owner) => require_utils$1.hasRunningRunStep(owner));
107284
107538
  const abortController = executing ? controller : void 0;
107285
107539
  if (!state.leaseRenewalTimers.has(runId) || record.registeredElsewhere || record.lateRetakeHandoff) {
@@ -107841,10 +108095,61 @@ var AgentThreadStreamRuntime = class {
107841
108095
  if (!active) return;
107842
108096
  const data = event.data;
107843
108097
  if (data?.type === "signal-enqueued") {
107844
- if (data.sourceId === this.#id && this.#isLocalSignalEcho(state, key, data.signal.id, data.runId) || subscription.admittedSignalIds.has(data.signal.id)) return;
108098
+ if (data.sourceId === this.#id && this.#isLocalSignalEcho(state, key, data.signal.id, data.runId) || subscription.admittedSignalIds.has(data.signal.id) || state.startedSignalIdsByThread.get(key)?.has(data.signal.id)) return;
107845
108099
  const answersTo = (runId) => state.threadKeysByRunId.get(runId) === key || subscription.ownedRunIds.has(runId) || state.storedSignals.endedRun(key)?.run.runId === runId;
107846
108100
  const runId = answersTo(data.runId) ? data.runId : forwardedSignalRunId(data.runId);
107847
108101
  if (!answersTo(runId)) return;
108102
+ if (state.threadRunsById.get(runId)?.registeredElsewhere) return;
108103
+ if (data.senderKeepsCopy && !state.activeThreadRunIds.has(key)) return;
108104
+ const activeRunId = data.queued ? state.activeThreadRunIds.get(key) : void 0;
108105
+ const live = activeRunId ? state.threadRunsById.get(activeRunId) : void 0;
108106
+ if (live && this.#isThreadBlockingRun(state, live)) {
108107
+ const signal = require_signals.createSignal(data.signal);
108108
+ subscription.admittedSignalIds.add(signal.id);
108109
+ const admit = () => {
108110
+ if (this.#pendingUserMessageChunk(runId, signal, "pending")) this.#publish(pubsub, key, {
108111
+ type: "user-message-admitted",
108112
+ signalId: signal.id,
108113
+ admittedRunId: runId
108114
+ });
108115
+ };
108116
+ const admitStored = () => {
108117
+ this.#publishPendingUserMessage(pubsub, key, live.runId, signal, "queued");
108118
+ admit();
108119
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, live);
108120
+ };
108121
+ if (data.stored) return admitStored();
108122
+ const liveStore = this.#signalsStoreOf(live);
108123
+ if (!liveStore) {
108124
+ this.queueSignal(live.agent, signal, { runId: live.runId }, pubsub);
108125
+ return admit();
108126
+ }
108127
+ const to = {
108128
+ runId: live.runId,
108129
+ agent: live.agent
108130
+ };
108131
+ const written = this.#enqueueStoredSignal(state, key, liveStore, signal, to, true, true);
108132
+ return { settled: (async () => {
108133
+ try {
108134
+ if (await written === "run-closed") {
108135
+ if (subscription.cancelledSignalIds.has(signal.id)) return;
108136
+ this.#announceLeftoverSignal(state, pubsub, key, live, signal);
108137
+ if (live.runId !== runId) admit();
108138
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, live);
108139
+ return;
108140
+ }
108141
+ } catch (error) {
108142
+ if (!subscription.cancelledSignalIds.has(signal.id)) subscription.admittedSignalIds.delete(signal.id);
108143
+ live.agent.__getLogger?.()?.warn?.("Could not store a queued signal forwarded to a running run", {
108144
+ runId,
108145
+ signalId: signal.id,
108146
+ error
108147
+ });
108148
+ throw error;
108149
+ }
108150
+ admitStored();
108151
+ })() };
108152
+ }
107848
108153
  const ended = state.storedSignals.endedRun(key)?.run;
107849
108154
  const run = state.threadRunsById.get(runId) ?? (ended?.runId === runId ? ended : void 0);
107850
108155
  const store = run && this.#signalsStoreOf(run);
@@ -107860,15 +108165,34 @@ var AgentThreadStreamRuntime = class {
107860
108165
  subscription.admittedSignalIds.add(data.signal.id);
107861
108166
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
107862
108167
  this.#notifyPendingSignals(state, key, signal);
108168
+ const record = state.threadRunsById.get(runId);
108169
+ if (record) this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
107863
108170
  } else if (data?.type === "user-message-admitted") this.#settleForwardedIdleSignal(state, key, data.signalId, data.admittedRunId);
107864
108171
  else if (data?.type === "user-message-presentation") {
107865
108172
  const { chunk } = data;
107866
108173
  if (chunk.type === "data-user-message-pending" && chunk.data.metadata?.status === "pending") this.#settleForwardedIdleSignal(state, key, chunk.data.id, chunk.runId);
107867
108174
  } else if (data?.type === "signals-cancelled") {
107868
108175
  for (const id of data.signalIds) this.#settleForwardedIdleSignal(state, key, id);
107869
- for (const id of data.signalIds) subscription.admittedSignalIds.add(id);
108176
+ for (const id of data.signalIds) {
108177
+ subscription.admittedSignalIds.add(id);
108178
+ subscription.cancelledSignalIds.add(id);
108179
+ }
107870
108180
  this.#cancelPendingSignals(state, key, new Set(data.signalIds), pubsub, this.#threadSignalsStore(state, key));
107871
108181
  this.#notifyThreadEvents(state);
108182
+ } else if (data?.type === "queued-input-waiting") {
108183
+ const record = state.threadRunsById.get(data.runId);
108184
+ if (data.sourceId === this.#getSourceId() || !record || state.threadKeysByRunId.get(data.runId) !== key) return;
108185
+ record.queuedInputElsewhere = true;
108186
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
108187
+ } else if (data?.type === "parked-run-released") {
108188
+ if (data.sourceId === this.#getSourceId() || state.activeThreadRunIds.get(key) !== data.runId) return;
108189
+ const record = state.threadRunsById.get(data.runId);
108190
+ if (record && record.registeredElsewhere === void 0) return;
108191
+ if (state.activeThreadStreamIds.get(key) !== data.streamId && record?.registeredElsewhere !== data.streamId) return;
108192
+ state.activeThreadRunIds.delete(key);
108193
+ state.activeThreadStreamIds.delete(key);
108194
+ this.#notifyThreadEvents(state);
108195
+ await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
107872
108196
  } else if (data?.type === "run-abort-requested") {
107873
108197
  const ownsRun = () => active && (state.preparedRunsById.has(data.runId) || state.threadRunsById.has(data.runId)) && state.threadKeysByRunId.get(data.runId) === key && state.activeThreadRunIds.get(key) === data.runId && (data.streamId === void 0 || state.activeThreadStreamIds.get(key) === data.streamId);
107874
108198
  const clearPendingSignals = ownsRun() && data.clearPendingSignals && await this.#holdsThreadLeaseThroughRetake(resolvedPubSub, key, data.runId);
@@ -107890,7 +108214,8 @@ var AgentThreadStreamRuntime = class {
107890
108214
  return;
107891
108215
  }
107892
108216
  const current = state.threadRunsById.get(data.runId);
107893
- if (current?.registrationSeen) current.registeredElsewhere = true;
108217
+ if (current?.registrationSeen) current.registeredElsewhere = data.streamId;
108218
+ if (state.activeThreadRunIds.get(key) === data.runId) this.#requestParkedRunReleaseElsewhere(state, resolvedPubSub, key, { executionChanged: true });
107894
108219
  if (lost?.runId === data.runId && lost.registrationSeen) {
107895
108220
  state.lostRunsByThread.delete(key);
107896
108221
  this.#handOffQueuedSignals(state, resolvedPubSub, key, data.runId, lost.streamId);
@@ -107900,6 +108225,8 @@ var AgentThreadStreamRuntime = class {
107900
108225
  if (data.type === "run-discarded" && !(state.forwardedIdleLeaseChecks.has(key) && await this.#leaseMayStillName(resolvedPubSub, key, data.runId)) && this.#requeueUnadmittedForwards(state, key, data.runId)) await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
107901
108226
  } else if (data?.type === "run-completed" || data?.type === "run-failed") {
107902
108227
  this.#releaseRunSupersededBy(state, resolvedPubSub, key, subscription, data.runId);
108228
+ if (data.type === "run-completed" && data.status === "interrupted" && state.threadRunsById.get(data.runId)?.registeredElsewhere === data.streamId) return;
108229
+ this.#retireRunEndedElsewhere(state, resolvedPubSub, key, data.runId, data.streamId);
107903
108230
  const lostStreamId = subscription.successorRunIds.get(data.runId);
107904
108231
  if (lostStreamId !== void 0 && data.streamId === lostStreamId) return;
107905
108232
  if (lostStreamId === void 0 && data.type === "run-completed" && data.superseded && state.forwardedIdleLeaseChecks.has(key)) return;
@@ -107916,7 +108243,7 @@ var AgentThreadStreamRuntime = class {
107916
108243
  const onEvent = (event, ack) => {
107917
108244
  const type = event.data?.type;
107918
108245
  const awaitingForwards = state.forwardedIdleSignalsByThread.has(key);
107919
- if (type !== "signal-enqueued" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !((type === "user-message-presentation" || type === "user-message-admitted") && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
108246
+ if (type !== "signal-enqueued" && type !== "queued-input-waiting" && type !== "parked-run-released" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !((type === "user-message-presentation" || type === "user-message-admitted") && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
107920
108247
  subscription.references++;
107921
108248
  const handled = tail.then(() => handleEvent(event));
107922
108249
  tail = handled.then(() => {}, () => {});
@@ -107931,6 +108258,7 @@ var AgentThreadStreamRuntime = class {
107931
108258
  observers: 0,
107932
108259
  ownedRunIds,
107933
108260
  admittedSignalIds: /* @__PURE__ */ new Set(),
108261
+ cancelledSignalIds: /* @__PURE__ */ new Set(),
107934
108262
  successorRunIds: /* @__PURE__ */ new Map(),
107935
108263
  supersedingRunIds: /* @__PURE__ */ new Map(),
107936
108264
  unsubscribe: () => {
@@ -107953,7 +108281,9 @@ var AgentThreadStreamRuntime = class {
107953
108281
  if (!subscription || subscription.references > subscription.observers || this.#hasPendingThreadWork(state, key) || state.forwardedIdleSignalsByThread.has(key) || state.drainingPendingSignalsByThread.has(key) || state.drainingIdleSignalsByThread.has(key) || state.recentlyEndedStoredRunTimers.has(key) || [...state.threadKeysByRunId.values()].includes(key) || [...state.preparedRunsById.values()].some((run) => run.threadKey === key)) return;
107954
108282
  subscription.ownedRunIds.clear();
107955
108283
  subscription.admittedSignalIds.clear();
108284
+ subscription.cancelledSignalIds.clear();
107956
108285
  state.locallyQueuedSignalIdsByThread.delete(key);
108286
+ state.startedSignalIdsByThread.delete(key);
107957
108287
  if (subscription.observers) return;
107958
108288
  state.threadControlSubscriptions.delete(key);
107959
108289
  subscription.unsubscribe();
@@ -108648,11 +108978,16 @@ var AgentThreadStreamRuntime = class {
108648
108978
  runId,
108649
108979
  resourceId: owner.resourceId,
108650
108980
  threadId: owner.threadId,
108651
- streamOptions
108981
+ streamOptions,
108982
+ ...waitForIdle ? { queued: true } : {}
108652
108983
  });
108653
108984
  state.pendingIdleSignalsByThread.set(key, idleQueue);
108654
108985
  this.#publishPendingUserMessage(pubsub, key, activeRunId, signal, "queued");
108655
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
108986
+ if (activeRecord) {
108987
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
108988
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, activeRecord);
108989
+ }
108990
+ this.#requestParkedRunReleaseElsewhere(state, pubsub, key);
108656
108991
  settleMessageIdentity?.({ runId });
108657
108992
  return { runId };
108658
108993
  }
@@ -108744,25 +109079,18 @@ var AgentThreadStreamRuntime = class {
108744
109079
  action: "remote",
108745
109080
  runId: ownerRunId
108746
109081
  });
108747
- if (this.#mayStoreForRunHeldElsewhere(state, owner.agent, forwardedSignalRunId(ownerRunId))) {
108748
- if (!await this.#forwardSignal(state, pubsub, key, owner.agent, ownerRunId, signal).catch((error) => {
108749
- releaseMessageIdentity(require_error.getErrorFromUnknown(error));
108750
- throw error;
108751
- })) {
108752
- const error = `Thread ${describeThreadKey(key)} is held by run ${ownerRunId}, which ended before it took the message`;
108753
- releaseMessageIdentity(error);
108754
- return {
108755
- runId: ownerRunId,
108756
- error,
108757
- blocked: true
108758
- };
108759
- }
108760
- } else this.#publish(pubsub, key, {
108761
- type: "signal-enqueued",
108762
- runId: ownerRunId,
108763
- signal: this.#serializeSignal(signal),
108764
- sourceId: this.#getSourceId()
108765
- });
109082
+ if (!await this.#forwardToOwner(state, pubsub, key, owner.agent, ownerRunId, signal, waitForIdle).catch((error) => {
109083
+ releaseMessageIdentity(require_error.getErrorFromUnknown(error));
109084
+ throw error;
109085
+ })) {
109086
+ const error = `Thread ${describeThreadKey(key)} is held by run ${ownerRunId}, which ended before it took the message`;
109087
+ releaseMessageIdentity(error);
109088
+ return {
109089
+ runId: ownerRunId,
109090
+ error,
109091
+ blocked: true
109092
+ };
109093
+ }
108766
109094
  settleMessageIdentity?.({ runId: ownerRunId }, false);
108767
109095
  return { runId: ownerRunId };
108768
109096
  }
@@ -108853,11 +109181,13 @@ var AgentThreadStreamRuntime = class {
108853
109181
  else if (entry.leaseGone) ended.add(entry.runId);
108854
109182
  else entry.leaseGone = true;
108855
109183
  for (const runId of ended) if (this.#requeueUnadmittedForwards(state, key, runId)) {
109184
+ const executedElsewhere = state.threadRunsById.get(runId)?.registeredElsewhere;
109185
+ if (executedElsewhere !== void 0) this.#retireRunEndedElsewhere(state, this.#getPubSub(pubsub), key, runId, executedElsewhere);
108856
109186
  if (!state.threadRunsById.has(runId) && state.activeThreadStreamIds.get(key) === streamBeforeRead && state.activeThreadRunIds.get(key) === runId) {
108857
109187
  state.activeThreadRunIds.delete(key);
108858
109188
  state.activeThreadStreamIds.delete(key);
108859
109189
  }
108860
- await this.#drainPendingIdleSignals(state, pubsub, key, runId);
109190
+ await this.#drainPendingIdleSignals(state, pubsub, key, executedElsewhere === void 0 ? runId : void 0);
108861
109191
  }
108862
109192
  };
108863
109193
  const check = setInterval(() => {
@@ -108891,6 +109221,21 @@ var AgentThreadStreamRuntime = class {
108891
109221
  state.pendingIdleSignalsByThread.set(key, [...unadmitted.map(([, entry]) => entry.pendingIdle), ...state.pendingIdleSignalsByThread.get(key) ?? []]);
108892
109222
  return true;
108893
109223
  }
109224
+ /** Signals taken from this runtime's queues as a turn's input; `#forgetStartedSignals` undoes it on a requeue. */
109225
+ #recordStartedSignals(state, key, signals) {
109226
+ if (signals.length === 0) return;
109227
+ const ids = state.startedSignalIdsByThread.get(key) ?? /* @__PURE__ */ new Set();
109228
+ for (const signal of signals) {
109229
+ ids.delete(signal.id);
109230
+ ids.add(signal.id);
109231
+ }
109232
+ while (ids.size > MAX_LOCALLY_QUEUED_SIGNAL_IDS_PER_THREAD) ids.delete(ids.values().next().value);
109233
+ state.startedSignalIdsByThread.set(key, ids);
109234
+ }
109235
+ #forgetStartedSignals(state, key, signals) {
109236
+ const ids = state.startedSignalIdsByThread.get(key);
109237
+ for (const signal of signals) ids?.delete(signal.id);
109238
+ }
108894
109239
  #recordLocallyQueuedSignal(state, key, signalId) {
108895
109240
  const ids = state.locallyQueuedSignalIdsByThread.get(key) ?? /* @__PURE__ */ new Map();
108896
109241
  ids.delete(signalId);
@@ -109488,6 +109833,26 @@ var AgentThreadStreamRuntime = class {
109488
109833
  else this.#releaseThreadLease(pubsub, key, runId);
109489
109834
  return true;
109490
109835
  }
109836
+ /**
109837
+ * The execution another process registered for a run parked here has ended, so nothing executes the run any more.
109838
+ * The stale record stops routing the thread's input to it: input sent from now on runs as a new turn here, and
109839
+ * forwards that crossed the end are queued again by the terminal handler. (#30190)
109840
+ */
109841
+ #retireRunEndedElsewhere(state, pubsub, key, runId, streamId) {
109842
+ const record = state.threadRunsById.get(runId);
109843
+ if (!record || streamId === void 0 || record.registeredElsewhere !== streamId) return;
109844
+ record.lifecycle = "completed";
109845
+ this.#clearSuspendedRun(state, runId);
109846
+ this.#stopLeaseRenewal(pubsub, runId);
109847
+ state.threadRunsByStreamId.delete(record.streamId);
109848
+ state.threadRunsById.delete(runId);
109849
+ state.threadKeysByRunId.delete(runId);
109850
+ if (state.activeThreadRunIds.get(key) === runId) {
109851
+ state.activeThreadRunIds.delete(key);
109852
+ state.activeThreadStreamIds.delete(key);
109853
+ }
109854
+ this.#notifyThreadEvents(state);
109855
+ }
109491
109856
  /** Release the local run that `runId` superseded, if it superseded one. */
109492
109857
  #releaseRunSupersededBy(state, pubsub, key, subscription, runId) {
109493
109858
  const supersededRunId = subscription.supersedingRunIds.get(runId);
@@ -109504,12 +109869,162 @@ var AgentThreadStreamRuntime = class {
109504
109869
  */
109505
109870
  #releaseSupersededParkedRun(state, pubsub, key, runId) {
109506
109871
  const record = state.threadRunsById.get(runId);
109507
- if (!record || state.activeThreadRunIds.get(key) !== runId || !this.#isParkedRun(state, runId)) return;
109872
+ if (!record || state.activeThreadRunIds.get(key) !== runId || !this.#isParkedRun(state, runId)) return false;
109508
109873
  state.activeThreadRunIds.delete(key);
109509
109874
  if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key);
109510
109875
  this.#stopReadingDisplacedRun(state, runId);
109511
109876
  if (this.#hasPendingThreadWork(state, key)) this.#drainPendingSignals(state, pubsub, key, record);
109512
109877
  else this.#releaseThreadLease(pubsub, key, runId);
109878
+ return true;
109879
+ }
109880
+ /**
109881
+ * With `autoResumeSuspendedTools`, the next turn is what resumes a run parked on
109882
+ * a tool's suspend(): the model reads the user's answer from the new message.
109883
+ * The parked run itself never drains its queue, so a message queued onto it
109884
+ * would be reported delivered and never run (#30190). Once the run has parked,
109885
+ * queued messages start the next turn the way a stream call on the thread
109886
+ * would; the parked run keeps its record and stays resumable.
109887
+ *
109888
+ * Without auto-resume, the message keeps waiting for the explicit resume (an
109889
+ * AgentController prompt waits for its answer), and a run parked on a tool
109890
+ * approval keeps holding the thread: consent arrives through the approval APIs.
109891
+ *
109892
+ * Any input starts the turn: a sent message, a continuation, or work queued
109893
+ * for after the run (`queueMessage`, `queueSignal`, here, forwarded from
109894
+ * another process, or held by another process that sent `queued-input-waiting`). Queued work waits for the thread's run to end (#32093), and
109895
+ * a run parked with auto-resume on counts as ended: it waits for the next
109896
+ * message and nothing else, so queued work is that message. Every other run
109897
+ * still holds queued work: one in flight, one parked without auto-resume, and
109898
+ * one parked on an approval.
109899
+ */
109900
+ async #startQueuedTurnAfterParkedRun(state, pubsub, key, record) {
109901
+ const options = record.streamOptions;
109902
+ const storageBacked = this.#isStorageBacked(record);
109903
+ const canStart = () => state.threadRunsById.get(record.runId) === record && record.streamOptions === options && record.lifecycle === "suspended" && !record.registeredElsewhere && !record.resumeHolds && !record.resumedUntracked && !this.#isApprovalSuspendedRun(state, record.runId) && !state.shutdownStreams.has(record.streamId) && (storageBacked || record.queuedInputElsewhere === true || this.#hasPendingThreadWork(state, key));
109904
+ if (!canStart()) return;
109905
+ if (!(options.autoResumeSuspendedTools ?? (await record.agent.getDefaultOptions({ requestContext: options.requestContext })).autoResumeSuspendedTools) || !canStart()) return;
109906
+ let owners = this.#runStepOwners(state, record);
109907
+ while (canStart() && owners.some((owner) => require_utils$1.hasRunningRunStep(owner))) {
109908
+ await Promise.all(owners.map((owner) => new Promise((resolve) => require_utils$1.whenRunStepsSettle(owner, resolve))));
109909
+ owners = this.#runStepOwners(state, record);
109910
+ }
109911
+ if (!canStart()) return;
109912
+ if (storageBacked ? await this.#releaseParkedStoredRunForInput(state, pubsub, key, record, canStart) : this.#releaseSupersededParkedRun(state, this.#getPubSub(pubsub), key, record.runId)) {
109913
+ record.queuedInputElsewhere = false;
109914
+ this.#publish(pubsub, key, {
109915
+ type: "parked-run-released",
109916
+ runId: record.runId,
109917
+ streamId: record.streamId,
109918
+ sourceId: this.#getSourceId()
109919
+ });
109920
+ }
109921
+ }
109922
+ /**
109923
+ * Whether the thread of a storage-backed run has input for it: a pending or queued row (`listPendingSignals` returns
109924
+ * both), or a continuation or queued work held here.
109925
+ */
109926
+ async #hasStoredRunInput(state, key, record) {
109927
+ if (this.#hasPendingThreadWork(state, key)) return true;
109928
+ const store = await this.#signalsStoreOf(record);
109929
+ if (!store) return false;
109930
+ return (await store.store.listPendingSignals({ threadId: store.threadId })).length > 0;
109931
+ }
109932
+ /**
109933
+ * `#releaseSupersededParkedRun` for a storage-backed run: its input waits in its store, so the thread is checked
109934
+ * as at the end of a run, which starts the next turn with the oldest pending row. The run's signals are closed first,
109935
+ * as when a parked run is aborted, so rows it took and never consumed are pending again for that turn. The run keeps
109936
+ * its record and stays resumable; a resume keeps the thread's signal run as it finds it. (#30190)
109937
+ */
109938
+ async #releaseParkedStoredRunForInput(state, pubsub, key, record, canStart) {
109939
+ const inFlight = this.#releasingParkedStoredRuns.get(record);
109940
+ if (inFlight) {
109941
+ inFlight.again = true;
109942
+ return false;
109943
+ }
109944
+ const release = { again: false };
109945
+ this.#releasingParkedStoredRuns.set(record, release);
109946
+ let released = false;
109947
+ const { runId } = record;
109948
+ const holds = () => canStart() && state.activeThreadRunIds.get(key) === runId && this.#isParkedRun(state, runId);
109949
+ try {
109950
+ for (let attempt = 0;; attempt++) {
109951
+ const outcome = await state.storedSignals.runWrite(key, async () => {
109952
+ if (!holds() || !(record.queuedInputElsewhere || await this.#hasStoredRunInput(state, key, record))) return "kept";
109953
+ if (!holds()) return "kept";
109954
+ if (await record.agent.__closeParkedRunSignals?.(runId, { exclusiveOfResume: true }) === false) return "retry";
109955
+ if (!holds()) return "kept";
109956
+ state.activeThreadRunIds.delete(key);
109957
+ if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key);
109958
+ this.#stopReadingDisplacedRun(state, runId);
109959
+ return "released";
109960
+ }).catch((error) => {
109961
+ this.#logParkedRunReleaseFailure(record, error);
109962
+ return "retry";
109963
+ });
109964
+ if (outcome === "kept") return false;
109965
+ if (outcome === "released") {
109966
+ released = true;
109967
+ break;
109968
+ }
109969
+ if (attempt >= PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS.length) {
109970
+ this.#logParkedRunReleaseFailure(record, /* @__PURE__ */ new Error("The parked run kept the thread after every retry"));
109971
+ return false;
109972
+ }
109973
+ await new Promise((resolve) => setTimeout(resolve, PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS[attempt]));
109974
+ }
109975
+ } finally {
109976
+ this.#releasingParkedStoredRuns.delete(record);
109977
+ if (release.again && !released) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109978
+ }
109979
+ const queued = this.#hasPendingThreadWork(state, key);
109980
+ if (!queued) this.#releaseEndedStoredRun(state, pubsub, key, record);
109981
+ this.#drainPendingSignals(state, pubsub, key, record, { freshLease: !queued });
109982
+ return true;
109983
+ }
109984
+ /**
109985
+ * Holds a parked run for a resume that is setting up, so input queued meanwhile stays the resumed run's next model
109986
+ * input, as it was before parked runs were released for queued input, instead of starting a turn beside the resumed
109987
+ * tool. The returned function ends the hold; if the run is still parked then, for example because the resume
109988
+ * failed, queued input starts the next turn, unless `startQueuedTurn` is false: a caller whose resume this record
109989
+ * doesn't follow, and that left the run parked again, marks the record so queued input keeps waiting. (#30190)
109990
+ */
109991
+ holdParkedRunForResume(runId, pubsub) {
109992
+ const state = this.#getState(pubsub);
109993
+ const record = state.threadRunsById.get(runId);
109994
+ if (!record) return () => {};
109995
+ record.resumeHolds = (record.resumeHolds ?? 0) + 1;
109996
+ let held = true;
109997
+ return ({ startQueuedTurn = true } = {}) => {
109998
+ if (!held) return;
109999
+ held = false;
110000
+ record.resumeHolds = (record.resumeHolds ?? 1) - 1;
110001
+ if (!startQueuedTurn) record.resumedUntracked = true;
110002
+ if (record.resumeHolds > 0 || !startQueuedTurn) return;
110003
+ const key = this.#threadKey(record.resourceId, record.threadId);
110004
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110005
+ };
110006
+ }
110007
+ #startQueuedTurnAfterParkedRunLater(state, pubsub, key, record) {
110008
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110009
+ }
110010
+ /**
110011
+ * The message that triggered the release was already answered `deliver`, so a failure here would otherwise
110012
+ * leave it queued on the parked run with no trace.
110013
+ */
110014
+ #logParkedRunReleaseFailure(record, error) {
110015
+ record.agent.__getLogger?.()?.error("Could not start the queued turn for a run parked on a suspended tool", {
110016
+ runId: record.runId,
110017
+ threadId: record.threadId,
110018
+ resourceId: record.resourceId,
110019
+ error
110020
+ });
110021
+ }
110022
+ /**
110023
+ * The objects the steps of a run register under while they run: the abort signal of its prepared run or current
110024
+ * segment, and a durable run's registry entry.
110025
+ */
110026
+ #runStepOwners(state, record) {
110027
+ return [(state.preparedRunsById.get(record.runId)?.abortController ?? record.segmentAbortController)?.signal, record.stepOwner?.()].filter((owner) => owner !== void 0);
109513
110028
  }
109514
110029
  /**
109515
110030
  * A parked run no longer holds its thread, so its answer resumes it on a new
@@ -109707,6 +110222,7 @@ var AgentThreadStreamRuntime = class {
109707
110222
  state.suspensionMetadataByRunId.clear();
109708
110223
  state.signalQueues.clear();
109709
110224
  state.locallyQueuedSignalIdsByThread.clear();
110225
+ state.startedSignalIdsByThread.clear();
109710
110226
  state.lostRunsByThread.clear();
109711
110227
  state.pendingIdleSignalsByThread.clear();
109712
110228
  state.forwardedIdleSignalsByThread.clear();
@@ -109777,11 +110293,43 @@ var AgentThreadStreamRuntime = class {
109777
110293
  /**
109778
110294
  * Queues a signal for in-loop draining by a same-agent run that is already in
109779
110295
  * flight here, so it becomes that run's next model input instead of waiting for
109780
- * the run to finish.
110296
+ * the run to finish. If the run is parked on a suspension that auto-resume
110297
+ * answers, the signal starts the next turn instead.
109781
110298
  */
109782
110299
  #queueForActiveRun(state, pubsub, key, record, signal) {
109783
- state.signalQueues.enqueue("pending", key, signal);
109784
110300
  this.#recordLocallyQueuedSignal(state, key, signal.id);
110301
+ if (record.registeredElsewhere) {
110302
+ const senderKeepsCopy = !!this.#pendingUserMessageChunk(record.runId, signal, "pending");
110303
+ if (senderKeepsCopy) {
110304
+ const forwarded = state.forwardedIdleSignalsByThread.get(key) ?? /* @__PURE__ */ new Map();
110305
+ forwarded.set(signal.id, {
110306
+ pendingIdle: {
110307
+ agent: record.agent,
110308
+ signal,
110309
+ runId: globalThis.crypto.randomUUID(),
110310
+ resourceId: record.resourceId ?? "",
110311
+ threadId: record.threadId,
110312
+ streamOptions: {
110313
+ ...record.streamOptions,
110314
+ abortSignal: void 0
110315
+ }
110316
+ },
110317
+ runId: record.runId
110318
+ });
110319
+ state.forwardedIdleSignalsByThread.set(key, forwarded);
110320
+ this.#ensureThreadControlSubscription(state, pubsub, key);
110321
+ this.#watchForwardedIdleLease(state, pubsub, key);
110322
+ }
110323
+ this.#publish(pubsub, key, {
110324
+ type: "signal-enqueued",
110325
+ runId: record.runId,
110326
+ signal: this.#serializeSignal(signal),
110327
+ sourceId: this.#getSourceId(),
110328
+ ...senderKeepsCopy ? { senderKeepsCopy } : {}
110329
+ });
110330
+ return;
110331
+ }
110332
+ state.signalQueues.enqueue("pending", key, signal);
109785
110333
  this.#publishPendingUserMessage(pubsub, key, record.runId, signal, "pending");
109786
110334
  this.#notifyPendingSignals(state, key, signal);
109787
110335
  this.#publish(pubsub, key, {
@@ -109791,6 +110339,7 @@ var AgentThreadStreamRuntime = class {
109791
110339
  sourceId: this.#getSourceId()
109792
110340
  });
109793
110341
  this.#watchThreadRunCompletion(state, pubsub, key, record);
110342
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109794
110343
  }
109795
110344
  /**
109796
110345
  * `#queueForActiveRun` for a run that keeps its signals in storage. Resolves
@@ -109802,13 +110351,14 @@ var AgentThreadStreamRuntime = class {
109802
110351
  this.#recordLocallyQueuedSignal(state, key, signal.id);
109803
110352
  let written;
109804
110353
  try {
109805
- written = await this.#enqueueStoredSignal(state, key, store, signal, record);
110354
+ written = await this.#enqueueStoredSignal(state, key, store, signal, record, false, true);
109806
110355
  } catch (error) {
109807
110356
  this.#forgetLocallyQueuedSignal(state, key, signal.id);
109808
110357
  throw error;
109809
110358
  }
109810
110359
  if (written === "run-closed") {
109811
- await this.#storeLeftoverSignal(state, pubsub, key, record, signal, store);
110360
+ this.#announceLeftoverSignal(state, pubsub, key, record, signal);
110361
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109812
110362
  return;
109813
110363
  }
109814
110364
  this.#publishSignalAvailable(record.agent, record.runId, signal.id);
@@ -109822,6 +110372,7 @@ var AgentThreadStreamRuntime = class {
109822
110372
  stored: true
109823
110373
  });
109824
110374
  this.#watchThreadRunCompletion(state, pubsub, key, record);
110375
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109825
110376
  }
109826
110377
  /**
109827
110378
  * `signal-enqueued` for a run this runtime holds that keeps its signals in
@@ -109835,12 +110386,16 @@ var AgentThreadStreamRuntime = class {
109835
110386
  const signal = require_signals.createSignal(data.signal);
109836
110387
  if (!data.stored) {
109837
110388
  try {
109838
- if (await this.#enqueueStoredSignal(state, key, store, signal, run) === "run-closed") {
109839
- await this.#storeLeftoverSignal(state, pubsub, key, run, signal, store);
110389
+ if (await this.#enqueueStoredSignal(state, key, store, signal, run, false, true) === "run-closed") {
110390
+ if (!subscription.cancelledSignalIds.has(signal.id)) {
110391
+ this.#announceLeftoverSignal(state, pubsub, key, run, signal);
110392
+ const parked = state.threadRunsById.get(runId);
110393
+ if (parked) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, parked);
110394
+ }
109840
110395
  return;
109841
110396
  }
109842
110397
  } catch (error) {
109843
- subscription.admittedSignalIds.delete(data.signal.id);
110398
+ if (!subscription.cancelledSignalIds.has(data.signal.id)) subscription.admittedSignalIds.delete(data.signal.id);
109844
110399
  run.agent.__getLogger?.()?.warn?.("Could not store a signal forwarded to a running run", {
109845
110400
  runId,
109846
110401
  signalId: signal.id,
@@ -109857,7 +110412,9 @@ var AgentThreadStreamRuntime = class {
109857
110412
  });
109858
110413
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
109859
110414
  this.#notifyPendingSignals(state, key, signal, runId);
109860
- if (!state.threadRunsById.has(runId)) this.#drainPendingSignals(state, pubsub, key, run, { freshLease: true });
110415
+ const record = state.threadRunsById.get(runId);
110416
+ if (record) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
110417
+ else this.#drainPendingSignals(state, pubsub, key, run, { freshLease: true });
109861
110418
  }
109862
110419
  /**
109863
110420
  * Move the signals this runtime queued for a run that is only reserved into
@@ -109881,10 +110438,8 @@ var AgentThreadStreamRuntime = class {
109881
110438
  return this.#enqueueStoredSignal(state, key, store, signal, {
109882
110439
  runId,
109883
110440
  agent
109884
- }).then((written) => {
109885
- if (written !== "run-closed") return;
109886
- leftForNextRun = true;
109887
- return this.#enqueueStoredSignal(state, key, store, signal);
110441
+ }, false, true).then((written) => {
110442
+ if (written === "run-closed") leftForNextRun = true;
109888
110443
  }).then(() => waiter?.resolve(), (error) => {
109889
110444
  if (waiter) {
109890
110445
  this.#forgetLocallyQueuedSignal(state, key, signal.id);
@@ -110025,17 +110580,12 @@ var AgentThreadStreamRuntime = class {
110025
110580
  return this.#getState(pubsub).storedSignals.writesSettled(this.#threadKey(store.resourceId, store.threadId));
110026
110581
  }
110027
110582
  /**
110028
- * Keep a signal whose run closed before it was stored, in the process that
110029
- * started that run: as a pending row of the thread, then run the end-of-run
110030
- * check again, since the run's own check may have found nothing.
110583
+ * After a signal whose run closed first was kept as a pending row of the
110584
+ * thread (`#enqueueStoredSignal` with `keepWhenClosed`), in the process that
110585
+ * started that run: present it, then run the end-of-run check again, since
110586
+ * the run's own check may have found nothing.
110031
110587
  */
110032
- async #storeLeftoverSignal(state, pubsub, key, endedRun, signal, store) {
110033
- try {
110034
- await this.#enqueueStoredSignal(state, key, store, signal);
110035
- } catch (error) {
110036
- this.#forgetLocallyQueuedSignal(state, key, signal.id);
110037
- throw error;
110038
- }
110588
+ #announceLeftoverSignal(state, pubsub, key, endedRun, signal) {
110039
110589
  this.#publishPendingUserMessage(pubsub, key, endedRun.runId, signal, "pending");
110040
110590
  this.#drainPendingSignals(state, pubsub, key, endedRun, { freshLease: true });
110041
110591
  }
@@ -110046,15 +110596,15 @@ var AgentThreadStreamRuntime = class {
110046
110596
  * when the event arrives. Returns `false` when the store reports that run
110047
110597
  * closed.
110048
110598
  */
110049
- async #forwardSignal(state, pubsub, key, agent, runId, signal) {
110599
+ async #forwardSignal(state, pubsub, key, agent, runId, signal, queued = false) {
110050
110600
  const target = forwardedSignalRunId(runId);
110051
110601
  const store = await this.#runSignalsStore(state, agent, target, key);
110052
110602
  if (store) {
110053
110603
  if (await this.#enqueueStoredSignal(state, key, store, signal, {
110054
110604
  runId: target,
110055
110605
  agent
110056
- }) === "run-closed") return false;
110057
- this.#publishSignalAvailable(agent, target, signal.id);
110606
+ }, queued) === "run-closed") return false;
110607
+ if (!queued) this.#publishSignalAvailable(agent, target, signal.id);
110058
110608
  this.#recordLocallyQueuedSignal(state, key, signal.id);
110059
110609
  state.locallyQueuedSignalIdsByThread.get(key)?.set(signal.id, target);
110060
110610
  }
@@ -110063,8 +110613,11 @@ var AgentThreadStreamRuntime = class {
110063
110613
  runId,
110064
110614
  signal: this.#serializeSignal(signal),
110065
110615
  sourceId: this.#getSourceId(),
110066
- ...store ? { stored: true } : {}
110067
- }).catch(() => {});
110616
+ ...store ? { stored: true } : {},
110617
+ ...queued ? { queued: true } : {}
110618
+ }).catch((error) => {
110619
+ if (queued && !store) throw error;
110620
+ });
110068
110621
  return true;
110069
110622
  }
110070
110623
  /**
@@ -110079,6 +110632,26 @@ var AgentThreadStreamRuntime = class {
110079
110632
  return state.remoteAgentIdsByRunId.get(runId) === agent.id && state.storedSignals.isRemoteRunStored(runId) && maySignalsBeStored(agent) && agent.__hasFixedMemory?.() === true;
110080
110633
  }
110081
110634
  /**
110635
+ * Hand `signal` to `ownerRunId`, a run another process holds. Queued input must wait for that run to end, so it is
110636
+ * never a row the run would claim: for a storage-backed run it is stored as a queued row, otherwise it travels as a
110637
+ * marked event its holder queues, and a failed publish of that event rejects. Other input is stored for a
110638
+ * storage-backed run and published otherwise, ignoring publish failure. Answers false only when the storage-backed
110639
+ * run ended before it took the row.
110640
+ */
110641
+ async #forwardToOwner(state, pubsub, key, agent, ownerRunId, signal, queued) {
110642
+ const target = forwardedSignalRunId(ownerRunId);
110643
+ if (this.#mayStoreForRunHeldElsewhere(state, agent, target)) return this.#forwardSignal(state, pubsub, key, agent, ownerRunId, signal, queued);
110644
+ const published = this.#publishAndWait(pubsub, key, {
110645
+ type: "signal-enqueued",
110646
+ runId: ownerRunId,
110647
+ signal: this.#serializeSignal(signal),
110648
+ sourceId: this.#getSourceId(),
110649
+ ...queued ? { queued: true } : {}
110650
+ });
110651
+ await (queued ? published : published.catch(() => {}));
110652
+ return true;
110653
+ }
110654
+ /**
110082
110655
  * Where `runId` keeps its signals as far as this process knows: the
110083
110656
  * decision on its record here (none for a run only reserved here), or, for
110084
110657
  * a run another process holds that passes `#mayStoreForRunHeldElsewhere`,
@@ -110120,17 +110693,23 @@ var AgentThreadStreamRuntime = class {
110120
110693
  /**
110121
110694
  * Insert a signal as a pending row of the thread, behind this process's
110122
110695
  * earlier writes for it. With `to` the row is only inserted while that run
110123
- * is the thread's signal run, and a thread without a row rejects.
110696
+ * is the thread's signal run, and a thread without a row rejects. With
110697
+ * `keepWhenClosed`, a run that closed first leaves the signal as a pending
110698
+ * row for the thread's next turn, inserted in the same write: a cancel
110699
+ * handled after this call is ordered after that insert too, so it deletes
110700
+ * the row. The answer is still `run-closed`.
110124
110701
  */
110125
- #enqueueStoredSignal(state, key, storeRef, signal, to) {
110702
+ #enqueueStoredSignal(state, key, storeRef, signal, to, queued = false, keepWhenClosed = false) {
110126
110703
  return state.storedSignals.runWrite(key, async () => {
110127
110704
  const store = storeRef instanceof Promise ? await storeRef : storeRef;
110128
110705
  if (!store) throw new Error(`The memory storage that keeps the signals of ${describeThreadKey(key)} could not be resolved, so the signal was not stored`);
110129
- return this.#insertStoredSignal(state, key, store, signal, to);
110706
+ const written = await this.#insertStoredSignal(state, key, store, signal, to, queued);
110707
+ if (written === "run-closed" && keepWhenClosed) await this.#insertStoredSignal(state, key, store, signal);
110708
+ return written;
110130
110709
  });
110131
110710
  }
110132
110711
  /** The insert of `#enqueueStoredSignal`, for a caller already inside a write of the thread's stored signals. */
110133
- async #insertStoredSignal(state, key, store, signal, to) {
110712
+ async #insertStoredSignal(state, key, store, signal, to, queued = false) {
110134
110713
  const message = signal.toDBMessage({
110135
110714
  threadId: store.threadId,
110136
110715
  resourceId: store.resourceId
@@ -110138,7 +110717,8 @@ var AgentThreadStreamRuntime = class {
110138
110717
  const recordAccepted = state.storedSignals.stampNewRow(key, message);
110139
110718
  const written = await store.store.enqueuePendingSignal({
110140
110719
  message,
110141
- ...to ? { toRunId: to.runId } : {}
110720
+ ...to ? { toRunId: to.runId } : {},
110721
+ ...queued ? { queued: true } : {}
110142
110722
  });
110143
110723
  if (written === "thread-not-found") throw new Error(`Thread ${store.threadId} of resource ${store.resourceId} was not found in the memory storage of agent ${to?.agent.id}, so the signal was not stored`);
110144
110724
  if (written === "accepted") recordAccepted();
@@ -110354,18 +110934,29 @@ var AgentThreadStreamRuntime = class {
110354
110934
  }
110355
110935
  }
110356
110936
  continueRun(agent, output, streamOptions, pubsub, claim) {
110357
- const { threadId, resourceId } = this.#getThreadTarget(streamOptions);
110358
- if (!threadId) return false;
110359
110937
  const state = this.#getState(pubsub);
110360
110938
  this.#sweepStaleSuspendedRecords(state, pubsub);
110361
- const key = this.#threadKey(resourceId, threadId);
110362
110939
  const existing = state.threadRunsById.get(output.runId);
110940
+ const named = this.#getThreadTarget(streamOptions);
110941
+ const continuesOwnThread = !named.threadId && existing !== void 0 && (named.resourceId === void 0 || named.resourceId === existing.resourceId);
110942
+ const { threadId, resourceId } = continuesOwnThread ? existing : named;
110943
+ if (!threadId) return false;
110944
+ const key = this.#threadKey(resourceId, threadId);
110363
110945
  if (!existing?.continuation?.canContinue() || existing.agent !== agent || existing.threadId !== threadId || existing.resourceId !== resourceId || state.activeThreadRunIds.get(key) !== output.runId || state.activeThreadStreamIds.get(key) !== existing.streamId || output.status !== "running" && output.status !== "suspended" || existing.lifecycle === "completed" || existing.lifecycle === "failed" || existing.lifecycle === "aborted") return false;
110364
110946
  const resumedToolCallId = streamOptions.toolCallId;
110365
110947
  if (resumedToolCallId) this.#clearSuspendedToolCall(state, output.runId, resumedToolCallId);
110366
110948
  else this.#clearSuspendedRun(state, output.runId);
110367
110949
  existing.lifecycle = "running";
110368
- existing.streamOptions = streamOptions;
110950
+ const resumeOptions = keepRunAutoResume(streamOptions, existing.streamOptions);
110951
+ existing.streamOptions = continuesOwnThread ? {
110952
+ ...resumeOptions,
110953
+ memory: resumeMemoryOnOwnThread({
110954
+ run: existing.streamOptions.memory,
110955
+ resume: streamOptions.memory,
110956
+ threadId,
110957
+ resourceId
110958
+ })
110959
+ } : resumeOptions;
110369
110960
  existing.currentSegmentOutput = output;
110370
110961
  if (claim?.generation !== void 0) existing.generation = claim.generation;
110371
110962
  if (claim?.ownershipLost) existing.ownershipLost = claim.ownershipLost;
@@ -110444,7 +111035,8 @@ var AgentThreadStreamRuntime = class {
110444
111035
  sourceOutput: output,
110445
111036
  canContinue: broadcast.canContinueBroadcast,
110446
111037
  didPublishTerminal: broadcast.didPublishTerminal
110447
- } : void 0
111038
+ } : void 0,
111039
+ queuedInputElsewhere: state.threadRunsById.get(output.runId)?.queuedInputElsewhere
110448
111040
  };
110449
111041
  return {
110450
111042
  record,
@@ -110479,7 +111071,8 @@ var AgentThreadStreamRuntime = class {
110479
111071
  const state = this.#getState(pubsub);
110480
111072
  this.#sweepStaleSuspendedRecords(state, pubsub);
110481
111073
  const key = this.#threadKey(resourceId, threadId);
110482
- const { record, streamId, streamSeq, startBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput(state, agent, output, streamOptions, pubsub, threadId, resourceId, registrationOptions);
111074
+ const runOptions = keepRunAutoResume(streamOptions, state.threadRunsById.get(output.runId)?.streamOptions);
111075
+ const { record, streamId, streamSeq, startBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput(state, agent, output, runOptions, pubsub, threadId, resourceId, registrationOptions);
110483
111076
  const activeRunId = state.activeThreadRunIds.get(key);
110484
111077
  const takesLeaseFrom = activeRunId !== void 0 && activeRunId !== output.runId && state.threadKeysByRunId.get(activeRunId) === key && this.#isParkedRun(state, activeRunId) ? activeRunId : void 0;
110485
111078
  state.threadRunsById.set(output.runId, record);
@@ -110627,6 +111220,7 @@ var AgentThreadStreamRuntime = class {
110627
111220
  runId: record.runId,
110628
111221
  streamId: record.streamId
110629
111222
  });
111223
+ this.#startQueuedTurnAfterParkedRun(this.#getState(pubsub), pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110630
111224
  }
110631
111225
  #watchThreadRunCompletion(state, pubsub, key, record, registered, isDisabled) {
110632
111226
  if (state.watchedThreadStreamIds.has(record.streamId)) return;
@@ -110760,6 +111354,7 @@ var AgentThreadStreamRuntime = class {
110760
111354
  try {
110761
111355
  signal = state.signalQueues.takeNextPending(key);
110762
111356
  if (signal) {
111357
+ this.#recordStartedSignals(state, key, [signal]);
110763
111358
  nextRunId = globalThis.crypto.randomUUID();
110764
111359
  const reservedRunId = nextRunId;
110765
111360
  state.activeThreadRunIds.set(key, reservedRunId);
@@ -110789,6 +111384,7 @@ var AgentThreadStreamRuntime = class {
110789
111384
  state.threadKeysByRunId.delete(nextRunId);
110790
111385
  state.storedSignals.settlePreRunWaiters(nextRunId);
110791
111386
  state.signalQueues.discardPreRunQueue(key);
111387
+ this.#forgetStartedSignals(state, key, [signal]);
110792
111388
  if (owns.owner && !isRetakeLeaseOwner(owns.owner)) {
110793
111389
  const ownerRunId = threadLeaseRunId(owns.owner);
110794
111390
  const ids = state.locallyQueuedSignalIdsByThread.get(key);
@@ -110824,6 +111420,7 @@ var AgentThreadStreamRuntime = class {
110824
111420
  if (state.activeThreadRunIds.get(key) === nextRunId) state.activeThreadRunIds.delete(key);
110825
111421
  }
110826
111422
  state.signalQueues.restoreAfterFailedStart(key, draining?.cancelled ? void 0 : signal);
111423
+ if (signal) this.#forgetStartedSignals(state, key, [signal]);
110827
111424
  this.#publish(pubsub, key, {
110828
111425
  type: "run-failed",
110829
111426
  runId: failedRunId,
@@ -110867,7 +111464,11 @@ var AgentThreadStreamRuntime = class {
110867
111464
  * with its oldest pending row as input, else a queued continuation, else a
110868
111465
  * queued message, else release the lease. Rows are neither moved nor
110869
111466
  * deleted here: the follow-up's first model request claims every pending
110870
- * row of the thread.
111467
+ * row of the thread. A row still queued at this read, because the ended
111468
+ * run's close has not landed, is not delivered twice: saving the
111469
+ * follow-up's input under the row's id moves the row into the thread in
111470
+ * every store, and a follow-up that keeps its signals in storage counts the
111471
+ * id as consumed, so its claims never return it.
110871
111472
  *
110872
111473
  * `freshLease` is for a check that a late send triggered after the run's own
110873
111474
  * check: the ended run's lease may be gone, so it is acquired fresh, and
@@ -111066,7 +111667,10 @@ var AgentThreadStreamRuntime = class {
111066
111667
  const queue = state.pendingContinuationsByThread.get(key) ?? [];
111067
111668
  queue.push(pending);
111068
111669
  state.pendingContinuationsByThread.set(key, queue);
111069
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
111670
+ if (activeRecord) {
111671
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
111672
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, activeRecord).catch((error) => this.#logParkedRunReleaseFailure(activeRecord, error));
111673
+ }
111070
111674
  return {
111071
111675
  accepted: true,
111072
111676
  runId
@@ -111078,6 +111682,27 @@ var AgentThreadStreamRuntime = class {
111078
111682
  runId
111079
111683
  };
111080
111684
  }
111685
+ /**
111686
+ * Queued work waits for the thread's run to end (#32093), and a run parked with auto-resume on counts as ended
111687
+ * (#30190). Only the process executing a run knows how it parked, so a runtime holding queued work behind a parked
111688
+ * run it doesn't execute asks that run's holder to let go of the thread. A holder whose run counts as ended releases
111689
+ * it and announces `parked-run-released`, and this runtime starts its queued work as after the run's end. The work
111690
+ * stays queued here meanwhile, with its own agent, options and queue owner, so it can still be cancelled here.
111691
+ */
111692
+ #requestParkedRunReleaseElsewhere(state, pubsub, key, { executionChanged = false } = {}) {
111693
+ const runId = state.activeThreadRunIds.get(key);
111694
+ if (!runId) return;
111695
+ const record = state.threadRunsById.get(runId);
111696
+ if (record && record.registeredElsewhere === void 0) return;
111697
+ if (!executionChanged && !this.#isSuspendedRun(state, runId) && record?.lifecycle !== "suspended") return;
111698
+ if (!state.pendingIdleSignalsByThread.get(key)?.some((entry) => entry.queued)) return;
111699
+ this.#ensureThreadControlSubscription(state, pubsub, key);
111700
+ this.#publish(pubsub, key, {
111701
+ type: "queued-input-waiting",
111702
+ runId,
111703
+ sourceId: this.#getSourceId()
111704
+ });
111705
+ }
111081
111706
  async #drainPendingIdleSignals(state, pubsub, key, fromRunId) {
111082
111707
  if (state.activeThreadRunIds.has(key)) return false;
111083
111708
  const idleQueue = state.pendingIdleSignalsByThread.get(key);
@@ -111147,9 +111772,9 @@ var AgentThreadStreamRuntime = class {
111147
111772
  this.#watchForwardedIdleLease(state, pubsub, key);
111148
111773
  }
111149
111774
  this.#notifyThreadEvents(state);
111150
- if (ownerRunId && this.#mayStoreForRunHeldElsewhere(state, pendingIdle.agent, forwardedSignalRunId(ownerRunId))) {
111151
- if (!await this.#forwardSignal(state, pubsub, key, pendingIdle.agent, ownerRunId, pendingIdle.signal).catch((error) => {
111152
- pendingIdle.agent.__getLogger?.()?.warn?.("Could not store a queued message for the run holding its thread", {
111775
+ if (ownerRunId) {
111776
+ if (!await this.#forwardToOwner(state, pubsub, key, pendingIdle.agent, ownerRunId, pendingIdle.signal, pendingIdle.queued === true).catch((error) => {
111777
+ pendingIdle.agent.__getLogger?.()?.warn?.("Could not forward a queued message to the run holding its thread", {
111153
111778
  runId: ownerRunId,
111154
111779
  signalId: pendingIdle.signal.id,
111155
111780
  error
@@ -111161,12 +111786,7 @@ var AgentThreadStreamRuntime = class {
111161
111786
  this.#notifyThreadEvents(state);
111162
111787
  return true;
111163
111788
  }
111164
- } else if (ownerRunId) await this.#publishAndWait(pubsub, key, {
111165
- type: "signal-enqueued",
111166
- runId: ownerRunId,
111167
- signal: this.#serializeSignal(pendingIdle.signal),
111168
- sourceId: this.#getSourceId()
111169
- }).catch(() => {});
111789
+ }
111170
111790
  const drained = await this.#drainPendingIdleSignals(state, pubsub, key, owns.acquired ? pendingIdle.runId : fromRunId);
111171
111791
  if (owns.acquired && !drained) this.#releaseThreadLease(pubsub, key, pendingIdle.runId);
111172
111792
  return drained || owns.acquired;
@@ -111263,7 +111883,9 @@ var AgentThreadStreamRuntime = class {
111263
111883
  const record = state.threadRunsById.get(runId);
111264
111884
  const key = record ? this.#threadKey(record.resourceId, record.threadId) : state.threadKeysByRunId.get(runId);
111265
111885
  if (!key) return [];
111266
- return state.signalQueues.take(scope, key);
111886
+ const queue = state.signalQueues.take(scope, key);
111887
+ this.#recordStartedSignals(state, key, queue);
111888
+ return queue;
111267
111889
  }
111268
111890
  /**
111269
111891
  * Resolves `'reserved'` when this call reserved the thread for `runId`; the
@@ -111985,6 +112607,7 @@ var AgentThreadStreamRuntime = class {
111985
112607
  state.suspendedRunIds.add(data.runId);
111986
112608
  const record = state.threadRunsByStreamId.get(eventStreamId) ?? state.threadRunsById.get(data.runId);
111987
112609
  if (record) record.lifecycle = "suspended";
112610
+ this.#requestParkedRunReleaseElsewhere(state, resolvedPubSub, key);
111988
112611
  } else clearActiveIfCurrent(data.runId, data.streamId);
111989
112612
  if (data.type !== "run-suspended" || suspendedRunEnded) this.#clearSuspendedRun(state, data.runId);
111990
112613
  const remoteRun = remoteRuns.get(eventStreamId);
@@ -112610,13 +113233,18 @@ var AgentThreadStreamRuntime = class {
112610
113233
  resourceId,
112611
113234
  threadId,
112612
113235
  streamOptions: queuedStreamOptions,
112613
- queueOwnerId: target.queueOwnerId
113236
+ queueOwnerId: target.queueOwnerId,
113237
+ queued: true
112614
113238
  });
112615
113239
  state.pendingIdleSignalsByThread.set(key, idleQueue);
112616
113240
  const control = this.#ensureThreadControlSubscription(state, pubsub, key);
112617
113241
  this.#publishPendingUserMessage(pubsub, key, runId ?? queuedRunId, queuedSignal, "queued");
112618
113242
  this.#notifyThreadEvents(state);
112619
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
113243
+ if (activeRecord) {
113244
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
113245
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, activeRecord);
113246
+ }
113247
+ this.#requestParkedRunReleaseElsewhere(state, pubsub, key);
112620
113248
  return {
112621
113249
  signal: queuedSignal,
112622
113250
  accepted: control.ready.then(() => ({
@@ -112955,7 +113583,8 @@ var AgentThreadStreamRuntime = class {
112955
113583
  runId,
112956
113584
  resourceId,
112957
113585
  threadId,
112958
- streamOptions: target.ifIdle?.streamOptions
113586
+ streamOptions: target.ifIdle?.streamOptions,
113587
+ ...waitForIdle ? { queued: true } : {}
112959
113588
  });
112960
113589
  state.pendingIdleSignalsByThread.set(key, idleQueue);
112961
113590
  if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
@@ -113073,18 +113702,11 @@ var AgentThreadStreamRuntime = class {
113073
113702
  reason: "scope-mismatch",
113074
113703
  runId: winnerRunId
113075
113704
  };
113076
- if (winnerRunId && this.#mayStoreForRunHeldElsewhere(state, agent, forwardedSignalRunId(winnerRunId))) {
113077
- if (!await this.#forwardSignal(state, pubsub, reservedKey, agent, winnerRunId, signal)) return {
113078
- action: "blocked",
113079
- reason: "thread-blocked",
113080
- runId: winnerRunId
113081
- };
113082
- } else if (winnerRunId) await this.#publishAndWait(pubsub, reservedKey, {
113083
- type: "signal-enqueued",
113084
- runId: winnerRunId,
113085
- signal: this.#serializeSignal(signal),
113086
- sourceId: this.#getSourceId()
113087
- }).catch(() => {});
113705
+ if (winnerRunId && !await this.#forwardToOwner(state, pubsub, reservedKey, agent, winnerRunId, signal, waitForIdle)) return {
113706
+ action: "blocked",
113707
+ reason: "thread-blocked",
113708
+ runId: winnerRunId
113709
+ };
113088
113710
  return {
113089
113711
  action: "deliver",
113090
113712
  runId: winnerRunId ?? reservedRunId