@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 @@ import { a as RegisteredLogger, t as ConsoleLogger, u as noopLogger } from "./lo
3
3
  import { t as MastraBase } from "./base-CKLWBhDo.js";
4
4
  import { a as MastraNonRetryableError, i as MastraError, n as ErrorDomain, o as getErrorFromUnknown, t as ErrorCategory } from "./error-oh2DLsP2.js";
5
5
  import { a as classifyProviderError, l as describeProviderError, t as recordTerminalErrorMessage, u as readProviderErrorDetails } from "./error-BC9Au-22.js";
6
- import { S as isLeaseProvider, _ as PublisherQueueLimitError, b as NoopLeaseProvider, d as isRunLocalTopic, g as stripModelSnapshots, i as CachingPubSub, m as slimNestedAgentChunks, r as serializeError$1, t as DefaultStepResult, v as EventEmitterPubSub, y as withAck } from "./output-helpers-k2-48ssH.js";
7
- import { $ as summarizeToolChoiceForSpan, $t as commitToolResult, A as isSignalChunkExcluded, An as isMastraTimeoutError, At as getSnapshotMemoryInfo, B as removeTrailingAssistantGuardContinuations, Bt as stateColumnsWrite, C as stampChunkProducedAt, Cn as DEADLINE_SAVE_CLAIM_HOLD_MS, D as isStructuredOutputError, Dn as getAbortReason, Dt as validateTemplate, E as escapeUnescapedControlCharsInJsonStrings, En as createTimeoutAbortSignal, Et as traverseMappingPath, F as endOutputStreamSpanOutsideStep, Fn as safeClose, Ft as latestStepResults, G as FLUSH_HELD_PARTS_KEY, Gt as diffStateAsJson, Ht as unusedStateEntries, I as findOwnModelStepSpan, In as safeEnqueue, It as materializeState, J as withoutHeldContent, K as REPROCESS_PART_KEY, Kt as patchState, Ln as safeError, Lt as materializeWorkflowRun, M as ProcessorRunner, Mn as settledOrElapsed, N as ProcessorState, Nt as applyStateColumnsWrite, O as asJsonSchema, On as guardStreamUntilMatch, Ot as getStepResult, P as endOutputStreamSpanAtStepEnd, Pn as MastraModelInput, Pt as isStateCheckpointDue, Q as summarizeProcessorToolsForSpan, R as isTrailingAssistantGuardContinuation, Rn as createRunScope, Rt as pickStateKeys, S as getChunkProducedAt, Sn as takenQueueThreadId, St as stepRefId, T as createOutputHandler, Tn as MastraTimeoutError, Tt as templateReadsState, Ut as applyStatePatch, V as ProviderHistoryCompat, Vt as summarizeStepResult, X as summarizeProcessorModelForSpan, Y as summarizeActiveToolsForSpan, Yt as isObservationalMemoryEnabled$1, Z as summarizeProcessorResultForSpan, Zt as parseMemoryRequestContext, _ as persistProcessorDataChunk, _t as stubStepResult, a as convertFullStreamChunkToMastra, an as snapshotToolResult, at as PROCESSOR_ABORT_SIGNAL, b as resolveOutputMessageSkippingCompletionChecks, bn as pendingQueueThreadId, bt as predicateReadsState, c as WorkflowRunOutput, cn as validationErrorModelOutput, ct as getHydratedStepResult, d as MastraModelOutput, dn as resolveSuspendedToolRunId, dt as lazyStepResults, en as computeModelOutputProviderMetadata, et as resolveProcessorSpanAttributes, f as clearStepPartIndexes, fn as resolveThreadIdFromArgs, ft as loadStepResults, g as isFeedbackContinuation, gn as applyStateSignal, gt as storageV2StepResultAccessors, h as findStepPartBoundaries, hn as tryStreamWithJsonFallback, ht as residentStepResultsLoader, in as resolveModelOutputAfterToolResultProcessors, it as createProcessorSendSignal, j as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, jn as raceAgainstAbort, k as getResponseFormat, kn as guardStreamWithAbort, kt as getStepResultAsync, l as TripWire, ln as isProcessorWorkflow, lt as hydrateStepResults, m as findIterationOffsetInParts, mn as tryGenerateWithJsonFallback, mt as residentStepResults, nn as latestProcessedModelOutput, nt as toProcessorSpanPhase, on as withAgentWorkflowToolMarker, ot as RunJournal, p as createDestructurableOutput, pn as supportedLanguageModelSpecifications, pt as loadedStepResults, q as takeHeldParts, rn as readModelOutput, rt as PROCESSOR_LATE_SIGNAL_SINK, s as MastraAgentNetworkStream, sn as normalizeModelOutput, st as buildStepResultAccessors, tn as hasToolResultProcessor, tt as resolveProcessorSpanName, u as getModelOutputForTripwire, un as isSupportedLanguageModel, ut as isStepResultStub, v as reconcileBufferedStepTexts, vn as assertNotQueueThreadId, vt as collectMappingStepRefs, w as markChunkOutputProcessed, wn as DEADLINE_SAVE_WAIT_MS, wt as resolveTemplate, x as resolveProcessorWriterMessageId, xn as queuedQueueThreadId, xt as resolveStepOutputs, y as resolveMessageText, yn as isQueueThreadId, yt as collectPredicateStepRefs, z as needsTrailingAssistantGuard, zn as createRunScopeKey, zt as stateBaseOf } from "./stream-D2rv1Ut1.js";
6
+ import { S as isLeaseProvider, _ as stripModelSnapshots, a as CachingPubSub, b as NoopLeaseProvider, f as isRunLocalTopic, h as slimNestedAgentChunks, i as PublisherQueueLimitError, r as serializeError$1, t as DefaultStepResult, v as EventEmitterPubSub, y as withAck } from "./output-helpers-D-qplq22.js";
7
+ import { $ as summarizeToolChoiceForSpan, $t as commitToolResult, A as isSignalChunkExcluded, An as isMastraTimeoutError, At as getSnapshotMemoryInfo, B as removeTrailingAssistantGuardContinuations, Bt as stateColumnsWrite, C as stampChunkProducedAt, Cn as DEADLINE_SAVE_CLAIM_HOLD_MS, D as isStructuredOutputError, Dn as getAbortReason, Dt as validateTemplate, E as escapeUnescapedControlCharsInJsonStrings, En as createTimeoutAbortSignal, Et as traverseMappingPath, F as endOutputStreamSpanOutsideStep, Fn as safeClose, Ft as latestStepResults, G as FLUSH_HELD_PARTS_KEY, Gt as diffStateAsJson, Ht as unusedStateEntries, I as findOwnModelStepSpan, In as safeEnqueue, It as materializeState, J as withoutHeldContent, K as REPROCESS_PART_KEY, Kt as patchState, Ln as safeError, Lt as materializeWorkflowRun, M as ProcessorRunner, Mn as settledOrElapsed, N as ProcessorState, Nt as applyStateColumnsWrite, O as asJsonSchema, On as guardStreamUntilMatch, Ot as getStepResult, P as endOutputStreamSpanAtStepEnd, Pn as MastraModelInput, Pt as isStateCheckpointDue, Q as summarizeProcessorToolsForSpan, R as isTrailingAssistantGuardContinuation, Rn as createRunScope, Rt as pickStateKeys, S as getChunkProducedAt, Sn as takenQueueThreadId, St as stepRefId, T as createOutputHandler, Tn as MastraTimeoutError, Tt as templateReadsState, Ut as applyStatePatch, V as ProviderHistoryCompat, Vt as summarizeStepResult, X as summarizeProcessorModelForSpan, Y as summarizeActiveToolsForSpan, Yt as isObservationalMemoryEnabled$1, Z as summarizeProcessorResultForSpan, Zt as parseMemoryRequestContext, _ as persistProcessorDataChunk, _t as stubStepResult, a as convertFullStreamChunkToMastra, an as snapshotToolResult, at as PROCESSOR_ABORT_SIGNAL, b as resolveOutputMessageSkippingCompletionChecks, bn as pendingQueueThreadId, bt as predicateReadsState, c as WorkflowRunOutput, cn as validationErrorModelOutput, ct as getHydratedStepResult, d as MastraModelOutput, dn as resolveSuspendedToolRunId, dt as lazyStepResults, en as computeModelOutputProviderMetadata, et as resolveProcessorSpanAttributes, f as clearStepPartIndexes, fn as resolveThreadIdFromArgs, ft as loadStepResults, g as isFeedbackContinuation, gn as applyStateSignal, gt as storageV2StepResultAccessors, h as findStepPartBoundaries, hn as tryStreamWithJsonFallback, ht as residentStepResultsLoader, in as resolveModelOutputAfterToolResultProcessors, it as createProcessorSendSignal, j as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, jn as raceAgainstAbort, k as getResponseFormat, kn as guardStreamWithAbort, kt as getStepResultAsync, l as TripWire, ln as isProcessorWorkflow, lt as hydrateStepResults, m as findIterationOffsetInParts, mn as tryGenerateWithJsonFallback, mt as residentStepResults, nn as latestProcessedModelOutput, nt as toProcessorSpanPhase, on as withAgentWorkflowToolMarker, ot as RunJournal, p as createDestructurableOutput, pn as supportedLanguageModelSpecifications, pt as loadedStepResults, q as takeHeldParts, rn as readModelOutput, rt as PROCESSOR_LATE_SIGNAL_SINK, s as MastraAgentNetworkStream, sn as normalizeModelOutput, st as buildStepResultAccessors, tn as hasToolResultProcessor, tt as resolveProcessorSpanName, u as getModelOutputForTripwire, un as isSupportedLanguageModel, ut as isStepResultStub, v as reconcileBufferedStepTexts, vn as assertNotQueueThreadId, vt as collectMappingStepRefs, w as markChunkOutputProcessed, wn as DEADLINE_SAVE_WAIT_MS, wt as resolveTemplate, x as resolveProcessorWriterMessageId, xn as queuedQueueThreadId, xt as resolveStepOutputs, y as resolveMessageText, yn as isQueueThreadId, yt as collectPredicateStepRefs, z as needsTrailingAssistantGuard, zn as createRunScopeKey, zt as stateBaseOf } from "./stream-H_wVxqdK.js";
8
8
  import { HAND_BACK_STATE_SYMBOL, PARENT_STATE_SYMBOL, PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL, WORKFLOW_CANCELLED_SYMBOL } from "./workflows/constants.js";
9
9
  import { c as MASTRA_THREAD_ID_KEY, d as isReservedRequestContextKey, f as mergeVersionOverrides$1, l as MASTRA_VERSIONS_KEY, n as MASTRA_AUTH_TOKEN_KEY, o as MASTRA_RESOURCE_ID_KEY, p as withoutLiveRequestKeys, r as MASTRA_INHERITED_MEMORY_KEY, s as MASTRA_SCOPES_KEY, t as MASTRA_CONTINUATION_TOOL_CALL_IDS_KEY, u as RequestContext } from "./request-context-COnZHt2-.js";
10
10
  import { _ as resolveObservabilityContext, a as agentLoopTermination, c as compactStopReasonContext, g as createObservabilityContext, h as wrapMastra, i as subtractReportedUsage, m as unwrapMastraTracingProxy, n as extractUsageMetrics, o as executionFailureTermination, r as isUsageIncomplete, s as tripwireTermination, t as calculateObservedUsage } from "./observability-DPDWibyH.js";
