@mastra/core 1.87.0 → 1.88.0-alpha.1

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 (450) hide show
  1. package/dist/_types/@internal_ai-v6@0.0.100/dist/index.d.ts +97 -2049
  2. package/dist/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +17 -1
  3. package/dist/agent/agent.d.ts +10 -2
  4. package/dist/agent/durable/create-evented-agent.d.ts +2 -1
  5. package/dist/agent/durable/execution-engine.d.ts +4 -2
  6. package/dist/agent/durable/index.cjs +3 -2
  7. package/dist/agent/durable/index.js +3 -2
  8. package/dist/agent/durable/segment-spans.d.ts +7 -0
  9. package/dist/agent/durable/stored-signal-drain.d.ts +1 -1
  10. package/dist/agent/durable/types.d.ts +6 -0
  11. package/dist/agent/index.cjs +2 -2
  12. package/dist/agent/index.js +2 -2
  13. package/dist/agent/request-context-snapshot.d.ts +5 -0
  14. package/dist/agent/thread-stream-runtime.d.ts +26 -4
  15. package/dist/agent-builder/ee/index.cjs +1 -1
  16. package/dist/agent-builder/ee/index.js +1 -1
  17. package/dist/agent-controller/index.cjs +1 -1
  18. package/dist/agent-controller/index.js +1 -1
  19. package/dist/agent-controller/model-catalog-cache.d.ts +9 -5
  20. package/dist/agent-controller/session.d.ts +17 -0
  21. package/dist/{agent-controller-DckvJ7bq.cjs → agent-controller-C-WK9bMA.cjs} +67 -57
  22. package/dist/{agent-controller-vUU_atR-.js → agent-controller-Wxbc6702.js} +67 -57
  23. package/dist/background-tasks/index.cjs +1 -1
  24. package/dist/background-tasks/index.js +1 -1
  25. package/dist/{background-tasks-HAzB0JtC.js → background-tasks-DSMkHpbu.js} +1 -1
  26. package/dist/{background-tasks-By_1e9Gf.cjs → background-tasks-DcKNctMR.cjs} +1 -1
  27. package/dist/browser/index.cjs +1 -1
  28. package/dist/browser/index.js +1 -1
  29. package/dist/{builder-Dx8GMhFn.cjs → builder-CybmqbZt.cjs} +2 -2
  30. package/dist/{builder-CmtDqFLe.js → builder-PXwZnGYe.js} +2 -2
  31. package/dist/capabilities/302ai.json +197 -197
  32. package/dist/capabilities/abliteratedllm.json +35 -35
  33. package/dist/capabilities/abliteration-ai.json +10 -10
  34. package/dist/capabilities/above.json +19 -19
  35. package/dist/capabilities/adaption.json +15 -15
  36. package/dist/capabilities/adzuki.json +19 -19
  37. package/dist/capabilities/agentrouter.json +6 -6
  38. package/dist/capabilities/agnes.json +4 -4
  39. package/dist/capabilities/ai-router.json +8 -8
  40. package/dist/capabilities/aiand.json +25 -17
  41. package/dist/capabilities/aigrow.json +14 -14
  42. package/dist/capabilities/aimlapi.json +153 -153
  43. package/dist/capabilities/aixy.json +20 -20
  44. package/dist/capabilities/aki-io.json +11 -11
  45. package/dist/capabilities/alibaba-cn.json +93 -93
  46. package/dist/capabilities/alibaba-coding-plan-cn.json +4 -4
  47. package/dist/capabilities/alibaba-coding-plan.json +4 -4
  48. package/dist/capabilities/alibaba-token-plan-cn.json +47 -47
  49. package/dist/capabilities/alibaba-token-plan.json +49 -49
  50. package/dist/capabilities/alibaba.json +72 -72
  51. package/dist/capabilities/ambient.json +9 -9
  52. package/dist/capabilities/amd-tokenlab.json +5 -5
  53. package/dist/capabilities/amd.json +11 -11
  54. package/dist/capabilities/anthropic.json +40 -40
  55. package/dist/capabilities/anyapi.json +48 -48
  56. package/dist/capabilities/apiko.json +5 -5
  57. package/dist/capabilities/arcee.json +10 -10
  58. package/dist/capabilities/augure.json +5 -5
  59. package/dist/capabilities/auriko.json +18 -18
  60. package/dist/capabilities/bailing.json +4 -4
  61. package/dist/capabilities/baseten.json +41 -32
  62. package/dist/capabilities/bee.json +4 -4
  63. package/dist/capabilities/bothub.json +10 -10
  64. package/dist/capabilities/boundless.json +33 -33
  65. package/dist/capabilities/bumo.json +48 -48
  66. package/dist/capabilities/byteplus.json +35 -35
  67. package/dist/capabilities/cerebras.json +4 -4
  68. package/dist/capabilities/cheapaimodel.json +3 -3
  69. package/dist/capabilities/cheapest-token.json +28 -28
  70. package/dist/capabilities/chutes.json +43 -41
  71. package/dist/capabilities/cline-pass.json +33 -33
  72. package/dist/capabilities/cloudcode.json +7 -7
  73. package/dist/capabilities/cloudferro-sherlock.json +4 -4
  74. package/dist/capabilities/cloudflare-workers-ai.json +18 -18
  75. package/dist/capabilities/commandcode.json +147 -147
  76. package/dist/capabilities/concentrate.json +288 -279
  77. package/dist/capabilities/cortecs.json +108 -108
  78. package/dist/capabilities/crossmodel.json +157 -157
  79. package/dist/capabilities/crusoe.json +16 -16
  80. package/dist/capabilities/daoxe.json +9 -9
  81. package/dist/capabilities/databricks.json +131 -123
  82. package/dist/capabilities/deepinfra.json +95 -95
  83. package/dist/capabilities/deepseek.json +2 -2
  84. package/dist/capabilities/digitalocean.json +114 -115
  85. package/dist/capabilities/dothoosh.json +32 -32
  86. package/dist/capabilities/doubleword.json +26 -26
  87. package/dist/capabilities/edenai.json +298 -280
  88. package/dist/capabilities/empiriolabs.json +164 -164
  89. package/dist/capabilities/engy.json +23 -17
  90. package/dist/capabilities/entrim.json +4 -4
  91. package/dist/capabilities/evroc.json +17 -17
  92. package/dist/capabilities/ezkielyna.json +8 -8
  93. package/dist/capabilities/fastrouter.json +94 -94
  94. package/dist/capabilities/fireworks-ai.json +106 -95
  95. package/dist/capabilities/freemodel.json +9 -9
  96. package/dist/capabilities/friendli.json +31 -10
  97. package/dist/capabilities/frogbot.json +100 -100
  98. package/dist/capabilities/gisoo.json +18 -18
  99. package/dist/capabilities/gmicloud.json +19 -19
  100. package/dist/capabilities/google.json +59 -59
  101. package/dist/capabilities/graphn.json +10 -10
  102. package/dist/capabilities/greenpt.json +31 -31
  103. package/dist/capabilities/groq.json +5 -5
  104. package/dist/capabilities/helicone.json +87 -87
  105. package/dist/capabilities/hostinger-router.json +5 -5
  106. package/dist/capabilities/hpc-ai.json +9 -9
  107. package/dist/capabilities/huawei-maas.json +11 -11
  108. package/dist/capabilities/hubris.json +31 -31
  109. package/dist/capabilities/huggingface.json +95 -85
  110. package/dist/capabilities/humain.json +2 -2
  111. package/dist/capabilities/hyper.json +23 -23
  112. package/dist/capabilities/impossibl.json +157 -157
  113. package/dist/capabilities/inception.json +2 -2
  114. package/dist/capabilities/inceptron.json +4 -4
  115. package/dist/capabilities/inco.json +2 -2
  116. package/dist/capabilities/infer.json +11 -11
  117. package/dist/capabilities/inferall.json +8 -8
  118. package/dist/capabilities/inference-coop.json +6 -6
  119. package/dist/capabilities/inferenceapis.json +25 -25
  120. package/dist/capabilities/inferris.json +4 -4
  121. package/dist/capabilities/infersia.json +12 -12
  122. package/dist/capabilities/inferx.json +2 -2
  123. package/dist/capabilities/io-net.json +5 -5
  124. package/dist/capabilities/isoquant.json +4 -4
  125. package/dist/capabilities/iteracompute.json +43 -43
  126. package/dist/capabilities/jalapeno.json +10 -10
  127. package/dist/capabilities/jiekou.json +34 -34
  128. package/dist/capabilities/jzstoken.json +43 -43
  129. package/dist/capabilities/keln.json +21 -21
  130. package/dist/capabilities/kenari.json +120 -135
  131. package/dist/capabilities/kilo.json +671 -630
  132. package/dist/capabilities/kimchi.json +16 -16
  133. package/dist/capabilities/kimi-code-plan-cn.json +7 -7
  134. package/dist/capabilities/kimi-code-plan-global.json +7 -7
  135. package/dist/capabilities/kitani.json +2 -2
  136. package/dist/capabilities/klavo.json +25 -25
  137. package/dist/capabilities/korouter.json +31 -31
  138. package/dist/capabilities/kunavo.json +9 -9
  139. package/dist/capabilities/liquid.json +10 -10
  140. package/dist/capabilities/lithosai.json +2 -2
  141. package/dist/capabilities/llmgateway-providers.json +944 -906
  142. package/dist/capabilities/llmgateway.json +359 -348
  143. package/dist/capabilities/llmtr.json +25 -25
  144. package/dist/capabilities/logits.json +2 -2
  145. package/dist/capabilities/longcat.json +2 -2
  146. package/dist/capabilities/lowrouter.json +64 -64
  147. package/dist/capabilities/lyceum.json +14 -14
  148. package/dist/capabilities/melious.json +10 -10
  149. package/dist/capabilities/merge-gateway.json +268 -260
  150. package/dist/capabilities/meta.json +10 -10
  151. package/dist/capabilities/minimax-cn-coding-plan.json +5 -5
  152. package/dist/capabilities/minimax-cn.json +5 -5
  153. package/dist/capabilities/minimax-coding-plan.json +5 -5
  154. package/dist/capabilities/minimax.json +5 -5
  155. package/dist/capabilities/mistral.json +23 -15
  156. package/dist/capabilities/mixlayer.json +5 -5
  157. package/dist/capabilities/modal.json +11 -11
  158. package/dist/capabilities/model-oracle-ai.json +22 -22
  159. package/dist/capabilities/modelis.json +21 -21
  160. package/dist/capabilities/modelscope.json +2 -2
  161. package/dist/capabilities/modular.json +15 -15
  162. package/dist/capabilities/moneo.json +7 -7
  163. package/dist/capabilities/moonshotai-cn.json +6 -6
  164. package/dist/capabilities/moonshotai.json +6 -6
  165. package/dist/capabilities/morph.json +19 -19
  166. package/dist/capabilities/munito-eu.json +4 -4
  167. package/dist/capabilities/munito.json +5 -5
  168. package/dist/capabilities/nan.json +21 -21
  169. package/dist/capabilities/nano-gpt.json +594 -598
  170. package/dist/capabilities/nearai.json +121 -121
  171. package/dist/capabilities/nebius.json +42 -34
  172. package/dist/capabilities/neon.json +125 -125
  173. package/dist/capabilities/neuralwatt.json +41 -41
  174. package/dist/capabilities/nokeep.json +4 -4
  175. package/dist/capabilities/novita-ai.json +136 -136
  176. package/dist/capabilities/nvidia.json +29 -29
  177. package/dist/capabilities/oathbreaker.json +4 -4
  178. package/dist/capabilities/obscurify.json +24 -24
  179. package/dist/capabilities/oci.json +7 -7
  180. package/dist/capabilities/ofox.json +251 -251
  181. package/dist/capabilities/ollama-cloud.json +57 -57
  182. package/dist/capabilities/openai.json +56 -59
  183. package/dist/capabilities/opencode-go.json +93 -84
  184. package/dist/capabilities/openreason.json +5 -5
  185. package/dist/capabilities/openrouter.json +534 -532
  186. package/dist/capabilities/opper.json +31 -31
  187. package/dist/capabilities/orcarouter.json +292 -276
  188. package/dist/capabilities/outerlabs.json +32 -32
  189. package/dist/capabilities/ovhcloud.json +23 -23
  190. package/dist/capabilities/perplexity-agent.json +64 -64
  191. package/dist/capabilities/phala.json +31 -31
  192. package/dist/capabilities/poe.json +139 -139
  193. package/dist/capabilities/poolside.json +2 -2
  194. package/dist/capabilities/powerspring.json +8 -8
  195. package/dist/capabilities/primalabs.json +8 -8
  196. package/dist/capabilities/prime.json +133 -125
  197. package/dist/capabilities/privatemode-ai.json +4 -4
  198. package/dist/capabilities/proxystacks.json +3 -3
  199. package/dist/capabilities/qiniu-ai.json +14 -14
  200. package/dist/capabilities/refuseless.json +6 -6
  201. package/dist/capabilities/regolo-ai.json +8 -8
  202. package/dist/capabilities/requesty.json +201 -201
  203. package/dist/capabilities/ruapi.json +24 -24
  204. package/dist/capabilities/runcrate.json +8 -8
  205. package/dist/capabilities/runinfra.json +13 -13
  206. package/dist/capabilities/sakana.json +2 -2
  207. package/dist/capabilities/sandbase.json +23 -23
  208. package/dist/capabilities/sarvam.json +11 -11
  209. package/dist/capabilities/scaleway.json +15 -15
  210. package/dist/capabilities/scnet-token-plan.json +13 -13
  211. package/dist/capabilities/scx-ai.json +23 -23
  212. package/dist/capabilities/sensenova.json +13 -13
  213. package/dist/capabilities/siliconflow-cn.json +46 -46
  214. package/dist/capabilities/siliconflow.json +57 -57
  215. package/dist/capabilities/snowflake-cortex.json +21 -21
  216. package/dist/capabilities/sokkan.json +6 -6
  217. package/dist/capabilities/sparrowcodes.json +19 -19
  218. package/dist/capabilities/standardcompute.json +69 -69
  219. package/dist/capabilities/steadyrouter.json +40 -40
  220. package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
  221. package/dist/capabilities/stepfun-ai.json +6 -6
  222. package/dist/capabilities/stepfun-step-plan.json +6 -6
  223. package/dist/capabilities/stepfun.json +6 -6
  224. package/dist/capabilities/stepping-stone.json +21 -21
  225. package/dist/capabilities/superbot-gg.json +4 -4
  226. package/dist/capabilities/synthetic.json +10 -10
  227. package/dist/capabilities/synthorai.json +24 -24
  228. package/dist/capabilities/teamorouter.json +14 -14
  229. package/dist/capabilities/teapot-router.json +4 -4
  230. package/dist/capabilities/tencent-token-plan-intl.json +16 -16
  231. package/dist/capabilities/tencent-token-plan.json +35 -35
  232. package/dist/capabilities/tencent-tokenhub.json +44 -44
  233. package/dist/capabilities/tensorx.json +49 -49
  234. package/dist/capabilities/the-grid-ai.json +28 -28
  235. package/dist/capabilities/thinkingmachines.json +76 -76
  236. package/dist/capabilities/tinfoil.json +9 -9
  237. package/dist/capabilities/togetherai.json +55 -55
  238. package/dist/capabilities/tokengo.json +24 -24
  239. package/dist/capabilities/tokenharbor.json +214 -214
  240. package/dist/capabilities/tokenify.json +8 -8
  241. package/dist/capabilities/trustedrouter.json +6 -6
  242. package/dist/capabilities/trustedtokens.json +19 -19
  243. package/dist/capabilities/umans-ai-coding-plan.json +11 -11
  244. package/dist/capabilities/umans-ai.json +11 -11
  245. package/dist/capabilities/uncensuredai.json +5 -5
  246. package/dist/capabilities/unrestricted.json +6 -6
  247. package/dist/capabilities/uplinkswitch.json +18 -18
  248. package/dist/capabilities/upstage.json +2 -2
  249. package/dist/capabilities/vancine.json +12 -12
  250. package/dist/capabilities/vercel.json +562 -549
  251. package/dist/capabilities/verda.json +4 -4
  252. package/dist/capabilities/vivgrid.json +62 -62
  253. package/dist/capabilities/volcengine-coding-plan.json +24 -24
  254. package/dist/capabilities/volcengine.json +31 -31
  255. package/dist/capabilities/vultr.json +18 -18
  256. package/dist/capabilities/wafer.ai.json +18 -18
  257. package/dist/capabilities/wallaby.json +5 -5
  258. package/dist/capabilities/wally.json +9 -9
  259. package/dist/capabilities/wandb.json +20 -20
  260. package/dist/capabilities/watt.json +20 -20
  261. package/dist/capabilities/xai.json +6 -6
  262. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -2
  263. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -2
  264. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -2
  265. package/dist/capabilities/xiaomi.json +3 -3
  266. package/dist/capabilities/xpersona.json +13 -13
  267. package/dist/capabilities/xxapi.json +27 -27
  268. package/dist/capabilities/zai-coding-plan.json +15 -15
  269. package/dist/capabilities/zai.json +29 -29
  270. package/dist/capabilities/zenifra.json +22 -22
  271. package/dist/capabilities/zenmux.json +185 -185
  272. package/dist/capabilities/zerogpu.json +14 -14
  273. package/dist/capabilities/zhipuai-coding-plan.json +3 -3
  274. package/dist/capabilities/zhipuai.json +27 -27
  275. package/dist/capabilities/zro.json +4 -4
  276. package/dist/channels/index.cjs +2 -2
  277. package/dist/channels/index.js +2 -2
  278. package/dist/{channels-DChC1kXm.js → channels-Cxy4jW11.js} +1 -1
  279. package/dist/{channels-BamLzaJG.cjs → channels-DNOI029U.cjs} +1 -1
  280. package/dist/coding-agent/index.cjs +1 -1
  281. package/dist/coding-agent/index.js +1 -1
  282. package/dist/{constants-Dro9fuhk.js → constants-C2Q-ZI5d.js} +6 -0
  283. package/dist/{constants-B2FVV_2e.cjs → constants-DPHwzvan.cjs} +6 -0
  284. package/dist/datasets/index.cjs +2 -2
  285. package/dist/datasets/index.js +2 -2
  286. package/dist/docs/SKILL.md +1 -1
  287. package/dist/docs/assets/SOURCE_MAP.json +1158 -1153
  288. package/dist/docs/references/docs-agents-human-in-the-loop.md +1 -1
  289. package/dist/docs/references/docs-agents-resumable-streams.md +3 -3
  290. package/dist/docs/references/docs-channels.md +50 -3
  291. package/dist/docs/references/docs-deployment-workers.md +10 -4
  292. package/dist/docs/references/docs-develop.md +2 -0
  293. package/dist/docs/references/docs-evals-experiments.md +2 -0
  294. package/dist/docs/references/docs-guides-build-an-eval-loop.md +5 -1
  295. package/dist/docs/references/docs-guides-overview.md +2 -1
  296. package/dist/docs/references/docs-harness-durable-agents.md +17 -15
  297. package/dist/docs/references/docs-knowledge-importers.md +11 -1
  298. package/dist/docs/references/docs-knowledge-scopes-and-access.md +26 -0
  299. package/dist/docs/references/docs-memory-message-history.md +24 -16
  300. package/dist/docs/references/docs-memory-overview.md +21 -17
  301. package/dist/docs/references/docs-sandbox-overview.md +12 -10
  302. package/dist/docs/references/docs-server-mcp.md +68 -0
  303. package/dist/docs/references/docs-server-pubsub.md +25 -16
  304. package/dist/docs/references/docs-signals-running-across-processes.md +9 -3
  305. package/dist/docs/references/docs-signals-sending-signals.md +1 -1
  306. package/dist/docs/references/docs-workflows-control-flow.md +20 -0
  307. package/dist/docs/references/docs-workflows-overview.md +3 -3
  308. package/dist/docs/references/integrations-observability-arthur.md +1 -1
  309. package/dist/docs/references/reference-agent-controller-agent-controller-class.md +1 -1
  310. package/dist/docs/references/reference-agent-controller-session.md +9 -0
  311. package/dist/docs/references/reference-agents-agent.md +3 -1
  312. package/dist/docs/references/reference-agents-durable-agent.md +3 -3
  313. package/dist/docs/references/reference-configuration.md +60 -0
  314. package/dist/docs/references/reference-knowledge-knowledge-class.md +1 -1
  315. package/dist/docs/references/reference-knowledge-knowledge-tools.md +1 -1
  316. package/dist/docs/references/reference-observability-tracing-bridges-datadog.md +12 -11
  317. package/dist/docs/references/reference-processors-processor-interface.md +1 -1
  318. package/dist/docs/references/reference-pubsub-base.md +1 -1
  319. package/dist/docs/references/reference-pubsub-caching-pubsub.md +1 -1
  320. package/dist/docs/references/reference-pubsub-google-cloud-pubsub.md +13 -7
  321. package/dist/docs/references/reference-pubsub-lease-provider.md +4 -0
  322. package/dist/docs/references/reference-pubsub-redis-streams.md +18 -9
  323. package/dist/docs/references/reference-pubsub-valkey-streams.md +25 -7
  324. package/dist/docs/references/reference-storage-overview.md +1 -1
  325. package/dist/docs/references/reference-voice-overview.md +0 -27
  326. package/dist/docs/references/reference-workflows-step.md +1 -1
  327. package/dist/docs/references/reference-workspace-workspace-class.md +3 -1
  328. package/dist/evals/index.cjs +2 -2
  329. package/dist/evals/index.js +2 -2
  330. package/dist/evals/scoreTraces/index.cjs +2 -2
  331. package/dist/evals/scoreTraces/index.js +2 -2
  332. package/dist/events/caching-pubsub.d.ts +3 -11
  333. package/dist/events/index.cjs +1 -1
  334. package/dist/events/index.js +1 -1
  335. package/dist/events/pubsub.d.ts +2 -1
  336. package/dist/{execution-fence-BBKnrhWR.cjs → execution-fence-C1nozqra.cjs} +1118 -309
  337. package/dist/{execution-fence--VdnD7p4.js → execution-fence-pJB0qqFJ.js} +1107 -310
  338. package/dist/harness/index.cjs +1 -1
  339. package/dist/harness/index.js +1 -1
  340. package/dist/index.cjs +1 -1
  341. package/dist/index.js +1 -1
  342. package/dist/knowledge/importers/local-host.d.ts +2 -1
  343. package/dist/knowledge/importers/sink.d.ts +6 -0
  344. package/dist/knowledge/importers/types.d.ts +5 -0
  345. package/dist/knowledge/index.cjs +105 -20
  346. package/dist/knowledge/index.js +105 -21
  347. package/dist/knowledge/links.d.ts +19 -6
  348. package/dist/llm/index.cjs +3 -3
  349. package/dist/llm/index.js +3 -3
  350. package/dist/llm/model/gateways/mastra.d.ts +19 -0
  351. package/dist/llm/model/gateways/refreshing-cache.d.ts +52 -0
  352. package/dist/llm/model/provider-types.generated.d.ts +7574 -7544
  353. package/dist/llm/reasoning/account-switch.d.ts +50 -0
  354. package/dist/llm/reasoning/index.cjs +65 -0
  355. package/dist/llm/reasoning/index.d.ts +1 -0
  356. package/dist/llm/reasoning/index.js +61 -1
  357. package/dist/{llm-DknPJDW6.cjs → llm-VhPqyULU.cjs} +2 -2
  358. package/dist/{llm-ccA_1Q-H.js → llm-_z1lIfCN.js} +2 -2
  359. package/dist/loop/index.cjs +2 -2
  360. package/dist/loop/index.js +2 -2
  361. package/dist/loop/suspended-run-auto-resume.d.ts +15 -0
  362. package/dist/loop/workflows/agentic-execution/background-task-check-step.d.ts +4 -0
  363. package/dist/loop/workflows/agentic-execution/goal-step.d.ts +4 -0
  364. package/dist/loop/workflows/agentic-execution/is-task-complete-step.d.ts +4 -0
  365. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +4 -0
  366. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +2 -0
  367. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +1 -1
  368. package/dist/loop/workflows/schema.d.ts +13 -0
  369. package/dist/{manager-D9F0i7O2.cjs → manager-BT70SgFz.cjs} +3 -3
  370. package/dist/{manager-DWX6-Cx4.js → manager-C3Kx39p_.js} +3 -3
  371. package/dist/mastra/index.cjs +1 -1
  372. package/dist/mastra/index.d.ts +35 -11
  373. package/dist/mastra/index.js +1 -1
  374. package/dist/{mastra-BzWL4xI8.cjs → mastra-CQGD2RoN.cjs} +108 -20
  375. package/dist/{mastra-oUDN81l8.js → mastra-fJ0iKYGP.js} +108 -20
  376. package/dist/memory/index.cjs +2 -2
  377. package/dist/memory/index.js +2 -2
  378. package/dist/{model-BnD7SPlA.cjs → model-D9NDbf-e.cjs} +1 -1
  379. package/dist/{model-BwxfS6T_.js → model-DmBDBf-q.js} +1 -1
  380. package/dist/{netlify-CS0VDbb9.cjs → netlify-DNaNhels.cjs} +1 -1
  381. package/dist/{netlify-DcY9gHCJ.js → netlify-_yV5Nwud.js} +1 -1
  382. package/dist/notifications/index.cjs +1 -1
  383. package/dist/notifications/index.js +1 -1
  384. package/dist/{output-helpers-k2-48ssH.js → output-helpers-D-qplq22.js} +13 -15
  385. package/dist/{output-helpers-By5FbLpp.cjs → output-helpers-D4O_oFne.cjs} +12 -14
  386. package/dist/processor-provider/index.cjs +1 -1
  387. package/dist/processor-provider/index.js +1 -1
  388. package/dist/processors/index.cjs +2 -2
  389. package/dist/processors/index.js +2 -2
  390. package/dist/{provider-registry-BvbEoScB.js → provider-registry-C4tv__fr.js} +22203 -21980
  391. package/dist/{provider-registry-OggbU6OE.cjs → provider-registry-_BUQuSKb.cjs} +21869 -21628
  392. package/dist/provider-registry.json +22243 -22188
  393. package/dist/{registry-generator-BFOQQHyt.js → registry-generator-CenhQnEi.js} +1 -1
  394. package/dist/{registry-generator-CDaf48a6.cjs → registry-generator-D7lsLJC-.cjs} +1 -1
  395. package/dist/{rehydrate-CFoKaNlm.js → rehydrate-CuWN_5No.js} +2 -2
  396. package/dist/{rehydrate-QeS0NjGw.cjs → rehydrate-SpC_gJCY.cjs} +2 -2
  397. package/dist/relevance/index.cjs +2 -2
  398. package/dist/relevance/index.js +2 -2
  399. package/dist/{scheduler-0ShtMM1I.js → scheduler-D1qdie5k.js} +4 -2
  400. package/dist/{scheduler-CMjK0LoQ.cjs → scheduler-DE5lcHJA.cjs} +4 -2
  401. package/dist/server/index.d.ts +1 -1
  402. package/dist/server/types.d.ts +57 -0
  403. package/dist/storage/constants.cjs +1 -1
  404. package/dist/storage/constants.js +1 -1
  405. package/dist/storage/domains/knowledge/base.d.ts +11 -0
  406. package/dist/storage/domains/knowledge/inmemory.d.ts +1 -0
  407. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +4 -0
  408. package/dist/storage/domains/knowledge/pages.d.ts +1 -1
  409. package/dist/storage/domains/memory/base.d.ts +6 -1
  410. package/dist/storage/domains/observability/tracing.d.ts +12 -0
  411. package/dist/storage/index.cjs +4 -3
  412. package/dist/storage/index.js +4 -4
  413. package/dist/stream/index.cjs +2 -2
  414. package/dist/stream/index.js +2 -2
  415. package/dist/{stream-D2rv1Ut1.js → stream-BfSwqzPi.js} +1 -1
  416. package/dist/{stream-CNqAlDJF.cjs → stream-CW3d1Xg6.cjs} +1 -1
  417. package/dist/test-utils/llm-mock.cjs +1 -1
  418. package/dist/test-utils/llm-mock.js +1 -1
  419. package/dist/tool-loop-agent/index.cjs +1 -1
  420. package/dist/tool-loop-agent/index.js +1 -1
  421. package/dist/{tool-loop-agent-CFsOjueT.js → tool-loop-agent-B4_o4-Me.js} +3 -3
  422. package/dist/{tool-loop-agent-Dusqj7-j.cjs → tool-loop-agent-JN_oKyfY.cjs} +3 -3
  423. package/dist/{utils-CIuOHPoS.cjs → utils-Bq606mC8.cjs} +1 -1
  424. package/dist/{utils-DLnCt6E9.js → utils-CnpMuTyD.js} +1 -1
  425. package/dist/utils.cjs +1 -1
  426. package/dist/utils.js +1 -1
  427. package/dist/{validate-1zReLtWc.cjs → validate-CFv6HWXx.cjs} +1 -1
  428. package/dist/{validate-ShLcQTA5.js → validate-Db2C7Sj_.js} +1 -1
  429. package/dist/vector/index.cjs +1 -1
  430. package/dist/vector/index.js +1 -1
  431. package/dist/worker/index.cjs +1 -1
  432. package/dist/worker/index.d.ts +1 -1
  433. package/dist/worker/index.js +1 -1
  434. package/dist/worker/workers/orchestration-worker.d.ts +13 -0
  435. package/dist/{worker-BPNrwCFs.cjs → worker-CNIBQPQy.cjs} +117 -32
  436. package/dist/{worker-CQ8rTJwQ.cjs → worker-IZeSOZjg.cjs} +2 -2
  437. package/dist/{worker-CKcQcPl8.js → worker-UXFAgWOK.js} +2 -2
  438. package/dist/{worker-ngt-F1Iv.js → worker-X0fAJfcx.js} +117 -32
  439. package/dist/{workflow-B_e5wMmz.cjs → workflow-CMLLlVDc.cjs} +4 -4
  440. package/dist/{workflow-XDIVRsu4.js → workflow-DfXq2p2f.js} +4 -4
  441. package/dist/workflows/builder/index.cjs +1 -1
  442. package/dist/workflows/builder/index.js +1 -1
  443. package/dist/workflows/evented/index.cjs +1 -1
  444. package/dist/workflows/evented/index.js +1 -1
  445. package/dist/workflows/evented/setup-warning.d.ts +20 -0
  446. package/dist/workflows/index.cjs +5 -5
  447. package/dist/workflows/index.js +5 -5
  448. package/dist/workflows/scheduler/types.d.ts +3 -0
  449. package/package.json +8 -8
  450. package/src/llm/model/provider-types.generated.d.ts +7574 -7544