@@ -13,9 +13,9 @@ import { a as getOrCreateSpan, f as resolveCurrentSpan, l as getTimeToFirstChunk
13
13
  import { _ as getRequestContextInputValues, a as getModelFacingValidationError, d as validateToolOutput, g as getRequestContextInputSource, l as resolveToolOutputValidationSchema, r as createTool, u as validateToolInput } from "./tool-DIFduuTw.js";
14
14
  import { isStandardSchemaWithJSON, standardSchemaToJSONSchema, toStandardSchema } from "./schema/index.js";
15
15
  import { i as setSpanErrorOrigin, n as getSpanErrorOrigin } from "./error-count-BH-rJW7q.js";
16
- import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-DLnCt6E9.js";
16
+ import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-h5k_ChdS.js";
17
17
  import { h as getWorkflowFGAResourceId, i as MastraFGAPermissions, y as requireFGA } from "./ee-iTj2bRDt-By_B9ngH.js";
18
- import { c as createBackgroundTask, o as resolveBackgroundConfig, s as sanitizeToolArguments, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-HAzB0JtC.js";
18
+ import { c as createBackgroundTask, o as resolveBackgroundConfig, s as sanitizeToolArguments, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-B7UygDdO.js";
19
19
  import { a as isApprovalExempt, c as isProviderDefinedTool, d as markAgentWorkflowTool, f as markApprovalExempt, l as isProviderTool, n as getNeedsApprovalFn, o as isBuiltBeforeApproval, r as getProviderToolName, s as isMastraTool, t as getBeforeApprovalFn } from "./toolchecks-CRAfUe9H.js";
20
20
  import { t as ToolStream } from "./stream-D9JOykz7.js";
21
21
  import { a as waitDelay, i as getRetryAfterMs, n as DEFAULT_MAX_RETRY_AFTER_MS, r as clampDelayMs } from "./fetchWithRetry-DFSvpYDT.js";
@@ -23,16 +23,16 @@ import { boundedStringify, ensureSerializable, safeStringify } from "./utils/saf
23
23
  import { t as deepEqual$3 } from "./deep-equal-d1xU02ag.js";
24
24
  import { n as resolveDynamicArgument, t as getRequestUser } from "./dynamic-argument-BzPK3qPN.js";
25
25
  import { A as stableStringify$1, E as removeWorkingMemoryTags, P as embed$3, Z as preserveResponseItemIdsOnMerge, a as isTerminalToolInvocationState, c as withUnavailableAttachmentUrls, d as aiV5UIMessagesToAIV5ModelMessages, f as coreContentToString, i as isClientToolInvocationUpdate, l as isDownloadAssetsError, m as filterMessagesForPersistence, n as MessageList, ot as normalizeToolOutput, p as messagesAreEqual, r as advancesToolInvocationState, s as unavailableAttachmentPlaceholder, t as convertMessages, u as MessageMerger } from "./message-list-RgFlLrxG.js";
26
- import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-ccA_1Q-H.js";
26
+ import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-YNjDFSui.js";
27
27
  import { a as withToolPayloadTransformMetadata, i as transformToolPayloadForTargets, n as hasTransformedToolPayload, o as withToolPayloadTransformProviderMetadata, r as normalizeToolPayloadTransformPolicy, t as getTransformedToolPayload } from "./payload-transform-Dj3HUeD4.js";
28
28
  import { d as signalSpanAttributes, h as signalToXmlMarkup, l as mastraDBMessageToSignal, n as createSignal, o as isMastraSignalMessage, s as isTransientSignalMessage, u as resolveDeliveryAttributes } from "./signals-CqR_iWkg.js";
29
29
  import { h as resolveFilePartMediaTypeAndData, m as parseDataUri, o as categorizeFileData } from "./to-prompt-CMlVGYxC.js";
30
30
  import { c as parsePartialJson, h as tool$1, m as generateId$1, p as asSchema$1, r as embed$4, u as APICallError$1 } from "./dist-TPVqg8oV.js";
31
31
  import { n as embed$5 } from "./dist-D3cKCUe-.js";
32
32
  import { i as hasFreeFormObject } from "./model-DS-b2R-R.js";
33
- import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-BvbEoScB.js";
33
+ import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-C_XQJvu2.js";
34
34
  import { t as InMemoryServerCache } from "./inmemory-BK3zLwvM.js";
35
- import { t as MastraLLMV1 } from "./model-BwxfS6T_.js";
35
+ import { t as MastraLLMV1 } from "./model-cS3d5rmF.js";
36
36
  import { MISSING, collectInvalidPredicatePaths, createPredicateEvaluator, derivePredicateLabel, normalizePredicatePath, walk } from "./predicate/index.js";
37
37
  import { Classifier } from "./classifier/index.js";
38
38
  import { initContextStorage, withSpanErrorAttempt } from "./observability/context-storage.js";
@@ -58,6 +58,7 @@ import { n as InMemorySkillsStorage, t as FilesystemSkillsStorage } from "./file
58
58
  import { n as InMemoryWorkspacesStorage, t as FilesystemWorkspacesStorage } from "./filesystem-BhYgU8qg.js";
59
59
  import { n as resolveAgentSkills, t as mergeWorkspaceSkills } from "./agent-skills-resolver-D2HktP6Y.js";
60
60
  import { n as DefaultVoice } from "./voice-OS-kmlEA.js";
61
+ import { TTLCache } from "@isaacs/ttlcache";
61
62
  import { any, array, boolean, custom, discriminatedUnion, enum as enum$1, instanceof as instanceof$1, json, lazy, literal, looseObject, never, null as null$1, number, object, record, safeParseAsync, string, union, unknown, z } from "zod/v4";
62
63
  import { createHash, randomUUID } from "crypto";
63
64
  import { jsonSchemaToZod } from "@mastra/schema-compat/json-to-zod";
@@ -70,7 +71,6 @@ import { config, toJSONSchema } from "zod/v4/core";
70
71
  import en from "zod/v4/locales/en.js";
71
72
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
72
73
  import { dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep, win32 } from "path";
73
- import { TTLCache } from "@isaacs/ttlcache";
74
74
  import { AsyncLocalStorage } from "async_hooks";
75
75
  import fastq from "fastq";
76
76
  import { readFile, realpath, stat } from "fs/promises";
@@ -502,6 +502,11 @@ const MASTRA_DURABLE_EXECUTIONS_KEY = "mastra__durableExecutions";
502
502
  */
503
503
  const MASTRA_DURABLE_SEGMENTS_KEY = "mastra__durableSegments";
504
504
  /**
505
+ * Reserved request-context key carrying `Record<runId, boolean>`: the `autoResumeSuspendedTools` a resumed execution
506
+ * runs with, so a step that suspends persists it on whichever worker runs the step. (#30190)
507
+ */
508
+ const MASTRA_DURABLE_AUTO_RESUME_KEY = "mastra__durableAutoResume";
509
+ /**
505
510
  * JSON-safe snapshot of `requestContext.entries()`, for a run that continues
506
511
  * somewhere the live context can't follow: a durable step, or a claimed
507
512
  * thread owner in another process. Best-effort: entries that fail a JSON
@@ -519,6 +524,7 @@ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
519
524
  if (key === "mastra__versions") continue;
520
525
  if (key === "mastra__durableExecutions") continue;
521
526
  if (key === "mastra__durableSegments") continue;
527
+ if (key === "mastra__durableAutoResume") continue;
522
528
  if (key === "__mastra_chat_channel_render") continue;
523
529
  const json = boundedStringify(value);
524
530
  if (json === void 0) {
@@ -12321,6 +12327,15 @@ var EventedExecutionEngine = class extends ExecutionEngine {
12321
12327
  const DOCS_URL = "https://mastra.ai/docs/server/pubsub#evented-workflows-and-agents";
12322
12328
  const warnedHosts = /* @__PURE__ */ new WeakSet();
12323
12329
  const warnedSignalHosts = /* @__PURE__ */ new WeakSet();
12330
+ const warnedCacheHosts = /* @__PURE__ */ new WeakSet();
12331
+ /**
12332
+ * Whether each process keeps its own copy of the run logs `cache` holds while
12333
+ * `pubsub` carries the runs to other processes. Only `InMemoryServerCache` is
12334
+ * known to be process-local; any other cache is assumed to be shared.
12335
+ */
12336
+ function keepsRunLogsInProcess(pubsub, cache) {
12337
+ return cache instanceof InMemoryServerCache && reachesOtherProcesses(pubsub);
12338
+ }
12324
12339
  /**
12325
12340
  * Evented runs spread over several processes need a pubsub that hands a stopped
12326
12341
  * worker's event to another worker, and a store whose step guards let one
@@ -12366,6 +12381,26 @@ function warnUnsharedAgentSignals(mastra, reason) {
12366
12381
  warnedSignalHosts.add(mastra);
12367
12382
  mastra.getLogger()?.warn(`Signals sent to running evented agents aren't supported on several processes with this setup: ${missing}. See ${DOCS_URL}`);
12368
12383
  }
12384
+ /**
12385
+ * An evented agent's steps append their stream frames to the run's log in the
12386
+ * server cache, which also holds the run's ownership record. With a cache each
12387
+ * process keeps to itself, a step in another process publishes its frames
12388
+ * unnumbered, so `observe(runId, { offset })` can't skip them, and another
12389
+ * process can't observe or stop the run. Logs once per Mastra instance, apart
12390
+ * from {@link warnUnsupportedEventedSetup} so that one does not hide this.
12391
+ *
12392
+ * Called when an evented agent is registered, in every process that can run
12393
+ * its steps, including dedicated workers that never start a run.
12394
+ */
12395
+ function warnProcessLocalServerCache(mastra) {
12396
+ if (warnedCacheHosts.has(mastra) || process.env.MASTRA_DISABLE_EVENTED_SETUP_WARNING === "true") return;
12397
+ const pubsub = mastra.pubsub;
12398
+ const wrapped = pubsub instanceof CachingPubSub;
12399
+ if (!keepsRunLogsInProcess(pubsub, wrapped ? pubsub.getCache() : mastra.serverCache)) return;
12400
+ 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`;
12401
+ warnedCacheHosts.add(mastra);
12402
+ mastra.getLogger()?.warn(`Evented agents aren't supported on several processes with this setup: ${problem}, such as RedisServerCache. See ${DOCS_URL}`);
12403
+ }
12369
12404
  // src/storage/workflow-step-guard.ts
12370
12405
  var WorkflowStepConflictError = class extends Error {
12371
12406
  reason;
@@ -12571,6 +12606,23 @@ function carrySegmentSpans(target, runId, segment) {
12571
12606
  else target[MASTRA_DURABLE_SEGMENTS_KEY] = next;
12572
12607
  }
12573
12608
  /**
12609
+ * Record the `autoResumeSuspendedTools` a resumed execution of `runId` runs with on the request context it hands the
12610
+ * engine, which carries it to every step of the segment wherever it runs. (#30190)
12611
+ */
12612
+ function carrySegmentAutoResume(requestContext, runId, value) {
12613
+ const current = requestContext.getRaw(MASTRA_DURABLE_AUTO_RESUME_KEY);
12614
+ requestContext.setRaw(MASTRA_DURABLE_AUTO_RESUME_KEY, {
12615
+ ...current && typeof current === "object" ? current : {},
12616
+ [runId]: value
12617
+ });
12618
+ }
12619
+ /** The `autoResumeSuspendedTools` a resume carried for the current execution of `runId`, if any. */
12620
+ function segmentAutoResume(requestContext, runId) {
12621
+ const all = requestContext?.getRaw?.(MASTRA_DURABLE_AUTO_RESUME_KEY);
12622
+ const value = all && typeof all === "object" ? all[runId] : void 0;
12623
+ return typeof value === "boolean" ? value : void 0;
12624
+ }
12625
+ /**
12574
12626
  * The pair the current execution reports under: the one a resume or recovery carried for `runId`,
12575
12627
  * else the run's first pair from `state` (the workflow input or the loop state). A carried `null`
12576
12628
  * means the execution opened no spans, so its steps end none. `carried` tells the two apart.
@@ -14462,7 +14514,7 @@ function closeStoredSignalRun({ mastra, runId, input, requestContext, state, dea
14462
14514
  agentId: input?.agentId,
14463
14515
  threadId: input?.state?.threadId
14464
14516
  });
14465
- return;
14517
+ return false;
14466
14518
  }
14467
14519
  const saved = typeof state === "function" ? await state() : state;
14468
14520
  await queue.store.closeSignalRun({
@@ -14470,11 +14522,13 @@ function closeStoredSignalRun({ mastra, runId, input, requestContext, state, dea
14470
14522
  runId,
14471
14523
  consumedIds: readConsumedSignalIds(saved)
14472
14524
  });
14525
+ return true;
14473
14526
  } catch (error) {
14474
14527
  mastra?.getLogger?.()?.warn?.("Could not close the stored signals of an ended run", {
14475
14528
  runId,
14476
14529
  error
14477
14530
  });
14531
+ return false;
14478
14532
  }
14479
14533
  })();
14480
14534
  }
@@ -15768,7 +15822,7 @@ function createDurableAgentStream(options) {
15768
15822
  armIdleTimer();
15769
15823
  resolveReady();
15770
15824
  releaseTerminalSubscription();
15771
- }).catch((error) => {
15825
+ }).catch(async (error) => {
15772
15826
  pubsub.unsubscribe(topic, subscribedCallback).catch((unsubscribeError) => {
15773
15827
  logError(`[DurableAgentStream] Failed to unsubscribe from ${topic}:`, unsubscribeError);
15774
15828
  });
@@ -15778,6 +15832,11 @@ function createDurableAgentStream(options) {
15778
15832
  markTerminated();
15779
15833
  if ((ctrl.desiredSize ?? 0) > 0) safeError(ctrl, error);
15780
15834
  else pendingRejection = error;
15835
+ try {
15836
+ await onError?.({ error });
15837
+ } catch (callbackError) {
15838
+ logError(`[DurableAgentStream] onError callback error:`, callbackError);
15839
+ }
15781
15840
  });
15782
15841
  },
15783
15842
  pull(ctrl) {
@@ -16318,7 +16377,6 @@ function scopedRunStorage(runId, runStorage) {
16318
16377
  var StepExecutor = class extends MastraBase {
16319
16378
  mastra;
16320
16379
  #stepPubsub;
16321
- #warnedUnnumbered = false;
16322
16380
  constructor({ mastra }) {
16323
16381
  super({
16324
16382
  name: "StepExecutor",
@@ -16351,31 +16409,24 @@ var StepExecutor = class extends MastraBase {
16351
16409
  * numbering the same run from 0 in its own cache would have observers drop
16352
16410
  * its frames as late duplicates. So with a process-local cache behind a
16353
16411
  * cross-process transport, steps only append to logs this process already
16354
- * holds — the caller writes the run's `start` frame before any step runs, so
16412
+ * holds. The caller writes the run's `start` frame before any step runs, so
16355
16413
  * steps in the caller's process are numbered (#28324) and steps on other
16356
- * workers publish unnumbered (live-only).
16414
+ * workers publish unnumbered (live-only). Mastra warns about that setup when
16415
+ * the evented agent is registered (`warnProcessLocalServerCache`).
16357
16416
  */
16358
16417
  #getStepPubsub() {
16359
16418
  if (this.#stepPubsub) return this.#stepPubsub;
16360
16419
  const inner = this.mastra.pubsub;
16361
16420
  const cache = this.mastra?.serverCache;
16362
16421
  if (inner instanceof CachingPubSub) this.#stepPubsub = inner;
16363
- else if (cache) {
16364
- const processLocalLogs = cache instanceof InMemoryServerCache && reachesOtherProcesses(inner);
16365
- this.#stepPubsub = new CachingPubSub(inner, cache, {
16366
- shouldCache: (topic) => !isRunLocalTopic(topic),
16367
- extendExistingLogsOnly: processLocalLogs,
16368
- onUnlogged: (topic) => this.#warnUnnumberedAgentStream(topic),
16369
- logger: this.logger
16370
- });
16371
- } else this.#stepPubsub = inner;
16422
+ else if (cache) this.#stepPubsub = new CachingPubSub(inner, cache, {
16423
+ shouldCache: (topic) => !isRunLocalTopic(topic),
16424
+ extendExistingLogsOnly: keepsRunLogsInProcess(inner, cache),
16425
+ logger: this.logger
16426
+ });
16427
+ else this.#stepPubsub = inner;
16372
16428
  return this.#stepPubsub;
16373
16429
  }
16374
- #warnUnnumberedAgentStream(topic) {
16375
- if (this.#warnedUnnumbered || !topic.startsWith(AGENT_STREAM_TOPIC(""))) return;
16376
- this.#warnedUnnumbered = true;
16377
- 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 });
16378
- }
16379
16430
  /**
16380
16431
  * Creates an output writer function that publishes chunks to the workflow event stream.
16381
16432
  * @param runId - The workflow run ID
@@ -25015,7 +25066,7 @@ const RETRYABLE_FAILURE_KINDS = /* @__PURE__ */ new Set([
25015
25066
  const ACCOUNT_REFUSALS = /* @__PURE__ */ new Set(["auth", "quota"]);
25016
25067
  const OPENAI_RETRY_MESSAGE_PATTERN = /you can retry your request/i;
25017
25068
  const DEFAULT_MATCHERS = [isRetryableOpenAIResponsesStreamError];
25018
- function isRecord$7(value) {
25069
+ function isRecord$8(value) {
25019
25070
  return typeof value === "object" && value !== null;
25020
25071
  }
25021
25072
  function getStringProperty(value, key) {
@@ -25024,15 +25075,15 @@ function getStringProperty(value, key) {
25024
25075
  }
25025
25076
  function getObjectCause(error) {
25026
25077
  if (error instanceof Error) return error.cause;
25027
- if (!isRecord$7(error)) return;
25078
+ if (!isRecord$8(error)) return;
25028
25079
  return error.cause;
25029
25080
  }
25030
25081
  function getOpenAIErrorPayload(error) {
25031
- if (!isRecord$7(error)) return;
25032
- if (error.type === "error" && isRecord$7(error.error)) return error.error;
25033
- if (error.type === "response.failed" && isRecord$7(error.response)) {
25082
+ if (!isRecord$8(error)) return;
25083
+ if (error.type === "error" && isRecord$8(error.error)) return error.error;
25084
+ if (error.type === "response.failed" && isRecord$8(error.response)) {
25034
25085
  const responseError = error.response.error;
25035
- return isRecord$7(responseError) ? responseError : void 0;
25086
+ return isRecord$8(responseError) ? responseError : void 0;
25036
25087
  }
25037
25088
  }
25038
25089
  function hasExplicitRetryMessage(payload) {
@@ -25064,12 +25115,12 @@ function isBadRequestError(error) {
25064
25115
  return false;
25065
25116
  }
25066
25117
  function isRetryableProviderMetadata(error) {
25067
- return (APICallError$1.isInstance(error) ? error.isRetryable : isRecord$7(error) && typeof error.isRetryable === "boolean" ? error.isRetryable : void 0) === true;
25118
+ return (APICallError$1.isInstance(error) ? error.isRetryable : isRecord$8(error) && typeof error.isRetryable === "boolean" ? error.isRetryable : void 0) === true;
25068
25119
  }
25069
25120
  function hasDeniedHttpStatus(error) {
25070
25121
  const visited = /* @__PURE__ */ new WeakSet();
25071
25122
  function visit(candidate) {
25072
- if (!isRecord$7(candidate) || visited.has(candidate)) return false;
25123
+ if (!isRecord$8(candidate) || visited.has(candidate)) return false;
25073
25124
  visited.add(candidate);
25074
25125
  if (candidate.status === 401 || candidate.status === 403) return true;
25075
25126
  return visit(candidate.error) || visit(candidate.data) || visit(candidate.cause);
@@ -25091,7 +25142,7 @@ function normalizeEntry(entry) {
25091
25142
  function findMatchingPolicy(error, entries) {
25092
25143
  const visited = /* @__PURE__ */ new WeakSet();
25093
25144
  function visit(candidate) {
25094
- if (isRecord$7(candidate)) {
25145
+ if (isRecord$8(candidate)) {
25095
25146
  if (visited.has(candidate)) return void 0;
25096
25147
  visited.add(candidate);
25097
25148
  }
@@ -30714,7 +30765,7 @@ async function localPathIdentity(path) {
30714
30765
  return toAbsolutePath(path);
30715
30766
  }
30716
30767
  }
30717
- function isRecord$6(value) {
30768
+ function isRecord$7(value) {
30718
30769
  return typeof value === "object" && value !== null;
30719
30770
  }
30720
30771
  function isInstructionFileName(name) {
@@ -30773,9 +30824,9 @@ async function findInstructionFileForPath(candidatePath, pathExists, isDirectory
30773
30824
  }
30774
30825
  }
30775
30826
  function getMessageText(message) {
30776
- const parts = isRecord$6(message.content) ? message.content.parts : void 0;
30827
+ const parts = isRecord$7(message.content) ? message.content.parts : void 0;
30777
30828
  if (!Array.isArray(parts)) return "";
30778
- return parts.filter((part) => isRecord$6(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
30829
+ return parts.filter((part) => isRecord$7(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
30779
30830
  }
30780
30831
  function decodeXmlEntities(value) {
30781
30832
  return value.replaceAll("&quot;", "\"").replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&amp;", "&");
@@ -30797,8 +30848,8 @@ function getReminderMetadata(instructionPath) {
30797
30848
  }
30798
30849
  function extractReminderPathFromMetadata(message) {
30799
30850
  const metadata = message.content.metadata;
30800
- if (!isRecord$6(metadata)) return;
30801
- 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;
30851
+ if (!isRecord$7(metadata)) return;
30852
+ 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;
30802
30853
  return typeof reminderMetadata.path === "string" ? reminderMetadata.path : void 0;
30803
30854
  }
30804
30855
  function getReminderMarkup(reminderText, instructionPath) {
@@ -30824,10 +30875,10 @@ function truncateToTokenLimit(content, maxTokens) {
30824
30875
  function getCompletedToolCalls(messages) {
30825
30876
  const completed = [];
30826
30877
  for (const message of [...messages].reverse()) {
30827
- const parts = isRecord$6(message.content) ? message.content.parts : void 0;
30878
+ const parts = isRecord$7(message.content) ? message.content.parts : void 0;
30828
30879
  if (!Array.isArray(parts)) continue;
30829
30880
  for (const part of [...parts].reverse()) {
30830
- if (!isRecord$6(part) || part.type !== "tool-invocation") continue;
30881
+ if (!isRecord$7(part) || part.type !== "tool-invocation") continue;
30831
30882
  const invocation = part.toolInvocation;
30832
30883
  if (!invocation || invocation.state !== "result" || typeof invocation.toolCallId !== "string") continue;
30833
30884
  completed.push({
@@ -30839,11 +30890,11 @@ function getCompletedToolCalls(messages) {
30839
30890
  return completed;
30840
30891
  }
30841
30892
  function parseInvocationArgs(args) {
30842
- if (isRecord$6(args)) return args;
30893
+ if (isRecord$7(args)) return args;
30843
30894
  if (typeof args !== "string") return;
30844
30895
  try {
30845
30896
  const parsed = JSON.parse(args);
30846
- return isRecord$6(parsed) ? parsed : void 0;
30897
+ return isRecord$7(parsed) ? parsed : void 0;
30847
30898
  } catch {
30848
30899
  return;
30849
30900
  }
@@ -30949,7 +31000,7 @@ var AgentsMDInjector = class {
30949
31000
  return this.reminderText?.trim() || void 0;
30950
31001
  }
30951
31002
  async *findInstructionPathsInInvocation(invocation, reader, basePath) {
30952
- if (!isRecord$6(invocation)) return;
31003
+ if (!isRecord$7(invocation)) return;
30953
31004
  const args = parseInvocationArgs(invocation.args);
30954
31005
  if (!args) return;
30955
31006
  for (const field of PATH_FIELDS) {
@@ -32489,7 +32540,7 @@ function hashBinary(value) {
32489
32540
  const CYBER_POLICY_ERROR_CODE = "cyber_policy";
32490
32541
  const CYBER_REFUSAL_MESSAGE = "this content was flagged for possible cybersecurity risk";
32491
32542
  const CYBER_STOP_CATEGORY = "cyber";
32492
- function isRecord$5(value) {
32543
+ function isRecord$6(value) {
32493
32544
  return typeof value === "object" && value !== null;
32494
32545
  }
32495
32546
  function parseJson(value) {
@@ -32512,7 +32563,7 @@ function parseJson(value) {
32512
32563
  function isCyberRefusalError(error) {
32513
32564
  const visited = /* @__PURE__ */ new WeakSet();
32514
32565
  function visit(candidate) {
32515
- if (!isRecord$5(candidate) || visited.has(candidate)) return false;
32566
+ if (!isRecord$6(candidate) || visited.has(candidate)) return false;
32516
32567
  visited.add(candidate);
32517
32568
  const { code, message, responseBody } = candidate;
32518
32569
  if (typeof code === "string" && code.toLowerCase() === CYBER_POLICY_ERROR_CODE) return true;
@@ -32532,10 +32583,10 @@ function isCyberRefusalError(error) {
32532
32583
  * still recognized when Claude is reached through another provider.
32533
32584
  */
32534
32585
  function isCyberStopRefusal(finishReason, providerMetadata) {
32535
- if (finishReason !== "content-filter" || !isRecord$5(providerMetadata)) return false;
32586
+ if (finishReason !== "content-filter" || !isRecord$6(providerMetadata)) return false;
32536
32587
  return Object.values(providerMetadata).some((namespace) => {
32537
- const stopDetails = isRecord$5(namespace) ? namespace.stopDetails : void 0;
32538
- return isRecord$5(stopDetails) && typeof stopDetails.category === "string" && stopDetails.category.toLowerCase() === CYBER_STOP_CATEGORY;
32588
+ const stopDetails = isRecord$6(namespace) ? namespace.stopDetails : void 0;
32589
+ return isRecord$6(stopDetails) && typeof stopDetails.category === "string" && stopDetails.category.toLowerCase() === CYBER_STOP_CATEGORY;
32539
32590
  });
32540
32591
  }
32541
32592
  /**
@@ -32801,18 +32852,18 @@ async function checkThreadFGA({ mastra, user, threadId, resourceId, agentId, req
32801
32852
  }
32802
32853
  // src/memory/system-reminders.ts
32803
32854
  const LEGACY_SYSTEM_REMINDER_METADATA_KEY = "dynamicAgentsMdReminder";
32804
- function isRecord$4(value) {
32855
+ function isRecord$5(value) {
32805
32856
  return typeof value === "object" && value !== null;
32806
32857
  }
32807
32858
  function isSystemReminderSignalType(type) {
32808
32859
  return type === "system-reminder" || type === "reactive";
32809
32860
  }
32810
32861
  function isSystemReminderMessage(message) {
32811
- if (!isRecord$4(message.content)) return false;
32862
+ if (!isRecord$5(message.content)) return false;
32812
32863
  const metadata = message.content.metadata;
32813
- if (message.role === "signal") return isRecord$4(metadata) && isRecord$4(metadata.signal) && isSystemReminderSignalType(metadata.signal.type);
32864
+ if (message.role === "signal") return isRecord$5(metadata) && isRecord$5(metadata.signal) && isSystemReminderSignalType(metadata.signal.type);
32814
32865
  if (message.role !== "user") return false;
32815
- if (isRecord$4(metadata) && (isRecord$4(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) return true;
32866
+ if (isRecord$5(metadata) && (isRecord$5(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) return true;
32816
32867
  const firstTextPart = message.content.parts.find((part) => part.type === "text");
32817
32868
  return typeof firstTextPart?.text === "string" && firstTextPart.text.startsWith("<system-reminder");
32818
32869
  }
@@ -32820,10 +32871,10 @@ function isRecallSignalType(type) {
32820
32871
  return type === "user" || type === "state" || type === "reactive" || type === "notification" || type === "user-message" || type === "system-reminder";
32821
32872
  }
32822
32873
  function getRecallSignalType(message) {
32823
- if (!isRecord$4(message.content)) return void 0;
32824
- 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;
32874
+ if (!isRecord$5(message.content)) return void 0;
32875
+ 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;
32825
32876
  const metadata = message.content.metadata;
32826
- if (message.role === "signal" && isRecord$4(metadata) && isRecord$4(metadata.signal)) {
32877
+ if (message.role === "signal" && isRecord$5(metadata) && isRecord$5(metadata.signal)) {
32827
32878
  if (isRecallSignalType(metadata.signal.type)) return metadata.signal.type;
32828
32879
  }
32829
32880
  return isSystemReminderMessage(message) ? "system-reminder" : void 0;
@@ -42679,7 +42730,12 @@ var MemoryStorage = class MemoryStorage extends StorageDomain {
42679
42730
  throw pendingSignalsNotSupportedError(this.constructor.name);
42680
42731
  }
42681
42732
  /**
42682
- * Delete the thread's taken rows whose id is in `consumedIds`. Then, if the
42733
+ * Delete the thread's taken rows whose id is in `consumedIds`. A consumed
42734
+ * id never names a queued row: a run consumes a row by claiming it or by
42735
+ * starting with it, a claim never returns a queued row, and a run that
42736
+ * keeps its signals here named itself the signal run through
42737
+ * `setSignalRun` before it started, which made the thread's queued rows
42738
+ * pending. Then, if the
42683
42739
  * thread's signal run is still `runId`, move its other taken rows and its
42684
42740
  * queued rows to pending and clear the signal run. A close that comes after another run
42685
42741
  * became the signal run deletes only what it consumed and leaves the other
@@ -51268,11 +51324,10 @@ function claimFirstReplyLink(requestContext, link) {
51268
51324
  /** Live posts of `reply_in_thread` calls whose text is still streaming in, by tool call id. */
51269
51325
  const STREAMS_KEY = "mastra__channelReplyStreams";
51270
51326
  function replyStreams(requestContext) {
51271
- let streams = requestContext.get(STREAMS_KEY);
51272
- if (!streams) {
51273
- streams = /* @__PURE__ */ new Map();
51274
- requestContext.set(STREAMS_KEY, streams);
51275
- }
51327
+ const stored = requestContext.get(STREAMS_KEY);
51328
+ if (stored instanceof Map) return stored;
51329
+ const streams = /* @__PURE__ */ new Map();
51330
+ requestContext.set(STREAMS_KEY, streams);
51276
51331
  return streams;
51277
51332
  }
51278
51333
  /**
@@ -51284,7 +51339,7 @@ function openReplyStream({ chatThread, logger }) {
51284
51339
  let sent = "";
51285
51340
  let closed = false;
51286
51341
  let wake;
51287
- let done;
51342
+ let posted;
51288
51343
  async function* chunks() {
51289
51344
  while (true) {
51290
51345
  while (queue.length > 0) yield queue.shift();
@@ -51295,12 +51350,16 @@ function openReplyStream({ chatThread, logger }) {
51295
51350
  const push = (text) => {
51296
51351
  if (!text) return;
51297
51352
  queue.push(text);
51298
- done ??= chatThread.post(chunks()).then(() => true, (error) => {
51353
+ posted ??= chatThread.post(chunks()).then((message) => message, (error) => {
51299
51354
  logger?.warn("[channels] streamed reply failed; posting it whole", { error });
51300
- return false;
51301
51355
  });
51302
51356
  wake?.();
51303
51357
  };
51358
+ const end = async () => {
51359
+ closed = true;
51360
+ wake?.();
51361
+ return posted;
51362
+ };
51304
51363
  return {
51305
51364
  update(text) {
51306
51365
  const visible = text.trimStart();
@@ -51310,16 +51369,20 @@ function openReplyStream({ chatThread, logger }) {
51310
51369
  },
51311
51370
  async finish(text, suffix) {
51312
51371
  if (text.startsWith(sent)) push(text.slice(sent.length));
51313
- if (!done) return false;
51372
+ if (!posted) return false;
51314
51373
  push(suffix);
51315
- closed = true;
51316
- wake?.();
51317
- return done;
51374
+ return !!await end();
51318
51375
  },
51319
51376
  async close() {
51320
- closed = true;
51321
- wake?.();
51322
- return done ?? false;
51377
+ return !!await end();
51378
+ },
51379
+ async discard() {
51380
+ const message = await end();
51381
+ try {
51382
+ await message?.delete();
51383
+ } catch (error) {
51384
+ logger?.warn("[channels] could not delete a streamed reply preview", { error });
51385
+ }
51323
51386
  }
51324
51387
  };
51325
51388
  }
@@ -51346,6 +51409,7 @@ var ChannelReplyStreamProcessor = class {
51346
51409
  if (!requestContext) return part;
51347
51410
  await this.#postUnsentAnswer(part, state, requestContext);
51348
51411
  const args = state.args ??= {};
51412
+ const called = state.called ??= {};
51349
51413
  if (part.type === "tool-call-input-streaming-start" && part.payload.toolName === "reply_in_thread") {
51350
51414
  const render = await this.#resolveRender(requestContext);
51351
51415
  if (render?.textDisplay !== "hidden" || !render.streaming?.enabled) return part;
@@ -51356,10 +51420,19 @@ var ChannelReplyStreamProcessor = class {
51356
51420
  if (text !== void 0) replyStreams(requestContext).get(part.payload.toolCallId)?.update(text);
51357
51421
  } else if ((part.type === "tool-error" || part.type === "tool-result") && part.payload.toolCallId in args) {
51358
51422
  delete args[part.payload.toolCallId];
51359
- await closeStream(requestContext, part.payload.toolCallId);
51360
- } else if (RUN_END.has(part.type)) {
51361
- for (const toolCallId of Object.keys(args)) await closeStream(requestContext, toolCallId);
51423
+ delete called[part.payload.toolCallId];
51424
+ await discardStream(requestContext, part.payload.toolCallId);
51425
+ } else if (part.type === "tool-call" && part.payload.toolCallId in args) called[part.payload.toolCallId] = true;
51426
+ else if (part.type === "step-finish") for (const toolCallId of Object.keys(called)) {
51427
+ delete args[toolCallId];
51428
+ delete called[toolCallId];
51429
+ await discardStream(requestContext, toolCallId);
51430
+ }
51431
+ else if (RUN_END.has(part.type)) {
51432
+ for (const toolCallId of Object.keys(args)) if (called[toolCallId]) await discardStream(requestContext, toolCallId);
51433
+ else await closeStream(requestContext, toolCallId);
51362
51434
  state.args = {};
51435
+ state.called = {};
51363
51436
  }
51364
51437
  return part;
51365
51438
  }
@@ -51367,8 +51440,7 @@ var ChannelReplyStreamProcessor = class {
51367
51440
  * Models sometimes end a turn with a plain-text answer and never call
51368
51441
  * `reply_in_thread`, so the thread never hears back. When a run finishes
51369
51442
  * without having replied, post the text written after its last tool call.
51370
- * A reply counts once it posts: a call that fails validation doesn't, unless
51371
- * its streamed post already left text in the thread.
51443
+ * A reply counts once it posts; a failed call's streamed preview is deleted, so it doesn't.
51372
51444
  */
51373
51445
  async #postUnsentAnswer(part, state, requestContext) {
51374
51446
  const answer = state.answer ??= {
@@ -51382,10 +51454,7 @@ var ChannelReplyStreamProcessor = class {
51382
51454
  answer.tail = "";
51383
51455
  if (part.payload.toolName === "reply_in_thread") answer.calls.add(part.payload.toolCallId);
51384
51456
  } else if (part.type === "tool-result" && answer.calls.has(part.payload.toolCallId)) answer.replied = true;
51385
- else if (part.type === "tool-error" && answer.calls.has(part.payload.toolCallId)) {
51386
- const stream = replyStreams(requestContext).get(part.payload.toolCallId);
51387
- if (stream && await stream.close()) answer.replied = true;
51388
- } else if (part.type === "tool-call-approval" || part.type === "tool-call-suspended") answer.held = true;
51457
+ else if (part.type === "tool-call-approval" || part.type === "tool-call-suspended") answer.held = true;
51389
51458
  else if (RUN_END.has(part.type)) {
51390
51459
  state.answer = void 0;
51391
51460
  const text = answer.tail.trim();
@@ -51420,6 +51489,13 @@ async function closeStream(requestContext, toolCallId) {
51420
51489
  streams.delete(toolCallId);
51421
51490
  await stream.close();
51422
51491
  }
51492
+ /** Deletes a streamed post that is only a preview of a reply posted, or failed, elsewhere. */
51493
+ async function discardStream(requestContext, toolCallId) {
51494
+ const streams = replyStreams(requestContext);
51495
+ const stream = streams.get(toolCallId);
51496
+ streams.delete(toolCallId);
51497
+ await stream?.discard();
51498
+ }
51423
51499
  const ESCAPES = {
51424
51500
  "\"": "\"",
51425
51501
  "\\": "\\",
@@ -51889,11 +51965,11 @@ var MastraStateAdapter = class {
51889
51965
  * otherwise reach the agent as just the notification fallback.
51890
51966
  */
51891
51967
  function layoutBlockTexts(raw) {
51892
- const blocks = isRecord$3(raw) ? raw.blocks : void 0;
51968
+ const blocks = isRecord$4(raw) ? raw.blocks : void 0;
51893
51969
  if (!Array.isArray(blocks)) return [];
51894
51970
  const texts = [];
51895
51971
  for (const block of blocks) {
51896
- if (!isRecord$3(block) || typeof block.type !== "string") continue;
51972
+ if (!isRecord$4(block) || typeof block.type !== "string") continue;
51897
51973
  const parts = blockParts(block).map((part) => part.trim()).filter(Boolean);
51898
51974
  if (parts.length) texts.push(parts);
51899
51975
  }
@@ -51906,13 +51982,13 @@ function blockParts(block) {
51906
51982
  const fields = Array.isArray(block.fields) ? block.fields.map(textObject) : [];
51907
51983
  return [textObject(block.text), ...fields];
51908
51984
  }
51909
- 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(" ")];
51985
+ 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(" ")];
51910
51986
  case "markdown": return [typeof block.text === "string" ? block.text : ""];
51911
51987
  default: return [];
51912
51988
  }
51913
51989
  }
51914
51990
  function textObject(value) {
51915
- if (!isRecord$3(value) || typeof value.text !== "string") return "";
51991
+ if (!isRecord$4(value) || typeof value.text !== "string") return "";
51916
51992
  const text = value.text.trim();
51917
51993
  return value.type === "mrkdwn" ? slackLinksToMarkdown(text) : text;
51918
51994
  }
@@ -51924,7 +52000,7 @@ function slackLinksToMarkdown(text) {
51924
52000
  return `[${label.replace(/[\\[\]]/g, "\\$&")}](${destination})`;
51925
52001
  });
51926
52002
  }
51927
- function isRecord$3(value) {
52003
+ function isRecord$4(value) {
51928
52004
  return typeof value === "object" && value !== null;
51929
52005
  }
51930
52006
  /**
@@ -57064,7 +57140,7 @@ function isBuffer(value) {
57064
57140
  /**
57065
57141
  * Checks whether a value is a non-null, non-array object.
57066
57142
  */
57067
- function isRecord$2(value) {
57143
+ function isRecord$3(value) {
57068
57144
  return value != null && typeof value === "object" && !Array.isArray(value);
57069
57145
  }
57070
57146
  /**
@@ -59058,7 +59134,7 @@ function parseSpeechStreamPart(text) {
59058
59134
  } catch {
59059
59135
  return;
59060
59136
  }
59061
- if (!isRecord$2(value)) return;
59137
+ if (!isRecord$3(value)) return;
59062
59138
  const part = value;
59063
59139
  switch (part.type) {
59064
59140
  case "stream-start": {
@@ -59069,10 +59145,10 @@ function parseSpeechStreamPart(text) {
59069
59145
  warnings
59070
59146
  } : void 0;
59071
59147
  }
59072
- 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;
59073
- case "finish": return isOptional$1(part.usage, isUsage) && isOptional$1(part.providerMetadata, isRecord$2) ? part : void 0;
59148
+ 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;
59149
+ case "finish": return isOptional$1(part.usage, isUsage) && isOptional$1(part.providerMetadata, isRecord$3) ? part : void 0;
59074
59150
  case "response-metadata": {
59075
- if (!(isOptional$1(part.modelId, isString$1) && isOptional$1(part.headers, isRecord$2))) return;
59151
+ if (!(isOptional$1(part.modelId, isString$1) && isOptional$1(part.headers, isRecord$3))) return;
59076
59152
  const timestamp = part.timestamp;
59077
59153
  if (timestamp == null) return {
59078
59154
  ...part,
@@ -59103,10 +59179,10 @@ const knownWarningTypes = /* @__PURE__ */ new Set([
59103
59179
  "unsupported"
59104
59180
  ]);
59105
59181
  function isUnknownWarningType(value) {
59106
- return isRecord$2(value) && isString$1(value.type) && !knownWarningTypes.has(value.type);
59182
+ return isRecord$3(value) && isString$1(value.type) && !knownWarningTypes.has(value.type);
59107
59183
  }
59108
59184
  function isWarning$1(value) {
59109
- if (!isRecord$2(value)) return false;
59185
+ if (!isRecord$3(value)) return false;
59110
59186
  switch (value.type) {
59111
59187
  case "compatibility":
59112
59188
  case "unsupported": return isString$1(value.feature) && isOptional$1(value.details, isString$1);
@@ -59116,10 +59192,10 @@ function isWarning$1(value) {
59116
59192
  }
59117
59193
  }
59118
59194
  function isAudioFormat(value) {
59119
- 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);
59195
+ 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);
59120
59196
  }
59121
59197
  function isUsage(value) {
59122
- return isRecord$2(value) && [
59198
+ return isRecord$3(value) && [
59123
59199
  "inputCharacters",
59124
59200
  "inputTokens",
59125
59201
  "outputTokens"
@@ -59186,12 +59262,12 @@ function parseTranscriptionStreamPart(text) {
59186
59262
  const part = value;
59187
59263
  switch (part.type) {
59188
59264
  case "stream-start": return Array.isArray(part.warnings) && part.warnings.every(isWarning) ? part : void 0;
59189
- case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59190
- 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;
59191
- 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;
59192
- 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;
59265
+ case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isRecord$3) ? part : void 0;
59266
+ 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;
59267
+ 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;
59268
+ 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;
59193
59269
  case "response-metadata": {
59194
- if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isRecord$2))) return;
59270
+ if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isRecord$3))) return;
59195
59271
  const timestamp = part.timestamp;
59196
59272
  if (timestamp == null) return {
59197
59273
  ...part,
@@ -59219,10 +59295,10 @@ function isOptional(value, check) {
59219
59295
  return value === void 0 || check(value);
59220
59296
  }
59221
59297
  function isWarning(value) {
59222
- return isRecord$2(value) && isString(value.type);
59298
+ return isRecord$3(value) && isString(value.type);
59223
59299
  }
59224
59300
  function isSegment(value) {
59225
- return isRecord$2(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
59301
+ return isRecord$3(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
59226
59302
  }
59227
59303
  function withoutTrailingSlash(url) {
59228
59304
  return url?.replace(/\/$/, "");
@@ -72752,6 +72828,50 @@ async function runIdleLoop(agent, streamOptions, deps, firstTurn, streamForConti
72752
72828
  resourceId
72753
72829
  });
72754
72830
  }
72831
+ // src/loop/suspended-run-auto-resume.ts
72832
+ /**
72833
+ * The `autoResumeSuspendedTools` a suspended agentic-loop run executed its latest segment with: the value persisted
72834
+ * with its most recent suspension. A resume can override the run's setting, so a resume in another process (or after
72835
+ * a restart) that leaves the option out keeps the latest one, not the one the first parked tool call recorded.
72836
+ * (#30190)
72837
+ *
72838
+ * Each tool call that suspends persists the segment's value in its own suspend payload, with its `suspendedAt`.
72839
+ * Tool calls that suspend side by side keep one record each, under `__workflow_meta.foreachOutput` or as the step's
72840
+ * `output`. The step's own suspend payload mirrors only the first suspended call, so a step with per-call records is
72841
+ * read through those records. A per-call record is read through its own payload first: on the evented engine its
72842
+ * `output` can hold stale copies of its siblings' records from before it was resumed. A snapshot written before the
72843
+ * value was persisted has none, and this returns `undefined`.
72844
+ */
72845
+ function findLatestSuspendedAutoResume(snapshot) {
72846
+ let latest;
72847
+ /** Records the values persisted at or under `entry`; whether it found one. */
72848
+ const visit = (entry, isToolCall) => {
72849
+ if (!isRecord$2(entry) || entry.status !== "suspended") return false;
72850
+ const suspendPayload = isRecord$2(entry.suspendPayload) ? entry.suspendPayload : void 0;
72851
+ const value = suspendPayload?.__autoResumeSuspendedTools;
72852
+ const record = () => {
72853
+ if (typeof value !== "boolean") return false;
72854
+ const at = typeof entry.suspendedAt === "number" ? entry.suspendedAt : 0;
72855
+ if (!latest || at >= latest.at) latest = {
72856
+ at,
72857
+ value
72858
+ };
72859
+ return true;
72860
+ };
72861
+ if (isToolCall && record()) return true;
72862
+ const meta = isRecord$2(suspendPayload?.__workflow_meta) ? suspendPayload.__workflow_meta : void 0;
72863
+ const perCall = Array.isArray(meta?.foreachOutput) ? meta.foreachOutput : Array.isArray(entry.output) ? entry.output : void 0;
72864
+ let found = false;
72865
+ for (const call of perCall ?? []) found = visit(call, true) || found;
72866
+ return found || !isToolCall && record();
72867
+ };
72868
+ const context = isRecord$2(snapshot) && isRecord$2(snapshot.context) ? snapshot.context : void 0;
72869
+ for (const step of Object.values(context ?? {})) visit(step, false);
72870
+ return latest?.value;
72871
+ }
72872
+ function isRecord$2(value) {
72873
+ return typeof value === "object" && value !== null;
72874
+ }
72755
72875
  // src/tools/provider-tool-utils.ts
72756
72876
  /**
72757
72877
  * Find a provider-defined tool by its model-facing name.
@@ -81203,6 +81323,16 @@ async function processChunkThroughOutputProcessors(chunk, registryEntry, stepReq
81203
81323
  });
81204
81324
  }
81205
81325
  /**
81326
+ * The run's `autoResumeSuspendedTools` for its current segment, persisted with each suspension: a resume can override
81327
+ * the value the run started with, and a later resume in another process that leaves the option out reads the latest
81328
+ * one back from the snapshot. The resume carries its value on the segment's request context, which reaches a step on
81329
+ * any worker; this process's registry entry stands in when user code cleared it. (#30190)
81330
+ */
81331
+ function runAutoResumeSuspendPayload(carried, registryEntry, startOptions) {
81332
+ const value = carried ?? registryEntry?.autoResumeSuspendedTools ?? startOptions?.autoResumeSuspendedTools;
81333
+ return value === void 0 ? {} : { __autoResumeSuspendedTools: value };
81334
+ }
81335
+ /**
81206
81336
  * Create a durable tool call step.
81207
81337
  *
81208
81338
  * This step mirrors the base Agent's createToolCallStep pattern:
@@ -81816,7 +81946,8 @@ function createDurableToolCallStep() {
81816
81946
  type: "approval",
81817
81947
  toolCallId,
81818
81948
  toolName,
81819
- args
81949
+ args,
81950
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
81820
81951
  }, { resumeLabel: toolCallId });
81821
81952
  }
81822
81953
  const isResumableTool = toolName?.startsWith("agent-") || toolName?.startsWith("workflow-");
@@ -82041,7 +82172,8 @@ function createDurableToolCallStep() {
82041
82172
  toolName: approvalToolName,
82042
82173
  args: approvalArgs
82043
82174
  },
82044
- ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
82175
+ ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {},
82176
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
82045
82177
  }, { resumeLabel: toolCallId });
82046
82178
  }
82047
82179
  const suspendedEventData = {
@@ -82095,7 +82227,8 @@ function createDurableToolCallStep() {
82095
82227
  toolCallId,
82096
82228
  toolName,
82097
82229
  resumeLabel: suspendOptions?.resumeLabel,
82098
- ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
82230
+ ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {},
82231
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
82099
82232
  }, { resumeLabel: toolCallId });
82100
82233
  };
82101
82234
  const toolOptions = defineLazyWriter(toolOptionsWithoutWriter, () => new ToolStream({
@@ -84770,6 +84903,8 @@ var DefaultAgentExecutionEngine = class {
84770
84903
  * Close the stored signals of a parked run that was aborted. Call it before
84771
84904
  * the snapshot is deleted and before the abort terminal is published.
84772
84905
  * Returns nothing to wait for when this engine's runs never store signals.
84906
+ * Resolves `false` when the run was left open: its committed state could not
84907
+ * be determined yet, or the close did not commit.
84773
84908
  */
84774
84909
  closeParkedRunSignals(_runId) {}
84775
84910
  /**
@@ -84906,7 +85041,10 @@ var DefaultAgentExecutionEngine = class {
84906
85041
  logger: this.mastra.getLogger(),
84907
85042
  storage: this.mastra.getStorage()
84908
85043
  });
84909
- if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === "evented") this.mastra.__registerInternalWorkflow(this.#workflow, void 0, { distributed: true });
85044
+ if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === "evented") {
85045
+ this.mastra.__registerInternalWorkflow(this.#workflow, void 0, { distributed: true });
85046
+ warnProcessLocalServerCache(this.mastra);
85047
+ }
84910
85048
  }
84911
85049
  }
84912
85050
  return this.#workflow;
@@ -85207,17 +85345,17 @@ var EventedAgentExecutionEngine = class extends DefaultAgentExecutionEngine {
85207
85345
  workflowName: DurableStepIds.AGENTIC_LOOP,
85208
85346
  runId
85209
85347
  }).catch(() => null);
85210
- if (!snapshot) return;
85348
+ if (!snapshot) return false;
85211
85349
  const context = snapshot.context;
85212
- if (!context?.input?.signalsStored) return;
85350
+ if (!context?.input?.signalsStored) return true;
85213
85351
  const committed = await this.#parkedRunState(workflowsStore, snapshot);
85214
- if (!committed) return;
85215
- await closeStoredSignalRun({
85352
+ if (!committed) return false;
85353
+ return await closeStoredSignalRun({
85216
85354
  mastra: this.mastra,
85217
85355
  runId,
85218
85356
  input: context.input,
85219
85357
  state: committed.state
85220
- });
85358
+ }) ?? false;
85221
85359
  }
85222
85360
  /**
85223
85361
  * The latest committed workflow state of a parked run, or `undefined` when
@@ -85720,7 +85858,7 @@ async function prepareForDurableExecution(options) {
85720
85858
  });
85721
85859
  let tripwireData;
85722
85860
  if (inputProcessors.length > 0) try {
85723
- const { ProcessorRunner } = await import("./stream-D2rv1Ut1.js").then((n) => n.L);
85861
+ const { ProcessorRunner } = await import("./stream-H_wVxqdK.js").then((n) => n.L);
85724
85862
  await new ProcessorRunner({
85725
85863
  inputProcessors,
85726
85864
  outputProcessors,
@@ -94229,9 +94367,30 @@ var Agent = class Agent extends MastraBase {
94229
94367
  if (!this.__usesSharedRunLog()) return void 0;
94230
94368
  return this.#resolveExecutionEngine()?.closeParkedRunSignals(runId);
94231
94369
  }
94232
- /** @internal Close the stored signals of a parked run that an abort requested by another process releases here. */
94233
- __closeParkedRunSignals(runId) {
94234
- return this.#closeParkedRunSignals(runId);
94370
+ /**
94371
+ * @internal Close the stored signals of a parked run that an abort requested by another process releases here.
94372
+ * With `exclusiveOfResume`, the close holds the run's execution claim from its snapshot read through its commit, as
94373
+ * a resume segment does. A resume that starts meanwhile waits for it, instead of consuming a signal that the close,
94374
+ * working from the snapshot it read before, would then return to pending. Resolves `false` while another
94375
+ * execution holds the run.
94376
+ */
94377
+ __closeParkedRunSignals(runId, options) {
94378
+ if (!options?.exclusiveOfResume || !this.__usesSharedRunLog() || !this.#resolveExecutionEngine()) return this.#closeParkedRunSignals(runId);
94379
+ return this.#closeParkedRunSignalsExclusively(runId);
94380
+ }
94381
+ async #closeParkedRunSignalsExclusively(runId) {
94382
+ let executionFence;
94383
+ try {
94384
+ executionFence = await this.#claimExecution(runId, "acquire");
94385
+ } catch (error) {
94386
+ if (error instanceof MastraError && error.id === "DURABLE_AGENT_EXECUTION_CONFLICT") return false;
94387
+ throw error;
94388
+ }
94389
+ let closed = false;
94390
+ await executionFence.settle(async () => {
94391
+ closed = await this.#closeParkedRunSignals(runId) ?? false;
94392
+ });
94393
+ return closed;
94235
94394
  }
94236
94395
  async #cancelAndCloseParkedRun(runId) {
94237
94396
  if (!await this.executionEngine.cancelParkedRun(runId)) return false;
@@ -94623,7 +94782,12 @@ var Agent = class Agent extends MastraBase {
94623
94782
  }
94624
94783
  async resumeStream(resumeData, streamOptions) {
94625
94784
  if (this.#resolveExecutionEngine()) return this.#resumeDurableStream(resumeData, streamOptions);
94626
- return this.#resumeStream(resumeData, streamOptions, false);
94785
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(streamOptions?.runId ?? "", this.getPubSub());
94786
+ try {
94787
+ return await this.#resumeStream(resumeData, streamOptions, false);
94788
+ } finally {
94789
+ releaseResumeHold();
94790
+ }
94627
94791
  }
94628
94792
  async #resumeDurableStream(resumeData, streamOptions) {
94629
94793
  const runId = streamOptions?.runId;
@@ -94653,7 +94817,10 @@ var Agent = class Agent extends MastraBase {
94653
94817
  const actor = mergedStreamOptions.actor;
94654
94818
  delete loopStreamOptions.actor;
94655
94819
  if (mergedStreamOptions.untilIdle) {
94656
- const { untilIdle, ...rest } = mergedStreamOptions ?? {};
94820
+ const { untilIdle, ...rest } = {
94821
+ ...mergedStreamOptions,
94822
+ autoResumeSuspendedTools: streamOptions?.autoResumeSuspendedTools
94823
+ };
94657
94824
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
94658
94825
  return runResumeStreamUntilIdle(this, resumeData, {
94659
94826
  ...rest,
@@ -94674,6 +94841,8 @@ var Agent = class Agent extends MastraBase {
94674
94841
  const snapshotMemoryInfo = this.#getSnapshotMemoryInfo(existingSnapshot);
94675
94842
  const persistedReturnScorerData = streamOptions?.returnScorerData === void 0 ? this.#getSnapshotReturnScorerData(existingSnapshot) : void 0;
94676
94843
  if (persistedReturnScorerData !== void 0) mergedStreamOptions.returnScorerData = loopStreamOptions.returnScorerData = persistedReturnScorerData;
94844
+ const runAutoResume = streamOptions?.autoResumeSuspendedTools ?? findLatestSuspendedAutoResume(existingSnapshot);
94845
+ if (runAutoResume !== void 0) mergedStreamOptions.autoResumeSuspendedTools = loopStreamOptions.autoResumeSuspendedTools = runAutoResume;
94677
94846
  if (snapshotMemoryInfo?.threadId) {
94678
94847
  mergedStreamOptions.memory = {
94679
94848
  ...mergedStreamOptions.memory ?? {},
@@ -94780,7 +94949,10 @@ var Agent = class Agent extends MastraBase {
94780
94949
  text: "An unknown error occurred while streaming"
94781
94950
  });
94782
94951
  }
94783
- await agentThreadStreamRuntime.registerRun(this, result.result, preparedOptions, threadStreamPubSub);
94952
+ await agentThreadStreamRuntime.registerRun(this, result.result, {
94953
+ ...preparedOptions,
94954
+ autoResumeSuspendedTools: runAutoResume
94955
+ }, threadStreamPubSub);
94784
94956
  return result.result;
94785
94957
  } catch (error) {
94786
94958
  await resumeClaim.release();
@@ -94809,6 +94981,17 @@ var Agent = class Agent extends MastraBase {
94809
94981
  async resumeGenerate(...args) {
94810
94982
  if (this.#resolveExecutionEngine()) return this.#resumeDurableGenerate(args);
94811
94983
  const [resumeData, options] = args;
94984
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(options?.runId ?? "", this.getPubSub());
94985
+ let completed = false;
94986
+ try {
94987
+ const output = await this.#resumePlainGenerate(resumeData, options);
94988
+ completed = output.finishReason !== "suspended";
94989
+ return output;
94990
+ } finally {
94991
+ releaseResumeHold({ startQueuedTurn: completed });
94992
+ }
94993
+ }
94994
+ async #resumePlainGenerate(resumeData, options) {
94812
94995
  const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });
94813
94996
  const mergedOptions = deepMerge$1(withDefaultToolCallConcurrencyLimit(defaultOptions, options), withDefinedToolHooks(options) ?? {});
94814
94997
  validateModelTimeoutSettings(mergedOptions.modelSettings?.timeout);
@@ -94822,6 +95005,8 @@ var Agent = class Agent extends MastraBase {
94822
95005
  });
94823
95006
  const persistedReturnScorerData = options?.returnScorerData === void 0 ? this.#getSnapshotReturnScorerData(existingSnapshot) : void 0;
94824
95007
  if (persistedReturnScorerData !== void 0) mergedOptions.returnScorerData = loopOptions.returnScorerData = persistedReturnScorerData;
95008
+ const persistedAutoResume = options?.autoResumeSuspendedTools === void 0 ? findLatestSuspendedAutoResume(existingSnapshot) : void 0;
95009
+ if (persistedAutoResume !== void 0) mergedOptions.autoResumeSuspendedTools = loopOptions.autoResumeSuspendedTools = persistedAutoResume;
94825
95010
  const { options: scopedOptions, resolved: resolvedScopes } = await this.#resolveRunScopes(mergedOptions, {
94826
95011
  callScopes: options?.scopes,
94827
95012
  defaultScopes: defaultOptions?.scopes,
@@ -94955,7 +95140,12 @@ var Agent = class Agent extends MastraBase {
94955
95140
  runId: options.runId
94956
95141
  }
94957
95142
  });
94958
- return this.#resumeStream(void 0, options, true);
95143
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(options.runId, this.getPubSub());
95144
+ try {
95145
+ return await this.#resumeStream(void 0, options, true);
95146
+ } finally {
95147
+ releaseResumeHold();
95148
+ }
94959
95149
  }
94960
95150
  /**
94961
95151
  * Approves a pending tool call and resumes execution.
@@ -96196,10 +96386,11 @@ var Agent = class Agent extends MastraBase {
96196
96386
  if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, registryEntry);
96197
96387
  }
96198
96388
  };
96389
+ let cleanupOutput;
96199
96390
  const runCleanup = createRunCleanup({
96200
96391
  scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
96201
96392
  release: () => {
96202
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
96393
+ if (cleanupOutput) agentThreadStreamRuntime.closeRunContinuation(cleanupOutput, this.getPubSub());
96203
96394
  streamCleanup?.();
96204
96395
  cleanupOwnedRegistryState();
96205
96396
  }
@@ -96232,6 +96423,7 @@ var Agent = class Agent extends MastraBase {
96232
96423
  });
96233
96424
  const { output, cleanup: createdStreamCleanup, ready } = stream;
96234
96425
  streamCleanup = createdStreamCleanup;
96426
+ cleanupOutput = output;
96235
96427
  const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
96236
96428
  const workflowExecution = executionFence.run(() => this.executionEngine.raceFenceLoss(ready, executionFence).then(async () => {
96237
96429
  const result = await this.executionEngine.restartRun(workflow, executionFence, recoveryPubsub, this.workflowEngine, this.logger, resourceId, requestContext, createObservabilityContext({ currentSpan: recoverAgentSpan }));
@@ -96948,12 +97140,15 @@ var Agent = class Agent extends MastraBase {
96948
97140
  });
96949
97141
  releaseResumeMarker = release;
96950
97142
  }
97143
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(runId, this.getPubSub());
96951
97144
  try {
96952
97145
  if (await this.#isRunCanceledInStorage(runId)) throw abortedRunError();
96953
97146
  return await this.#resumeRun(runId, resumeData, options, releaseResumeMarker);
96954
97147
  } catch (error) {
96955
97148
  releaseResumeMarker();
96956
97149
  throw error;
97150
+ } finally {
97151
+ releaseResumeHold();
96957
97152
  }
96958
97153
  }
96959
97154
  /**
@@ -96995,6 +97190,7 @@ var Agent = class Agent extends MastraBase {
96995
97190
  let entry = this.executionRunRegistry.get(runId);
96996
97191
  let rehydratedScopes;
96997
97192
  let coldSnapshot;
97193
+ let coldRunAutoResume;
96998
97194
  if (!entry) {
96999
97195
  const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
97000
97196
  const persisted = workflowsStore ? await this.executionEngine.loadPersistedRunSnapshot(workflowsStore, runId) : void 0;
@@ -97093,6 +97289,7 @@ var Agent = class Agent extends MastraBase {
97093
97289
  }
97094
97290
  });
97095
97291
  rehydratedScopes = persistedScopes;
97292
+ coldRunAutoResume = findLatestSuspendedAutoResume(snapshot) ?? workflowInput.options?.autoResumeSuspendedTools;
97096
97293
  const memory = threadId ? {
97097
97294
  ...options?.memory,
97098
97295
  thread: threadId,
@@ -97153,8 +97350,12 @@ var Agent = class Agent extends MastraBase {
97153
97350
  requestContextKeys
97154
97351
  };
97155
97352
  resumeRequestContext = resolvedOptions.requestContext ?? resumeRequestContext;
97353
+ const runAutoResume = options?.autoResumeSuspendedTools ?? (coldSnapshot ? coldRunAutoResume : entry.autoResumeSuspendedTools);
97156
97354
  if (resolvedOptions.untilIdle) {
97157
- const { untilIdle, ...rest } = resolvedOptions;
97355
+ const { untilIdle, ...rest } = {
97356
+ ...resolvedOptions,
97357
+ autoResumeSuspendedTools: runAutoResume
97358
+ };
97158
97359
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
97159
97360
  releaseResumeMarker();
97160
97361
  return runResumeDurableStreamUntilIdle({
@@ -97317,6 +97518,7 @@ var Agent = class Agent extends MastraBase {
97317
97518
  globalEntryForContext.requestContext = resumeRequestContext;
97318
97519
  globalEntryForContext.requestContextRebuilt = false;
97319
97520
  }
97521
+ for (const reg of /* @__PURE__ */ new Set([entry, globalEntryForContext])) if (reg && runAutoResume !== void 0) reg.autoResumeSuspendedTools = runAutoResume;
97320
97522
  } catch (error) {
97321
97523
  await executionFence.settle(async () => {});
97322
97524
  throw error;
@@ -97430,6 +97632,7 @@ var Agent = class Agent extends MastraBase {
97430
97632
  this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open resume spans: ${error}`);
97431
97633
  }
97432
97634
  carrySegmentSpans(resumeRequestContext, runId, resumeSegment);
97635
+ if (runAutoResume !== void 0) carrySegmentAutoResume(resumeRequestContext, runId, runAutoResume);
97433
97636
  const resumeSegmentSpan = entry.resumeAgentSpan ?? entry.agentSpan;
97434
97637
  const closeOnSuspend = resolvedOptions.closeOnSuspend ?? false;
97435
97638
  const { output, cleanup: createdStreamCleanup, detach: detachResumeStream, fail: failResumeStream, waitForEventDelivery, ready } = createDurableAgentStream({
@@ -97551,7 +97754,8 @@ var Agent = class Agent extends MastraBase {
97551
97754
  workflowExecution.then(releaseResumeMarker, releaseResumeMarker);
97552
97755
  const resumeStreamOptions = {
97553
97756
  ...resolvedOptions,
97554
- runId
97757
+ runId,
97758
+ autoResumeSuspendedTools: runAutoResume
97555
97759
  };
97556
97760
  if (!agentThreadStreamRuntime.continueRun(this, output, resumeStreamOptions, this.getPubSub(), {
97557
97761
  generation: executionFence.generation,
@@ -104770,7 +104974,7 @@ function createLLMMappingStep({ models, _internal, ...rest }, llmExecutionStep)
104770
104974
  });
104771
104975
  }
104772
104976
  // src/loop/workflows/agentic-execution/tool-call-step.ts
104773
- function createToolCallStep({ tools, messageList, options, outputWriter, controller, runId, streamState, modelSpanTracker, _internal, logger, agentId, agentVersionId, resolvedScopes, returnScorerData, mastra, requireToolApproval: requireToolApprovalFromFactory, actor, mcp, agent }) {
104977
+ function createToolCallStep({ tools, messageList, options, outputWriter, controller, runId, streamState, modelSpanTracker, _internal, logger, agentId, agentVersionId, resolvedScopes, returnScorerData, autoResumeSuspendedTools, mastra, requireToolApproval: requireToolApprovalFromFactory, actor, mcp, agent }) {
104774
104978
  const memoryMessageRefs = new MemoryMessageRefs();
104775
104979
  return createStep$1({
104776
104980
  id: "toolCallStep",
@@ -105118,6 +105322,7 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105118
105322
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105119
105323
  __resolvedScopes: resolvedScopes ?? [],
105120
105324
  ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105325
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {},
105121
105326
  suspendedToolRunId: options.runId
105122
105327
  }, { resumeLabel: inputData.toolCallId });
105123
105328
  }
@@ -105158,6 +105363,7 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105158
105363
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105159
105364
  __resolvedScopes: resolvedScopes ?? [],
105160
105365
  ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105366
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {},
105161
105367
  toolCallId: inputData.toolCallId,
105162
105368
  toolName: inputData.toolName,
105163
105369
  resumeLabel: options?.resumeLabel,
@@ -105231,7 +105437,8 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105231
105437
  __agentId: agentId,
105232
105438
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105233
105439
  __resolvedScopes: resolvedScopes ?? [],
105234
- ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {}
105440
+ ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105441
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {}
105235
105442
  }, { resumeLabel: inputData.toolCallId });
105236
105443
  }
105237
105444
  const clearedApproval = await removeToolMetadata({
@@ -106674,6 +106881,15 @@ const AGENT_THREAD_WAKE_OWNER_DISCOVERY_DEADLINE_MS = readPositiveIntEnv("MASTRA
106674
106881
  const AGENT_THREAD_CLAIM_LEASE_PREFIX = "thread-claim:";
106675
106882
  const AGENT_THREAD_OWNER_ACCEPTANCE_TIMEOUT_MS = 5e3;
106676
106883
  const UNSAVED_RUN_TRIM_DELAY_MS = 3e4;
106884
+ /** Waits before a parked storage-backed run tries again to let go of its thread for queued input (#30190). */
106885
+ const PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS = [
106886
+ 100,
106887
+ 200,
106888
+ 400,
106889
+ 800,
106890
+ 1600,
106891
+ 3200
106892
+ ];
106677
106893
  const AGENT_THREAD_PEER_DISCOVERY_TOPIC = "agent.thread-peer-discovery";
106678
106894
  const AGENT_THREAD_PEER_DISCOVERY_TIMEOUT_MS = 100;
106679
106895
  const THREAD_LEASE_OWNER_PREFIX = "mastra:thread-lease:";
@@ -106962,6 +107178,38 @@ function withThreadMemory(memory, resourceId, threadId) {
106962
107178
  thread: memory?.thread ?? threadId
106963
107179
  };
106964
107180
  }
107181
+ /**
107182
+ * The memory a resume that names no thread continues its run with: the run's thread and resource, the run's
107183
+ * settings, and on top of those every setting the resume passes itself (`options` merged key by key, so a resume
107184
+ * that sets only `lastMessages` or `readOnly` keeps the rest).
107185
+ */
107186
+ function resumeMemoryOnOwnThread({ run, resume, threadId, resourceId }) {
107187
+ const options = run?.options || resume?.options ? {
107188
+ ...run?.options,
107189
+ ...resume?.options
107190
+ } : void 0;
107191
+ return {
107192
+ ...run,
107193
+ ...resume,
107194
+ thread: run?.thread ?? threadId,
107195
+ resource: run?.resource ?? resourceId,
107196
+ ...options ? { options } : {}
107197
+ };
107198
+ }
107199
+ /**
107200
+ * The options a resume leaves on its run's record. Resume callers hand over the resume's own
107201
+ * `autoResumeSuspendedTools`, not the agent default merged in, so `undefined` means the resume left it out. The run
107202
+ * then keeps the value it started with: a run that turned auto-resume off keeps holding a queued message for an
107203
+ * explicit resume after it parks again. Callers that resume a run rebuilt from storage pass the run's persisted value
107204
+ * instead, since this process has no record of it. (#30190)
107205
+ */
107206
+ function keepRunAutoResume(resume, run) {
107207
+ if (resume.autoResumeSuspendedTools !== void 0 || run?.autoResumeSuspendedTools === void 0) return resume;
107208
+ return {
107209
+ ...resume,
107210
+ autoResumeSuspendedTools: run.autoResumeSuspendedTools
107211
+ };
107212
+ }
106965
107213
  const CANCELLED_BEFORE_RUN = "The accepted message was cancelled before it ran";
106966
107214
  function toPublicThreadPeer(peer) {
106967
107215
  const { unsubscribe: _unsubscribe, ...publicPeer } = peer;
@@ -106992,6 +107240,7 @@ function createRuntimeState() {
106992
107240
  suspensionMetadataByRunId: /* @__PURE__ */ new Map(),
106993
107241
  signalQueues: createActiveRunSignalQueues(),
106994
107242
  locallyQueuedSignalIdsByThread: /* @__PURE__ */ new Map(),
107243
+ startedSignalIdsByThread: /* @__PURE__ */ new Map(),
106995
107244
  pendingSignalListenersByRunId: /* @__PURE__ */ new Map(),
106996
107245
  lostRunsByThread: /* @__PURE__ */ new Map(),
106997
107246
  pendingIdleSignalsByThread: /* @__PURE__ */ new Map(),
@@ -107039,6 +107288,11 @@ var AgentThreadStreamRuntime = class {
107039
107288
  #stalledLeaseReads = /* @__PURE__ */ new WeakMap();
107040
107289
  /** Per run, the resolution of its signals store in flight (see `#signalsStoreOf`). */
107041
107290
  #storeResolutions = /* @__PURE__ */ new WeakMap();
107291
+ /**
107292
+ * Parked storage-backed runs letting go of their thread for queued input, one release at a time per run. `again`
107293
+ * records a trigger that arrived meanwhile, which checks the run again unless the release let go of the thread.
107294
+ */
107295
+ #releasingParkedStoredRuns = /* @__PURE__ */ new WeakMap();
107042
107296
  #threadlessRunFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(({ state, runId, token }) => {
107043
107297
  if (state.preparedRunsById.get(runId)?.finalizerToken !== token) return;
107044
107298
  this.#cleanupPreparedRun(state, runId);
@@ -107273,7 +107527,7 @@ var AgentThreadStreamRuntime = class {
107273
107527
  }
107274
107528
  const preparedRun = state.preparedRunsById.get(runId);
107275
107529
  const controller = preparedRun?.abortController ?? record.segmentAbortController;
107276
- const stepOwners = [controller?.signal, record.stepOwner?.()].filter((owner) => owner !== void 0);
107530
+ const stepOwners = this.#runStepOwners(state, record);
107277
107531
  const executing = !!preparedRun && record.lifecycle !== "suspended" || stepOwners.some((owner) => hasRunningRunStep(owner));
107278
107532
  const abortController = executing ? controller : void 0;
107279
107533
  if (!state.leaseRenewalTimers.has(runId) || record.registeredElsewhere || record.lateRetakeHandoff) {
@@ -107835,10 +108089,61 @@ var AgentThreadStreamRuntime = class {
107835
108089
  if (!active) return;
107836
108090
  const data = event.data;
107837
108091
  if (data?.type === "signal-enqueued") {
107838
- if (data.sourceId === this.#id && this.#isLocalSignalEcho(state, key, data.signal.id, data.runId) || subscription.admittedSignalIds.has(data.signal.id)) return;
108092
+ 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;
107839
108093
  const answersTo = (runId) => state.threadKeysByRunId.get(runId) === key || subscription.ownedRunIds.has(runId) || state.storedSignals.endedRun(key)?.run.runId === runId;
107840
108094
  const runId = answersTo(data.runId) ? data.runId : forwardedSignalRunId(data.runId);
107841
108095
  if (!answersTo(runId)) return;
108096
+ if (state.threadRunsById.get(runId)?.registeredElsewhere) return;
108097
+ if (data.senderKeepsCopy && !state.activeThreadRunIds.has(key)) return;
108098
+ const activeRunId = data.queued ? state.activeThreadRunIds.get(key) : void 0;
108099
+ const live = activeRunId ? state.threadRunsById.get(activeRunId) : void 0;
108100
+ if (live && this.#isThreadBlockingRun(state, live)) {
108101
+ const signal = createSignal(data.signal);
108102
+ subscription.admittedSignalIds.add(signal.id);
108103
+ const admit = () => {
108104
+ if (this.#pendingUserMessageChunk(runId, signal, "pending")) this.#publish(pubsub, key, {
108105
+ type: "user-message-admitted",
108106
+ signalId: signal.id,
108107
+ admittedRunId: runId
108108
+ });
108109
+ };
108110
+ const admitStored = () => {
108111
+ this.#publishPendingUserMessage(pubsub, key, live.runId, signal, "queued");
108112
+ admit();
108113
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, live);
108114
+ };
108115
+ if (data.stored) return admitStored();
108116
+ const liveStore = this.#signalsStoreOf(live);
108117
+ if (!liveStore) {
108118
+ this.queueSignal(live.agent, signal, { runId: live.runId }, pubsub);
108119
+ return admit();
108120
+ }
108121
+ const to = {
108122
+ runId: live.runId,
108123
+ agent: live.agent
108124
+ };
108125
+ const written = this.#enqueueStoredSignal(state, key, liveStore, signal, to, true, true);
108126
+ return { settled: (async () => {
108127
+ try {
108128
+ if (await written === "run-closed") {
108129
+ if (subscription.cancelledSignalIds.has(signal.id)) return;
108130
+ this.#announceLeftoverSignal(state, pubsub, key, live, signal);
108131
+ if (live.runId !== runId) admit();
108132
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, live);
108133
+ return;
108134
+ }
108135
+ } catch (error) {
108136
+ if (!subscription.cancelledSignalIds.has(signal.id)) subscription.admittedSignalIds.delete(signal.id);
108137
+ live.agent.__getLogger?.()?.warn?.("Could not store a queued signal forwarded to a running run", {
108138
+ runId,
108139
+ signalId: signal.id,
108140
+ error
108141
+ });
108142
+ throw error;
108143
+ }
108144
+ admitStored();
108145
+ })() };
108146
+ }
107842
108147
  const ended = state.storedSignals.endedRun(key)?.run;
107843
108148
  const run = state.threadRunsById.get(runId) ?? (ended?.runId === runId ? ended : void 0);
107844
108149
  const store = run && this.#signalsStoreOf(run);
@@ -107854,15 +108159,34 @@ var AgentThreadStreamRuntime = class {
107854
108159
  subscription.admittedSignalIds.add(data.signal.id);
107855
108160
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
107856
108161
  this.#notifyPendingSignals(state, key, signal);
108162
+ const record = state.threadRunsById.get(runId);
108163
+ if (record) this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
107857
108164
  } else if (data?.type === "user-message-admitted") this.#settleForwardedIdleSignal(state, key, data.signalId, data.admittedRunId);
107858
108165
  else if (data?.type === "user-message-presentation") {
107859
108166
  const { chunk } = data;
107860
108167
  if (chunk.type === "data-user-message-pending" && chunk.data.metadata?.status === "pending") this.#settleForwardedIdleSignal(state, key, chunk.data.id, chunk.runId);
107861
108168
  } else if (data?.type === "signals-cancelled") {
107862
108169
  for (const id of data.signalIds) this.#settleForwardedIdleSignal(state, key, id);
107863
- for (const id of data.signalIds) subscription.admittedSignalIds.add(id);
108170
+ for (const id of data.signalIds) {
108171
+ subscription.admittedSignalIds.add(id);
108172
+ subscription.cancelledSignalIds.add(id);
108173
+ }
107864
108174
  this.#cancelPendingSignals(state, key, new Set(data.signalIds), pubsub, this.#threadSignalsStore(state, key));
107865
108175
  this.#notifyThreadEvents(state);
108176
+ } else if (data?.type === "queued-input-waiting") {
108177
+ const record = state.threadRunsById.get(data.runId);
108178
+ if (data.sourceId === this.#getSourceId() || !record || state.threadKeysByRunId.get(data.runId) !== key) return;
108179
+ record.queuedInputElsewhere = true;
108180
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
108181
+ } else if (data?.type === "parked-run-released") {
108182
+ if (data.sourceId === this.#getSourceId() || state.activeThreadRunIds.get(key) !== data.runId) return;
108183
+ const record = state.threadRunsById.get(data.runId);
108184
+ if (record && record.registeredElsewhere === void 0) return;
108185
+ if (state.activeThreadStreamIds.get(key) !== data.streamId && record?.registeredElsewhere !== data.streamId) return;
108186
+ state.activeThreadRunIds.delete(key);
108187
+ state.activeThreadStreamIds.delete(key);
108188
+ this.#notifyThreadEvents(state);
108189
+ await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
107866
108190
  } else if (data?.type === "run-abort-requested") {
107867
108191
  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);
107868
108192
  const clearPendingSignals = ownsRun() && data.clearPendingSignals && await this.#holdsThreadLeaseThroughRetake(resolvedPubSub, key, data.runId);
@@ -107884,7 +108208,8 @@ var AgentThreadStreamRuntime = class {
107884
108208
  return;
107885
108209
  }
107886
108210
  const current = state.threadRunsById.get(data.runId);
107887
- if (current?.registrationSeen) current.registeredElsewhere = true;
108211
+ if (current?.registrationSeen) current.registeredElsewhere = data.streamId;
108212
+ if (state.activeThreadRunIds.get(key) === data.runId) this.#requestParkedRunReleaseElsewhere(state, resolvedPubSub, key, { executionChanged: true });
107888
108213
  if (lost?.runId === data.runId && lost.registrationSeen) {
107889
108214
  state.lostRunsByThread.delete(key);
107890
108215
  this.#handOffQueuedSignals(state, resolvedPubSub, key, data.runId, lost.streamId);
@@ -107894,6 +108219,8 @@ var AgentThreadStreamRuntime = class {
107894
108219
  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);
107895
108220
  } else if (data?.type === "run-completed" || data?.type === "run-failed") {
107896
108221
  this.#releaseRunSupersededBy(state, resolvedPubSub, key, subscription, data.runId);
108222
+ if (data.type === "run-completed" && data.status === "interrupted" && state.threadRunsById.get(data.runId)?.registeredElsewhere === data.streamId) return;
108223
+ this.#retireRunEndedElsewhere(state, resolvedPubSub, key, data.runId, data.streamId);
107897
108224
  const lostStreamId = subscription.successorRunIds.get(data.runId);
107898
108225
  if (lostStreamId !== void 0 && data.streamId === lostStreamId) return;
107899
108226
  if (lostStreamId === void 0 && data.type === "run-completed" && data.superseded && state.forwardedIdleLeaseChecks.has(key)) return;
@@ -107910,7 +108237,7 @@ var AgentThreadStreamRuntime = class {
107910
108237
  const onEvent = (event, ack) => {
107911
108238
  const type = event.data?.type;
107912
108239
  const awaitingForwards = state.forwardedIdleSignalsByThread.has(key);
107913
- 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?.();
108240
+ 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?.();
107914
108241
  subscription.references++;
107915
108242
  const handled = tail.then(() => handleEvent(event));
107916
108243
  tail = handled.then(() => {}, () => {});
@@ -107925,6 +108252,7 @@ var AgentThreadStreamRuntime = class {
107925
108252
  observers: 0,
107926
108253
  ownedRunIds,
107927
108254
  admittedSignalIds: /* @__PURE__ */ new Set(),
108255
+ cancelledSignalIds: /* @__PURE__ */ new Set(),
107928
108256
  successorRunIds: /* @__PURE__ */ new Map(),
107929
108257
  supersedingRunIds: /* @__PURE__ */ new Map(),
107930
108258
  unsubscribe: () => {
@@ -107947,7 +108275,9 @@ var AgentThreadStreamRuntime = class {
107947
108275
  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;
107948
108276
  subscription.ownedRunIds.clear();
107949
108277
  subscription.admittedSignalIds.clear();
108278
+ subscription.cancelledSignalIds.clear();
107950
108279
  state.locallyQueuedSignalIdsByThread.delete(key);
108280
+ state.startedSignalIdsByThread.delete(key);
107951
108281
  if (subscription.observers) return;
107952
108282
  state.threadControlSubscriptions.delete(key);
107953
108283
  subscription.unsubscribe();
@@ -108642,11 +108972,16 @@ var AgentThreadStreamRuntime = class {
108642
108972
  runId,
108643
108973
  resourceId: owner.resourceId,
108644
108974
  threadId: owner.threadId,
108645
- streamOptions
108975
+ streamOptions,
108976
+ ...waitForIdle ? { queued: true } : {}
108646
108977
  });
108647
108978
  state.pendingIdleSignalsByThread.set(key, idleQueue);
108648
108979
  this.#publishPendingUserMessage(pubsub, key, activeRunId, signal, "queued");
108649
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
108980
+ if (activeRecord) {
108981
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
108982
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, activeRecord);
108983
+ }
108984
+ this.#requestParkedRunReleaseElsewhere(state, pubsub, key);
108650
108985
  settleMessageIdentity?.({ runId });
108651
108986
  return { runId };
108652
108987
  }
@@ -108738,25 +109073,18 @@ var AgentThreadStreamRuntime = class {
108738
109073
  action: "remote",
108739
109074
  runId: ownerRunId
108740
109075
  });
108741
- if (this.#mayStoreForRunHeldElsewhere(state, owner.agent, forwardedSignalRunId(ownerRunId))) {
108742
- if (!await this.#forwardSignal(state, pubsub, key, owner.agent, ownerRunId, signal).catch((error) => {
108743
- releaseMessageIdentity(getErrorFromUnknown(error));
108744
- throw error;
108745
- })) {
108746
- const error = `Thread ${describeThreadKey(key)} is held by run ${ownerRunId}, which ended before it took the message`;
108747
- releaseMessageIdentity(error);
108748
- return {
108749
- runId: ownerRunId,
108750
- error,
108751
- blocked: true
108752
- };
108753
- }
108754
- } else this.#publish(pubsub, key, {
108755
- type: "signal-enqueued",
108756
- runId: ownerRunId,
108757
- signal: this.#serializeSignal(signal),
108758
- sourceId: this.#getSourceId()
108759
- });
109076
+ if (!await this.#forwardToOwner(state, pubsub, key, owner.agent, ownerRunId, signal, waitForIdle).catch((error) => {
109077
+ releaseMessageIdentity(getErrorFromUnknown(error));
109078
+ throw error;
109079
+ })) {
109080
+ const error = `Thread ${describeThreadKey(key)} is held by run ${ownerRunId}, which ended before it took the message`;
109081
+ releaseMessageIdentity(error);
109082
+ return {
109083
+ runId: ownerRunId,
109084
+ error,
109085
+ blocked: true
109086
+ };
109087
+ }
108760
109088
  settleMessageIdentity?.({ runId: ownerRunId }, false);
108761
109089
  return { runId: ownerRunId };
108762
109090
  }
@@ -108847,11 +109175,13 @@ var AgentThreadStreamRuntime = class {
108847
109175
  else if (entry.leaseGone) ended.add(entry.runId);
108848
109176
  else entry.leaseGone = true;
108849
109177
  for (const runId of ended) if (this.#requeueUnadmittedForwards(state, key, runId)) {
109178
+ const executedElsewhere = state.threadRunsById.get(runId)?.registeredElsewhere;
109179
+ if (executedElsewhere !== void 0) this.#retireRunEndedElsewhere(state, this.#getPubSub(pubsub), key, runId, executedElsewhere);
108850
109180
  if (!state.threadRunsById.has(runId) && state.activeThreadStreamIds.get(key) === streamBeforeRead && state.activeThreadRunIds.get(key) === runId) {
108851
109181
  state.activeThreadRunIds.delete(key);
108852
109182
  state.activeThreadStreamIds.delete(key);
108853
109183
  }
108854
- await this.#drainPendingIdleSignals(state, pubsub, key, runId);
109184
+ await this.#drainPendingIdleSignals(state, pubsub, key, executedElsewhere === void 0 ? runId : void 0);
108855
109185
  }
108856
109186
  };
108857
109187
  const check = setInterval(() => {
@@ -108885,6 +109215,21 @@ var AgentThreadStreamRuntime = class {
108885
109215
  state.pendingIdleSignalsByThread.set(key, [...unadmitted.map(([, entry]) => entry.pendingIdle), ...state.pendingIdleSignalsByThread.get(key) ?? []]);
108886
109216
  return true;
108887
109217
  }
109218
+ /** Signals taken from this runtime's queues as a turn's input; `#forgetStartedSignals` undoes it on a requeue. */
109219
+ #recordStartedSignals(state, key, signals) {
109220
+ if (signals.length === 0) return;
109221
+ const ids = state.startedSignalIdsByThread.get(key) ?? /* @__PURE__ */ new Set();
109222
+ for (const signal of signals) {
109223
+ ids.delete(signal.id);
109224
+ ids.add(signal.id);
109225
+ }
109226
+ while (ids.size > MAX_LOCALLY_QUEUED_SIGNAL_IDS_PER_THREAD) ids.delete(ids.values().next().value);
109227
+ state.startedSignalIdsByThread.set(key, ids);
109228
+ }
109229
+ #forgetStartedSignals(state, key, signals) {
109230
+ const ids = state.startedSignalIdsByThread.get(key);
109231
+ for (const signal of signals) ids?.delete(signal.id);
109232
+ }
108888
109233
  #recordLocallyQueuedSignal(state, key, signalId) {
108889
109234
  const ids = state.locallyQueuedSignalIdsByThread.get(key) ?? /* @__PURE__ */ new Map();
108890
109235
  ids.delete(signalId);
@@ -109482,6 +109827,26 @@ var AgentThreadStreamRuntime = class {
109482
109827
  else this.#releaseThreadLease(pubsub, key, runId);
109483
109828
  return true;
109484
109829
  }
109830
+ /**
109831
+ * The execution another process registered for a run parked here has ended, so nothing executes the run any more.
109832
+ * The stale record stops routing the thread's input to it: input sent from now on runs as a new turn here, and
109833
+ * forwards that crossed the end are queued again by the terminal handler. (#30190)
109834
+ */
109835
+ #retireRunEndedElsewhere(state, pubsub, key, runId, streamId) {
109836
+ const record = state.threadRunsById.get(runId);
109837
+ if (!record || streamId === void 0 || record.registeredElsewhere !== streamId) return;
109838
+ record.lifecycle = "completed";
109839
+ this.#clearSuspendedRun(state, runId);
109840
+ this.#stopLeaseRenewal(pubsub, runId);
109841
+ state.threadRunsByStreamId.delete(record.streamId);
109842
+ state.threadRunsById.delete(runId);
109843
+ state.threadKeysByRunId.delete(runId);
109844
+ if (state.activeThreadRunIds.get(key) === runId) {
109845
+ state.activeThreadRunIds.delete(key);
109846
+ state.activeThreadStreamIds.delete(key);
109847
+ }
109848
+ this.#notifyThreadEvents(state);
109849
+ }
109485
109850
  /** Release the local run that `runId` superseded, if it superseded one. */
109486
109851
  #releaseRunSupersededBy(state, pubsub, key, subscription, runId) {
109487
109852
  const supersededRunId = subscription.supersedingRunIds.get(runId);
@@ -109498,12 +109863,162 @@ var AgentThreadStreamRuntime = class {
109498
109863
  */
109499
109864
  #releaseSupersededParkedRun(state, pubsub, key, runId) {
109500
109865
  const record = state.threadRunsById.get(runId);
109501
- if (!record || state.activeThreadRunIds.get(key) !== runId || !this.#isParkedRun(state, runId)) return;
109866
+ if (!record || state.activeThreadRunIds.get(key) !== runId || !this.#isParkedRun(state, runId)) return false;
109502
109867
  state.activeThreadRunIds.delete(key);
109503
109868
  if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key);
109504
109869
  this.#stopReadingDisplacedRun(state, runId);
109505
109870
  if (this.#hasPendingThreadWork(state, key)) this.#drainPendingSignals(state, pubsub, key, record);
109506
109871
  else this.#releaseThreadLease(pubsub, key, runId);
109872
+ return true;
109873
+ }
109874
+ /**
109875
+ * With `autoResumeSuspendedTools`, the next turn is what resumes a run parked on
109876
+ * a tool's suspend(): the model reads the user's answer from the new message.
109877
+ * The parked run itself never drains its queue, so a message queued onto it
109878
+ * would be reported delivered and never run (#30190). Once the run has parked,
109879
+ * queued messages start the next turn the way a stream call on the thread
109880
+ * would; the parked run keeps its record and stays resumable.
109881
+ *
109882
+ * Without auto-resume, the message keeps waiting for the explicit resume (an
109883
+ * AgentController prompt waits for its answer), and a run parked on a tool
109884
+ * approval keeps holding the thread: consent arrives through the approval APIs.
109885
+ *
109886
+ * Any input starts the turn: a sent message, a continuation, or work queued
109887
+ * for after the run (`queueMessage`, `queueSignal`, here, forwarded from
109888
+ * another process, or held by another process that sent `queued-input-waiting`). Queued work waits for the thread's run to end (#32093), and
109889
+ * a run parked with auto-resume on counts as ended: it waits for the next
109890
+ * message and nothing else, so queued work is that message. Every other run
109891
+ * still holds queued work: one in flight, one parked without auto-resume, and
109892
+ * one parked on an approval.
109893
+ */
109894
+ async #startQueuedTurnAfterParkedRun(state, pubsub, key, record) {
109895
+ const options = record.streamOptions;
109896
+ const storageBacked = this.#isStorageBacked(record);
109897
+ 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));
109898
+ if (!canStart()) return;
109899
+ if (!(options.autoResumeSuspendedTools ?? (await record.agent.getDefaultOptions({ requestContext: options.requestContext })).autoResumeSuspendedTools) || !canStart()) return;
109900
+ let owners = this.#runStepOwners(state, record);
109901
+ while (canStart() && owners.some((owner) => hasRunningRunStep(owner))) {
109902
+ await Promise.all(owners.map((owner) => new Promise((resolve) => whenRunStepsSettle(owner, resolve))));
109903
+ owners = this.#runStepOwners(state, record);
109904
+ }
109905
+ if (!canStart()) return;
109906
+ if (storageBacked ? await this.#releaseParkedStoredRunForInput(state, pubsub, key, record, canStart) : this.#releaseSupersededParkedRun(state, this.#getPubSub(pubsub), key, record.runId)) {
109907
+ record.queuedInputElsewhere = false;
109908
+ this.#publish(pubsub, key, {
109909
+ type: "parked-run-released",
109910
+ runId: record.runId,
109911
+ streamId: record.streamId,
109912
+ sourceId: this.#getSourceId()
109913
+ });
109914
+ }
109915
+ }
109916
+ /**
109917
+ * Whether the thread of a storage-backed run has input for it: a pending or queued row (`listPendingSignals` returns
109918
+ * both), or a continuation or queued work held here.
109919
+ */
109920
+ async #hasStoredRunInput(state, key, record) {
109921
+ if (this.#hasPendingThreadWork(state, key)) return true;
109922
+ const store = await this.#signalsStoreOf(record);
109923
+ if (!store) return false;
109924
+ return (await store.store.listPendingSignals({ threadId: store.threadId })).length > 0;
109925
+ }
109926
+ /**
109927
+ * `#releaseSupersededParkedRun` for a storage-backed run: its input waits in its store, so the thread is checked
109928
+ * as at the end of a run, which starts the next turn with the oldest pending row. The run's signals are closed first,
109929
+ * as when a parked run is aborted, so rows it took and never consumed are pending again for that turn. The run keeps
109930
+ * its record and stays resumable; a resume keeps the thread's signal run as it finds it. (#30190)
109931
+ */
109932
+ async #releaseParkedStoredRunForInput(state, pubsub, key, record, canStart) {
109933
+ const inFlight = this.#releasingParkedStoredRuns.get(record);
109934
+ if (inFlight) {
109935
+ inFlight.again = true;
109936
+ return false;
109937
+ }
109938
+ const release = { again: false };
109939
+ this.#releasingParkedStoredRuns.set(record, release);
109940
+ let released = false;
109941
+ const { runId } = record;
109942
+ const holds = () => canStart() && state.activeThreadRunIds.get(key) === runId && this.#isParkedRun(state, runId);
109943
+ try {
109944
+ for (let attempt = 0;; attempt++) {
109945
+ const outcome = await state.storedSignals.runWrite(key, async () => {
109946
+ if (!holds() || !(record.queuedInputElsewhere || await this.#hasStoredRunInput(state, key, record))) return "kept";
109947
+ if (!holds()) return "kept";
109948
+ if (await record.agent.__closeParkedRunSignals?.(runId, { exclusiveOfResume: true }) === false) return "retry";
109949
+ if (!holds()) return "kept";
109950
+ state.activeThreadRunIds.delete(key);
109951
+ if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key);
109952
+ this.#stopReadingDisplacedRun(state, runId);
109953
+ return "released";
109954
+ }).catch((error) => {
109955
+ this.#logParkedRunReleaseFailure(record, error);
109956
+ return "retry";
109957
+ });
109958
+ if (outcome === "kept") return false;
109959
+ if (outcome === "released") {
109960
+ released = true;
109961
+ break;
109962
+ }
109963
+ if (attempt >= PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS.length) {
109964
+ this.#logParkedRunReleaseFailure(record, /* @__PURE__ */ new Error("The parked run kept the thread after every retry"));
109965
+ return false;
109966
+ }
109967
+ await new Promise((resolve) => setTimeout(resolve, PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS[attempt]));
109968
+ }
109969
+ } finally {
109970
+ this.#releasingParkedStoredRuns.delete(record);
109971
+ if (release.again && !released) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109972
+ }
109973
+ const queued = this.#hasPendingThreadWork(state, key);
109974
+ if (!queued) this.#releaseEndedStoredRun(state, pubsub, key, record);
109975
+ this.#drainPendingSignals(state, pubsub, key, record, { freshLease: !queued });
109976
+ return true;
109977
+ }
109978
+ /**
109979
+ * Holds a parked run for a resume that is setting up, so input queued meanwhile stays the resumed run's next model
109980
+ * input, as it was before parked runs were released for queued input, instead of starting a turn beside the resumed
109981
+ * tool. The returned function ends the hold; if the run is still parked then, for example because the resume
109982
+ * failed, queued input starts the next turn, unless `startQueuedTurn` is false: a caller whose resume this record
109983
+ * doesn't follow, and that left the run parked again, marks the record so queued input keeps waiting. (#30190)
109984
+ */
109985
+ holdParkedRunForResume(runId, pubsub) {
109986
+ const state = this.#getState(pubsub);
109987
+ const record = state.threadRunsById.get(runId);
109988
+ if (!record) return () => {};
109989
+ record.resumeHolds = (record.resumeHolds ?? 0) + 1;
109990
+ let held = true;
109991
+ return ({ startQueuedTurn = true } = {}) => {
109992
+ if (!held) return;
109993
+ held = false;
109994
+ record.resumeHolds = (record.resumeHolds ?? 1) - 1;
109995
+ if (!startQueuedTurn) record.resumedUntracked = true;
109996
+ if (record.resumeHolds > 0 || !startQueuedTurn) return;
109997
+ const key = this.#threadKey(record.resourceId, record.threadId);
109998
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
109999
+ };
110000
+ }
110001
+ #startQueuedTurnAfterParkedRunLater(state, pubsub, key, record) {
110002
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110003
+ }
110004
+ /**
110005
+ * The message that triggered the release was already answered `deliver`, so a failure here would otherwise
110006
+ * leave it queued on the parked run with no trace.
110007
+ */
110008
+ #logParkedRunReleaseFailure(record, error) {
110009
+ record.agent.__getLogger?.()?.error("Could not start the queued turn for a run parked on a suspended tool", {
110010
+ runId: record.runId,
110011
+ threadId: record.threadId,
110012
+ resourceId: record.resourceId,
110013
+ error
110014
+ });
110015
+ }
110016
+ /**
110017
+ * The objects the steps of a run register under while they run: the abort signal of its prepared run or current
110018
+ * segment, and a durable run's registry entry.
110019
+ */
110020
+ #runStepOwners(state, record) {
110021
+ return [(state.preparedRunsById.get(record.runId)?.abortController ?? record.segmentAbortController)?.signal, record.stepOwner?.()].filter((owner) => owner !== void 0);
109507
110022
  }
109508
110023
  /**
109509
110024
  * A parked run no longer holds its thread, so its answer resumes it on a new
@@ -109701,6 +110216,7 @@ var AgentThreadStreamRuntime = class {
109701
110216
  state.suspensionMetadataByRunId.clear();
109702
110217
  state.signalQueues.clear();
109703
110218
  state.locallyQueuedSignalIdsByThread.clear();
110219
+ state.startedSignalIdsByThread.clear();
109704
110220
  state.lostRunsByThread.clear();
109705
110221
  state.pendingIdleSignalsByThread.clear();
109706
110222
  state.forwardedIdleSignalsByThread.clear();
@@ -109771,11 +110287,43 @@ var AgentThreadStreamRuntime = class {
109771
110287
  /**
109772
110288
  * Queues a signal for in-loop draining by a same-agent run that is already in
109773
110289
  * flight here, so it becomes that run's next model input instead of waiting for
109774
- * the run to finish.
110290
+ * the run to finish. If the run is parked on a suspension that auto-resume
110291
+ * answers, the signal starts the next turn instead.
109775
110292
  */
109776
110293
  #queueForActiveRun(state, pubsub, key, record, signal) {
109777
- state.signalQueues.enqueue("pending", key, signal);
109778
110294
  this.#recordLocallyQueuedSignal(state, key, signal.id);
110295
+ if (record.registeredElsewhere) {
110296
+ const senderKeepsCopy = !!this.#pendingUserMessageChunk(record.runId, signal, "pending");
110297
+ if (senderKeepsCopy) {
110298
+ const forwarded = state.forwardedIdleSignalsByThread.get(key) ?? /* @__PURE__ */ new Map();
110299
+ forwarded.set(signal.id, {
110300
+ pendingIdle: {
110301
+ agent: record.agent,
110302
+ signal,
110303
+ runId: globalThis.crypto.randomUUID(),
110304
+ resourceId: record.resourceId ?? "",
110305
+ threadId: record.threadId,
110306
+ streamOptions: {
110307
+ ...record.streamOptions,
110308
+ abortSignal: void 0
110309
+ }
110310
+ },
110311
+ runId: record.runId
110312
+ });
110313
+ state.forwardedIdleSignalsByThread.set(key, forwarded);
110314
+ this.#ensureThreadControlSubscription(state, pubsub, key);
110315
+ this.#watchForwardedIdleLease(state, pubsub, key);
110316
+ }
110317
+ this.#publish(pubsub, key, {
110318
+ type: "signal-enqueued",
110319
+ runId: record.runId,
110320
+ signal: this.#serializeSignal(signal),
110321
+ sourceId: this.#getSourceId(),
110322
+ ...senderKeepsCopy ? { senderKeepsCopy } : {}
110323
+ });
110324
+ return;
110325
+ }
110326
+ state.signalQueues.enqueue("pending", key, signal);
109779
110327
  this.#publishPendingUserMessage(pubsub, key, record.runId, signal, "pending");
109780
110328
  this.#notifyPendingSignals(state, key, signal);
109781
110329
  this.#publish(pubsub, key, {
@@ -109785,6 +110333,7 @@ var AgentThreadStreamRuntime = class {
109785
110333
  sourceId: this.#getSourceId()
109786
110334
  });
109787
110335
  this.#watchThreadRunCompletion(state, pubsub, key, record);
110336
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109788
110337
  }
109789
110338
  /**
109790
110339
  * `#queueForActiveRun` for a run that keeps its signals in storage. Resolves
@@ -109796,13 +110345,14 @@ var AgentThreadStreamRuntime = class {
109796
110345
  this.#recordLocallyQueuedSignal(state, key, signal.id);
109797
110346
  let written;
109798
110347
  try {
109799
- written = await this.#enqueueStoredSignal(state, key, store, signal, record);
110348
+ written = await this.#enqueueStoredSignal(state, key, store, signal, record, false, true);
109800
110349
  } catch (error) {
109801
110350
  this.#forgetLocallyQueuedSignal(state, key, signal.id);
109802
110351
  throw error;
109803
110352
  }
109804
110353
  if (written === "run-closed") {
109805
- await this.#storeLeftoverSignal(state, pubsub, key, record, signal, store);
110354
+ this.#announceLeftoverSignal(state, pubsub, key, record, signal);
110355
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109806
110356
  return;
109807
110357
  }
109808
110358
  this.#publishSignalAvailable(record.agent, record.runId, signal.id);
@@ -109816,6 +110366,7 @@ var AgentThreadStreamRuntime = class {
109816
110366
  stored: true
109817
110367
  });
109818
110368
  this.#watchThreadRunCompletion(state, pubsub, key, record);
110369
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109819
110370
  }
109820
110371
  /**
109821
110372
  * `signal-enqueued` for a run this runtime holds that keeps its signals in
@@ -109829,12 +110380,16 @@ var AgentThreadStreamRuntime = class {
109829
110380
  const signal = createSignal(data.signal);
109830
110381
  if (!data.stored) {
109831
110382
  try {
109832
- if (await this.#enqueueStoredSignal(state, key, store, signal, run) === "run-closed") {
109833
- await this.#storeLeftoverSignal(state, pubsub, key, run, signal, store);
110383
+ if (await this.#enqueueStoredSignal(state, key, store, signal, run, false, true) === "run-closed") {
110384
+ if (!subscription.cancelledSignalIds.has(signal.id)) {
110385
+ this.#announceLeftoverSignal(state, pubsub, key, run, signal);
110386
+ const parked = state.threadRunsById.get(runId);
110387
+ if (parked) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, parked);
110388
+ }
109834
110389
  return;
109835
110390
  }
109836
110391
  } catch (error) {
109837
- subscription.admittedSignalIds.delete(data.signal.id);
110392
+ if (!subscription.cancelledSignalIds.has(data.signal.id)) subscription.admittedSignalIds.delete(data.signal.id);
109838
110393
  run.agent.__getLogger?.()?.warn?.("Could not store a signal forwarded to a running run", {
109839
110394
  runId,
109840
110395
  signalId: signal.id,
@@ -109851,7 +110406,9 @@ var AgentThreadStreamRuntime = class {
109851
110406
  });
109852
110407
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
109853
110408
  this.#notifyPendingSignals(state, key, signal, runId);
109854
- if (!state.threadRunsById.has(runId)) this.#drainPendingSignals(state, pubsub, key, run, { freshLease: true });
110409
+ const record = state.threadRunsById.get(runId);
110410
+ if (record) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
110411
+ else this.#drainPendingSignals(state, pubsub, key, run, { freshLease: true });
109855
110412
  }
109856
110413
  /**
109857
110414
  * Move the signals this runtime queued for a run that is only reserved into
@@ -109875,10 +110432,8 @@ var AgentThreadStreamRuntime = class {
109875
110432
  return this.#enqueueStoredSignal(state, key, store, signal, {
109876
110433
  runId,
109877
110434
  agent
109878
- }).then((written) => {
109879
- if (written !== "run-closed") return;
109880
- leftForNextRun = true;
109881
- return this.#enqueueStoredSignal(state, key, store, signal);
110435
+ }, false, true).then((written) => {
110436
+ if (written === "run-closed") leftForNextRun = true;
109882
110437
  }).then(() => waiter?.resolve(), (error) => {
109883
110438
  if (waiter) {
109884
110439
  this.#forgetLocallyQueuedSignal(state, key, signal.id);
@@ -110019,17 +110574,12 @@ var AgentThreadStreamRuntime = class {
110019
110574
  return this.#getState(pubsub).storedSignals.writesSettled(this.#threadKey(store.resourceId, store.threadId));
110020
110575
  }
110021
110576
  /**
110022
- * Keep a signal whose run closed before it was stored, in the process that
110023
- * started that run: as a pending row of the thread, then run the end-of-run
110024
- * check again, since the run's own check may have found nothing.
110577
+ * After a signal whose run closed first was kept as a pending row of the
110578
+ * thread (`#enqueueStoredSignal` with `keepWhenClosed`), in the process that
110579
+ * started that run: present it, then run the end-of-run check again, since
110580
+ * the run's own check may have found nothing.
110025
110581
  */
110026
- async #storeLeftoverSignal(state, pubsub, key, endedRun, signal, store) {
110027
- try {
110028
- await this.#enqueueStoredSignal(state, key, store, signal);
110029
- } catch (error) {
110030
- this.#forgetLocallyQueuedSignal(state, key, signal.id);
110031
- throw error;
110032
- }
110582
+ #announceLeftoverSignal(state, pubsub, key, endedRun, signal) {
110033
110583
  this.#publishPendingUserMessage(pubsub, key, endedRun.runId, signal, "pending");
110034
110584
  this.#drainPendingSignals(state, pubsub, key, endedRun, { freshLease: true });
110035
110585
  }
@@ -110040,15 +110590,15 @@ var AgentThreadStreamRuntime = class {
110040
110590
  * when the event arrives. Returns `false` when the store reports that run
110041
110591
  * closed.
110042
110592
  */
110043
- async #forwardSignal(state, pubsub, key, agent, runId, signal) {
110593
+ async #forwardSignal(state, pubsub, key, agent, runId, signal, queued = false) {
110044
110594
  const target = forwardedSignalRunId(runId);
110045
110595
  const store = await this.#runSignalsStore(state, agent, target, key);
110046
110596
  if (store) {
110047
110597
  if (await this.#enqueueStoredSignal(state, key, store, signal, {
110048
110598
  runId: target,
110049
110599
  agent
110050
- }) === "run-closed") return false;
110051
- this.#publishSignalAvailable(agent, target, signal.id);
110600
+ }, queued) === "run-closed") return false;
110601
+ if (!queued) this.#publishSignalAvailable(agent, target, signal.id);
110052
110602
  this.#recordLocallyQueuedSignal(state, key, signal.id);
110053
110603
  state.locallyQueuedSignalIdsByThread.get(key)?.set(signal.id, target);
110054
110604
  }
@@ -110057,8 +110607,11 @@ var AgentThreadStreamRuntime = class {
110057
110607
  runId,
110058
110608
  signal: this.#serializeSignal(signal),
110059
110609
  sourceId: this.#getSourceId(),
110060
- ...store ? { stored: true } : {}
110061
- }).catch(() => {});
110610
+ ...store ? { stored: true } : {},
110611
+ ...queued ? { queued: true } : {}
110612
+ }).catch((error) => {
110613
+ if (queued && !store) throw error;
110614
+ });
110062
110615
  return true;
110063
110616
  }
110064
110617
  /**
@@ -110073,6 +110626,26 @@ var AgentThreadStreamRuntime = class {
110073
110626
  return state.remoteAgentIdsByRunId.get(runId) === agent.id && state.storedSignals.isRemoteRunStored(runId) && maySignalsBeStored(agent) && agent.__hasFixedMemory?.() === true;
110074
110627
  }
110075
110628
  /**
110629
+ * Hand `signal` to `ownerRunId`, a run another process holds. Queued input must wait for that run to end, so it is
110630
+ * never a row the run would claim: for a storage-backed run it is stored as a queued row, otherwise it travels as a
110631
+ * marked event its holder queues, and a failed publish of that event rejects. Other input is stored for a
110632
+ * storage-backed run and published otherwise, ignoring publish failure. Answers false only when the storage-backed
110633
+ * run ended before it took the row.
110634
+ */
110635
+ async #forwardToOwner(state, pubsub, key, agent, ownerRunId, signal, queued) {
110636
+ const target = forwardedSignalRunId(ownerRunId);
110637
+ if (this.#mayStoreForRunHeldElsewhere(state, agent, target)) return this.#forwardSignal(state, pubsub, key, agent, ownerRunId, signal, queued);
110638
+ const published = this.#publishAndWait(pubsub, key, {
110639
+ type: "signal-enqueued",
110640
+ runId: ownerRunId,
110641
+ signal: this.#serializeSignal(signal),
110642
+ sourceId: this.#getSourceId(),
110643
+ ...queued ? { queued: true } : {}
110644
+ });
110645
+ await (queued ? published : published.catch(() => {}));
110646
+ return true;
110647
+ }
110648
+ /**
110076
110649
  * Where `runId` keeps its signals as far as this process knows: the
110077
110650
  * decision on its record here (none for a run only reserved here), or, for
110078
110651
  * a run another process holds that passes `#mayStoreForRunHeldElsewhere`,
@@ -110114,17 +110687,23 @@ var AgentThreadStreamRuntime = class {
110114
110687
  /**
110115
110688
  * Insert a signal as a pending row of the thread, behind this process's
110116
110689
  * earlier writes for it. With `to` the row is only inserted while that run
110117
- * is the thread's signal run, and a thread without a row rejects.
110690
+ * is the thread's signal run, and a thread without a row rejects. With
110691
+ * `keepWhenClosed`, a run that closed first leaves the signal as a pending
110692
+ * row for the thread's next turn, inserted in the same write: a cancel
110693
+ * handled after this call is ordered after that insert too, so it deletes
110694
+ * the row. The answer is still `run-closed`.
110118
110695
  */
110119
- #enqueueStoredSignal(state, key, storeRef, signal, to) {
110696
+ #enqueueStoredSignal(state, key, storeRef, signal, to, queued = false, keepWhenClosed = false) {
110120
110697
  return state.storedSignals.runWrite(key, async () => {
110121
110698
  const store = storeRef instanceof Promise ? await storeRef : storeRef;
110122
110699
  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`);
110123
- return this.#insertStoredSignal(state, key, store, signal, to);
110700
+ const written = await this.#insertStoredSignal(state, key, store, signal, to, queued);
110701
+ if (written === "run-closed" && keepWhenClosed) await this.#insertStoredSignal(state, key, store, signal);
110702
+ return written;
110124
110703
  });
110125
110704
  }
110126
110705
  /** The insert of `#enqueueStoredSignal`, for a caller already inside a write of the thread's stored signals. */
110127
- async #insertStoredSignal(state, key, store, signal, to) {
110706
+ async #insertStoredSignal(state, key, store, signal, to, queued = false) {
110128
110707
  const message = signal.toDBMessage({
110129
110708
  threadId: store.threadId,
110130
110709
  resourceId: store.resourceId
@@ -110132,7 +110711,8 @@ var AgentThreadStreamRuntime = class {
110132
110711
  const recordAccepted = state.storedSignals.stampNewRow(key, message);
110133
110712
  const written = await store.store.enqueuePendingSignal({
110134
110713
  message,
110135
- ...to ? { toRunId: to.runId } : {}
110714
+ ...to ? { toRunId: to.runId } : {},
110715
+ ...queued ? { queued: true } : {}
110136
110716
  });
110137
110717
  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`);
110138
110718
  if (written === "accepted") recordAccepted();
@@ -110348,18 +110928,29 @@ var AgentThreadStreamRuntime = class {
110348
110928
  }
110349
110929
  }
110350
110930
  continueRun(agent, output, streamOptions, pubsub, claim) {
110351
- const { threadId, resourceId } = this.#getThreadTarget(streamOptions);
110352
- if (!threadId) return false;
110353
110931
  const state = this.#getState(pubsub);
110354
110932
  this.#sweepStaleSuspendedRecords(state, pubsub);
110355
- const key = this.#threadKey(resourceId, threadId);
110356
110933
  const existing = state.threadRunsById.get(output.runId);
110934
+ const named = this.#getThreadTarget(streamOptions);
110935
+ const continuesOwnThread = !named.threadId && existing !== void 0 && (named.resourceId === void 0 || named.resourceId === existing.resourceId);
110936
+ const { threadId, resourceId } = continuesOwnThread ? existing : named;
110937
+ if (!threadId) return false;
110938
+ const key = this.#threadKey(resourceId, threadId);
110357
110939
  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;
110358
110940
  const resumedToolCallId = streamOptions.toolCallId;
110359
110941
  if (resumedToolCallId) this.#clearSuspendedToolCall(state, output.runId, resumedToolCallId);
110360
110942
  else this.#clearSuspendedRun(state, output.runId);
110361
110943
  existing.lifecycle = "running";
110362
- existing.streamOptions = streamOptions;
110944
+ const resumeOptions = keepRunAutoResume(streamOptions, existing.streamOptions);
110945
+ existing.streamOptions = continuesOwnThread ? {
110946
+ ...resumeOptions,
110947
+ memory: resumeMemoryOnOwnThread({
110948
+ run: existing.streamOptions.memory,
110949
+ resume: streamOptions.memory,
110950
+ threadId,
110951
+ resourceId
110952
+ })
110953
+ } : resumeOptions;
110363
110954
  existing.currentSegmentOutput = output;
110364
110955
  if (claim?.generation !== void 0) existing.generation = claim.generation;
110365
110956
  if (claim?.ownershipLost) existing.ownershipLost = claim.ownershipLost;
@@ -110438,7 +111029,8 @@ var AgentThreadStreamRuntime = class {
110438
111029
  sourceOutput: output,
110439
111030
  canContinue: broadcast.canContinueBroadcast,
110440
111031
  didPublishTerminal: broadcast.didPublishTerminal
110441
- } : void 0
111032
+ } : void 0,
111033
+ queuedInputElsewhere: state.threadRunsById.get(output.runId)?.queuedInputElsewhere
110442
111034
  };
110443
111035
  return {
110444
111036
  record,
@@ -110473,7 +111065,8 @@ var AgentThreadStreamRuntime = class {
110473
111065
  const state = this.#getState(pubsub);
110474
111066
  this.#sweepStaleSuspendedRecords(state, pubsub);
110475
111067
  const key = this.#threadKey(resourceId, threadId);
110476
- const { record, streamId, streamSeq, startBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput(state, agent, output, streamOptions, pubsub, threadId, resourceId, registrationOptions);
111068
+ const runOptions = keepRunAutoResume(streamOptions, state.threadRunsById.get(output.runId)?.streamOptions);
111069
+ const { record, streamId, streamSeq, startBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput(state, agent, output, runOptions, pubsub, threadId, resourceId, registrationOptions);
110477
111070
  const activeRunId = state.activeThreadRunIds.get(key);
110478
111071
  const takesLeaseFrom = activeRunId !== void 0 && activeRunId !== output.runId && state.threadKeysByRunId.get(activeRunId) === key && this.#isParkedRun(state, activeRunId) ? activeRunId : void 0;
110479
111072
  state.threadRunsById.set(output.runId, record);
@@ -110621,6 +111214,7 @@ var AgentThreadStreamRuntime = class {
110621
111214
  runId: record.runId,
110622
111215
  streamId: record.streamId
110623
111216
  });
111217
+ this.#startQueuedTurnAfterParkedRun(this.#getState(pubsub), pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110624
111218
  }
110625
111219
  #watchThreadRunCompletion(state, pubsub, key, record, registered, isDisabled) {
110626
111220
  if (state.watchedThreadStreamIds.has(record.streamId)) return;
@@ -110754,6 +111348,7 @@ var AgentThreadStreamRuntime = class {
110754
111348
  try {
110755
111349
  signal = state.signalQueues.takeNextPending(key);
110756
111350
  if (signal) {
111351
+ this.#recordStartedSignals(state, key, [signal]);
110757
111352
  nextRunId = globalThis.crypto.randomUUID();
110758
111353
  const reservedRunId = nextRunId;
110759
111354
  state.activeThreadRunIds.set(key, reservedRunId);
@@ -110783,6 +111378,7 @@ var AgentThreadStreamRuntime = class {
110783
111378
  state.threadKeysByRunId.delete(nextRunId);
110784
111379
  state.storedSignals.settlePreRunWaiters(nextRunId);
110785
111380
  state.signalQueues.discardPreRunQueue(key);
111381
+ this.#forgetStartedSignals(state, key, [signal]);
110786
111382
  if (owns.owner && !isRetakeLeaseOwner(owns.owner)) {
110787
111383
  const ownerRunId = threadLeaseRunId(owns.owner);
110788
111384
  const ids = state.locallyQueuedSignalIdsByThread.get(key);
@@ -110818,6 +111414,7 @@ var AgentThreadStreamRuntime = class {
110818
111414
  if (state.activeThreadRunIds.get(key) === nextRunId) state.activeThreadRunIds.delete(key);
110819
111415
  }
110820
111416
  state.signalQueues.restoreAfterFailedStart(key, draining?.cancelled ? void 0 : signal);
111417
+ if (signal) this.#forgetStartedSignals(state, key, [signal]);
110821
111418
  this.#publish(pubsub, key, {
110822
111419
  type: "run-failed",
110823
111420
  runId: failedRunId,
@@ -110861,7 +111458,11 @@ var AgentThreadStreamRuntime = class {
110861
111458
  * with its oldest pending row as input, else a queued continuation, else a
110862
111459
  * queued message, else release the lease. Rows are neither moved nor
110863
111460
  * deleted here: the follow-up's first model request claims every pending
110864
- * row of the thread.
111461
+ * row of the thread. A row still queued at this read, because the ended
111462
+ * run's close has not landed, is not delivered twice: saving the
111463
+ * follow-up's input under the row's id moves the row into the thread in
111464
+ * every store, and a follow-up that keeps its signals in storage counts the
111465
+ * id as consumed, so its claims never return it.
110865
111466
  *
110866
111467
  * `freshLease` is for a check that a late send triggered after the run's own
110867
111468
  * check: the ended run's lease may be gone, so it is acquired fresh, and
@@ -111060,7 +111661,10 @@ var AgentThreadStreamRuntime = class {
111060
111661
  const queue = state.pendingContinuationsByThread.get(key) ?? [];
111061
111662
  queue.push(pending);
111062
111663
  state.pendingContinuationsByThread.set(key, queue);
111063
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
111664
+ if (activeRecord) {
111665
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
111666
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, activeRecord).catch((error) => this.#logParkedRunReleaseFailure(activeRecord, error));
111667
+ }
111064
111668
  return {
111065
111669
  accepted: true,
111066
111670
  runId
@@ -111072,6 +111676,27 @@ var AgentThreadStreamRuntime = class {
111072
111676
  runId
111073
111677
  };
111074
111678
  }
111679
+ /**
111680
+ * Queued work waits for the thread's run to end (#32093), and a run parked with auto-resume on counts as ended
111681
+ * (#30190). Only the process executing a run knows how it parked, so a runtime holding queued work behind a parked
111682
+ * run it doesn't execute asks that run's holder to let go of the thread. A holder whose run counts as ended releases
111683
+ * it and announces `parked-run-released`, and this runtime starts its queued work as after the run's end. The work
111684
+ * stays queued here meanwhile, with its own agent, options and queue owner, so it can still be cancelled here.
111685
+ */
111686
+ #requestParkedRunReleaseElsewhere(state, pubsub, key, { executionChanged = false } = {}) {
111687
+ const runId = state.activeThreadRunIds.get(key);
111688
+ if (!runId) return;
111689
+ const record = state.threadRunsById.get(runId);
111690
+ if (record && record.registeredElsewhere === void 0) return;
111691
+ if (!executionChanged && !this.#isSuspendedRun(state, runId) && record?.lifecycle !== "suspended") return;
111692
+ if (!state.pendingIdleSignalsByThread.get(key)?.some((entry) => entry.queued)) return;
111693
+ this.#ensureThreadControlSubscription(state, pubsub, key);
111694
+ this.#publish(pubsub, key, {
111695
+ type: "queued-input-waiting",
111696
+ runId,
111697
+ sourceId: this.#getSourceId()
111698
+ });
111699
+ }
111075
111700
  async #drainPendingIdleSignals(state, pubsub, key, fromRunId) {
111076
111701
  if (state.activeThreadRunIds.has(key)) return false;
111077
111702
  const idleQueue = state.pendingIdleSignalsByThread.get(key);
@@ -111141,9 +111766,9 @@ var AgentThreadStreamRuntime = class {
111141
111766
  this.#watchForwardedIdleLease(state, pubsub, key);
111142
111767
  }
111143
111768
  this.#notifyThreadEvents(state);
111144
- if (ownerRunId && this.#mayStoreForRunHeldElsewhere(state, pendingIdle.agent, forwardedSignalRunId(ownerRunId))) {
111145
- if (!await this.#forwardSignal(state, pubsub, key, pendingIdle.agent, ownerRunId, pendingIdle.signal).catch((error) => {
111146
- pendingIdle.agent.__getLogger?.()?.warn?.("Could not store a queued message for the run holding its thread", {
111769
+ if (ownerRunId) {
111770
+ if (!await this.#forwardToOwner(state, pubsub, key, pendingIdle.agent, ownerRunId, pendingIdle.signal, pendingIdle.queued === true).catch((error) => {
111771
+ pendingIdle.agent.__getLogger?.()?.warn?.("Could not forward a queued message to the run holding its thread", {
111147
111772
  runId: ownerRunId,
111148
111773
  signalId: pendingIdle.signal.id,
111149
111774
  error
@@ -111155,12 +111780,7 @@ var AgentThreadStreamRuntime = class {
111155
111780
  this.#notifyThreadEvents(state);
111156
111781
  return true;
111157
111782
  }
111158
- } else if (ownerRunId) await this.#publishAndWait(pubsub, key, {
111159
- type: "signal-enqueued",
111160
- runId: ownerRunId,
111161
- signal: this.#serializeSignal(pendingIdle.signal),
111162
- sourceId: this.#getSourceId()
111163
- }).catch(() => {});
111783
+ }
111164
111784
  const drained = await this.#drainPendingIdleSignals(state, pubsub, key, owns.acquired ? pendingIdle.runId : fromRunId);
111165
111785
  if (owns.acquired && !drained) this.#releaseThreadLease(pubsub, key, pendingIdle.runId);
111166
111786
  return drained || owns.acquired;
@@ -111257,7 +111877,9 @@ var AgentThreadStreamRuntime = class {
111257
111877
  const record = state.threadRunsById.get(runId);
111258
111878
  const key = record ? this.#threadKey(record.resourceId, record.threadId) : state.threadKeysByRunId.get(runId);
111259
111879
  if (!key) return [];
111260
- return state.signalQueues.take(scope, key);
111880
+ const queue = state.signalQueues.take(scope, key);
111881
+ this.#recordStartedSignals(state, key, queue);
111882
+ return queue;
111261
111883
  }
111262
111884
  /**
111263
111885
  * Resolves `'reserved'` when this call reserved the thread for `runId`; the
@@ -111979,6 +112601,7 @@ var AgentThreadStreamRuntime = class {
111979
112601
  state.suspendedRunIds.add(data.runId);
111980
112602
  const record = state.threadRunsByStreamId.get(eventStreamId) ?? state.threadRunsById.get(data.runId);
111981
112603
  if (record) record.lifecycle = "suspended";
112604
+ this.#requestParkedRunReleaseElsewhere(state, resolvedPubSub, key);
111982
112605
  } else clearActiveIfCurrent(data.runId, data.streamId);
111983
112606
  if (data.type !== "run-suspended" || suspendedRunEnded) this.#clearSuspendedRun(state, data.runId);
111984
112607
  const remoteRun = remoteRuns.get(eventStreamId);
@@ -112604,13 +113227,18 @@ var AgentThreadStreamRuntime = class {
112604
113227
  resourceId,
112605
113228
  threadId,
112606
113229
  streamOptions: queuedStreamOptions,
112607
- queueOwnerId: target.queueOwnerId
113230
+ queueOwnerId: target.queueOwnerId,
113231
+ queued: true
112608
113232
  });
112609
113233
  state.pendingIdleSignalsByThread.set(key, idleQueue);
112610
113234
  const control = this.#ensureThreadControlSubscription(state, pubsub, key);
112611
113235
  this.#publishPendingUserMessage(pubsub, key, runId ?? queuedRunId, queuedSignal, "queued");
112612
113236
  this.#notifyThreadEvents(state);
112613
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
113237
+ if (activeRecord) {
113238
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
113239
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, activeRecord);
113240
+ }
113241
+ this.#requestParkedRunReleaseElsewhere(state, pubsub, key);
112614
113242
  return {
112615
113243
  signal: queuedSignal,
112616
113244
  accepted: control.ready.then(() => ({
@@ -112949,7 +113577,8 @@ var AgentThreadStreamRuntime = class {
112949
113577
  runId,
112950
113578
  resourceId,
112951
113579
  threadId,
112952
- streamOptions: target.ifIdle?.streamOptions
113580
+ streamOptions: target.ifIdle?.streamOptions,
113581
+ ...waitForIdle ? { queued: true } : {}
112953
113582
  });
112954
113583
  state.pendingIdleSignalsByThread.set(key, idleQueue);
112955
113584
  if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
@@ -113067,18 +113696,11 @@ var AgentThreadStreamRuntime = class {
113067
113696
  reason: "scope-mismatch",
113068
113697
  runId: winnerRunId
113069
113698
  };
113070
- if (winnerRunId && this.#mayStoreForRunHeldElsewhere(state, agent, forwardedSignalRunId(winnerRunId))) {
113071
- if (!await this.#forwardSignal(state, pubsub, reservedKey, agent, winnerRunId, signal)) return {
113072
- action: "blocked",
113073
- reason: "thread-blocked",
113074
- runId: winnerRunId
113075
- };
113076
- } else if (winnerRunId) await this.#publishAndWait(pubsub, reservedKey, {
113077
- type: "signal-enqueued",
113078
- runId: winnerRunId,
113079
- signal: this.#serializeSignal(signal),
113080
- sourceId: this.#getSourceId()
113081
- }).catch(() => {});
113699
+ if (winnerRunId && !await this.#forwardToOwner(state, pubsub, reservedKey, agent, winnerRunId, signal, waitForIdle)) return {
113700
+ action: "blocked",
113701
+ reason: "thread-blocked",
113702
+ runId: winnerRunId
113703
+ };
113082
113704
  return {
113083
113705
  action: "deliver",
113084
113706
  runId: winnerRunId ?? reservedRunId