@@ -3,8 +3,8 @@ const require_logger = require("./logger-CvzZYuJd.cjs");
3
3
  const require_base = require("./base-BIzR1D3_.cjs");
4
4
  const require_error = require("./error-D90lJ6M7.cjs");
5
5
  const require_error$1 = require("./error-L1V4uUbd.cjs");
6
- const require_output_helpers = require("./output-helpers-By5FbLpp.cjs");
7
- const require_stream = require("./stream-CNqAlDJF.cjs");
6
+ const require_output_helpers = require("./output-helpers-D4O_oFne.cjs");
7
+ const require_stream = require("./stream-CW3d1Xg6.cjs");
8
8
  const require_workflows_constants = require("./workflows/constants.cjs");
9
9
  const require_request_context = require("./request-context-D9RXYCy8.cjs");
10
10
  const require_observability = require("./observability-VaoaeadK.cjs");
@@ -12,9 +12,9 @@ const require_storage = require("./storage-CfG0I2aF.cjs");
12
12
  const require_utils = require("./utils-D-eNsgDM.cjs");
13
13
  const require_tool = require("./tool-Dn9WSDVn.cjs");
14
14
  const require_error_count = require("./error-count-DeDpeWU2.cjs");
15
- const require_utils$1 = require("./utils-CIuOHPoS.cjs");
15
+ const require_utils$1 = require("./utils-Bq606mC8.cjs");
16
16
  const require_ee_iTj2bRDt = require("./ee-iTj2bRDt-D3-QLGDF.cjs");
17
- const require_background_tasks = require("./background-tasks-By_1e9Gf.cjs");
17
+ const require_background_tasks = require("./background-tasks-DcKNctMR.cjs");
18
18
  const require_toolchecks = require("./toolchecks-DbBsQGHW.cjs");
19
19
  const require_stream$1 = require("./stream-BGbj9jAU.cjs");
20
20
  const require_fetchWithRetry = require("./fetchWithRetry-f5k4p7_1.cjs");
@@ -22,23 +22,23 @@ const require_utils_safe_stringify = require("./utils/safe-stringify.cjs");
22
22
  const require_deep_equal = require("./deep-equal-TMDmByBC.cjs");
23
23
  const require_dynamic_argument = require("./dynamic-argument-CUc1BBOS.cjs");
24
24
  const require_message_list = require("./message-list-C0F2sDNC.cjs");
25
- const require_llm = require("./llm-DknPJDW6.cjs");
25
+ const require_llm = require("./llm-VhPqyULU.cjs");
26
26
  const require_payload_transform = require("./payload-transform-CWgnsO9w.cjs");
27
27
  const require_signals = require("./signals-CWxAMEmE.cjs");
28
28
  const require_to_prompt = require("./to-prompt-CG-LyaBY.cjs");
29
29
  const require_dist = require("./dist-P2rjrlmj.cjs");
30
30
  const require_dist$1 = require("./dist-CXeCeeW7.cjs");
31
31
  const require_model = require("./model-jBymoqGa.cjs");
32
- const require_provider_registry = require("./provider-registry-OggbU6OE.cjs");
32
+ const require_provider_registry = require("./provider-registry-_BUQuSKb.cjs");
33
33
  const require_inmemory = require("./inmemory-Dc86VWGB.cjs");
34
- const require_model$1 = require("./model-BnD7SPlA.cjs");
34
+ const require_model$1 = require("./model-D9NDbf-e.cjs");
35
35
  const require_predicate_index = require("./predicate/index.cjs");
36
36
  const require_classifier_index = require("./classifier/index.cjs");
37
37
  const require_observability_context_storage = require("./observability/context-storage.cjs");
38
38
  const require_hooks = require("./hooks-D7VDBETj.cjs");
39
39
  const require_schedules = require("./schedules-BZS8McF7.cjs");
40
40
  const require_state_processor = require("./state-processor-DaSmhVUX.cjs");
41
- const require_constants = require("./constants-B2FVV_2e.cjs");
41
+ const require_constants = require("./constants-DPHwzvan.cjs");
42
42
  const require_signal_provider = require("./signal-provider-D9gbevHN.cjs");
43
43
  const require_slugify = require("./slugify-B_WzG9IY.cjs");
44
44
  const require_workspace = require("./workspace-BQD4tcQi.cjs");
@@ -57,6 +57,7 @@ const require_filesystem$4 = require("./filesystem-BP5yz5LG.cjs");
57
57
  const require_filesystem$5 = require("./filesystem-Fpsu7e24.cjs");
58
58
  const require_agent_skills_resolver = require("./agent-skills-resolver-2d8k7ioj.cjs");
59
59
  const require_voice = require("./voice-Cuev6Md3.cjs");
60
+ let _isaacs_ttlcache = require("@isaacs/ttlcache");
60
61
  let zod_v4 = require("zod/v4");
61
62
  let crypto$1 = require("crypto");
62
63
  let _mastra_schema_compat_json_to_zod = require("@mastra/schema-compat/json-to-zod");
@@ -71,7 +72,6 @@ let zod_v4_locales_en_js = require("zod/v4/locales/en.js");
71
72
  zod_v4_locales_en_js = require_rolldown_runtime.__toESM(zod_v4_locales_en_js, 1);
72
73
  let fs = require("fs");
73
74
  let path = require("path");
74
- let _isaacs_ttlcache = require("@isaacs/ttlcache");
75
75
  let async_hooks = require("async_hooks");
76
76
  let fastq = require("fastq");
77
77
  fastq = require_rolldown_runtime.__toESM(fastq, 1);
@@ -506,6 +506,11 @@ const MASTRA_DURABLE_EXECUTIONS_KEY = "mastra__durableExecutions";
506
506
  */
507
507
  const MASTRA_DURABLE_SEGMENTS_KEY = "mastra__durableSegments";
508
508
  /**
509
+ * Reserved request-context key carrying `Record<runId, boolean>`: the `autoResumeSuspendedTools` a resumed execution
510
+ * runs with, so a step that suspends persists it on whichever worker runs the step. (#30190)
511
+ */
512
+ const MASTRA_DURABLE_AUTO_RESUME_KEY = "mastra__durableAutoResume";
513
+ /**
509
514
  * JSON-safe snapshot of `requestContext.entries()`, for a run that continues
510
515
  * somewhere the live context can't follow: a durable step, or a claimed
511
516
  * thread owner in another process. Best-effort: entries that fail a JSON
@@ -523,6 +528,7 @@ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
523
528
  if (key === "mastra__versions") continue;
524
529
  if (key === "mastra__durableExecutions") continue;
525
530
  if (key === "mastra__durableSegments") continue;
531
+ if (key === "mastra__durableAutoResume") continue;
526
532
  if (key === "__mastra_chat_channel_render") continue;
527
533
  const json = require_utils_safe_stringify.boundedStringify(value);
528
534
  if (json === void 0) {
@@ -12325,6 +12331,15 @@ var EventedExecutionEngine = class extends ExecutionEngine {
12325
12331
  const DOCS_URL = "https://mastra.ai/docs/server/pubsub#evented-workflows-and-agents";
12326
12332
  const warnedHosts = /* @__PURE__ */ new WeakSet();
12327
12333
  const warnedSignalHosts = /* @__PURE__ */ new WeakSet();
12334
+ const warnedCacheHosts = /* @__PURE__ */ new WeakSet();
12335
+ /**
12336
+ * Whether each process keeps its own copy of the run logs `cache` holds while
12337
+ * `pubsub` carries the runs to other processes. Only `InMemoryServerCache` is
12338
+ * known to be process-local; any other cache is assumed to be shared.
12339
+ */
12340
+ function keepsRunLogsInProcess(pubsub, cache) {
12341
+ return cache instanceof require_inmemory.InMemoryServerCache && reachesOtherProcesses(pubsub);
12342
+ }
12328
12343
  /**
12329
12344
  * Evented runs spread over several processes need a pubsub that hands a stopped
12330
12345
  * worker's event to another worker, and a store whose step guards let one
@@ -12370,6 +12385,26 @@ function warnUnsharedAgentSignals(mastra, reason) {
12370
12385
  warnedSignalHosts.add(mastra);
12371
12386
  mastra.getLogger()?.warn(`Signals sent to running evented agents aren't supported on several processes with this setup: ${missing}. See ${DOCS_URL}`);
12372
12387
  }
12388
+ /**
12389
+ * An evented agent's steps append their stream frames to the run's log in the
12390
+ * server cache, which also holds the run's ownership record. With a cache each
12391
+ * process keeps to itself, a step in another process publishes its frames
12392
+ * unnumbered, so `observe(runId, { offset })` can't skip them, and another
12393
+ * process can't observe or stop the run. Logs once per Mastra instance, apart
12394
+ * from {@link warnUnsupportedEventedSetup} so that one does not hide this.
12395
+ *
12396
+ * Called when an evented agent is registered, in every process that can run
12397
+ * its steps, including dedicated workers that never start a run.
12398
+ */
12399
+ function warnProcessLocalServerCache(mastra) {
12400
+ if (warnedCacheHosts.has(mastra) || process.env.MASTRA_DISABLE_EVENTED_SETUP_WARNING === "true") return;
12401
+ const pubsub = mastra.pubsub;
12402
+ const wrapped = pubsub instanceof require_output_helpers.CachingPubSub;
12403
+ if (!keepsRunLogsInProcess(pubsub, wrapped ? pubsub.getCache() : mastra.serverCache)) return;
12404
+ const problem = wrapped ? `the configured CachingPubSub keeps run logs in an InMemoryServerCache, which only this process reads. Give that CachingPubSub a server cache every process shares` : `the server cache is an InMemoryServerCache, which only this process reads. Set \`cache\` on Mastra to a server cache every process shares`;
12405
+ warnedCacheHosts.add(mastra);
12406
+ mastra.getLogger()?.warn(`Evented agents aren't supported on several processes with this setup: ${problem}, such as RedisServerCache. See ${DOCS_URL}`);
12407
+ }
12373
12408
  // src/storage/workflow-step-guard.ts
12374
12409
  var WorkflowStepConflictError = class extends Error {
12375
12410
  reason;
@@ -12575,6 +12610,23 @@ function carrySegmentSpans(target, runId, segment) {
12575
12610
  else target[MASTRA_DURABLE_SEGMENTS_KEY] = next;
12576
12611
  }
12577
12612
  /**
12613
+ * Record the `autoResumeSuspendedTools` a resumed execution of `runId` runs with on the request context it hands the
12614
+ * engine, which carries it to every step of the segment wherever it runs. (#30190)
12615
+ */
12616
+ function carrySegmentAutoResume(requestContext, runId, value) {
12617
+ const current = requestContext.getRaw(MASTRA_DURABLE_AUTO_RESUME_KEY);
12618
+ requestContext.setRaw(MASTRA_DURABLE_AUTO_RESUME_KEY, {
12619
+ ...current && typeof current === "object" ? current : {},
12620
+ [runId]: value
12621
+ });
12622
+ }
12623
+ /** The `autoResumeSuspendedTools` a resume carried for the current execution of `runId`, if any. */
12624
+ function segmentAutoResume(requestContext, runId) {
12625
+ const all = requestContext?.getRaw?.(MASTRA_DURABLE_AUTO_RESUME_KEY);
12626
+ const value = all && typeof all === "object" ? all[runId] : void 0;
12627
+ return typeof value === "boolean" ? value : void 0;
12628
+ }
12629
+ /**
12578
12630
  * The pair the current execution reports under: the one a resume or recovery carried for `runId`,
12579
12631
  * else the run's first pair from `state` (the workflow input or the loop state). A carried `null`
12580
12632
  * means the execution opened no spans, so its steps end none. `carried` tells the two apart.
@@ -14466,7 +14518,7 @@ function closeStoredSignalRun({ mastra, runId, input, requestContext, state, dea
14466
14518
  agentId: input?.agentId,
14467
14519
  threadId: input?.state?.threadId
14468
14520
  });
14469
- return;
14521
+ return false;
14470
14522
  }
14471
14523
  const saved = typeof state === "function" ? await state() : state;
14472
14524
  await queue.store.closeSignalRun({
@@ -14474,11 +14526,13 @@ function closeStoredSignalRun({ mastra, runId, input, requestContext, state, dea
14474
14526
  runId,
14475
14527
  consumedIds: readConsumedSignalIds(saved)
14476
14528
  });
14529
+ return true;
14477
14530
  } catch (error) {
14478
14531
  mastra?.getLogger?.()?.warn?.("Could not close the stored signals of an ended run", {
14479
14532
  runId,
14480
14533
  error
14481
14534
  });
14535
+ return false;
14482
14536
  }
14483
14537
  })();
14484
14538
  }
@@ -15772,7 +15826,7 @@ function createDurableAgentStream(options) {
15772
15826
  armIdleTimer();
15773
15827
  resolveReady();
15774
15828
  releaseTerminalSubscription();
15775
- }).catch((error) => {
15829
+ }).catch(async (error) => {
15776
15830
  pubsub.unsubscribe(topic, subscribedCallback).catch((unsubscribeError) => {
15777
15831
  logError(`[DurableAgentStream] Failed to unsubscribe from ${topic}:`, unsubscribeError);
15778
15832
  });
@@ -15782,6 +15836,11 @@ function createDurableAgentStream(options) {
15782
15836
  markTerminated();
15783
15837
  if ((ctrl.desiredSize ?? 0) > 0) require_stream.safeError(ctrl, error);
15784
15838
  else pendingRejection = error;
15839
+ try {
15840
+ await onError?.({ error });
15841
+ } catch (callbackError) {
15842
+ logError(`[DurableAgentStream] onError callback error:`, callbackError);
15843
+ }
15785
15844
  });
15786
15845
  },
15787
15846
  pull(ctrl) {
@@ -16322,7 +16381,6 @@ function scopedRunStorage(runId, runStorage) {
16322
16381
  var StepExecutor = class extends require_base.MastraBase {
16323
16382
  mastra;
16324
16383
  #stepPubsub;
16325
- #warnedUnnumbered = false;
16326
16384
  constructor({ mastra }) {
16327
16385
  super({
16328
16386
  name: "StepExecutor",
@@ -16355,31 +16413,24 @@ var StepExecutor = class extends require_base.MastraBase {
16355
16413
  * numbering the same run from 0 in its own cache would have observers drop
16356
16414
  * its frames as late duplicates. So with a process-local cache behind a
16357
16415
  * cross-process transport, steps only append to logs this process already
16358
- * holds — the caller writes the run's `start` frame before any step runs, so
16416
+ * holds. The caller writes the run's `start` frame before any step runs, so
16359
16417
  * steps in the caller's process are numbered (#28324) and steps on other
16360
- * workers publish unnumbered (live-only).
16418
+ * workers publish unnumbered (live-only). Mastra warns about that setup when
16419
+ * the evented agent is registered (`warnProcessLocalServerCache`).
16361
16420
  */
16362
16421
  #getStepPubsub() {
16363
16422
  if (this.#stepPubsub) return this.#stepPubsub;
16364
16423
  const inner = this.mastra.pubsub;
16365
16424
  const cache = this.mastra?.serverCache;
16366
16425
  if (inner instanceof require_output_helpers.CachingPubSub) this.#stepPubsub = inner;
16367
- else if (cache) {
16368
- const processLocalLogs = cache instanceof require_inmemory.InMemoryServerCache && reachesOtherProcesses(inner);
16369
- this.#stepPubsub = new require_output_helpers.CachingPubSub(inner, cache, {
16370
- shouldCache: (topic) => !require_output_helpers.isRunLocalTopic(topic),
16371
- extendExistingLogsOnly: processLocalLogs,
16372
- onUnlogged: (topic) => this.#warnUnnumberedAgentStream(topic),
16373
- logger: this.logger
16374
- });
16375
- } else this.#stepPubsub = inner;
16426
+ else if (cache) this.#stepPubsub = new require_output_helpers.CachingPubSub(inner, cache, {
16427
+ shouldCache: (topic) => !require_output_helpers.isRunLocalTopic(topic),
16428
+ extendExistingLogsOnly: keepsRunLogsInProcess(inner, cache),
16429
+ logger: this.logger
16430
+ });
16431
+ else this.#stepPubsub = inner;
16376
16432
  return this.#stepPubsub;
16377
16433
  }
16378
- #warnUnnumberedAgentStream(topic) {
16379
- if (this.#warnedUnnumbered || !topic.startsWith(AGENT_STREAM_TOPIC(""))) return;
16380
- this.#warnedUnnumbered = true;
16381
- this.logger.warn(`Agent stream frames published from this process are not numbered: the run started in another process and the in-memory server cache is process-local, so observe(runId, { offset }) cannot skip these frames. Configure a shared server cache (e.g. RedisServerCache) on Mastra.`, { topic });
16382
- }
16383
16434
  /**
16384
16435
  * Creates an output writer function that publishes chunks to the workflow event stream.
16385
16436
  * @param runId - The workflow run ID
@@ -24760,6 +24811,8 @@ const llmIterationOutputSchema = zod_v4.z.object({
24760
24811
  stepResult: llmIterationStepResultSchema,
24761
24812
  processorRetryCount: zod_v4.z.number().optional(),
24762
24813
  fallbackModelIndex: zod_v4.z.number().optional(),
24814
+ fallbackModelId: zod_v4.z.string().optional(),
24815
+ fallbackModelTriesEarlierEntries: zod_v4.z.boolean().optional(),
24763
24816
  skipUnavailableAttachments: zod_v4.z.boolean().optional(),
24764
24817
  processorRetryFeedback: zod_v4.z.string().optional(),
24765
24818
  isTaskCompleteCheckFailed: zod_v4.z.boolean().optional(),
@@ -25019,7 +25072,7 @@ const RETRYABLE_FAILURE_KINDS = /* @__PURE__ */ new Set([
25019
25072
  const ACCOUNT_REFUSALS = /* @__PURE__ */ new Set(["auth", "quota"]);
25020
25073
  const OPENAI_RETRY_MESSAGE_PATTERN = /you can retry your request/i;
25021
25074
  const DEFAULT_MATCHERS = [isRetryableOpenAIResponsesStreamError];
25022
- function isRecord$7(value) {
25075
+ function isRecord$8(value) {
25023
25076
  return typeof value === "object" && value !== null;
25024
25077
  }
25025
25078
  function getStringProperty(value, key) {
@@ -25028,15 +25081,15 @@ function getStringProperty(value, key) {
25028
25081
  }
25029
25082
  function getObjectCause(error) {
25030
25083
  if (error instanceof Error) return error.cause;
25031
- if (!isRecord$7(error)) return;
25084
+ if (!isRecord$8(error)) return;
25032
25085
  return error.cause;
25033
25086
  }
25034
25087
  function getOpenAIErrorPayload(error) {
25035
- if (!isRecord$7(error)) return;
25036
- if (error.type === "error" && isRecord$7(error.error)) return error.error;
25037
- if (error.type === "response.failed" && isRecord$7(error.response)) {
25088
+ if (!isRecord$8(error)) return;
25089
+ if (error.type === "error" && isRecord$8(error.error)) return error.error;
25090
+ if (error.type === "response.failed" && isRecord$8(error.response)) {
25038
25091
  const responseError = error.response.error;
25039
- return isRecord$7(responseError) ? responseError : void 0;
25092
+ return isRecord$8(responseError) ? responseError : void 0;
25040
25093
  }
25041
25094
  }
25042
25095
  function hasExplicitRetryMessage(payload) {
@@ -25068,12 +25121,12 @@ function isBadRequestError(error) {
25068
25121
  return false;
25069
25122
  }
25070
25123
  function isRetryableProviderMetadata(error) {
25071
- return (require_dist.APICallError.isInstance(error) ? error.isRetryable : isRecord$7(error) && typeof error.isRetryable === "boolean" ? error.isRetryable : void 0) === true;
25124
+ return (require_dist.APICallError.isInstance(error) ? error.isRetryable : isRecord$8(error) && typeof error.isRetryable === "boolean" ? error.isRetryable : void 0) === true;
25072
25125
  }
25073
25126
  function hasDeniedHttpStatus(error) {
25074
25127
  const visited = /* @__PURE__ */ new WeakSet();
25075
25128
  function visit(candidate) {
25076
- if (!isRecord$7(candidate) || visited.has(candidate)) return false;
25129
+ if (!isRecord$8(candidate) || visited.has(candidate)) return false;
25077
25130
  visited.add(candidate);
25078
25131
  if (candidate.status === 401 || candidate.status === 403) return true;
25079
25132
  return visit(candidate.error) || visit(candidate.data) || visit(candidate.cause);
@@ -25095,7 +25148,7 @@ function normalizeEntry(entry) {
25095
25148
  function findMatchingPolicy(error, entries) {
25096
25149
  const visited = /* @__PURE__ */ new WeakSet();
25097
25150
  function visit(candidate) {
25098
- if (isRecord$7(candidate)) {
25151
+ if (isRecord$8(candidate)) {
25099
25152
  if (visited.has(candidate)) return void 0;
25100
25153
  visited.add(candidate);
25101
25154
  }
@@ -30718,7 +30771,7 @@ async function localPathIdentity(path) {
30718
30771
  return toAbsolutePath(path);
30719
30772
  }
30720
30773
  }
30721
- function isRecord$6(value) {
30774
+ function isRecord$7(value) {
30722
30775
  return typeof value === "object" && value !== null;
30723
30776
  }
30724
30777
  function isInstructionFileName(name) {
@@ -30777,9 +30830,9 @@ async function findInstructionFileForPath(candidatePath, pathExists, isDirectory
30777
30830
  }
30778
30831
  }
30779
30832
  function getMessageText(message) {
30780
- const parts = isRecord$6(message.content) ? message.content.parts : void 0;
30833
+ const parts = isRecord$7(message.content) ? message.content.parts : void 0;
30781
30834
  if (!Array.isArray(parts)) return "";
30782
- return parts.filter((part) => isRecord$6(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
30835
+ return parts.filter((part) => isRecord$7(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
30783
30836
  }
30784
30837
  function decodeXmlEntities(value) {
30785
30838
  return value.replaceAll("&quot;", "\"").replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&amp;", "&");
@@ -30801,8 +30854,8 @@ function getReminderMetadata(instructionPath) {
30801
30854
  }
30802
30855
  function extractReminderPathFromMetadata(message) {
30803
30856
  const metadata = message.content.metadata;
30804
- if (!isRecord$6(metadata)) return;
30805
- const reminderMetadata = isRecord$6(metadata.systemReminder) ? metadata.systemReminder : isRecord$6(metadata[LEGACY_REMINDER_METADATA_KEY]) ? metadata[LEGACY_REMINDER_METADATA_KEY] : isRecord$6(metadata.signal) && isRecord$6(metadata.signal.attributes) ? metadata.signal.attributes : metadata;
30857
+ if (!isRecord$7(metadata)) return;
30858
+ const reminderMetadata = isRecord$7(metadata.systemReminder) ? metadata.systemReminder : isRecord$7(metadata[LEGACY_REMINDER_METADATA_KEY]) ? metadata[LEGACY_REMINDER_METADATA_KEY] : isRecord$7(metadata.signal) && isRecord$7(metadata.signal.attributes) ? metadata.signal.attributes : metadata;
30806
30859
  return typeof reminderMetadata.path === "string" ? reminderMetadata.path : void 0;
30807
30860
  }
30808
30861
  function getReminderMarkup(reminderText, instructionPath) {
@@ -30828,10 +30881,10 @@ function truncateToTokenLimit(content, maxTokens) {
30828
30881
  function getCompletedToolCalls(messages) {
30829
30882
  const completed = [];
30830
30883
  for (const message of [...messages].reverse()) {
30831
- const parts = isRecord$6(message.content) ? message.content.parts : void 0;
30884
+ const parts = isRecord$7(message.content) ? message.content.parts : void 0;
30832
30885
  if (!Array.isArray(parts)) continue;
30833
30886
  for (const part of [...parts].reverse()) {
30834
- if (!isRecord$6(part) || part.type !== "tool-invocation") continue;
30887
+ if (!isRecord$7(part) || part.type !== "tool-invocation") continue;
30835
30888
  const invocation = part.toolInvocation;
30836
30889
  if (!invocation || invocation.state !== "result" || typeof invocation.toolCallId !== "string") continue;
30837
30890
  completed.push({
@@ -30843,11 +30896,11 @@ function getCompletedToolCalls(messages) {
30843
30896
  return completed;
30844
30897
  }
30845
30898
  function parseInvocationArgs(args) {
30846
- if (isRecord$6(args)) return args;
30899
+ if (isRecord$7(args)) return args;
30847
30900
  if (typeof args !== "string") return;
30848
30901
  try {
30849
30902
  const parsed = JSON.parse(args);
30850
- return isRecord$6(parsed) ? parsed : void 0;
30903
+ return isRecord$7(parsed) ? parsed : void 0;
30851
30904
  } catch {
30852
30905
  return;
30853
30906
  }
@@ -30953,7 +31006,7 @@ var AgentsMDInjector = class {
30953
31006
  return this.reminderText?.trim() || void 0;
30954
31007
  }
30955
31008
  async *findInstructionPathsInInvocation(invocation, reader, basePath) {
30956
- if (!isRecord$6(invocation)) return;
31009
+ if (!isRecord$7(invocation)) return;
30957
31010
  const args = parseInvocationArgs(invocation.args);
30958
31011
  if (!args) return;
30959
31012
  for (const field of PATH_FIELDS) {
@@ -32493,7 +32546,7 @@ function hashBinary(value) {
32493
32546
  const CYBER_POLICY_ERROR_CODE = "cyber_policy";
32494
32547
  const CYBER_REFUSAL_MESSAGE = "this content was flagged for possible cybersecurity risk";
32495
32548
  const CYBER_STOP_CATEGORY = "cyber";
32496
- function isRecord$5(value) {
32549
+ function isRecord$6(value) {
32497
32550
  return typeof value === "object" && value !== null;
32498
32551
  }
32499
32552
  function parseJson(value) {
@@ -32516,7 +32569,7 @@ function parseJson(value) {
32516
32569
  function isCyberRefusalError(error) {
32517
32570
  const visited = /* @__PURE__ */ new WeakSet();
32518
32571
  function visit(candidate) {
32519
- if (!isRecord$5(candidate) || visited.has(candidate)) return false;
32572
+ if (!isRecord$6(candidate) || visited.has(candidate)) return false;
32520
32573
  visited.add(candidate);
32521
32574
  const { code, message, responseBody } = candidate;
32522
32575
  if (typeof code === "string" && code.toLowerCase() === CYBER_POLICY_ERROR_CODE) return true;
@@ -32536,10 +32589,10 @@ function isCyberRefusalError(error) {
32536
32589
  * still recognized when Claude is reached through another provider.
32537
32590
  */
32538
32591
  function isCyberStopRefusal(finishReason, providerMetadata) {
32539
- if (finishReason !== "content-filter" || !isRecord$5(providerMetadata)) return false;
32592
+ if (finishReason !== "content-filter" || !isRecord$6(providerMetadata)) return false;
32540
32593
  return Object.values(providerMetadata).some((namespace) => {
32541
- const stopDetails = isRecord$5(namespace) ? namespace.stopDetails : void 0;
32542
- return isRecord$5(stopDetails) && typeof stopDetails.category === "string" && stopDetails.category.toLowerCase() === CYBER_STOP_CATEGORY;
32594
+ const stopDetails = isRecord$6(namespace) ? namespace.stopDetails : void 0;
32595
+ return isRecord$6(stopDetails) && typeof stopDetails.category === "string" && stopDetails.category.toLowerCase() === CYBER_STOP_CATEGORY;
32543
32596
  });
32544
32597
  }
32545
32598
  /**
@@ -32805,18 +32858,18 @@ async function checkThreadFGA({ mastra, user, threadId, resourceId, agentId, req
32805
32858
  }
32806
32859
  // src/memory/system-reminders.ts
32807
32860
  const LEGACY_SYSTEM_REMINDER_METADATA_KEY = "dynamicAgentsMdReminder";
32808
- function isRecord$4(value) {
32861
+ function isRecord$5(value) {
32809
32862
  return typeof value === "object" && value !== null;
32810
32863
  }
32811
32864
  function isSystemReminderSignalType(type) {
32812
32865
  return type === "system-reminder" || type === "reactive";
32813
32866
  }
32814
32867
  function isSystemReminderMessage(message) {
32815
- if (!isRecord$4(message.content)) return false;
32868
+ if (!isRecord$5(message.content)) return false;
32816
32869
  const metadata = message.content.metadata;
32817
- if (message.role === "signal") return isRecord$4(metadata) && isRecord$4(metadata.signal) && isSystemReminderSignalType(metadata.signal.type);
32870
+ if (message.role === "signal") return isRecord$5(metadata) && isRecord$5(metadata.signal) && isSystemReminderSignalType(metadata.signal.type);
32818
32871
  if (message.role !== "user") return false;
32819
- if (isRecord$4(metadata) && (isRecord$4(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) return true;
32872
+ if (isRecord$5(metadata) && (isRecord$5(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) return true;
32820
32873
  const firstTextPart = message.content.parts.find((part) => part.type === "text");
32821
32874
  return typeof firstTextPart?.text === "string" && firstTextPart.text.startsWith("<system-reminder");
32822
32875
  }
@@ -32824,10 +32877,10 @@ function isRecallSignalType(type) {
32824
32877
  return type === "user" || type === "state" || type === "reactive" || type === "notification" || type === "user-message" || type === "system-reminder";
32825
32878
  }
32826
32879
  function getRecallSignalType(message) {
32827
- if (!isRecord$4(message.content)) return void 0;
32828
- for (const part of message.content.parts) if ((part.type === "data-signal" || part.type === "data-user-message") && isRecord$4(part.data) && isRecallSignalType(part.data.type)) return part.data.type;
32880
+ if (!isRecord$5(message.content)) return void 0;
32881
+ for (const part of message.content.parts) if ((part.type === "data-signal" || part.type === "data-user-message") && isRecord$5(part.data) && isRecallSignalType(part.data.type)) return part.data.type;
32829
32882
  const metadata = message.content.metadata;
32830
- if (message.role === "signal" && isRecord$4(metadata) && isRecord$4(metadata.signal)) {
32883
+ if (message.role === "signal" && isRecord$5(metadata) && isRecord$5(metadata.signal)) {
32831
32884
  if (isRecallSignalType(metadata.signal.type)) return metadata.signal.type;
32832
32885
  }
32833
32886
  return isSystemReminderMessage(message) ? "system-reminder" : void 0;
@@ -35096,6 +35149,9 @@ var ObservabilityInMemory = class extends ObservabilityStorage {
35096
35149
  entityType: span.entityType,
35097
35150
  entityId: span.entityId,
35098
35151
  entityName: span.entityName,
35152
+ outcome: span.outcome,
35153
+ stopReason: span.stopReason,
35154
+ stopReasonContext: span.stopReasonContext,
35099
35155
  createdAt: span.createdAt,
35100
35156
  updatedAt: span.updatedAt
35101
35157
  }))
@@ -40259,12 +40315,35 @@ var KnowledgeInvalidCursorError = class extends Error {
40259
40315
  }
40260
40316
  };
40261
40317
  /**
40318
+ * A keyword search the store refuses, such as one with a word over
40319
+ * {@link KNOWLEDGE_SEARCH_MAX_WORD_LENGTH} characters. Recognise it by `name`; adapters bundle their
40320
+ * own copy.
40321
+ * @experimental
40322
+ */
40323
+ var KnowledgeInvalidSearchError = class extends Error {
40324
+ constructor(message) {
40325
+ super(message);
40326
+ this.name = "KnowledgeInvalidSearchError";
40327
+ }
40328
+ };
40329
+ /**
40262
40330
  * Keyword-search words: the query split on whitespace, lowercased, deduplicated, keeping the first
40263
40331
  * {@link KNOWLEDGE_SEARCH_MAX_WORDS}. A hit needs at least one of them (as a case-insensitive
40264
- * substring); an empty list means the search returns nothing.
40332
+ * substring); an empty list means the search returns nothing. Throws
40333
+ * {@link KnowledgeInvalidSearchError} for any word over {@link KNOWLEDGE_SEARCH_MAX_WORD_LENGTH}
40334
+ * characters rather than dropping or cutting it, which would match the wrong pages.
40265
40335
  */
40266
40336
  function knowledgeSearchWords(query) {
40267
- return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))].slice(0, 16);
40337
+ const words = [];
40338
+ for (const raw of query.split(/\s+/)) {
40339
+ if (!raw) continue;
40340
+ const length = raw.length > 128 ? [...raw].length : raw.length;
40341
+ if (length > 128) throw new KnowledgeInvalidSearchError(`Knowledge search words can be at most 128 characters; one word has ${length}`);
40342
+ if (words.length === 16) continue;
40343
+ const word = raw.toLowerCase();
40344
+ if (!words.includes(word)) words.push(word);
40345
+ }
40346
+ return words;
40268
40347
  }
40269
40348
  /**
40270
40349
  * Points one matched search word earns on a page, by the best field it appears in: name, then
@@ -41697,6 +41776,13 @@ var InMemoryKnowledgePageStore = class {
41697
41776
  for (const [pageId, links] of this.#bodyLinks) if (links.some((link) => link.toPageId === null ? refs.has(link.ref) : targets.has(link.toPageId))) sources.push(pageId);
41698
41777
  return sources;
41699
41778
  }
41779
+ async listPageBodyLinkSourcesByRef(input) {
41780
+ const refs = new Set(input.refs);
41781
+ const targets = new Set(input.toPageIds);
41782
+ const sources = [];
41783
+ for (const [pageId, links] of this.#bodyLinks) if (links.some((link) => link.toPageId !== null && targets.has(link.toPageId) && refs.has(link.ref))) sources.push(pageId);
41784
+ return sources;
41785
+ }
41700
41786
  /** Every resolved link both of whose ends are live and readable, and not a self-link. */
41701
41787
  #visibleLinks(read, kinds) {
41702
41788
  const wanted = new Set(kinds ?? ["body", "note"]);
@@ -42298,6 +42384,9 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
42298
42384
  findPagesByNames(input) {
42299
42385
  return this.#pageStore.findPagesByNames(input);
42300
42386
  }
42387
+ listPageBodyLinkSourcesByRef(input) {
42388
+ return this.#pageStore.listPageBodyLinkSourcesByRef(input);
42389
+ }
42301
42390
  findPagesByName(input) {
42302
42391
  return this.#pageStore.findPagesByName(input);
42303
42392
  }
@@ -42685,7 +42774,12 @@ var MemoryStorage = class MemoryStorage extends require_filesystem_versioned.Sto
42685
42774
  throw pendingSignalsNotSupportedError(this.constructor.name);
42686
42775
  }
42687
42776
  /**
42688
- * Delete the thread's taken rows whose id is in `consumedIds`. Then, if the
42777
+ * Delete the thread's taken rows whose id is in `consumedIds`. A consumed
42778
+ * id never names a queued row: a run consumes a row by claiming it or by
42779
+ * starting with it, a claim never returns a queued row, and a run that
42780
+ * keeps its signals here named itself the signal run through
42781
+ * `setSignalRun` before it started, which made the thread's queued rows
42782
+ * pending. Then, if the
42689
42783
  * thread's signal run is still `runId`, move its other taken rows and its
42690
42784
  * queued rows to pending and clear the signal run. A close that comes after another run
42691
42785
  * became the signal run deletes only what it consumed and leaves the other
@@ -51274,11 +51368,10 @@ function claimFirstReplyLink(requestContext, link) {
51274
51368
  /** Live posts of `reply_in_thread` calls whose text is still streaming in, by tool call id. */
51275
51369
  const STREAMS_KEY = "mastra__channelReplyStreams";
51276
51370
  function replyStreams(requestContext) {
51277
- let streams = requestContext.get(STREAMS_KEY);
51278
- if (!streams) {
51279
- streams = /* @__PURE__ */ new Map();
51280
- requestContext.set(STREAMS_KEY, streams);
51281
- }
51371
+ const stored = requestContext.get(STREAMS_KEY);
51372
+ if (stored instanceof Map) return stored;
51373
+ const streams = /* @__PURE__ */ new Map();
51374
+ requestContext.set(STREAMS_KEY, streams);
51282
51375
  return streams;
51283
51376
  }
51284
51377
  /**
@@ -51290,7 +51383,7 @@ function openReplyStream({ chatThread, logger }) {
51290
51383
  let sent = "";
51291
51384
  let closed = false;
51292
51385
  let wake;
51293
- let done;
51386
+ let posted;
51294
51387
  async function* chunks() {
51295
51388
  while (true) {
51296
51389
  while (queue.length > 0) yield queue.shift();
@@ -51301,12 +51394,16 @@ function openReplyStream({ chatThread, logger }) {
51301
51394
  const push = (text) => {
51302
51395
  if (!text) return;
51303
51396
  queue.push(text);
51304
- done ??= chatThread.post(chunks()).then(() => true, (error) => {
51397
+ posted ??= chatThread.post(chunks()).then((message) => message, (error) => {
51305
51398
  logger?.warn("[channels] streamed reply failed; posting it whole", { error });
51306
- return false;
51307
51399
  });
51308
51400
  wake?.();
51309
51401
  };
51402
+ const end = async () => {
51403
+ closed = true;
51404
+ wake?.();
51405
+ return posted;
51406
+ };
51310
51407
  return {
51311
51408
  update(text) {
51312
51409
  const visible = text.trimStart();
@@ -51316,16 +51413,20 @@ function openReplyStream({ chatThread, logger }) {
51316
51413
  },
51317
51414
  async finish(text, suffix) {
51318
51415
  if (text.startsWith(sent)) push(text.slice(sent.length));
51319
- if (!done) return false;
51416
+ if (!posted) return false;
51320
51417
  push(suffix);
51321
- closed = true;
51322
- wake?.();
51323
- return done;
51418
+ return !!await end();
51324
51419
  },
51325
51420
  async close() {
51326
- closed = true;
51327
- wake?.();
51328
- return done ?? false;
51421
+ return !!await end();
51422
+ },
51423
+ async discard() {
51424
+ const message = await end();
51425
+ try {
51426
+ await message?.delete();
51427
+ } catch (error) {
51428
+ logger?.warn("[channels] could not delete a streamed reply preview", { error });
51429
+ }
51329
51430
  }
51330
51431
  };
51331
51432
  }
@@ -51352,6 +51453,7 @@ var ChannelReplyStreamProcessor = class {
51352
51453
  if (!requestContext) return part;
51353
51454
  await this.#postUnsentAnswer(part, state, requestContext);
51354
51455
  const args = state.args ??= {};
51456
+ const called = state.called ??= {};
51355
51457
  if (part.type === "tool-call-input-streaming-start" && part.payload.toolName === "reply_in_thread") {
51356
51458
  const render = await this.#resolveRender(requestContext);
51357
51459
  if (render?.textDisplay !== "hidden" || !render.streaming?.enabled) return part;
@@ -51362,10 +51464,19 @@ var ChannelReplyStreamProcessor = class {
51362
51464
  if (text !== void 0) replyStreams(requestContext).get(part.payload.toolCallId)?.update(text);
51363
51465
  } else if ((part.type === "tool-error" || part.type === "tool-result") && part.payload.toolCallId in args) {
51364
51466
  delete args[part.payload.toolCallId];
51365
- await closeStream(requestContext, part.payload.toolCallId);
51366
- } else if (RUN_END.has(part.type)) {
51367
- for (const toolCallId of Object.keys(args)) await closeStream(requestContext, toolCallId);
51467
+ delete called[part.payload.toolCallId];
51468
+ await discardStream(requestContext, part.payload.toolCallId);
51469
+ } else if (part.type === "tool-call" && part.payload.toolCallId in args) called[part.payload.toolCallId] = true;
51470
+ else if (part.type === "step-finish") for (const toolCallId of Object.keys(called)) {
51471
+ delete args[toolCallId];
51472
+ delete called[toolCallId];
51473
+ await discardStream(requestContext, toolCallId);
51474
+ }
51475
+ else if (RUN_END.has(part.type)) {
51476
+ for (const toolCallId of Object.keys(args)) if (called[toolCallId]) await discardStream(requestContext, toolCallId);
51477
+ else await closeStream(requestContext, toolCallId);
51368
51478
  state.args = {};
51479
+ state.called = {};
51369
51480
  }
51370
51481
  return part;
51371
51482
  }
@@ -51373,8 +51484,7 @@ var ChannelReplyStreamProcessor = class {
51373
51484
  * Models sometimes end a turn with a plain-text answer and never call
51374
51485
  * `reply_in_thread`, so the thread never hears back. When a run finishes
51375
51486
  * without having replied, post the text written after its last tool call.
51376
- * A reply counts once it posts: a call that fails validation doesn't, unless
51377
- * its streamed post already left text in the thread.
51487
+ * A reply counts once it posts; a failed call's streamed preview is deleted, so it doesn't.
51378
51488
  */
51379
51489
  async #postUnsentAnswer(part, state, requestContext) {
51380
51490
  const answer = state.answer ??= {
@@ -51388,10 +51498,7 @@ var ChannelReplyStreamProcessor = class {
51388
51498
  answer.tail = "";
51389
51499
  if (part.payload.toolName === "reply_in_thread") answer.calls.add(part.payload.toolCallId);
51390
51500
  } else if (part.type === "tool-result" && answer.calls.has(part.payload.toolCallId)) answer.replied = true;
51391
- else if (part.type === "tool-error" && answer.calls.has(part.payload.toolCallId)) {
51392
- const stream = replyStreams(requestContext).get(part.payload.toolCallId);
51393
- if (stream && await stream.close()) answer.replied = true;
51394
- } else if (part.type === "tool-call-approval" || part.type === "tool-call-suspended") answer.held = true;
51501
+ else if (part.type === "tool-call-approval" || part.type === "tool-call-suspended") answer.held = true;
51395
51502
  else if (RUN_END.has(part.type)) {
51396
51503
  state.answer = void 0;
51397
51504
  const text = answer.tail.trim();
@@ -51426,6 +51533,13 @@ async function closeStream(requestContext, toolCallId) {
51426
51533
  streams.delete(toolCallId);
51427
51534
  await stream.close();
51428
51535
  }
51536
+ /** Deletes a streamed post that is only a preview of a reply posted, or failed, elsewhere. */
51537
+ async function discardStream(requestContext, toolCallId) {
51538
+ const streams = replyStreams(requestContext);
51539
+ const stream = streams.get(toolCallId);
51540
+ streams.delete(toolCallId);
51541
+ await stream?.discard();
51542
+ }
51429
51543
  const ESCAPES = {
51430
51544
  "\"": "\"",
51431
51545
  "\\": "\\",
@@ -51895,11 +52009,11 @@ var MastraStateAdapter = class {
51895
52009
  * otherwise reach the agent as just the notification fallback.
51896
52010
  */
51897
52011
  function layoutBlockTexts(raw) {
51898
- const blocks = isRecord$3(raw) ? raw.blocks : void 0;
52012
+ const blocks = isRecord$4(raw) ? raw.blocks : void 0;
51899
52013
  if (!Array.isArray(blocks)) return [];
51900
52014
  const texts = [];
51901
52015
  for (const block of blocks) {
51902
- if (!isRecord$3(block) || typeof block.type !== "string") continue;
52016
+ if (!isRecord$4(block) || typeof block.type !== "string") continue;
51903
52017
  const parts = blockParts(block).map((part) => part.trim()).filter(Boolean);
51904
52018
  if (parts.length) texts.push(parts);
51905
52019
  }
@@ -51912,13 +52026,13 @@ function blockParts(block) {
51912
52026
  const fields = Array.isArray(block.fields) ? block.fields.map(textObject) : [];
51913
52027
  return [textObject(block.text), ...fields];
51914
52028
  }
51915
- case "context": return [(Array.isArray(block.elements) ? block.elements : []).filter((el) => isRecord$3(el) && (el.type === "mrkdwn" || el.type === "plain_text")).map(textObject).filter(Boolean).join(" ")];
52029
+ case "context": return [(Array.isArray(block.elements) ? block.elements : []).filter((el) => isRecord$4(el) && (el.type === "mrkdwn" || el.type === "plain_text")).map(textObject).filter(Boolean).join(" ")];
51916
52030
  case "markdown": return [typeof block.text === "string" ? block.text : ""];
51917
52031
  default: return [];
51918
52032
  }
51919
52033
  }
51920
52034
  function textObject(value) {
51921
- if (!isRecord$3(value) || typeof value.text !== "string") return "";
52035
+ if (!isRecord$4(value) || typeof value.text !== "string") return "";
51922
52036
  const text = value.text.trim();
51923
52037
  return value.type === "mrkdwn" ? slackLinksToMarkdown(text) : text;
51924
52038
  }
@@ -51930,7 +52044,7 @@ function slackLinksToMarkdown(text) {
51930
52044
  return `[${label.replace(/[\\[\]]/g, "\\$&")}](${destination})`;
51931
52045
  });
51932
52046
  }
51933
- function isRecord$3(value) {
52047
+ function isRecord$4(value) {
51934
52048
  return typeof value === "object" && value !== null;
51935
52049
  }
51936
52050
  /**
@@ -55506,6 +55620,11 @@ async function knowledgeSubtree(storage, root) {
55506
55620
  */
55507
55621
  const MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES = 99;
55508
55622
  /**
55623
+ * Most linking pages one batched {@link repairKnowledgeLinks} re-resolves by default, in chunks of
55624
+ * {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES}; it hands back the rest for the caller to repair later.
55625
+ */
55626
+ const MAX_KNOWLEDGE_LINK_REPAIR_SOURCES = 1e3;
55627
+ /**
55509
55628
  * A link refresh that landed but stopped at {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES} linking pages
55510
55629
  * or {@link MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES} namesakes: the rest keep their links until they're
55511
55630
  * next written or `knowledge.reindexLinks()` runs.
@@ -55517,6 +55636,75 @@ var KnowledgeLinkRefreshIncompleteError = class extends Error {
55517
55636
  }
55518
55637
  };
55519
55638
  /**
55639
+ * The pages whose body links may resolve differently now that `affected` answer to what they do:
55640
+ * an unresolved link by a ref one of them answers to, a link resolved to one of them, and a link
55641
+ * resolved to a namesake by one of `names`. A namesake's other linkers name it by id or path, which
55642
+ * a name can't change, so they are left out (an importer re-creating a site's pages would otherwise
55643
+ * re-resolve every page linking to the old copies, on every flush). A store with
55644
+ * `listPageBodyLinkSourcesByRef` tells them apart from its link index; otherwise their bodies are
55645
+ * read once to tell, and a linker with no live page stays in: it keeps no links. `read` holds the
55646
+ * namesake linkers' pages read that way.
55647
+ */
55648
+ async function linkSources(storage, input, maxReads) {
55649
+ const own = new Set(input.affected.map((page) => page.id));
55650
+ const ids = new Set(await storage.listPageBodyLinkSources({
55651
+ refs: [...input.refs],
55652
+ toPageIds: [...own]
55653
+ }));
55654
+ const read = /* @__PURE__ */ new Map();
55655
+ const others = [...input.namesakes].filter((id) => !own.has(id));
55656
+ if (!others.length) return {
55657
+ ids: [...ids],
55658
+ read
55659
+ };
55660
+ const nameKeys = new Set([...input.names].map((name) => knowledgeLinkRefKey(name)));
55661
+ if (storage.listPageBodyLinkSourcesByRef) {
55662
+ if (!nameKeys.size) return {
55663
+ ids: [...ids],
55664
+ read
55665
+ };
55666
+ for (const id of await storage.listPageBodyLinkSourcesByRef({
55667
+ refs: [...nameKeys],
55668
+ toPageIds: others
55669
+ })) ids.add(id);
55670
+ return {
55671
+ ids: [...ids],
55672
+ read
55673
+ };
55674
+ }
55675
+ const candidates = (await storage.listPageBodyLinkSources({ toPageIds: others })).filter((id) => !ids.has(id));
55676
+ if (!candidates.length) return {
55677
+ ids: [...ids],
55678
+ read
55679
+ };
55680
+ if (candidates.length > maxReads - ids.size) {
55681
+ for (const id of candidates) ids.add(id);
55682
+ return {
55683
+ ids: [...ids],
55684
+ read
55685
+ };
55686
+ }
55687
+ for (let i = 0; i < candidates.length; i += 100) for (const page of await storage.getPages({
55688
+ ids: candidates.slice(i, i + 100),
55689
+ read: "all"
55690
+ })) read.set(page.id, page);
55691
+ for (const id of candidates) {
55692
+ const page = read.get(id);
55693
+ if (!page || page.deletedAt) {
55694
+ ids.add(id);
55695
+ continue;
55696
+ }
55697
+ for (const ref of knowledgeBodyLinkRefs(page.body).keys()) if (nameKeys.has(knowledgeLinkRefKey(ref))) {
55698
+ ids.add(id);
55699
+ break;
55700
+ }
55701
+ }
55702
+ return {
55703
+ ids: [...ids],
55704
+ read
55705
+ };
55706
+ }
55707
+ /**
55520
55708
  * Re-resolves the pages whose body links one of `pages` or names a ref one of them answers to now,
55521
55709
  * after they were created, renamed, moved, merged or deleted, in page id order up to
55522
55710
  * {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES}. With `withDescendants`, the pages' subtrees count too
@@ -55526,36 +55714,44 @@ var KnowledgeLinkRefreshIncompleteError = class extends Error {
55526
55714
  async function refreshKnowledgeLinksTo(storage, pages, options = {}) {
55527
55715
  const affected = options.withDescendants ? (await Promise.all(pages.map((page) => knowledgeSubtree(storage, page)))).flat() : pages;
55528
55716
  const refs = /* @__PURE__ */ new Set();
55529
- const targets = new Set(affected.map((page) => page.id));
55530
55717
  const names = /* @__PURE__ */ new Set();
55531
55718
  for (const page of affected) {
55532
55719
  for (const key of await pageRefKeys(storage, page)) refs.add(key);
55533
55720
  if (!page.deletedAt) names.add(page.name);
55534
55721
  }
55535
55722
  const crowded = [];
55723
+ const namesakes = /* @__PURE__ */ new Set();
55536
55724
  for (const name of names) {
55537
- const namesakes = await storage.findPagesByName({
55725
+ const found = await storage.findPagesByName({
55538
55726
  name,
55539
55727
  read: "all",
55540
55728
  limit: 100
55541
55729
  });
55542
- if (namesakes.length > MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES) crowded.push(`"${name}"`);
55543
- for (const namesake of namesakes.slice(0, MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES)) targets.add(namesake.id);
55730
+ if (found.length > MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES) crowded.push(`"${name}"`);
55731
+ for (const namesake of found.slice(0, MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES)) namesakes.add(namesake.id);
55544
55732
  }
55545
- const sources = (await storage.listPageBodyLinkSources({
55546
- refs: [...refs],
55547
- toPageIds: [...targets]
55548
- })).sort();
55733
+ const found = await linkSources(storage, {
55734
+ refs,
55735
+ affected,
55736
+ names,
55737
+ namesakes
55738
+ }, 100);
55739
+ const sources = found.ids.sort();
55549
55740
  const crowdedError = () => new KnowledgeLinkRefreshIncompleteError(`More than ${MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES} pages are named ${crowded.join(", ")}; links to the rest were left as they were`);
55550
55741
  if (!sources.length) {
55551
55742
  if (crowded.length) throw crowdedError();
55552
55743
  return;
55553
55744
  }
55554
55745
  const batch = sources.slice(0, 100);
55555
- const live = new Map((await storage.getPages({
55556
- ids: batch,
55746
+ const toRead = batch.filter((id) => !found.read.has(id));
55747
+ const live = new Map(toRead.length ? (await storage.getPages({
55748
+ ids: toRead,
55557
55749
  read: "all"
55558
- })).map((page) => [page.id, page]));
55750
+ })).map((page) => [page.id, page]) : []);
55751
+ for (const id of batch) {
55752
+ const page = found.read.get(id);
55753
+ if (page) live.set(id, page);
55754
+ }
55559
55755
  const resolver = new BodyLinkResolver(storage);
55560
55756
  let done = 0;
55561
55757
  for (const id of batch) {
@@ -55622,8 +55818,8 @@ async function reindexKnowledgeLinks(storage) {
55622
55818
  }
55623
55819
  /**
55624
55820
  * A batched link repair that would stop at a cap the op-by-op refreshes enforce one write at a time
55625
- * (linking pages, namesakes, refs looked up, subtree size): the caller saves op by op instead, so the
55626
- * caps apply exactly as they do there.
55821
+ * (namesakes, subtree size): the caller saves op by op instead, so the caps apply exactly as they do
55822
+ * there.
55627
55823
  */
55628
55824
  var KnowledgeLinkRepairUnsupportedError = class extends Error {
55629
55825
  reason;
@@ -55639,13 +55835,19 @@ function canRepairKnowledgeLinksInBatch(storage) {
55639
55835
  }
55640
55836
  /**
55641
55837
  * Every {@link syncKnowledgePageBodyLinks} and {@link refreshKnowledgeLinksTo} of a flush, run once
55642
- * over the store as the flush left it, in a fixed number of statements: each page's links come out
55643
- * as they do when the calls run one after another after the writes. Throws
55644
- * {@link KnowledgeLinkRepairUnsupportedError}, having written nothing, when a cap could bite.
55645
- */
55646
- async function repairKnowledgeLinks(storage, repair) {
55838
+ * over the store as the flush left it, a few statements per chunk of up to
55839
+ * {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES} pages: each page's links come out as they do when the
55840
+ * calls run one after another after the writes. Linking pages past `limit` (default
55841
+ * {@link MAX_KNOWLEDGE_LINK_REPAIR_SOURCES}), in page id order, keep their links and come back in
55842
+ * `deferred`; the synced pages are always written. Throws {@link KnowledgeLinkRepairUnsupportedError},
55843
+ * having written nothing, when a namesake or subtree cap could bite.
55844
+ */
55845
+ async function repairKnowledgeLinks(storage, repair, options = {}) {
55647
55846
  const synced = new Map(repair.synced.map((page) => [page.id, page]));
55648
- if (!synced.size && !repair.refreshed.length) return;
55847
+ if (!synced.size && !repair.refreshed.length) return {
55848
+ rewritten: 0,
55849
+ deferred: []
55850
+ };
55649
55851
  const roots = repair.refreshed.filter((item) => item.withDescendants).map((item) => item.page.id);
55650
55852
  const subtrees = roots.length ? await storage.getPageSubtrees({
55651
55853
  rootIds: [...new Set(roots)],
@@ -55665,40 +55867,51 @@ async function repairKnowledgeLinks(storage, repair) {
55665
55867
  read: "all"
55666
55868
  }) : {};
55667
55869
  const refs = /* @__PURE__ */ new Set();
55668
- const targets = new Set(affected.map((page) => page.id));
55669
55870
  const names = /* @__PURE__ */ new Set();
55670
55871
  for (const page of affected) {
55671
55872
  const parents = !page.isScope && page.key && page.parentId ? chains[page.parentId] ?? [] : [];
55672
55873
  for (const key of refKeysOf(page, parents)) refs.add(key);
55673
55874
  if (!page.deletedAt) names.add(page.name);
55674
55875
  }
55876
+ const namesakes = /* @__PURE__ */ new Set();
55675
55877
  if (names.size) {
55676
- const namesakes = await storage.findPagesByNames({
55878
+ const byName = await storage.findPagesByNames({
55677
55879
  names: [...names],
55678
55880
  read: "all",
55679
55881
  limit: 100
55680
55882
  });
55681
- for (const found of Object.values(namesakes)) {
55883
+ for (const found of Object.values(byName)) {
55682
55884
  if (found.length > MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES) throw new KnowledgeLinkRepairUnsupportedError("a name past the namesake limit");
55683
- for (const namesake of found) targets.add(namesake.id);
55885
+ for (const namesake of found) namesakes.add(namesake.id);
55684
55886
  }
55685
55887
  }
55686
- const sources = affected.length ? await storage.listPageBodyLinkSources({
55687
- refs: [...refs],
55688
- toPageIds: [...targets]
55689
- }) : [];
55690
- if (sources.length > 100) throw new KnowledgeLinkRepairUnsupportedError("linking pages past the refresh limit");
55691
- const unread = sources.filter((id) => !synced.has(id));
55692
- const live = new Map((unread.length ? await storage.getPages({
55693
- ids: unread,
55888
+ const limit = options.limit ?? 1e3;
55889
+ const found = affected.length ? await linkSources(storage, {
55890
+ refs,
55891
+ affected,
55892
+ names,
55893
+ namesakes
55894
+ }, Math.max(0, limit)) : {
55895
+ ids: [],
55896
+ read: /* @__PURE__ */ new Map()
55897
+ };
55898
+ const unread = found.ids.filter((id) => !synced.has(id)).sort();
55899
+ const now = unread.slice(0, Math.max(0, limit));
55900
+ const deferred = unread.slice(now.length);
55901
+ const toRead = now.filter((id) => !found.read.has(id));
55902
+ const live = /* @__PURE__ */ new Map();
55903
+ for (let i = 0; i < toRead.length; i += 100) for (const page of await storage.getPages({
55904
+ ids: toRead.slice(i, i + 100),
55694
55905
  read: "all"
55695
- }) : []).map((page) => [page.id, page]));
55906
+ })) live.set(page.id, page);
55907
+ for (const id of now) {
55908
+ const page = found.read.get(id);
55909
+ if (page && !page.deletedAt) live.set(id, page);
55910
+ }
55696
55911
  const rewrite = /* @__PURE__ */ new Map();
55697
- for (const id of unread) rewrite.set(id, live.get(id) ?? null);
55698
55912
  for (const [id, page] of synced) rewrite.set(id, page);
55699
- const wanted = /* @__PURE__ */ new Map();
55700
- const lookups = [];
55701
- const refreshing = new Set(sources);
55913
+ for (const id of now) rewrite.set(id, live.get(id) ?? null);
55914
+ const chunks = [[]];
55702
55915
  let looked = 0;
55703
55916
  for (const [id, page] of rewrite) {
55704
55917
  const byKey = /* @__PURE__ */ new Map();
@@ -55713,27 +55926,42 @@ async function repairKnowledgeLinks(storage, repair) {
55713
55926
  });
55714
55927
  }
55715
55928
  const entries = [...byKey];
55716
- wanted.set(id, entries);
55717
- if (page) for (const [, { ref }] of entries) lookups.push({
55718
- ref,
55719
- home: page.scopeId
55720
- });
55721
- if (refreshing.has(id)) looked += new Set(entries.map(([, { ref }]) => ref)).size;
55929
+ let chunk = chunks.at(-1);
55930
+ if (chunk.length && (chunk.length >= 100 || looked + entries.length > 1e3)) {
55931
+ chunks.push(chunk = []);
55932
+ looked = 0;
55933
+ }
55934
+ chunk.push([id, entries]);
55935
+ looked += entries.length;
55722
55936
  }
55723
- if (looked >= 1e3) throw new KnowledgeLinkRepairUnsupportedError("refs looked up past the refresh limit");
55724
- const resolved = await resolveKnowledgeBodyLinks(storage, lookups);
55725
- await storage.applyPageWrites({ writes: [...wanted].map(([pageId, entries]) => {
55726
- const home = rewrite.get(pageId)?.scopeId;
55727
- return {
55728
- op: "replace-links",
55729
- pageId,
55730
- links: entries.map(([key, { ref, count }]) => ({
55731
- ref: key,
55732
- toPageId: home === void 0 ? null : resolved.get(`${home}\u0000${ref}`) ?? null,
55733
- count
55734
- }))
55735
- };
55736
- }) });
55937
+ for (const chunk of chunks) {
55938
+ if (!chunk.length) continue;
55939
+ const lookups = [];
55940
+ for (const [id, entries] of chunk) {
55941
+ const page = rewrite.get(id);
55942
+ if (page) for (const [, { ref }] of entries) lookups.push({
55943
+ ref,
55944
+ home: page.scopeId
55945
+ });
55946
+ }
55947
+ const resolved = await resolveKnowledgeBodyLinks(storage, lookups);
55948
+ await storage.applyPageWrites({ writes: chunk.map(([pageId, entries]) => {
55949
+ const home = rewrite.get(pageId)?.scopeId;
55950
+ return {
55951
+ op: "replace-links",
55952
+ pageId,
55953
+ links: entries.map(([key, { ref, count }]) => ({
55954
+ ref: key,
55955
+ toPageId: home === void 0 ? null : resolved.get(`${home}\u0000${ref}`) ?? null,
55956
+ count
55957
+ }))
55958
+ };
55959
+ }) });
55960
+ }
55961
+ return {
55962
+ rewritten: now.length,
55963
+ deferred
55964
+ };
55737
55965
  }
55738
55966
  /** What {@link BodyLinkResolver} answers for each `(home, ref)`, keyed `home\0ref`, in a fixed number of reads. */
55739
55967
  async function resolveKnowledgeBodyLinks(storage, lookups) {
@@ -57070,7 +57298,7 @@ function isBuffer(value) {
57070
57298
  /**
57071
57299
  * Checks whether a value is a non-null, non-array object.
57072
57300
  */
57073
- function isRecord$2(value) {
57301
+ function isRecord$3(value) {
57074
57302
  return value != null && typeof value === "object" && !Array.isArray(value);
57075
57303
  }
57076
57304
  /**
@@ -59064,7 +59292,7 @@ function parseSpeechStreamPart(text) {
59064
59292
  } catch {
59065
59293
  return;
59066
59294
  }
59067
- if (!isRecord$2(value)) return;
59295
+ if (!isRecord$3(value)) return;
59068
59296
  const part = value;
59069
59297
  switch (part.type) {
59070
59298
  case "stream-start": {
@@ -59075,10 +59303,10 @@ function parseSpeechStreamPart(text) {
59075
59303
  warnings
59076
59304
  } : void 0;
59077
59305
  }
59078
- case "audio": return isString$1(part.audio) && isAudioFormat(part.audioFormat) && isOptional$1(part.id, isString$1) && isOptional$1(part.providerMetadata, isRecord$2) ? part : void 0;
59079
- case "finish": return isOptional$1(part.usage, isUsage) && isOptional$1(part.providerMetadata, isRecord$2) ? part : void 0;
59306
+ 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;
59307
+ case "finish": return isOptional$1(part.usage, isUsage) && isOptional$1(part.providerMetadata, isRecord$3) ? part : void 0;
59080
59308
  case "response-metadata": {
59081
- if (!(isOptional$1(part.modelId, isString$1) && isOptional$1(part.headers, isRecord$2))) return;
59309
+ if (!(isOptional$1(part.modelId, isString$1) && isOptional$1(part.headers, isRecord$3))) return;
59082
59310
  const timestamp = part.timestamp;
59083
59311
  if (timestamp == null) return {
59084
59312
  ...part,
@@ -59109,10 +59337,10 @@ const knownWarningTypes = /* @__PURE__ */ new Set([
59109
59337
  "unsupported"
59110
59338
  ]);
59111
59339
  function isUnknownWarningType(value) {
59112
- return isRecord$2(value) && isString$1(value.type) && !knownWarningTypes.has(value.type);
59340
+ return isRecord$3(value) && isString$1(value.type) && !knownWarningTypes.has(value.type);
59113
59341
  }
59114
59342
  function isWarning$1(value) {
59115
- if (!isRecord$2(value)) return false;
59343
+ if (!isRecord$3(value)) return false;
59116
59344
  switch (value.type) {
59117
59345
  case "compatibility":
59118
59346
  case "unsupported": return isString$1(value.feature) && isOptional$1(value.details, isString$1);
@@ -59122,10 +59350,10 @@ function isWarning$1(value) {
59122
59350
  }
59123
59351
  }
59124
59352
  function isAudioFormat(value) {
59125
- return isRecord$2(value) && isString$1(value.type) && value.type.length > 0 && isOptional$1(value.rate, (rate) => typeof rate === "number" && Number.isFinite(rate) && rate > 0);
59353
+ return isRecord$3(value) && isString$1(value.type) && value.type.length > 0 && isOptional$1(value.rate, (rate) => typeof rate === "number" && Number.isFinite(rate) && rate > 0);
59126
59354
  }
59127
59355
  function isUsage(value) {
59128
- return isRecord$2(value) && [
59356
+ return isRecord$3(value) && [
59129
59357
  "inputCharacters",
59130
59358
  "inputTokens",
59131
59359
  "outputTokens"
@@ -59192,12 +59420,12 @@ function parseTranscriptionStreamPart(text) {
59192
59420
  const part = value;
59193
59421
  switch (part.type) {
59194
59422
  case "stream-start": return Array.isArray(part.warnings) && part.warnings.every(isWarning) ? part : void 0;
59195
- case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59196
- case "transcript-partial": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59197
- case "transcript-final": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.endSecond, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59198
- case "finish": return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.usage, isRecord$2) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59423
+ case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isRecord$3) ? part : void 0;
59424
+ 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;
59425
+ 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;
59426
+ case "finish": return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.usage, isRecord$3) && isOptional(part.providerMetadata, isRecord$3) ? part : void 0;
59199
59427
  case "response-metadata": {
59200
- if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isRecord$2))) return;
59428
+ if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isRecord$3))) return;
59201
59429
  const timestamp = part.timestamp;
59202
59430
  if (timestamp == null) return {
59203
59431
  ...part,
@@ -59225,10 +59453,10 @@ function isOptional(value, check) {
59225
59453
  return value === void 0 || check(value);
59226
59454
  }
59227
59455
  function isWarning(value) {
59228
- return isRecord$2(value) && isString(value.type);
59456
+ return isRecord$3(value) && isString(value.type);
59229
59457
  }
59230
59458
  function isSegment(value) {
59231
- return isRecord$2(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
59459
+ return isRecord$3(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
59232
59460
  }
59233
59461
  function withoutTrailingSlash(url) {
59234
59462
  return url?.replace(/\/$/, "");
@@ -72758,6 +72986,50 @@ async function runIdleLoop(agent, streamOptions, deps, firstTurn, streamForConti
72758
72986
  resourceId
72759
72987
  });
72760
72988
  }
72989
+ // src/loop/suspended-run-auto-resume.ts
72990
+ /**
72991
+ * The `autoResumeSuspendedTools` a suspended agentic-loop run executed its latest segment with: the value persisted
72992
+ * with its most recent suspension. A resume can override the run's setting, so a resume in another process (or after
72993
+ * a restart) that leaves the option out keeps the latest one, not the one the first parked tool call recorded.
72994
+ * (#30190)
72995
+ *
72996
+ * Each tool call that suspends persists the segment's value in its own suspend payload, with its `suspendedAt`.
72997
+ * Tool calls that suspend side by side keep one record each, under `__workflow_meta.foreachOutput` or as the step's
72998
+ * `output`. The step's own suspend payload mirrors only the first suspended call, so a step with per-call records is
72999
+ * read through those records. A per-call record is read through its own payload first: on the evented engine its
73000
+ * `output` can hold stale copies of its siblings' records from before it was resumed. A snapshot written before the
73001
+ * value was persisted has none, and this returns `undefined`.
73002
+ */
73003
+ function findLatestSuspendedAutoResume(snapshot) {
73004
+ let latest;
73005
+ /** Records the values persisted at or under `entry`; whether it found one. */
73006
+ const visit = (entry, isToolCall) => {
73007
+ if (!isRecord$2(entry) || entry.status !== "suspended") return false;
73008
+ const suspendPayload = isRecord$2(entry.suspendPayload) ? entry.suspendPayload : void 0;
73009
+ const value = suspendPayload?.__autoResumeSuspendedTools;
73010
+ const record = () => {
73011
+ if (typeof value !== "boolean") return false;
73012
+ const at = typeof entry.suspendedAt === "number" ? entry.suspendedAt : 0;
73013
+ if (!latest || at >= latest.at) latest = {
73014
+ at,
73015
+ value
73016
+ };
73017
+ return true;
73018
+ };
73019
+ if (isToolCall && record()) return true;
73020
+ const meta = isRecord$2(suspendPayload?.__workflow_meta) ? suspendPayload.__workflow_meta : void 0;
73021
+ const perCall = Array.isArray(meta?.foreachOutput) ? meta.foreachOutput : Array.isArray(entry.output) ? entry.output : void 0;
73022
+ let found = false;
73023
+ for (const call of perCall ?? []) found = visit(call, true) || found;
73024
+ return found || !isToolCall && record();
73025
+ };
73026
+ const context = isRecord$2(snapshot) && isRecord$2(snapshot.context) ? snapshot.context : void 0;
73027
+ for (const step of Object.values(context ?? {})) visit(step, false);
73028
+ return latest?.value;
73029
+ }
73030
+ function isRecord$2(value) {
73031
+ return typeof value === "object" && value !== null;
73032
+ }
72761
73033
  // src/tools/provider-tool-utils.ts
72762
73034
  /**
72763
73035
  * Find a provider-defined tool by its model-facing name.
@@ -81209,6 +81481,16 @@ async function processChunkThroughOutputProcessors(chunk, registryEntry, stepReq
81209
81481
  });
81210
81482
  }
81211
81483
  /**
81484
+ * The run's `autoResumeSuspendedTools` for its current segment, persisted with each suspension: a resume can override
81485
+ * the value the run started with, and a later resume in another process that leaves the option out reads the latest
81486
+ * one back from the snapshot. The resume carries its value on the segment's request context, which reaches a step on
81487
+ * any worker; this process's registry entry stands in when user code cleared it. (#30190)
81488
+ */
81489
+ function runAutoResumeSuspendPayload(carried, registryEntry, startOptions) {
81490
+ const value = carried ?? registryEntry?.autoResumeSuspendedTools ?? startOptions?.autoResumeSuspendedTools;
81491
+ return value === void 0 ? {} : { __autoResumeSuspendedTools: value };
81492
+ }
81493
+ /**
81212
81494
  * Create a durable tool call step.
81213
81495
  *
81214
81496
  * This step mirrors the base Agent's createToolCallStep pattern:
@@ -81822,7 +82104,8 @@ function createDurableToolCallStep() {
81822
82104
  type: "approval",
81823
82105
  toolCallId,
81824
82106
  toolName,
81825
- args
82107
+ args,
82108
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
81826
82109
  }, { resumeLabel: toolCallId });
81827
82110
  }
81828
82111
  const isResumableTool = toolName?.startsWith("agent-") || toolName?.startsWith("workflow-");
@@ -82047,7 +82330,8 @@ function createDurableToolCallStep() {
82047
82330
  toolName: approvalToolName,
82048
82331
  args: approvalArgs
82049
82332
  },
82050
- ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
82333
+ ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {},
82334
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
82051
82335
  }, { resumeLabel: toolCallId });
82052
82336
  }
82053
82337
  const suspendedEventData = {
@@ -82101,7 +82385,8 @@ function createDurableToolCallStep() {
82101
82385
  toolCallId,
82102
82386
  toolName,
82103
82387
  resumeLabel: suspendOptions?.resumeLabel,
82104
- ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
82388
+ ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {},
82389
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
82105
82390
  }, { resumeLabel: toolCallId });
82106
82391
  };
82107
82392
  const toolOptions = defineLazyWriter(toolOptionsWithoutWriter, () => new require_stream$1.ToolStream({
@@ -84776,6 +85061,8 @@ var DefaultAgentExecutionEngine = class {
84776
85061
  * Close the stored signals of a parked run that was aborted. Call it before
84777
85062
  * the snapshot is deleted and before the abort terminal is published.
84778
85063
  * Returns nothing to wait for when this engine's runs never store signals.
85064
+ * Resolves `false` when the run was left open: its committed state could not
85065
+ * be determined yet, or the close did not commit.
84779
85066
  */
84780
85067
  closeParkedRunSignals(_runId) {}
84781
85068
  /**
@@ -84912,7 +85199,10 @@ var DefaultAgentExecutionEngine = class {
84912
85199
  logger: this.mastra.getLogger(),
84913
85200
  storage: this.mastra.getStorage()
84914
85201
  });
84915
- if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === "evented") this.mastra.__registerInternalWorkflow(this.#workflow, void 0, { distributed: true });
85202
+ if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === "evented") {
85203
+ this.mastra.__registerInternalWorkflow(this.#workflow, void 0, { distributed: true });
85204
+ warnProcessLocalServerCache(this.mastra);
85205
+ }
84916
85206
  }
84917
85207
  }
84918
85208
  return this.#workflow;
@@ -85213,17 +85503,17 @@ var EventedAgentExecutionEngine = class extends DefaultAgentExecutionEngine {
85213
85503
  workflowName: DurableStepIds.AGENTIC_LOOP,
85214
85504
  runId
85215
85505
  }).catch(() => null);
85216
- if (!snapshot) return;
85506
+ if (!snapshot) return false;
85217
85507
  const context = snapshot.context;
85218
- if (!context?.input?.signalsStored) return;
85508
+ if (!context?.input?.signalsStored) return true;
85219
85509
  const committed = await this.#parkedRunState(workflowsStore, snapshot);
85220
- if (!committed) return;
85221
- await closeStoredSignalRun({
85510
+ if (!committed) return false;
85511
+ return await closeStoredSignalRun({
85222
85512
  mastra: this.mastra,
85223
85513
  runId,
85224
85514
  input: context.input,
85225
85515
  state: committed.state
85226
- });
85516
+ }) ?? false;
85227
85517
  }
85228
85518
  /**
85229
85519
  * The latest committed workflow state of a parked run, or `undefined` when
@@ -85726,7 +86016,7 @@ async function prepareForDurableExecution(options) {
85726
86016
  });
85727
86017
  let tripwireData;
85728
86018
  if (inputProcessors.length > 0) try {
85729
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-CNqAlDJF.cjs")).then((n) => n.runner_exports);
86019
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-CW3d1Xg6.cjs")).then((n) => n.runner_exports);
85730
86020
  await new ProcessorRunner({
85731
86021
  inputProcessors,
85732
86022
  outputProcessors,
@@ -94235,9 +94525,30 @@ var Agent = class Agent extends require_base.MastraBase {
94235
94525
  if (!this.__usesSharedRunLog()) return void 0;
94236
94526
  return this.#resolveExecutionEngine()?.closeParkedRunSignals(runId);
94237
94527
  }
94238
- /** @internal Close the stored signals of a parked run that an abort requested by another process releases here. */
94239
- __closeParkedRunSignals(runId) {
94240
- return this.#closeParkedRunSignals(runId);
94528
+ /**
94529
+ * @internal Close the stored signals of a parked run that an abort requested by another process releases here.
94530
+ * With `exclusiveOfResume`, the close holds the run's execution claim from its snapshot read through its commit, as
94531
+ * a resume segment does. A resume that starts meanwhile waits for it, instead of consuming a signal that the close,
94532
+ * working from the snapshot it read before, would then return to pending. Resolves `false` while another
94533
+ * execution holds the run.
94534
+ */
94535
+ __closeParkedRunSignals(runId, options) {
94536
+ if (!options?.exclusiveOfResume || !this.__usesSharedRunLog() || !this.#resolveExecutionEngine()) return this.#closeParkedRunSignals(runId);
94537
+ return this.#closeParkedRunSignalsExclusively(runId);
94538
+ }
94539
+ async #closeParkedRunSignalsExclusively(runId) {
94540
+ let executionFence;
94541
+ try {
94542
+ executionFence = await this.#claimExecution(runId, "acquire");
94543
+ } catch (error) {
94544
+ if (error instanceof require_error.MastraError && error.id === "DURABLE_AGENT_EXECUTION_CONFLICT") return false;
94545
+ throw error;
94546
+ }
94547
+ let closed = false;
94548
+ await executionFence.settle(async () => {
94549
+ closed = await this.#closeParkedRunSignals(runId) ?? false;
94550
+ });
94551
+ return closed;
94241
94552
  }
94242
94553
  async #cancelAndCloseParkedRun(runId) {
94243
94554
  if (!await this.executionEngine.cancelParkedRun(runId)) return false;
@@ -94629,7 +94940,12 @@ var Agent = class Agent extends require_base.MastraBase {
94629
94940
  }
94630
94941
  async resumeStream(resumeData, streamOptions) {
94631
94942
  if (this.#resolveExecutionEngine()) return this.#resumeDurableStream(resumeData, streamOptions);
94632
- return this.#resumeStream(resumeData, streamOptions, false);
94943
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(streamOptions?.runId ?? "", this.getPubSub());
94944
+ try {
94945
+ return await this.#resumeStream(resumeData, streamOptions, false);
94946
+ } finally {
94947
+ releaseResumeHold();
94948
+ }
94633
94949
  }
94634
94950
  async #resumeDurableStream(resumeData, streamOptions) {
94635
94951
  const runId = streamOptions?.runId;
@@ -94659,7 +94975,10 @@ var Agent = class Agent extends require_base.MastraBase {
94659
94975
  const actor = mergedStreamOptions.actor;
94660
94976
  delete loopStreamOptions.actor;
94661
94977
  if (mergedStreamOptions.untilIdle) {
94662
- const { untilIdle, ...rest } = mergedStreamOptions ?? {};
94978
+ const { untilIdle, ...rest } = {
94979
+ ...mergedStreamOptions,
94980
+ autoResumeSuspendedTools: streamOptions?.autoResumeSuspendedTools
94981
+ };
94663
94982
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
94664
94983
  return runResumeStreamUntilIdle(this, resumeData, {
94665
94984
  ...rest,
@@ -94680,6 +94999,8 @@ var Agent = class Agent extends require_base.MastraBase {
94680
94999
  const snapshotMemoryInfo = this.#getSnapshotMemoryInfo(existingSnapshot);
94681
95000
  const persistedReturnScorerData = streamOptions?.returnScorerData === void 0 ? this.#getSnapshotReturnScorerData(existingSnapshot) : void 0;
94682
95001
  if (persistedReturnScorerData !== void 0) mergedStreamOptions.returnScorerData = loopStreamOptions.returnScorerData = persistedReturnScorerData;
95002
+ const runAutoResume = streamOptions?.autoResumeSuspendedTools ?? findLatestSuspendedAutoResume(existingSnapshot);
95003
+ if (runAutoResume !== void 0) mergedStreamOptions.autoResumeSuspendedTools = loopStreamOptions.autoResumeSuspendedTools = runAutoResume;
94683
95004
  if (snapshotMemoryInfo?.threadId) {
94684
95005
  mergedStreamOptions.memory = {
94685
95006
  ...mergedStreamOptions.memory ?? {},
@@ -94786,7 +95107,10 @@ var Agent = class Agent extends require_base.MastraBase {
94786
95107
  text: "An unknown error occurred while streaming"
94787
95108
  });
94788
95109
  }
94789
- await agentThreadStreamRuntime.registerRun(this, result.result, preparedOptions, threadStreamPubSub);
95110
+ await agentThreadStreamRuntime.registerRun(this, result.result, {
95111
+ ...preparedOptions,
95112
+ autoResumeSuspendedTools: runAutoResume
95113
+ }, threadStreamPubSub);
94790
95114
  return result.result;
94791
95115
  } catch (error) {
94792
95116
  await resumeClaim.release();
@@ -94815,6 +95139,17 @@ var Agent = class Agent extends require_base.MastraBase {
94815
95139
  async resumeGenerate(...args) {
94816
95140
  if (this.#resolveExecutionEngine()) return this.#resumeDurableGenerate(args);
94817
95141
  const [resumeData, options] = args;
95142
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(options?.runId ?? "", this.getPubSub());
95143
+ let completed = false;
95144
+ try {
95145
+ const output = await this.#resumePlainGenerate(resumeData, options);
95146
+ completed = output.finishReason !== "suspended";
95147
+ return output;
95148
+ } finally {
95149
+ releaseResumeHold({ startQueuedTurn: completed });
95150
+ }
95151
+ }
95152
+ async #resumePlainGenerate(resumeData, options) {
94818
95153
  const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });
94819
95154
  const mergedOptions = require_utils$1.deepMerge(withDefaultToolCallConcurrencyLimit(defaultOptions, options), withDefinedToolHooks(options) ?? {});
94820
95155
  validateModelTimeoutSettings(mergedOptions.modelSettings?.timeout);
@@ -94828,6 +95163,8 @@ var Agent = class Agent extends require_base.MastraBase {
94828
95163
  });
94829
95164
  const persistedReturnScorerData = options?.returnScorerData === void 0 ? this.#getSnapshotReturnScorerData(existingSnapshot) : void 0;
94830
95165
  if (persistedReturnScorerData !== void 0) mergedOptions.returnScorerData = loopOptions.returnScorerData = persistedReturnScorerData;
95166
+ const persistedAutoResume = options?.autoResumeSuspendedTools === void 0 ? findLatestSuspendedAutoResume(existingSnapshot) : void 0;
95167
+ if (persistedAutoResume !== void 0) mergedOptions.autoResumeSuspendedTools = loopOptions.autoResumeSuspendedTools = persistedAutoResume;
94831
95168
  const { options: scopedOptions, resolved: resolvedScopes } = await this.#resolveRunScopes(mergedOptions, {
94832
95169
  callScopes: options?.scopes,
94833
95170
  defaultScopes: defaultOptions?.scopes,
@@ -94961,7 +95298,12 @@ var Agent = class Agent extends require_base.MastraBase {
94961
95298
  runId: options.runId
94962
95299
  }
94963
95300
  });
94964
- return this.#resumeStream(void 0, options, true);
95301
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(options.runId, this.getPubSub());
95302
+ try {
95303
+ return await this.#resumeStream(void 0, options, true);
95304
+ } finally {
95305
+ releaseResumeHold();
95306
+ }
94965
95307
  }
94966
95308
  /**
94967
95309
  * Approves a pending tool call and resumes execution.
@@ -96202,10 +96544,11 @@ var Agent = class Agent extends require_base.MastraBase {
96202
96544
  if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, registryEntry);
96203
96545
  }
96204
96546
  };
96547
+ let cleanupOutput;
96205
96548
  const runCleanup = createRunCleanup({
96206
96549
  scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
96207
96550
  release: () => {
96208
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
96551
+ if (cleanupOutput) agentThreadStreamRuntime.closeRunContinuation(cleanupOutput, this.getPubSub());
96209
96552
  streamCleanup?.();
96210
96553
  cleanupOwnedRegistryState();
96211
96554
  }
@@ -96238,6 +96581,7 @@ var Agent = class Agent extends require_base.MastraBase {
96238
96581
  });
96239
96582
  const { output, cleanup: createdStreamCleanup, ready } = stream;
96240
96583
  streamCleanup = createdStreamCleanup;
96584
+ cleanupOutput = output;
96241
96585
  const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
96242
96586
  const workflowExecution = executionFence.run(() => this.executionEngine.raceFenceLoss(ready, executionFence).then(async () => {
96243
96587
  const result = await this.executionEngine.restartRun(workflow, executionFence, recoveryPubsub, this.workflowEngine, this.logger, resourceId, requestContext, require_observability.createObservabilityContext({ currentSpan: recoverAgentSpan }));
@@ -96954,12 +97298,15 @@ var Agent = class Agent extends require_base.MastraBase {
96954
97298
  });
96955
97299
  releaseResumeMarker = release;
96956
97300
  }
97301
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(runId, this.getPubSub());
96957
97302
  try {
96958
97303
  if (await this.#isRunCanceledInStorage(runId)) throw abortedRunError();
96959
97304
  return await this.#resumeRun(runId, resumeData, options, releaseResumeMarker);
96960
97305
  } catch (error) {
96961
97306
  releaseResumeMarker();
96962
97307
  throw error;
97308
+ } finally {
97309
+ releaseResumeHold();
96963
97310
  }
96964
97311
  }
96965
97312
  /**
@@ -97001,6 +97348,7 @@ var Agent = class Agent extends require_base.MastraBase {
97001
97348
  let entry = this.executionRunRegistry.get(runId);
97002
97349
  let rehydratedScopes;
97003
97350
  let coldSnapshot;
97351
+ let coldRunAutoResume;
97004
97352
  if (!entry) {
97005
97353
  const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
97006
97354
  const persisted = workflowsStore ? await this.executionEngine.loadPersistedRunSnapshot(workflowsStore, runId) : void 0;
@@ -97099,6 +97447,7 @@ var Agent = class Agent extends require_base.MastraBase {
97099
97447
  }
97100
97448
  });
97101
97449
  rehydratedScopes = persistedScopes;
97450
+ coldRunAutoResume = findLatestSuspendedAutoResume(snapshot) ?? workflowInput.options?.autoResumeSuspendedTools;
97102
97451
  const memory = threadId ? {
97103
97452
  ...options?.memory,
97104
97453
  thread: threadId,
@@ -97159,8 +97508,12 @@ var Agent = class Agent extends require_base.MastraBase {
97159
97508
  requestContextKeys
97160
97509
  };
97161
97510
  resumeRequestContext = resolvedOptions.requestContext ?? resumeRequestContext;
97511
+ const runAutoResume = options?.autoResumeSuspendedTools ?? (coldSnapshot ? coldRunAutoResume : entry.autoResumeSuspendedTools);
97162
97512
  if (resolvedOptions.untilIdle) {
97163
- const { untilIdle, ...rest } = resolvedOptions;
97513
+ const { untilIdle, ...rest } = {
97514
+ ...resolvedOptions,
97515
+ autoResumeSuspendedTools: runAutoResume
97516
+ };
97164
97517
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
97165
97518
  releaseResumeMarker();
97166
97519
  return runResumeDurableStreamUntilIdle({
@@ -97323,6 +97676,7 @@ var Agent = class Agent extends require_base.MastraBase {
97323
97676
  globalEntryForContext.requestContext = resumeRequestContext;
97324
97677
  globalEntryForContext.requestContextRebuilt = false;
97325
97678
  }
97679
+ for (const reg of /* @__PURE__ */ new Set([entry, globalEntryForContext])) if (reg && runAutoResume !== void 0) reg.autoResumeSuspendedTools = runAutoResume;
97326
97680
  } catch (error) {
97327
97681
  await executionFence.settle(async () => {});
97328
97682
  throw error;
@@ -97436,6 +97790,7 @@ var Agent = class Agent extends require_base.MastraBase {
97436
97790
  this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open resume spans: ${error}`);
97437
97791
  }
97438
97792
  carrySegmentSpans(resumeRequestContext, runId, resumeSegment);
97793
+ if (runAutoResume !== void 0) carrySegmentAutoResume(resumeRequestContext, runId, runAutoResume);
97439
97794
  const resumeSegmentSpan = entry.resumeAgentSpan ?? entry.agentSpan;
97440
97795
  const closeOnSuspend = resolvedOptions.closeOnSuspend ?? false;
97441
97796
  const { output, cleanup: createdStreamCleanup, detach: detachResumeStream, fail: failResumeStream, waitForEventDelivery, ready } = createDurableAgentStream({
@@ -97557,7 +97912,8 @@ var Agent = class Agent extends require_base.MastraBase {
97557
97912
  workflowExecution.then(releaseResumeMarker, releaseResumeMarker);
97558
97913
  const resumeStreamOptions = {
97559
97914
  ...resolvedOptions,
97560
- runId
97915
+ runId,
97916
+ autoResumeSuspendedTools: runAutoResume
97561
97917
  };
97562
97918
  if (!agentThreadStreamRuntime.continueRun(this, output, resumeStreamOptions, this.getPubSub(), {
97563
97919
  generation: executionFence.generation,
@@ -102697,33 +103053,56 @@ async function processOutputStream({ collectedChunks = [], tools, messageId, mes
102697
103053
  toolResultTripwire
102698
103054
  };
102699
103055
  }
102700
- function executeStreamWithFallbackModels(models, logger, startIndex = 0, throwIfInterrupted) {
103056
+ /**
103057
+ * What the next step needs to stay on the model serving this generation. A resumed run
103058
+ * resolves its models again, and the list can come back in another order: the id finds the
103059
+ * model again when the caller named it, the first one included.
103060
+ */
103061
+ function carriedFallbackModel(models, index, triesEarlierEntries) {
103062
+ if (models.length < 2) return {};
103063
+ return {
103064
+ ...index > 0 ? { fallbackModelIndex: index } : {},
103065
+ fallbackModelId: models[index]?.id,
103066
+ ...triesEarlierEntries ? { fallbackModelTriesEarlierEntries: true } : {}
103067
+ };
103068
+ }
103069
+ function carriedFallbackModelIndex(models, carried) {
103070
+ const saved = carried.fallbackModelIndex ?? 0;
103071
+ if (models[saved]?.id === carried.fallbackModelId) return saved;
103072
+ const byId = models.findIndex((candidate) => candidate.id === carried.fallbackModelId);
103073
+ return byId >= 0 ? byId : carried.fallbackModelIndex || 0;
103074
+ }
103075
+ /**
103076
+ * True when a resumed run found its model by id at another position than the one it saved: the
103077
+ * list came back in another order, so the entries now ahead of that model were not tried yet.
103078
+ */
103079
+ function resumedInAnotherOrder(models, carried) {
103080
+ const saved = carried.fallbackModelIndex ?? 0;
103081
+ if (carried.fallbackModelId === void 0 || models[saved]?.id === carried.fallbackModelId) return false;
103082
+ return models.some((candidate) => candidate.id === carried.fallbackModelId);
103083
+ }
103084
+ function executeStreamWithFallbackModels(models, logger, startIndex = 0, throwIfInterrupted, tryEntriesBeforeStart = false) {
102701
103085
  return async (callback) => {
102702
- let index = startIndex;
103086
+ const order = [...models.slice(startIndex), ...tryEntriesBeforeStart ? models.slice(0, startIndex) : []];
102703
103087
  let finalResult;
102704
- let done = false;
102705
103088
  let lastError;
102706
- for (const modelConfig of models.slice(startIndex)) {
102707
- index++;
102708
- if (done) break;
102709
- try {
102710
- finalResult = await callback(modelConfig, index === models.length);
102711
- done = true;
102712
- } catch (err) {
102713
- throwIfInterrupted?.();
102714
- if (err instanceof require_stream.TripWire) throw err;
102715
- if (require_stream.isMastraTimeoutError(err) && err.timeoutType === "total") throw err;
102716
- lastError = err;
102717
- const nextModel = models[index];
102718
- if (nextModel) logger?.warn(`Model ${modelConfig.model.modelId} failed; falling back to ${nextModel.model.modelId}`, {
102719
- error: err,
102720
- modelId: modelConfig.model.modelId,
102721
- nextModelId: nextModel.model.modelId,
102722
- attempt: index,
102723
- totalModels: models.length
102724
- });
102725
- else logger?.error(`Error executing model ${modelConfig.model.modelId}`, err);
102726
- }
103089
+ for (const [attempt, modelConfig] of order.entries()) try {
103090
+ finalResult = await callback(modelConfig, attempt === order.length - 1);
103091
+ break;
103092
+ } catch (err) {
103093
+ throwIfInterrupted?.();
103094
+ if (err instanceof require_stream.TripWire) throw err;
103095
+ if (require_stream.isMastraTimeoutError(err) && err.timeoutType === "total") throw err;
103096
+ lastError = err;
103097
+ const nextModel = order[attempt + 1];
103098
+ if (nextModel) logger?.warn(`Model ${modelConfig.model.modelId} failed; falling back to ${nextModel.model.modelId}`, {
103099
+ error: err,
103100
+ modelId: modelConfig.model.modelId,
103101
+ nextModelId: nextModel.model.modelId,
103102
+ attempt: attempt + 1,
103103
+ totalModels: order.length
103104
+ });
103105
+ else logger?.error(`Error executing model ${modelConfig.model.modelId}`, err);
102727
103106
  }
102728
103107
  if (typeof finalResult === "undefined") {
102729
103108
  const fatalError = lastError ?? /* @__PURE__ */ new Error("Exhausted all fallback models without receiving a result.");
@@ -102990,7 +103369,8 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
102990
103369
  let warnings;
102991
103370
  let request;
102992
103371
  let rawResponse;
102993
- let activeFallbackModelIndex = inputData.fallbackModelIndex || 0;
103372
+ let activeFallbackModelIndex = carriedFallbackModelIndex(models, inputData);
103373
+ const triesEarlierEntries = inputData.fallbackModelTriesEarlierEntries === true || resumedInAnotherOrder(models, inputData);
102994
103374
  let executedStepModel;
102995
103375
  let terminalInputStepFailure;
102996
103376
  let materializeFailedAttempt;
@@ -103002,8 +103382,8 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
103002
103382
  logger
103003
103383
  });
103004
103384
  let settleRequest = () => {};
103005
- const execution = await executeStreamWithFallbackModels(models, logger, activeFallbackModelIndex, throwIfInterrupted)(async (modelConfig, isLastModel) => {
103006
- activeFallbackModelIndex = models.findIndex((candidate) => candidate.id === modelConfig.id);
103385
+ const execution = await executeStreamWithFallbackModels(models, logger, activeFallbackModelIndex, throwIfInterrupted, triesEarlierEntries)(async (modelConfig, isLastModel) => {
103386
+ activeFallbackModelIndex = models.indexOf(modelConfig);
103007
103387
  materializeFailedAttempt = void 0;
103008
103388
  settleRequest();
103009
103389
  settleRequest = require_utils$1.startRunStep(options?.stepOwner ?? options?.abortSignal);
@@ -103877,7 +104257,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
103877
104257
  nonUser: []
103878
104258
  },
103879
104259
  processorRetryCount: inputData.processorRetryCount,
103880
- ...activeFallbackModelIndex > 0 ? { fallbackModelIndex: activeFallbackModelIndex } : {},
104260
+ ...carriedFallbackModel(models, activeFallbackModelIndex, triesEarlierEntries),
103881
104261
  ...inputData.skipUnavailableAttachments ? { skipUnavailableAttachments: true } : {}
103882
104262
  };
103883
104263
  if (!aborted) return result;
@@ -104090,7 +104470,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
104090
104470
  },
104091
104471
  messages,
104092
104472
  processorRetryCount: nextProcessorRetryCount,
104093
- ...activeFallbackModelIndex > 0 ? { fallbackModelIndex: activeFallbackModelIndex } : {},
104473
+ ...carriedFallbackModel(models, activeFallbackModelIndex, triesEarlierEntries),
104094
104474
  ...skipUnavailableAttachments ? { skipUnavailableAttachments } : {}
104095
104475
  };
104096
104476
  }
@@ -104272,7 +104652,6 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
104272
104652
  nonUser: messageList.get.response.aiV5.model()
104273
104653
  };
104274
104654
  const stepReason = shouldRetry ? "retry" : tripwireTriggered ? "tripwire" : hasErrored ? "error" : finishReason;
104275
- const nextFallbackModelIndex = shouldContinue ? activeFallbackModelIndex : 0;
104276
104655
  cleanupProviderToolSpans(!shouldContinue || shouldRetry);
104277
104656
  const nextProcessorRetryCount = shouldRetry ? currentProcessorRetryCount + 1 : 0;
104278
104657
  return {
@@ -104306,7 +104685,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
104306
104685
  messages,
104307
104686
  processorRetryCount: nextProcessorRetryCount,
104308
104687
  processorRetryFeedback: retryFeedbackText,
104309
- ...nextFallbackModelIndex > 0 ? { fallbackModelIndex: nextFallbackModelIndex } : {}
104688
+ ...shouldContinue ? carriedFallbackModel(models, activeFallbackModelIndex, triesEarlierEntries) : {}
104310
104689
  };
104311
104690
  }
104312
104691
  });
@@ -104776,7 +105155,7 @@ function createLLMMappingStep({ models, _internal, ...rest }, llmExecutionStep)
104776
105155
  });
104777
105156
  }
104778
105157
  // src/loop/workflows/agentic-execution/tool-call-step.ts
104779
- function createToolCallStep({ tools, messageList, options, outputWriter, controller, runId, streamState, modelSpanTracker, _internal, logger, agentId, agentVersionId, resolvedScopes, returnScorerData, mastra, requireToolApproval: requireToolApprovalFromFactory, actor, mcp, agent }) {
105158
+ function createToolCallStep({ tools, messageList, options, outputWriter, controller, runId, streamState, modelSpanTracker, _internal, logger, agentId, agentVersionId, resolvedScopes, returnScorerData, autoResumeSuspendedTools, mastra, requireToolApproval: requireToolApprovalFromFactory, actor, mcp, agent }) {
104780
105159
  const memoryMessageRefs = new MemoryMessageRefs();
104781
105160
  return createStep$1({
104782
105161
  id: "toolCallStep",
@@ -105124,6 +105503,7 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105124
105503
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105125
105504
  __resolvedScopes: resolvedScopes ?? [],
105126
105505
  ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105506
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {},
105127
105507
  suspendedToolRunId: options.runId
105128
105508
  }, { resumeLabel: inputData.toolCallId });
105129
105509
  }
@@ -105164,6 +105544,7 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105164
105544
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105165
105545
  __resolvedScopes: resolvedScopes ?? [],
105166
105546
  ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105547
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {},
105167
105548
  toolCallId: inputData.toolCallId,
105168
105549
  toolName: inputData.toolName,
105169
105550
  resumeLabel: options?.resumeLabel,
@@ -105237,7 +105618,8 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105237
105618
  __agentId: agentId,
105238
105619
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105239
105620
  __resolvedScopes: resolvedScopes ?? [],
105240
- ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {}
105621
+ ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105622
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {}
105241
105623
  }, { resumeLabel: inputData.toolCallId });
105242
105624
  }
105243
105625
  const clearedApproval = await removeToolMetadata({
@@ -106680,6 +107062,15 @@ const AGENT_THREAD_WAKE_OWNER_DISCOVERY_DEADLINE_MS = require_utils$1.readPositi
106680
107062
  const AGENT_THREAD_CLAIM_LEASE_PREFIX = "thread-claim:";
106681
107063
  const AGENT_THREAD_OWNER_ACCEPTANCE_TIMEOUT_MS = 5e3;
106682
107064
  const UNSAVED_RUN_TRIM_DELAY_MS = 3e4;
107065
+ /** Waits before a parked storage-backed run tries again to let go of its thread for queued input (#30190). */
107066
+ const PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS = [
107067
+ 100,
107068
+ 200,
107069
+ 400,
107070
+ 800,
107071
+ 1600,
107072
+ 3200
107073
+ ];
106683
107074
  const AGENT_THREAD_PEER_DISCOVERY_TOPIC = "agent.thread-peer-discovery";
106684
107075
  const AGENT_THREAD_PEER_DISCOVERY_TIMEOUT_MS = 100;
106685
107076
  const THREAD_LEASE_OWNER_PREFIX = "mastra:thread-lease:";
@@ -106968,6 +107359,38 @@ function withThreadMemory(memory, resourceId, threadId) {
106968
107359
  thread: memory?.thread ?? threadId
106969
107360
  };
106970
107361
  }
107362
+ /**
107363
+ * The memory a resume that names no thread continues its run with: the run's thread and resource, the run's
107364
+ * settings, and on top of those every setting the resume passes itself (`options` merged key by key, so a resume
107365
+ * that sets only `lastMessages` or `readOnly` keeps the rest).
107366
+ */
107367
+ function resumeMemoryOnOwnThread({ run, resume, threadId, resourceId }) {
107368
+ const options = run?.options || resume?.options ? {
107369
+ ...run?.options,
107370
+ ...resume?.options
107371
+ } : void 0;
107372
+ return {
107373
+ ...run,
107374
+ ...resume,
107375
+ thread: run?.thread ?? threadId,
107376
+ resource: run?.resource ?? resourceId,
107377
+ ...options ? { options } : {}
107378
+ };
107379
+ }
107380
+ /**
107381
+ * The options a resume leaves on its run's record. Resume callers hand over the resume's own
107382
+ * `autoResumeSuspendedTools`, not the agent default merged in, so `undefined` means the resume left it out. The run
107383
+ * then keeps the value it started with: a run that turned auto-resume off keeps holding a queued message for an
107384
+ * explicit resume after it parks again. Callers that resume a run rebuilt from storage pass the run's persisted value
107385
+ * instead, since this process has no record of it. (#30190)
107386
+ */
107387
+ function keepRunAutoResume(resume, run) {
107388
+ if (resume.autoResumeSuspendedTools !== void 0 || run?.autoResumeSuspendedTools === void 0) return resume;
107389
+ return {
107390
+ ...resume,
107391
+ autoResumeSuspendedTools: run.autoResumeSuspendedTools
107392
+ };
107393
+ }
106971
107394
  const CANCELLED_BEFORE_RUN = "The accepted message was cancelled before it ran";
106972
107395
  function toPublicThreadPeer(peer) {
106973
107396
  const { unsubscribe: _unsubscribe, ...publicPeer } = peer;
@@ -106998,6 +107421,7 @@ function createRuntimeState() {
106998
107421
  suspensionMetadataByRunId: /* @__PURE__ */ new Map(),
106999
107422
  signalQueues: createActiveRunSignalQueues(),
107000
107423
  locallyQueuedSignalIdsByThread: /* @__PURE__ */ new Map(),
107424
+ startedSignalIdsByThread: /* @__PURE__ */ new Map(),
107001
107425
  pendingSignalListenersByRunId: /* @__PURE__ */ new Map(),
107002
107426
  lostRunsByThread: /* @__PURE__ */ new Map(),
107003
107427
  pendingIdleSignalsByThread: /* @__PURE__ */ new Map(),
@@ -107045,6 +107469,11 @@ var AgentThreadStreamRuntime = class {
107045
107469
  #stalledLeaseReads = /* @__PURE__ */ new WeakMap();
107046
107470
  /** Per run, the resolution of its signals store in flight (see `#signalsStoreOf`). */
107047
107471
  #storeResolutions = /* @__PURE__ */ new WeakMap();
107472
+ /**
107473
+ * Parked storage-backed runs letting go of their thread for queued input, one release at a time per run. `again`
107474
+ * records a trigger that arrived meanwhile, which checks the run again unless the release let go of the thread.
107475
+ */
107476
+ #releasingParkedStoredRuns = /* @__PURE__ */ new WeakMap();
107048
107477
  #threadlessRunFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(({ state, runId, token }) => {
107049
107478
  if (state.preparedRunsById.get(runId)?.finalizerToken !== token) return;
107050
107479
  this.#cleanupPreparedRun(state, runId);
@@ -107279,7 +107708,7 @@ var AgentThreadStreamRuntime = class {
107279
107708
  }
107280
107709
  const preparedRun = state.preparedRunsById.get(runId);
107281
107710
  const controller = preparedRun?.abortController ?? record.segmentAbortController;
107282
- const stepOwners = [controller?.signal, record.stepOwner?.()].filter((owner) => owner !== void 0);
107711
+ const stepOwners = this.#runStepOwners(state, record);
107283
107712
  const executing = !!preparedRun && record.lifecycle !== "suspended" || stepOwners.some((owner) => require_utils$1.hasRunningRunStep(owner));
107284
107713
  const abortController = executing ? controller : void 0;
107285
107714
  if (!state.leaseRenewalTimers.has(runId) || record.registeredElsewhere || record.lateRetakeHandoff) {
@@ -107841,10 +108270,61 @@ var AgentThreadStreamRuntime = class {
107841
108270
  if (!active) return;
107842
108271
  const data = event.data;
107843
108272
  if (data?.type === "signal-enqueued") {
107844
- if (data.sourceId === this.#id && this.#isLocalSignalEcho(state, key, data.signal.id, data.runId) || subscription.admittedSignalIds.has(data.signal.id)) return;
108273
+ if (data.sourceId === this.#id && this.#isLocalSignalEcho(state, key, data.signal.id, data.runId) || subscription.admittedSignalIds.has(data.signal.id) || state.startedSignalIdsByThread.get(key)?.has(data.signal.id)) return;
107845
108274
  const answersTo = (runId) => state.threadKeysByRunId.get(runId) === key || subscription.ownedRunIds.has(runId) || state.storedSignals.endedRun(key)?.run.runId === runId;
107846
108275
  const runId = answersTo(data.runId) ? data.runId : forwardedSignalRunId(data.runId);
107847
108276
  if (!answersTo(runId)) return;
108277
+ if (state.threadRunsById.get(runId)?.registeredElsewhere) return;
108278
+ if (data.senderKeepsCopy && !state.activeThreadRunIds.has(key)) return;
108279
+ const activeRunId = data.queued ? state.activeThreadRunIds.get(key) : void 0;
108280
+ const live = activeRunId ? state.threadRunsById.get(activeRunId) : void 0;
108281
+ if (live && this.#isThreadBlockingRun(state, live)) {
108282
+ const signal = require_signals.createSignal(data.signal);
108283
+ subscription.admittedSignalIds.add(signal.id);
108284
+ const admit = () => {
108285
+ if (this.#pendingUserMessageChunk(runId, signal, "pending")) this.#publish(pubsub, key, {
108286
+ type: "user-message-admitted",
108287
+ signalId: signal.id,
108288
+ admittedRunId: runId
108289
+ });
108290
+ };
108291
+ const admitStored = () => {
108292
+ this.#publishPendingUserMessage(pubsub, key, live.runId, signal, "queued");
108293
+ admit();
108294
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, live);
108295
+ };
108296
+ if (data.stored) return admitStored();
108297
+ const liveStore = this.#signalsStoreOf(live);
108298
+ if (!liveStore) {
108299
+ this.queueSignal(live.agent, signal, { runId: live.runId }, pubsub);
108300
+ return admit();
108301
+ }
108302
+ const to = {
108303
+ runId: live.runId,
108304
+ agent: live.agent
108305
+ };
108306
+ const written = this.#enqueueStoredSignal(state, key, liveStore, signal, to, true, true);
108307
+ return { settled: (async () => {
108308
+ try {
108309
+ if (await written === "run-closed") {
108310
+ if (subscription.cancelledSignalIds.has(signal.id)) return;
108311
+ this.#announceLeftoverSignal(state, pubsub, key, live, signal);
108312
+ if (live.runId !== runId) admit();
108313
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, live);
108314
+ return;
108315
+ }
108316
+ } catch (error) {
108317
+ if (!subscription.cancelledSignalIds.has(signal.id)) subscription.admittedSignalIds.delete(signal.id);
108318
+ live.agent.__getLogger?.()?.warn?.("Could not store a queued signal forwarded to a running run", {
108319
+ runId,
108320
+ signalId: signal.id,
108321
+ error
108322
+ });
108323
+ throw error;
108324
+ }
108325
+ admitStored();
108326
+ })() };
108327
+ }
107848
108328
  const ended = state.storedSignals.endedRun(key)?.run;
107849
108329
  const run = state.threadRunsById.get(runId) ?? (ended?.runId === runId ? ended : void 0);
107850
108330
  const store = run && this.#signalsStoreOf(run);
@@ -107860,15 +108340,34 @@ var AgentThreadStreamRuntime = class {
107860
108340
  subscription.admittedSignalIds.add(data.signal.id);
107861
108341
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
107862
108342
  this.#notifyPendingSignals(state, key, signal);
108343
+ const record = state.threadRunsById.get(runId);
108344
+ if (record) this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
107863
108345
  } else if (data?.type === "user-message-admitted") this.#settleForwardedIdleSignal(state, key, data.signalId, data.admittedRunId);
107864
108346
  else if (data?.type === "user-message-presentation") {
107865
108347
  const { chunk } = data;
107866
108348
  if (chunk.type === "data-user-message-pending" && chunk.data.metadata?.status === "pending") this.#settleForwardedIdleSignal(state, key, chunk.data.id, chunk.runId);
107867
108349
  } else if (data?.type === "signals-cancelled") {
107868
108350
  for (const id of data.signalIds) this.#settleForwardedIdleSignal(state, key, id);
107869
- for (const id of data.signalIds) subscription.admittedSignalIds.add(id);
108351
+ for (const id of data.signalIds) {
108352
+ subscription.admittedSignalIds.add(id);
108353
+ subscription.cancelledSignalIds.add(id);
108354
+ }
107870
108355
  this.#cancelPendingSignals(state, key, new Set(data.signalIds), pubsub, this.#threadSignalsStore(state, key));
107871
108356
  this.#notifyThreadEvents(state);
108357
+ } else if (data?.type === "queued-input-waiting") {
108358
+ const record = state.threadRunsById.get(data.runId);
108359
+ if (data.sourceId === this.#getSourceId() || !record || state.threadKeysByRunId.get(data.runId) !== key) return;
108360
+ record.queuedInputElsewhere = true;
108361
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
108362
+ } else if (data?.type === "parked-run-released") {
108363
+ if (data.sourceId === this.#getSourceId() || state.activeThreadRunIds.get(key) !== data.runId) return;
108364
+ const record = state.threadRunsById.get(data.runId);
108365
+ if (record && record.registeredElsewhere === void 0) return;
108366
+ if (state.activeThreadStreamIds.get(key) !== data.streamId && record?.registeredElsewhere !== data.streamId) return;
108367
+ state.activeThreadRunIds.delete(key);
108368
+ state.activeThreadStreamIds.delete(key);
108369
+ this.#notifyThreadEvents(state);
108370
+ await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
107872
108371
  } else if (data?.type === "run-abort-requested") {
107873
108372
  const ownsRun = () => active && (state.preparedRunsById.has(data.runId) || state.threadRunsById.has(data.runId)) && state.threadKeysByRunId.get(data.runId) === key && state.activeThreadRunIds.get(key) === data.runId && (data.streamId === void 0 || state.activeThreadStreamIds.get(key) === data.streamId);
107874
108373
  const clearPendingSignals = ownsRun() && data.clearPendingSignals && await this.#holdsThreadLeaseThroughRetake(resolvedPubSub, key, data.runId);
@@ -107890,7 +108389,8 @@ var AgentThreadStreamRuntime = class {
107890
108389
  return;
107891
108390
  }
107892
108391
  const current = state.threadRunsById.get(data.runId);
107893
- if (current?.registrationSeen) current.registeredElsewhere = true;
108392
+ if (current?.registrationSeen) current.registeredElsewhere = data.streamId;
108393
+ if (state.activeThreadRunIds.get(key) === data.runId) this.#requestParkedRunReleaseElsewhere(state, resolvedPubSub, key, { executionChanged: true });
107894
108394
  if (lost?.runId === data.runId && lost.registrationSeen) {
107895
108395
  state.lostRunsByThread.delete(key);
107896
108396
  this.#handOffQueuedSignals(state, resolvedPubSub, key, data.runId, lost.streamId);
@@ -107900,6 +108400,8 @@ var AgentThreadStreamRuntime = class {
107900
108400
  if (data.type === "run-discarded" && !(state.forwardedIdleLeaseChecks.has(key) && await this.#leaseMayStillName(resolvedPubSub, key, data.runId)) && this.#requeueUnadmittedForwards(state, key, data.runId)) await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
107901
108401
  } else if (data?.type === "run-completed" || data?.type === "run-failed") {
107902
108402
  this.#releaseRunSupersededBy(state, resolvedPubSub, key, subscription, data.runId);
108403
+ if (data.type === "run-completed" && data.status === "interrupted" && state.threadRunsById.get(data.runId)?.registeredElsewhere === data.streamId) return;
108404
+ this.#retireRunEndedElsewhere(state, resolvedPubSub, key, data.runId, data.streamId);
107903
108405
  const lostStreamId = subscription.successorRunIds.get(data.runId);
107904
108406
  if (lostStreamId !== void 0 && data.streamId === lostStreamId) return;
107905
108407
  if (lostStreamId === void 0 && data.type === "run-completed" && data.superseded && state.forwardedIdleLeaseChecks.has(key)) return;
@@ -107916,7 +108418,7 @@ var AgentThreadStreamRuntime = class {
107916
108418
  const onEvent = (event, ack) => {
107917
108419
  const type = event.data?.type;
107918
108420
  const awaitingForwards = state.forwardedIdleSignalsByThread.has(key);
107919
- if (type !== "signal-enqueued" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !((type === "user-message-presentation" || type === "user-message-admitted") && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
108421
+ if (type !== "signal-enqueued" && type !== "queued-input-waiting" && type !== "parked-run-released" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !((type === "user-message-presentation" || type === "user-message-admitted") && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
107920
108422
  subscription.references++;
107921
108423
  const handled = tail.then(() => handleEvent(event));
107922
108424
  tail = handled.then(() => {}, () => {});
@@ -107931,6 +108433,7 @@ var AgentThreadStreamRuntime = class {
107931
108433
  observers: 0,
107932
108434
  ownedRunIds,
107933
108435
  admittedSignalIds: /* @__PURE__ */ new Set(),
108436
+ cancelledSignalIds: /* @__PURE__ */ new Set(),
107934
108437
  successorRunIds: /* @__PURE__ */ new Map(),
107935
108438
  supersedingRunIds: /* @__PURE__ */ new Map(),
107936
108439
  unsubscribe: () => {
@@ -107953,7 +108456,9 @@ var AgentThreadStreamRuntime = class {
107953
108456
  if (!subscription || subscription.references > subscription.observers || this.#hasPendingThreadWork(state, key) || state.forwardedIdleSignalsByThread.has(key) || state.drainingPendingSignalsByThread.has(key) || state.drainingIdleSignalsByThread.has(key) || state.recentlyEndedStoredRunTimers.has(key) || [...state.threadKeysByRunId.values()].includes(key) || [...state.preparedRunsById.values()].some((run) => run.threadKey === key)) return;
107954
108457
  subscription.ownedRunIds.clear();
107955
108458
  subscription.admittedSignalIds.clear();
108459
+ subscription.cancelledSignalIds.clear();
107956
108460
  state.locallyQueuedSignalIdsByThread.delete(key);
108461
+ state.startedSignalIdsByThread.delete(key);
107957
108462
  if (subscription.observers) return;
107958
108463
  state.threadControlSubscriptions.delete(key);
107959
108464
  subscription.unsubscribe();
@@ -108648,11 +109153,16 @@ var AgentThreadStreamRuntime = class {
108648
109153
  runId,
108649
109154
  resourceId: owner.resourceId,
108650
109155
  threadId: owner.threadId,
108651
- streamOptions
109156
+ streamOptions,
109157
+ ...waitForIdle ? { queued: true } : {}
108652
109158
  });
108653
109159
  state.pendingIdleSignalsByThread.set(key, idleQueue);
108654
109160
  this.#publishPendingUserMessage(pubsub, key, activeRunId, signal, "queued");
108655
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
109161
+ if (activeRecord) {
109162
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
109163
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, activeRecord);
109164
+ }
109165
+ this.#requestParkedRunReleaseElsewhere(state, pubsub, key);
108656
109166
  settleMessageIdentity?.({ runId });
108657
109167
  return { runId };
108658
109168
  }
@@ -108744,25 +109254,18 @@ var AgentThreadStreamRuntime = class {
108744
109254
  action: "remote",
108745
109255
  runId: ownerRunId
108746
109256
  });
108747
- if (this.#mayStoreForRunHeldElsewhere(state, owner.agent, forwardedSignalRunId(ownerRunId))) {
108748
- if (!await this.#forwardSignal(state, pubsub, key, owner.agent, ownerRunId, signal).catch((error) => {
108749
- releaseMessageIdentity(require_error.getErrorFromUnknown(error));
108750
- throw error;
108751
- })) {
108752
- const error = `Thread ${describeThreadKey(key)} is held by run ${ownerRunId}, which ended before it took the message`;
108753
- releaseMessageIdentity(error);
108754
- return {
108755
- runId: ownerRunId,
108756
- error,
108757
- blocked: true
108758
- };
108759
- }
108760
- } else this.#publish(pubsub, key, {
108761
- type: "signal-enqueued",
108762
- runId: ownerRunId,
108763
- signal: this.#serializeSignal(signal),
108764
- sourceId: this.#getSourceId()
108765
- });
109257
+ if (!await this.#forwardToOwner(state, pubsub, key, owner.agent, ownerRunId, signal, waitForIdle).catch((error) => {
109258
+ releaseMessageIdentity(require_error.getErrorFromUnknown(error));
109259
+ throw error;
109260
+ })) {
109261
+ const error = `Thread ${describeThreadKey(key)} is held by run ${ownerRunId}, which ended before it took the message`;
109262
+ releaseMessageIdentity(error);
109263
+ return {
109264
+ runId: ownerRunId,
109265
+ error,
109266
+ blocked: true
109267
+ };
109268
+ }
108766
109269
  settleMessageIdentity?.({ runId: ownerRunId }, false);
108767
109270
  return { runId: ownerRunId };
108768
109271
  }
@@ -108853,11 +109356,13 @@ var AgentThreadStreamRuntime = class {
108853
109356
  else if (entry.leaseGone) ended.add(entry.runId);
108854
109357
  else entry.leaseGone = true;
108855
109358
  for (const runId of ended) if (this.#requeueUnadmittedForwards(state, key, runId)) {
109359
+ const executedElsewhere = state.threadRunsById.get(runId)?.registeredElsewhere;
109360
+ if (executedElsewhere !== void 0) this.#retireRunEndedElsewhere(state, this.#getPubSub(pubsub), key, runId, executedElsewhere);
108856
109361
  if (!state.threadRunsById.has(runId) && state.activeThreadStreamIds.get(key) === streamBeforeRead && state.activeThreadRunIds.get(key) === runId) {
108857
109362
  state.activeThreadRunIds.delete(key);
108858
109363
  state.activeThreadStreamIds.delete(key);
108859
109364
  }
108860
- await this.#drainPendingIdleSignals(state, pubsub, key, runId);
109365
+ await this.#drainPendingIdleSignals(state, pubsub, key, executedElsewhere === void 0 ? runId : void 0);
108861
109366
  }
108862
109367
  };
108863
109368
  const check = setInterval(() => {
@@ -108891,6 +109396,21 @@ var AgentThreadStreamRuntime = class {
108891
109396
  state.pendingIdleSignalsByThread.set(key, [...unadmitted.map(([, entry]) => entry.pendingIdle), ...state.pendingIdleSignalsByThread.get(key) ?? []]);
108892
109397
  return true;
108893
109398
  }
109399
+ /** Signals taken from this runtime's queues as a turn's input; `#forgetStartedSignals` undoes it on a requeue. */
109400
+ #recordStartedSignals(state, key, signals) {
109401
+ if (signals.length === 0) return;
109402
+ const ids = state.startedSignalIdsByThread.get(key) ?? /* @__PURE__ */ new Set();
109403
+ for (const signal of signals) {
109404
+ ids.delete(signal.id);
109405
+ ids.add(signal.id);
109406
+ }
109407
+ while (ids.size > MAX_LOCALLY_QUEUED_SIGNAL_IDS_PER_THREAD) ids.delete(ids.values().next().value);
109408
+ state.startedSignalIdsByThread.set(key, ids);
109409
+ }
109410
+ #forgetStartedSignals(state, key, signals) {
109411
+ const ids = state.startedSignalIdsByThread.get(key);
109412
+ for (const signal of signals) ids?.delete(signal.id);
109413
+ }
108894
109414
  #recordLocallyQueuedSignal(state, key, signalId) {
108895
109415
  const ids = state.locallyQueuedSignalIdsByThread.get(key) ?? /* @__PURE__ */ new Map();
108896
109416
  ids.delete(signalId);
@@ -109488,6 +110008,26 @@ var AgentThreadStreamRuntime = class {
109488
110008
  else this.#releaseThreadLease(pubsub, key, runId);
109489
110009
  return true;
109490
110010
  }
110011
+ /**
110012
+ * The execution another process registered for a run parked here has ended, so nothing executes the run any more.
110013
+ * The stale record stops routing the thread's input to it: input sent from now on runs as a new turn here, and
110014
+ * forwards that crossed the end are queued again by the terminal handler. (#30190)
110015
+ */
110016
+ #retireRunEndedElsewhere(state, pubsub, key, runId, streamId) {
110017
+ const record = state.threadRunsById.get(runId);
110018
+ if (!record || streamId === void 0 || record.registeredElsewhere !== streamId) return;
110019
+ record.lifecycle = "completed";
110020
+ this.#clearSuspendedRun(state, runId);
110021
+ this.#stopLeaseRenewal(pubsub, runId);
110022
+ state.threadRunsByStreamId.delete(record.streamId);
110023
+ state.threadRunsById.delete(runId);
110024
+ state.threadKeysByRunId.delete(runId);
110025
+ if (state.activeThreadRunIds.get(key) === runId) {
110026
+ state.activeThreadRunIds.delete(key);
110027
+ state.activeThreadStreamIds.delete(key);
110028
+ }
110029
+ this.#notifyThreadEvents(state);
110030
+ }
109491
110031
  /** Release the local run that `runId` superseded, if it superseded one. */
109492
110032
  #releaseRunSupersededBy(state, pubsub, key, subscription, runId) {
109493
110033
  const supersededRunId = subscription.supersedingRunIds.get(runId);
@@ -109504,12 +110044,162 @@ var AgentThreadStreamRuntime = class {
109504
110044
  */
109505
110045
  #releaseSupersededParkedRun(state, pubsub, key, runId) {
109506
110046
  const record = state.threadRunsById.get(runId);
109507
- if (!record || state.activeThreadRunIds.get(key) !== runId || !this.#isParkedRun(state, runId)) return;
110047
+ if (!record || state.activeThreadRunIds.get(key) !== runId || !this.#isParkedRun(state, runId)) return false;
109508
110048
  state.activeThreadRunIds.delete(key);
109509
110049
  if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key);
109510
110050
  this.#stopReadingDisplacedRun(state, runId);
109511
110051
  if (this.#hasPendingThreadWork(state, key)) this.#drainPendingSignals(state, pubsub, key, record);
109512
110052
  else this.#releaseThreadLease(pubsub, key, runId);
110053
+ return true;
110054
+ }
110055
+ /**
110056
+ * With `autoResumeSuspendedTools`, the next turn is what resumes a run parked on
110057
+ * a tool's suspend(): the model reads the user's answer from the new message.
110058
+ * The parked run itself never drains its queue, so a message queued onto it
110059
+ * would be reported delivered and never run (#30190). Once the run has parked,
110060
+ * queued messages start the next turn the way a stream call on the thread
110061
+ * would; the parked run keeps its record and stays resumable.
110062
+ *
110063
+ * Without auto-resume, the message keeps waiting for the explicit resume (an
110064
+ * AgentController prompt waits for its answer), and a run parked on a tool
110065
+ * approval keeps holding the thread: consent arrives through the approval APIs.
110066
+ *
110067
+ * Any input starts the turn: a sent message, a continuation, or work queued
110068
+ * for after the run (`queueMessage`, `queueSignal`, here, forwarded from
110069
+ * another process, or held by another process that sent `queued-input-waiting`). Queued work waits for the thread's run to end (#32093), and
110070
+ * a run parked with auto-resume on counts as ended: it waits for the next
110071
+ * message and nothing else, so queued work is that message. Every other run
110072
+ * still holds queued work: one in flight, one parked without auto-resume, and
110073
+ * one parked on an approval.
110074
+ */
110075
+ async #startQueuedTurnAfterParkedRun(state, pubsub, key, record) {
110076
+ const options = record.streamOptions;
110077
+ const storageBacked = this.#isStorageBacked(record);
110078
+ 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));
110079
+ if (!canStart()) return;
110080
+ if (!(options.autoResumeSuspendedTools ?? (await record.agent.getDefaultOptions({ requestContext: options.requestContext })).autoResumeSuspendedTools) || !canStart()) return;
110081
+ let owners = this.#runStepOwners(state, record);
110082
+ while (canStart() && owners.some((owner) => require_utils$1.hasRunningRunStep(owner))) {
110083
+ await Promise.all(owners.map((owner) => new Promise((resolve) => require_utils$1.whenRunStepsSettle(owner, resolve))));
110084
+ owners = this.#runStepOwners(state, record);
110085
+ }
110086
+ if (!canStart()) return;
110087
+ if (storageBacked ? await this.#releaseParkedStoredRunForInput(state, pubsub, key, record, canStart) : this.#releaseSupersededParkedRun(state, this.#getPubSub(pubsub), key, record.runId)) {
110088
+ record.queuedInputElsewhere = false;
110089
+ this.#publish(pubsub, key, {
110090
+ type: "parked-run-released",
110091
+ runId: record.runId,
110092
+ streamId: record.streamId,
110093
+ sourceId: this.#getSourceId()
110094
+ });
110095
+ }
110096
+ }
110097
+ /**
110098
+ * Whether the thread of a storage-backed run has input for it: a pending or queued row (`listPendingSignals` returns
110099
+ * both), or a continuation or queued work held here.
110100
+ */
110101
+ async #hasStoredRunInput(state, key, record) {
110102
+ if (this.#hasPendingThreadWork(state, key)) return true;
110103
+ const store = await this.#signalsStoreOf(record);
110104
+ if (!store) return false;
110105
+ return (await store.store.listPendingSignals({ threadId: store.threadId })).length > 0;
110106
+ }
110107
+ /**
110108
+ * `#releaseSupersededParkedRun` for a storage-backed run: its input waits in its store, so the thread is checked
110109
+ * as at the end of a run, which starts the next turn with the oldest pending row. The run's signals are closed first,
110110
+ * as when a parked run is aborted, so rows it took and never consumed are pending again for that turn. The run keeps
110111
+ * its record and stays resumable; a resume keeps the thread's signal run as it finds it. (#30190)
110112
+ */
110113
+ async #releaseParkedStoredRunForInput(state, pubsub, key, record, canStart) {
110114
+ const inFlight = this.#releasingParkedStoredRuns.get(record);
110115
+ if (inFlight) {
110116
+ inFlight.again = true;
110117
+ return false;
110118
+ }
110119
+ const release = { again: false };
110120
+ this.#releasingParkedStoredRuns.set(record, release);
110121
+ let released = false;
110122
+ const { runId } = record;
110123
+ const holds = () => canStart() && state.activeThreadRunIds.get(key) === runId && this.#isParkedRun(state, runId);
110124
+ try {
110125
+ for (let attempt = 0;; attempt++) {
110126
+ const outcome = await state.storedSignals.runWrite(key, async () => {
110127
+ if (!holds() || !(record.queuedInputElsewhere || await this.#hasStoredRunInput(state, key, record))) return "kept";
110128
+ if (!holds()) return "kept";
110129
+ if (await record.agent.__closeParkedRunSignals?.(runId, { exclusiveOfResume: true }) === false) return "retry";
110130
+ if (!holds()) return "kept";
110131
+ state.activeThreadRunIds.delete(key);
110132
+ if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key);
110133
+ this.#stopReadingDisplacedRun(state, runId);
110134
+ return "released";
110135
+ }).catch((error) => {
110136
+ this.#logParkedRunReleaseFailure(record, error);
110137
+ return "retry";
110138
+ });
110139
+ if (outcome === "kept") return false;
110140
+ if (outcome === "released") {
110141
+ released = true;
110142
+ break;
110143
+ }
110144
+ if (attempt >= PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS.length) {
110145
+ this.#logParkedRunReleaseFailure(record, /* @__PURE__ */ new Error("The parked run kept the thread after every retry"));
110146
+ return false;
110147
+ }
110148
+ await new Promise((resolve) => setTimeout(resolve, PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS[attempt]));
110149
+ }
110150
+ } finally {
110151
+ this.#releasingParkedStoredRuns.delete(record);
110152
+ if (release.again && !released) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
110153
+ }
110154
+ const queued = this.#hasPendingThreadWork(state, key);
110155
+ if (!queued) this.#releaseEndedStoredRun(state, pubsub, key, record);
110156
+ this.#drainPendingSignals(state, pubsub, key, record, { freshLease: !queued });
110157
+ return true;
110158
+ }
110159
+ /**
110160
+ * Holds a parked run for a resume that is setting up, so input queued meanwhile stays the resumed run's next model
110161
+ * input, as it was before parked runs were released for queued input, instead of starting a turn beside the resumed
110162
+ * tool. The returned function ends the hold; if the run is still parked then, for example because the resume
110163
+ * failed, queued input starts the next turn, unless `startQueuedTurn` is false: a caller whose resume this record
110164
+ * doesn't follow, and that left the run parked again, marks the record so queued input keeps waiting. (#30190)
110165
+ */
110166
+ holdParkedRunForResume(runId, pubsub) {
110167
+ const state = this.#getState(pubsub);
110168
+ const record = state.threadRunsById.get(runId);
110169
+ if (!record) return () => {};
110170
+ record.resumeHolds = (record.resumeHolds ?? 0) + 1;
110171
+ let held = true;
110172
+ return ({ startQueuedTurn = true } = {}) => {
110173
+ if (!held) return;
110174
+ held = false;
110175
+ record.resumeHolds = (record.resumeHolds ?? 1) - 1;
110176
+ if (!startQueuedTurn) record.resumedUntracked = true;
110177
+ if (record.resumeHolds > 0 || !startQueuedTurn) return;
110178
+ const key = this.#threadKey(record.resourceId, record.threadId);
110179
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110180
+ };
110181
+ }
110182
+ #startQueuedTurnAfterParkedRunLater(state, pubsub, key, record) {
110183
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110184
+ }
110185
+ /**
110186
+ * The message that triggered the release was already answered `deliver`, so a failure here would otherwise
110187
+ * leave it queued on the parked run with no trace.
110188
+ */
110189
+ #logParkedRunReleaseFailure(record, error) {
110190
+ record.agent.__getLogger?.()?.error("Could not start the queued turn for a run parked on a suspended tool", {
110191
+ runId: record.runId,
110192
+ threadId: record.threadId,
110193
+ resourceId: record.resourceId,
110194
+ error
110195
+ });
110196
+ }
110197
+ /**
110198
+ * The objects the steps of a run register under while they run: the abort signal of its prepared run or current
110199
+ * segment, and a durable run's registry entry.
110200
+ */
110201
+ #runStepOwners(state, record) {
110202
+ return [(state.preparedRunsById.get(record.runId)?.abortController ?? record.segmentAbortController)?.signal, record.stepOwner?.()].filter((owner) => owner !== void 0);
109513
110203
  }
109514
110204
  /**
109515
110205
  * A parked run no longer holds its thread, so its answer resumes it on a new
@@ -109707,6 +110397,7 @@ var AgentThreadStreamRuntime = class {
109707
110397
  state.suspensionMetadataByRunId.clear();
109708
110398
  state.signalQueues.clear();
109709
110399
  state.locallyQueuedSignalIdsByThread.clear();
110400
+ state.startedSignalIdsByThread.clear();
109710
110401
  state.lostRunsByThread.clear();
109711
110402
  state.pendingIdleSignalsByThread.clear();
109712
110403
  state.forwardedIdleSignalsByThread.clear();
@@ -109777,11 +110468,43 @@ var AgentThreadStreamRuntime = class {
109777
110468
  /**
109778
110469
  * Queues a signal for in-loop draining by a same-agent run that is already in
109779
110470
  * flight here, so it becomes that run's next model input instead of waiting for
109780
- * the run to finish.
110471
+ * the run to finish. If the run is parked on a suspension that auto-resume
110472
+ * answers, the signal starts the next turn instead.
109781
110473
  */
109782
110474
  #queueForActiveRun(state, pubsub, key, record, signal) {
109783
- state.signalQueues.enqueue("pending", key, signal);
109784
110475
  this.#recordLocallyQueuedSignal(state, key, signal.id);
110476
+ if (record.registeredElsewhere) {
110477
+ const senderKeepsCopy = !!this.#pendingUserMessageChunk(record.runId, signal, "pending");
110478
+ if (senderKeepsCopy) {
110479
+ const forwarded = state.forwardedIdleSignalsByThread.get(key) ?? /* @__PURE__ */ new Map();
110480
+ forwarded.set(signal.id, {
110481
+ pendingIdle: {
110482
+ agent: record.agent,
110483
+ signal,
110484
+ runId: globalThis.crypto.randomUUID(),
110485
+ resourceId: record.resourceId ?? "",
110486
+ threadId: record.threadId,
110487
+ streamOptions: {
110488
+ ...record.streamOptions,
110489
+ abortSignal: void 0
110490
+ }
110491
+ },
110492
+ runId: record.runId
110493
+ });
110494
+ state.forwardedIdleSignalsByThread.set(key, forwarded);
110495
+ this.#ensureThreadControlSubscription(state, pubsub, key);
110496
+ this.#watchForwardedIdleLease(state, pubsub, key);
110497
+ }
110498
+ this.#publish(pubsub, key, {
110499
+ type: "signal-enqueued",
110500
+ runId: record.runId,
110501
+ signal: this.#serializeSignal(signal),
110502
+ sourceId: this.#getSourceId(),
110503
+ ...senderKeepsCopy ? { senderKeepsCopy } : {}
110504
+ });
110505
+ return;
110506
+ }
110507
+ state.signalQueues.enqueue("pending", key, signal);
109785
110508
  this.#publishPendingUserMessage(pubsub, key, record.runId, signal, "pending");
109786
110509
  this.#notifyPendingSignals(state, key, signal);
109787
110510
  this.#publish(pubsub, key, {
@@ -109791,6 +110514,7 @@ var AgentThreadStreamRuntime = class {
109791
110514
  sourceId: this.#getSourceId()
109792
110515
  });
109793
110516
  this.#watchThreadRunCompletion(state, pubsub, key, record);
110517
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109794
110518
  }
109795
110519
  /**
109796
110520
  * `#queueForActiveRun` for a run that keeps its signals in storage. Resolves
@@ -109802,13 +110526,14 @@ var AgentThreadStreamRuntime = class {
109802
110526
  this.#recordLocallyQueuedSignal(state, key, signal.id);
109803
110527
  let written;
109804
110528
  try {
109805
- written = await this.#enqueueStoredSignal(state, key, store, signal, record);
110529
+ written = await this.#enqueueStoredSignal(state, key, store, signal, record, false, true);
109806
110530
  } catch (error) {
109807
110531
  this.#forgetLocallyQueuedSignal(state, key, signal.id);
109808
110532
  throw error;
109809
110533
  }
109810
110534
  if (written === "run-closed") {
109811
- await this.#storeLeftoverSignal(state, pubsub, key, record, signal, store);
110535
+ this.#announceLeftoverSignal(state, pubsub, key, record, signal);
110536
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109812
110537
  return;
109813
110538
  }
109814
110539
  this.#publishSignalAvailable(record.agent, record.runId, signal.id);
@@ -109822,6 +110547,7 @@ var AgentThreadStreamRuntime = class {
109822
110547
  stored: true
109823
110548
  });
109824
110549
  this.#watchThreadRunCompletion(state, pubsub, key, record);
110550
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109825
110551
  }
109826
110552
  /**
109827
110553
  * `signal-enqueued` for a run this runtime holds that keeps its signals in
@@ -109835,12 +110561,16 @@ var AgentThreadStreamRuntime = class {
109835
110561
  const signal = require_signals.createSignal(data.signal);
109836
110562
  if (!data.stored) {
109837
110563
  try {
109838
- if (await this.#enqueueStoredSignal(state, key, store, signal, run) === "run-closed") {
109839
- await this.#storeLeftoverSignal(state, pubsub, key, run, signal, store);
110564
+ if (await this.#enqueueStoredSignal(state, key, store, signal, run, false, true) === "run-closed") {
110565
+ if (!subscription.cancelledSignalIds.has(signal.id)) {
110566
+ this.#announceLeftoverSignal(state, pubsub, key, run, signal);
110567
+ const parked = state.threadRunsById.get(runId);
110568
+ if (parked) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, parked);
110569
+ }
109840
110570
  return;
109841
110571
  }
109842
110572
  } catch (error) {
109843
- subscription.admittedSignalIds.delete(data.signal.id);
110573
+ if (!subscription.cancelledSignalIds.has(data.signal.id)) subscription.admittedSignalIds.delete(data.signal.id);
109844
110574
  run.agent.__getLogger?.()?.warn?.("Could not store a signal forwarded to a running run", {
109845
110575
  runId,
109846
110576
  signalId: signal.id,
@@ -109857,7 +110587,9 @@ var AgentThreadStreamRuntime = class {
109857
110587
  });
109858
110588
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
109859
110589
  this.#notifyPendingSignals(state, key, signal, runId);
109860
- if (!state.threadRunsById.has(runId)) this.#drainPendingSignals(state, pubsub, key, run, { freshLease: true });
110590
+ const record = state.threadRunsById.get(runId);
110591
+ if (record) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
110592
+ else this.#drainPendingSignals(state, pubsub, key, run, { freshLease: true });
109861
110593
  }
109862
110594
  /**
109863
110595
  * Move the signals this runtime queued for a run that is only reserved into
@@ -109881,10 +110613,8 @@ var AgentThreadStreamRuntime = class {
109881
110613
  return this.#enqueueStoredSignal(state, key, store, signal, {
109882
110614
  runId,
109883
110615
  agent
109884
- }).then((written) => {
109885
- if (written !== "run-closed") return;
109886
- leftForNextRun = true;
109887
- return this.#enqueueStoredSignal(state, key, store, signal);
110616
+ }, false, true).then((written) => {
110617
+ if (written === "run-closed") leftForNextRun = true;
109888
110618
  }).then(() => waiter?.resolve(), (error) => {
109889
110619
  if (waiter) {
109890
110620
  this.#forgetLocallyQueuedSignal(state, key, signal.id);
@@ -110025,17 +110755,12 @@ var AgentThreadStreamRuntime = class {
110025
110755
  return this.#getState(pubsub).storedSignals.writesSettled(this.#threadKey(store.resourceId, store.threadId));
110026
110756
  }
110027
110757
  /**
110028
- * Keep a signal whose run closed before it was stored, in the process that
110029
- * started that run: as a pending row of the thread, then run the end-of-run
110030
- * check again, since the run's own check may have found nothing.
110758
+ * After a signal whose run closed first was kept as a pending row of the
110759
+ * thread (`#enqueueStoredSignal` with `keepWhenClosed`), in the process that
110760
+ * started that run: present it, then run the end-of-run check again, since
110761
+ * the run's own check may have found nothing.
110031
110762
  */
110032
- async #storeLeftoverSignal(state, pubsub, key, endedRun, signal, store) {
110033
- try {
110034
- await this.#enqueueStoredSignal(state, key, store, signal);
110035
- } catch (error) {
110036
- this.#forgetLocallyQueuedSignal(state, key, signal.id);
110037
- throw error;
110038
- }
110763
+ #announceLeftoverSignal(state, pubsub, key, endedRun, signal) {
110039
110764
  this.#publishPendingUserMessage(pubsub, key, endedRun.runId, signal, "pending");
110040
110765
  this.#drainPendingSignals(state, pubsub, key, endedRun, { freshLease: true });
110041
110766
  }
@@ -110046,15 +110771,15 @@ var AgentThreadStreamRuntime = class {
110046
110771
  * when the event arrives. Returns `false` when the store reports that run
110047
110772
  * closed.
110048
110773
  */
110049
- async #forwardSignal(state, pubsub, key, agent, runId, signal) {
110774
+ async #forwardSignal(state, pubsub, key, agent, runId, signal, queued = false) {
110050
110775
  const target = forwardedSignalRunId(runId);
110051
110776
  const store = await this.#runSignalsStore(state, agent, target, key);
110052
110777
  if (store) {
110053
110778
  if (await this.#enqueueStoredSignal(state, key, store, signal, {
110054
110779
  runId: target,
110055
110780
  agent
110056
- }) === "run-closed") return false;
110057
- this.#publishSignalAvailable(agent, target, signal.id);
110781
+ }, queued) === "run-closed") return false;
110782
+ if (!queued) this.#publishSignalAvailable(agent, target, signal.id);
110058
110783
  this.#recordLocallyQueuedSignal(state, key, signal.id);
110059
110784
  state.locallyQueuedSignalIdsByThread.get(key)?.set(signal.id, target);
110060
110785
  }
@@ -110063,8 +110788,11 @@ var AgentThreadStreamRuntime = class {
110063
110788
  runId,
110064
110789
  signal: this.#serializeSignal(signal),
110065
110790
  sourceId: this.#getSourceId(),
110066
- ...store ? { stored: true } : {}
110067
- }).catch(() => {});
110791
+ ...store ? { stored: true } : {},
110792
+ ...queued ? { queued: true } : {}
110793
+ }).catch((error) => {
110794
+ if (queued && !store) throw error;
110795
+ });
110068
110796
  return true;
110069
110797
  }
110070
110798
  /**
@@ -110079,6 +110807,26 @@ var AgentThreadStreamRuntime = class {
110079
110807
  return state.remoteAgentIdsByRunId.get(runId) === agent.id && state.storedSignals.isRemoteRunStored(runId) && maySignalsBeStored(agent) && agent.__hasFixedMemory?.() === true;
110080
110808
  }
110081
110809
  /**
110810
+ * Hand `signal` to `ownerRunId`, a run another process holds. Queued input must wait for that run to end, so it is
110811
+ * never a row the run would claim: for a storage-backed run it is stored as a queued row, otherwise it travels as a
110812
+ * marked event its holder queues, and a failed publish of that event rejects. Other input is stored for a
110813
+ * storage-backed run and published otherwise, ignoring publish failure. Answers false only when the storage-backed
110814
+ * run ended before it took the row.
110815
+ */
110816
+ async #forwardToOwner(state, pubsub, key, agent, ownerRunId, signal, queued) {
110817
+ const target = forwardedSignalRunId(ownerRunId);
110818
+ if (this.#mayStoreForRunHeldElsewhere(state, agent, target)) return this.#forwardSignal(state, pubsub, key, agent, ownerRunId, signal, queued);
110819
+ const published = this.#publishAndWait(pubsub, key, {
110820
+ type: "signal-enqueued",
110821
+ runId: ownerRunId,
110822
+ signal: this.#serializeSignal(signal),
110823
+ sourceId: this.#getSourceId(),
110824
+ ...queued ? { queued: true } : {}
110825
+ });
110826
+ await (queued ? published : published.catch(() => {}));
110827
+ return true;
110828
+ }
110829
+ /**
110082
110830
  * Where `runId` keeps its signals as far as this process knows: the
110083
110831
  * decision on its record here (none for a run only reserved here), or, for
110084
110832
  * a run another process holds that passes `#mayStoreForRunHeldElsewhere`,
@@ -110120,17 +110868,23 @@ var AgentThreadStreamRuntime = class {
110120
110868
  /**
110121
110869
  * Insert a signal as a pending row of the thread, behind this process's
110122
110870
  * earlier writes for it. With `to` the row is only inserted while that run
110123
- * is the thread's signal run, and a thread without a row rejects.
110871
+ * is the thread's signal run, and a thread without a row rejects. With
110872
+ * `keepWhenClosed`, a run that closed first leaves the signal as a pending
110873
+ * row for the thread's next turn, inserted in the same write: a cancel
110874
+ * handled after this call is ordered after that insert too, so it deletes
110875
+ * the row. The answer is still `run-closed`.
110124
110876
  */
110125
- #enqueueStoredSignal(state, key, storeRef, signal, to) {
110877
+ #enqueueStoredSignal(state, key, storeRef, signal, to, queued = false, keepWhenClosed = false) {
110126
110878
  return state.storedSignals.runWrite(key, async () => {
110127
110879
  const store = storeRef instanceof Promise ? await storeRef : storeRef;
110128
110880
  if (!store) throw new Error(`The memory storage that keeps the signals of ${describeThreadKey(key)} could not be resolved, so the signal was not stored`);
110129
- return this.#insertStoredSignal(state, key, store, signal, to);
110881
+ const written = await this.#insertStoredSignal(state, key, store, signal, to, queued);
110882
+ if (written === "run-closed" && keepWhenClosed) await this.#insertStoredSignal(state, key, store, signal);
110883
+ return written;
110130
110884
  });
110131
110885
  }
110132
110886
  /** The insert of `#enqueueStoredSignal`, for a caller already inside a write of the thread's stored signals. */
110133
- async #insertStoredSignal(state, key, store, signal, to) {
110887
+ async #insertStoredSignal(state, key, store, signal, to, queued = false) {
110134
110888
  const message = signal.toDBMessage({
110135
110889
  threadId: store.threadId,
110136
110890
  resourceId: store.resourceId
@@ -110138,7 +110892,8 @@ var AgentThreadStreamRuntime = class {
110138
110892
  const recordAccepted = state.storedSignals.stampNewRow(key, message);
110139
110893
  const written = await store.store.enqueuePendingSignal({
110140
110894
  message,
110141
- ...to ? { toRunId: to.runId } : {}
110895
+ ...to ? { toRunId: to.runId } : {},
110896
+ ...queued ? { queued: true } : {}
110142
110897
  });
110143
110898
  if (written === "thread-not-found") throw new Error(`Thread ${store.threadId} of resource ${store.resourceId} was not found in the memory storage of agent ${to?.agent.id}, so the signal was not stored`);
110144
110899
  if (written === "accepted") recordAccepted();
@@ -110354,18 +111109,29 @@ var AgentThreadStreamRuntime = class {
110354
111109
  }
110355
111110
  }
110356
111111
  continueRun(agent, output, streamOptions, pubsub, claim) {
110357
- const { threadId, resourceId } = this.#getThreadTarget(streamOptions);
110358
- if (!threadId) return false;
110359
111112
  const state = this.#getState(pubsub);
110360
111113
  this.#sweepStaleSuspendedRecords(state, pubsub);
110361
- const key = this.#threadKey(resourceId, threadId);
110362
111114
  const existing = state.threadRunsById.get(output.runId);
111115
+ const named = this.#getThreadTarget(streamOptions);
111116
+ const continuesOwnThread = !named.threadId && existing !== void 0 && (named.resourceId === void 0 || named.resourceId === existing.resourceId);
111117
+ const { threadId, resourceId } = continuesOwnThread ? existing : named;
111118
+ if (!threadId) return false;
111119
+ const key = this.#threadKey(resourceId, threadId);
110363
111120
  if (!existing?.continuation?.canContinue() || existing.agent !== agent || existing.threadId !== threadId || existing.resourceId !== resourceId || state.activeThreadRunIds.get(key) !== output.runId || state.activeThreadStreamIds.get(key) !== existing.streamId || output.status !== "running" && output.status !== "suspended" || existing.lifecycle === "completed" || existing.lifecycle === "failed" || existing.lifecycle === "aborted") return false;
110364
111121
  const resumedToolCallId = streamOptions.toolCallId;
110365
111122
  if (resumedToolCallId) this.#clearSuspendedToolCall(state, output.runId, resumedToolCallId);
110366
111123
  else this.#clearSuspendedRun(state, output.runId);
110367
111124
  existing.lifecycle = "running";
110368
- existing.streamOptions = streamOptions;
111125
+ const resumeOptions = keepRunAutoResume(streamOptions, existing.streamOptions);
111126
+ existing.streamOptions = continuesOwnThread ? {
111127
+ ...resumeOptions,
111128
+ memory: resumeMemoryOnOwnThread({
111129
+ run: existing.streamOptions.memory,
111130
+ resume: streamOptions.memory,
111131
+ threadId,
111132
+ resourceId
111133
+ })
111134
+ } : resumeOptions;
110369
111135
  existing.currentSegmentOutput = output;
110370
111136
  if (claim?.generation !== void 0) existing.generation = claim.generation;
110371
111137
  if (claim?.ownershipLost) existing.ownershipLost = claim.ownershipLost;
@@ -110444,7 +111210,8 @@ var AgentThreadStreamRuntime = class {
110444
111210
  sourceOutput: output,
110445
111211
  canContinue: broadcast.canContinueBroadcast,
110446
111212
  didPublishTerminal: broadcast.didPublishTerminal
110447
- } : void 0
111213
+ } : void 0,
111214
+ queuedInputElsewhere: state.threadRunsById.get(output.runId)?.queuedInputElsewhere
110448
111215
  };
110449
111216
  return {
110450
111217
  record,
@@ -110479,7 +111246,8 @@ var AgentThreadStreamRuntime = class {
110479
111246
  const state = this.#getState(pubsub);
110480
111247
  this.#sweepStaleSuspendedRecords(state, pubsub);
110481
111248
  const key = this.#threadKey(resourceId, threadId);
110482
- const { record, streamId, streamSeq, startBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput(state, agent, output, streamOptions, pubsub, threadId, resourceId, registrationOptions);
111249
+ const runOptions = keepRunAutoResume(streamOptions, state.threadRunsById.get(output.runId)?.streamOptions);
111250
+ const { record, streamId, streamSeq, startBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput(state, agent, output, runOptions, pubsub, threadId, resourceId, registrationOptions);
110483
111251
  const activeRunId = state.activeThreadRunIds.get(key);
110484
111252
  const takesLeaseFrom = activeRunId !== void 0 && activeRunId !== output.runId && state.threadKeysByRunId.get(activeRunId) === key && this.#isParkedRun(state, activeRunId) ? activeRunId : void 0;
110485
111253
  state.threadRunsById.set(output.runId, record);
@@ -110627,6 +111395,7 @@ var AgentThreadStreamRuntime = class {
110627
111395
  runId: record.runId,
110628
111396
  streamId: record.streamId
110629
111397
  });
111398
+ this.#startQueuedTurnAfterParkedRun(this.#getState(pubsub), pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110630
111399
  }
110631
111400
  #watchThreadRunCompletion(state, pubsub, key, record, registered, isDisabled) {
110632
111401
  if (state.watchedThreadStreamIds.has(record.streamId)) return;
@@ -110760,6 +111529,7 @@ var AgentThreadStreamRuntime = class {
110760
111529
  try {
110761
111530
  signal = state.signalQueues.takeNextPending(key);
110762
111531
  if (signal) {
111532
+ this.#recordStartedSignals(state, key, [signal]);
110763
111533
  nextRunId = globalThis.crypto.randomUUID();
110764
111534
  const reservedRunId = nextRunId;
110765
111535
  state.activeThreadRunIds.set(key, reservedRunId);
@@ -110789,6 +111559,7 @@ var AgentThreadStreamRuntime = class {
110789
111559
  state.threadKeysByRunId.delete(nextRunId);
110790
111560
  state.storedSignals.settlePreRunWaiters(nextRunId);
110791
111561
  state.signalQueues.discardPreRunQueue(key);
111562
+ this.#forgetStartedSignals(state, key, [signal]);
110792
111563
  if (owns.owner && !isRetakeLeaseOwner(owns.owner)) {
110793
111564
  const ownerRunId = threadLeaseRunId(owns.owner);
110794
111565
  const ids = state.locallyQueuedSignalIdsByThread.get(key);
@@ -110824,6 +111595,7 @@ var AgentThreadStreamRuntime = class {
110824
111595
  if (state.activeThreadRunIds.get(key) === nextRunId) state.activeThreadRunIds.delete(key);
110825
111596
  }
110826
111597
  state.signalQueues.restoreAfterFailedStart(key, draining?.cancelled ? void 0 : signal);
111598
+ if (signal) this.#forgetStartedSignals(state, key, [signal]);
110827
111599
  this.#publish(pubsub, key, {
110828
111600
  type: "run-failed",
110829
111601
  runId: failedRunId,
@@ -110867,7 +111639,11 @@ var AgentThreadStreamRuntime = class {
110867
111639
  * with its oldest pending row as input, else a queued continuation, else a
110868
111640
  * queued message, else release the lease. Rows are neither moved nor
110869
111641
  * deleted here: the follow-up's first model request claims every pending
110870
- * row of the thread.
111642
+ * row of the thread. A row still queued at this read, because the ended
111643
+ * run's close has not landed, is not delivered twice: saving the
111644
+ * follow-up's input under the row's id moves the row into the thread in
111645
+ * every store, and a follow-up that keeps its signals in storage counts the
111646
+ * id as consumed, so its claims never return it.
110871
111647
  *
110872
111648
  * `freshLease` is for a check that a late send triggered after the run's own
110873
111649
  * check: the ended run's lease may be gone, so it is acquired fresh, and
@@ -111066,7 +111842,10 @@ var AgentThreadStreamRuntime = class {
111066
111842
  const queue = state.pendingContinuationsByThread.get(key) ?? [];
111067
111843
  queue.push(pending);
111068
111844
  state.pendingContinuationsByThread.set(key, queue);
111069
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
111845
+ if (activeRecord) {
111846
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
111847
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, activeRecord).catch((error) => this.#logParkedRunReleaseFailure(activeRecord, error));
111848
+ }
111070
111849
  return {
111071
111850
  accepted: true,
111072
111851
  runId
@@ -111078,6 +111857,27 @@ var AgentThreadStreamRuntime = class {
111078
111857
  runId
111079
111858
  };
111080
111859
  }
111860
+ /**
111861
+ * Queued work waits for the thread's run to end (#32093), and a run parked with auto-resume on counts as ended
111862
+ * (#30190). Only the process executing a run knows how it parked, so a runtime holding queued work behind a parked
111863
+ * run it doesn't execute asks that run's holder to let go of the thread. A holder whose run counts as ended releases
111864
+ * it and announces `parked-run-released`, and this runtime starts its queued work as after the run's end. The work
111865
+ * stays queued here meanwhile, with its own agent, options and queue owner, so it can still be cancelled here.
111866
+ */
111867
+ #requestParkedRunReleaseElsewhere(state, pubsub, key, { executionChanged = false } = {}) {
111868
+ const runId = state.activeThreadRunIds.get(key);
111869
+ if (!runId) return;
111870
+ const record = state.threadRunsById.get(runId);
111871
+ if (record && record.registeredElsewhere === void 0) return;
111872
+ if (!executionChanged && !this.#isSuspendedRun(state, runId) && record?.lifecycle !== "suspended") return;
111873
+ if (!state.pendingIdleSignalsByThread.get(key)?.some((entry) => entry.queued)) return;
111874
+ this.#ensureThreadControlSubscription(state, pubsub, key);
111875
+ this.#publish(pubsub, key, {
111876
+ type: "queued-input-waiting",
111877
+ runId,
111878
+ sourceId: this.#getSourceId()
111879
+ });
111880
+ }
111081
111881
  async #drainPendingIdleSignals(state, pubsub, key, fromRunId) {
111082
111882
  if (state.activeThreadRunIds.has(key)) return false;
111083
111883
  const idleQueue = state.pendingIdleSignalsByThread.get(key);
@@ -111147,9 +111947,9 @@ var AgentThreadStreamRuntime = class {
111147
111947
  this.#watchForwardedIdleLease(state, pubsub, key);
111148
111948
  }
111149
111949
  this.#notifyThreadEvents(state);
111150
- if (ownerRunId && this.#mayStoreForRunHeldElsewhere(state, pendingIdle.agent, forwardedSignalRunId(ownerRunId))) {
111151
- if (!await this.#forwardSignal(state, pubsub, key, pendingIdle.agent, ownerRunId, pendingIdle.signal).catch((error) => {
111152
- pendingIdle.agent.__getLogger?.()?.warn?.("Could not store a queued message for the run holding its thread", {
111950
+ if (ownerRunId) {
111951
+ if (!await this.#forwardToOwner(state, pubsub, key, pendingIdle.agent, ownerRunId, pendingIdle.signal, pendingIdle.queued === true).catch((error) => {
111952
+ pendingIdle.agent.__getLogger?.()?.warn?.("Could not forward a queued message to the run holding its thread", {
111153
111953
  runId: ownerRunId,
111154
111954
  signalId: pendingIdle.signal.id,
111155
111955
  error
@@ -111161,12 +111961,7 @@ var AgentThreadStreamRuntime = class {
111161
111961
  this.#notifyThreadEvents(state);
111162
111962
  return true;
111163
111963
  }
111164
- } else if (ownerRunId) await this.#publishAndWait(pubsub, key, {
111165
- type: "signal-enqueued",
111166
- runId: ownerRunId,
111167
- signal: this.#serializeSignal(pendingIdle.signal),
111168
- sourceId: this.#getSourceId()
111169
- }).catch(() => {});
111964
+ }
111170
111965
  const drained = await this.#drainPendingIdleSignals(state, pubsub, key, owns.acquired ? pendingIdle.runId : fromRunId);
111171
111966
  if (owns.acquired && !drained) this.#releaseThreadLease(pubsub, key, pendingIdle.runId);
111172
111967
  return drained || owns.acquired;
@@ -111263,7 +112058,9 @@ var AgentThreadStreamRuntime = class {
111263
112058
  const record = state.threadRunsById.get(runId);
111264
112059
  const key = record ? this.#threadKey(record.resourceId, record.threadId) : state.threadKeysByRunId.get(runId);
111265
112060
  if (!key) return [];
111266
- return state.signalQueues.take(scope, key);
112061
+ const queue = state.signalQueues.take(scope, key);
112062
+ this.#recordStartedSignals(state, key, queue);
112063
+ return queue;
111267
112064
  }
111268
112065
  /**
111269
112066
  * Resolves `'reserved'` when this call reserved the thread for `runId`; the
@@ -111985,6 +112782,7 @@ var AgentThreadStreamRuntime = class {
111985
112782
  state.suspendedRunIds.add(data.runId);
111986
112783
  const record = state.threadRunsByStreamId.get(eventStreamId) ?? state.threadRunsById.get(data.runId);
111987
112784
  if (record) record.lifecycle = "suspended";
112785
+ this.#requestParkedRunReleaseElsewhere(state, resolvedPubSub, key);
111988
112786
  } else clearActiveIfCurrent(data.runId, data.streamId);
111989
112787
  if (data.type !== "run-suspended" || suspendedRunEnded) this.#clearSuspendedRun(state, data.runId);
111990
112788
  const remoteRun = remoteRuns.get(eventStreamId);
@@ -112610,13 +113408,18 @@ var AgentThreadStreamRuntime = class {
112610
113408
  resourceId,
112611
113409
  threadId,
112612
113410
  streamOptions: queuedStreamOptions,
112613
- queueOwnerId: target.queueOwnerId
113411
+ queueOwnerId: target.queueOwnerId,
113412
+ queued: true
112614
113413
  });
112615
113414
  state.pendingIdleSignalsByThread.set(key, idleQueue);
112616
113415
  const control = this.#ensureThreadControlSubscription(state, pubsub, key);
112617
113416
  this.#publishPendingUserMessage(pubsub, key, runId ?? queuedRunId, queuedSignal, "queued");
112618
113417
  this.#notifyThreadEvents(state);
112619
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
113418
+ if (activeRecord) {
113419
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
113420
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, activeRecord);
113421
+ }
113422
+ this.#requestParkedRunReleaseElsewhere(state, pubsub, key);
112620
113423
  return {
112621
113424
  signal: queuedSignal,
112622
113425
  accepted: control.ready.then(() => ({
@@ -112955,7 +113758,8 @@ var AgentThreadStreamRuntime = class {
112955
113758
  runId,
112956
113759
  resourceId,
112957
113760
  threadId,
112958
- streamOptions: target.ifIdle?.streamOptions
113761
+ streamOptions: target.ifIdle?.streamOptions,
113762
+ ...waitForIdle ? { queued: true } : {}
112959
113763
  });
112960
113764
  state.pendingIdleSignalsByThread.set(key, idleQueue);
112961
113765
  if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
@@ -113073,18 +113877,11 @@ var AgentThreadStreamRuntime = class {
113073
113877
  reason: "scope-mismatch",
113074
113878
  runId: winnerRunId
113075
113879
  };
113076
- if (winnerRunId && this.#mayStoreForRunHeldElsewhere(state, agent, forwardedSignalRunId(winnerRunId))) {
113077
- if (!await this.#forwardSignal(state, pubsub, reservedKey, agent, winnerRunId, signal)) return {
113078
- action: "blocked",
113079
- reason: "thread-blocked",
113080
- runId: winnerRunId
113081
- };
113082
- } else if (winnerRunId) await this.#publishAndWait(pubsub, reservedKey, {
113083
- type: "signal-enqueued",
113084
- runId: winnerRunId,
113085
- signal: this.#serializeSignal(signal),
113086
- sourceId: this.#getSourceId()
113087
- }).catch(() => {});
113880
+ if (winnerRunId && !await this.#forwardToOwner(state, pubsub, reservedKey, agent, winnerRunId, signal, waitForIdle)) return {
113881
+ action: "blocked",
113882
+ reason: "thread-blocked",
113883
+ runId: winnerRunId
113884
+ };
113088
113885
  return {
113089
113886
  action: "deliver",
113090
113887
  runId: winnerRunId ?? reservedRunId
@@ -115234,6 +116031,12 @@ Object.defineProperty(exports, "KnowledgeInvalidCursorError", {
115234
116031
  return KnowledgeInvalidCursorError;
115235
116032
  }
115236
116033
  });
116034
+ Object.defineProperty(exports, "KnowledgeInvalidSearchError", {
116035
+ enumerable: true,
116036
+ get: function() {
116037
+ return KnowledgeInvalidSearchError;
116038
+ }
116039
+ });
115237
116040
  Object.defineProperty(exports, "KnowledgeLinkRefreshIncompleteError", {
115238
116041
  enumerable: true,
115239
116042
  get: function() {
@@ -115330,6 +116133,12 @@ Object.defineProperty(exports, "MAX_FS_SUBAGENT_DEPTH", {
115330
116133
  return MAX_FS_SUBAGENT_DEPTH;
115331
116134
  }
115332
116135
  });
116136
+ Object.defineProperty(exports, "MAX_KNOWLEDGE_LINK_REPAIR_SOURCES", {
116137
+ enumerable: true,
116138
+ get: function() {
116139
+ return MAX_KNOWLEDGE_LINK_REPAIR_SOURCES;
116140
+ }
116141
+ });
115333
116142
  Object.defineProperty(exports, "MAX_KNOWLEDGE_MOVE_PAGES", {
115334
116143
  enumerable: true,
115335
116144
  get: function() {