@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 @@ import { a as RegisteredLogger, t as ConsoleLogger, u as noopLogger } from "./lo
3
3
  import { t as MastraBase } from "./base-CKLWBhDo.js";
4
4
  import { a as MastraNonRetryableError, i as MastraError, n as ErrorDomain, o as getErrorFromUnknown, t as ErrorCategory } from "./error-oh2DLsP2.js";
5
5
  import { a as classifyProviderError, l as describeProviderError, t as recordTerminalErrorMessage, u as readProviderErrorDetails } from "./error-BC9Au-22.js";
6
- import { S as isLeaseProvider, _ as PublisherQueueLimitError, b as NoopLeaseProvider, d as isRunLocalTopic, g as stripModelSnapshots, i as CachingPubSub, m as slimNestedAgentChunks, r as serializeError$1, t as DefaultStepResult, v as EventEmitterPubSub, y as withAck } from "./output-helpers-k2-48ssH.js";
7
- import { $ as summarizeToolChoiceForSpan, $t as commitToolResult, A as isSignalChunkExcluded, An as isMastraTimeoutError, At as getSnapshotMemoryInfo, B as removeTrailingAssistantGuardContinuations, Bt as stateColumnsWrite, C as stampChunkProducedAt, Cn as DEADLINE_SAVE_CLAIM_HOLD_MS, D as isStructuredOutputError, Dn as getAbortReason, Dt as validateTemplate, E as escapeUnescapedControlCharsInJsonStrings, En as createTimeoutAbortSignal, Et as traverseMappingPath, F as endOutputStreamSpanOutsideStep, Fn as safeClose, Ft as latestStepResults, G as FLUSH_HELD_PARTS_KEY, Gt as diffStateAsJson, Ht as unusedStateEntries, I as findOwnModelStepSpan, In as safeEnqueue, It as materializeState, J as withoutHeldContent, K as REPROCESS_PART_KEY, Kt as patchState, Ln as safeError, Lt as materializeWorkflowRun, M as ProcessorRunner, Mn as settledOrElapsed, N as ProcessorState, Nt as applyStateColumnsWrite, O as asJsonSchema, On as guardStreamUntilMatch, Ot as getStepResult, P as endOutputStreamSpanAtStepEnd, Pn as MastraModelInput, Pt as isStateCheckpointDue, Q as summarizeProcessorToolsForSpan, R as isTrailingAssistantGuardContinuation, Rn as createRunScope, Rt as pickStateKeys, S as getChunkProducedAt, Sn as takenQueueThreadId, St as stepRefId, T as createOutputHandler, Tn as MastraTimeoutError, Tt as templateReadsState, Ut as applyStatePatch, V as ProviderHistoryCompat, Vt as summarizeStepResult, X as summarizeProcessorModelForSpan, Y as summarizeActiveToolsForSpan, Yt as isObservationalMemoryEnabled$1, Z as summarizeProcessorResultForSpan, Zt as parseMemoryRequestContext, _ as persistProcessorDataChunk, _t as stubStepResult, a as convertFullStreamChunkToMastra, an as snapshotToolResult, at as PROCESSOR_ABORT_SIGNAL, b as resolveOutputMessageSkippingCompletionChecks, bn as pendingQueueThreadId, bt as predicateReadsState, c as WorkflowRunOutput, cn as validationErrorModelOutput, ct as getHydratedStepResult, d as MastraModelOutput, dn as resolveSuspendedToolRunId, dt as lazyStepResults, en as computeModelOutputProviderMetadata, et as resolveProcessorSpanAttributes, f as clearStepPartIndexes, fn as resolveThreadIdFromArgs, ft as loadStepResults, g as isFeedbackContinuation, gn as applyStateSignal, gt as storageV2StepResultAccessors, h as findStepPartBoundaries, hn as tryStreamWithJsonFallback, ht as residentStepResultsLoader, in as resolveModelOutputAfterToolResultProcessors, it as createProcessorSendSignal, j as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, jn as raceAgainstAbort, k as getResponseFormat, kn as guardStreamWithAbort, kt as getStepResultAsync, l as TripWire, ln as isProcessorWorkflow, lt as hydrateStepResults, m as findIterationOffsetInParts, mn as tryGenerateWithJsonFallback, mt as residentStepResults, nn as latestProcessedModelOutput, nt as toProcessorSpanPhase, on as withAgentWorkflowToolMarker, ot as RunJournal, p as createDestructurableOutput, pn as supportedLanguageModelSpecifications, pt as loadedStepResults, q as takeHeldParts, rn as readModelOutput, rt as PROCESSOR_LATE_SIGNAL_SINK, s as MastraAgentNetworkStream, sn as normalizeModelOutput, st as buildStepResultAccessors, tn as hasToolResultProcessor, tt as resolveProcessorSpanName, u as getModelOutputForTripwire, un as isSupportedLanguageModel, ut as isStepResultStub, v as reconcileBufferedStepTexts, vn as assertNotQueueThreadId, vt as collectMappingStepRefs, w as markChunkOutputProcessed, wn as DEADLINE_SAVE_WAIT_MS, wt as resolveTemplate, x as resolveProcessorWriterMessageId, xn as queuedQueueThreadId, xt as resolveStepOutputs, y as resolveMessageText, yn as isQueueThreadId, yt as collectPredicateStepRefs, z as needsTrailingAssistantGuard, zn as createRunScopeKey, zt as stateBaseOf } from "./stream-D2rv1Ut1.js";
6
+ import { S as isLeaseProvider, _ as stripModelSnapshots, a as CachingPubSub, b as NoopLeaseProvider, f as isRunLocalTopic, h as slimNestedAgentChunks, i as PublisherQueueLimitError, r as serializeError$1, t as DefaultStepResult, v as EventEmitterPubSub, y as withAck } from "./output-helpers-D-qplq22.js";
7
+ import { $ as summarizeToolChoiceForSpan, $t as commitToolResult, A as isSignalChunkExcluded, An as isMastraTimeoutError, At as getSnapshotMemoryInfo, B as removeTrailingAssistantGuardContinuations, Bt as stateColumnsWrite, C as stampChunkProducedAt, Cn as DEADLINE_SAVE_CLAIM_HOLD_MS, D as isStructuredOutputError, Dn as getAbortReason, Dt as validateTemplate, E as escapeUnescapedControlCharsInJsonStrings, En as createTimeoutAbortSignal, Et as traverseMappingPath, F as endOutputStreamSpanOutsideStep, Fn as safeClose, Ft as latestStepResults, G as FLUSH_HELD_PARTS_KEY, Gt as diffStateAsJson, Ht as unusedStateEntries, I as findOwnModelStepSpan, In as safeEnqueue, It as materializeState, J as withoutHeldContent, K as REPROCESS_PART_KEY, Kt as patchState, Ln as safeError, Lt as materializeWorkflowRun, M as ProcessorRunner, Mn as settledOrElapsed, N as ProcessorState, Nt as applyStateColumnsWrite, O as asJsonSchema, On as guardStreamUntilMatch, Ot as getStepResult, P as endOutputStreamSpanAtStepEnd, Pn as MastraModelInput, Pt as isStateCheckpointDue, Q as summarizeProcessorToolsForSpan, R as isTrailingAssistantGuardContinuation, Rn as createRunScope, Rt as pickStateKeys, S as getChunkProducedAt, Sn as takenQueueThreadId, St as stepRefId, T as createOutputHandler, Tn as MastraTimeoutError, Tt as templateReadsState, Ut as applyStatePatch, V as ProviderHistoryCompat, Vt as summarizeStepResult, X as summarizeProcessorModelForSpan, Y as summarizeActiveToolsForSpan, Yt as isObservationalMemoryEnabled$1, Z as summarizeProcessorResultForSpan, Zt as parseMemoryRequestContext, _ as persistProcessorDataChunk, _t as stubStepResult, a as convertFullStreamChunkToMastra, an as snapshotToolResult, at as PROCESSOR_ABORT_SIGNAL, b as resolveOutputMessageSkippingCompletionChecks, bn as pendingQueueThreadId, bt as predicateReadsState, c as WorkflowRunOutput, cn as validationErrorModelOutput, ct as getHydratedStepResult, d as MastraModelOutput, dn as resolveSuspendedToolRunId, dt as lazyStepResults, en as computeModelOutputProviderMetadata, et as resolveProcessorSpanAttributes, f as clearStepPartIndexes, fn as resolveThreadIdFromArgs, ft as loadStepResults, g as isFeedbackContinuation, gn as applyStateSignal, gt as storageV2StepResultAccessors, h as findStepPartBoundaries, hn as tryStreamWithJsonFallback, ht as residentStepResultsLoader, in as resolveModelOutputAfterToolResultProcessors, it as createProcessorSendSignal, j as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, jn as raceAgainstAbort, k as getResponseFormat, kn as guardStreamWithAbort, kt as getStepResultAsync, l as TripWire, ln as isProcessorWorkflow, lt as hydrateStepResults, m as findIterationOffsetInParts, mn as tryGenerateWithJsonFallback, mt as residentStepResults, nn as latestProcessedModelOutput, nt as toProcessorSpanPhase, on as withAgentWorkflowToolMarker, ot as RunJournal, p as createDestructurableOutput, pn as supportedLanguageModelSpecifications, pt as loadedStepResults, q as takeHeldParts, rn as readModelOutput, rt as PROCESSOR_LATE_SIGNAL_SINK, s as MastraAgentNetworkStream, sn as normalizeModelOutput, st as buildStepResultAccessors, tn as hasToolResultProcessor, tt as resolveProcessorSpanName, u as getModelOutputForTripwire, un as isSupportedLanguageModel, ut as isStepResultStub, v as reconcileBufferedStepTexts, vn as assertNotQueueThreadId, vt as collectMappingStepRefs, w as markChunkOutputProcessed, wn as DEADLINE_SAVE_WAIT_MS, wt as resolveTemplate, x as resolveProcessorWriterMessageId, xn as queuedQueueThreadId, xt as resolveStepOutputs, y as resolveMessageText, yn as isQueueThreadId, yt as collectPredicateStepRefs, z as needsTrailingAssistantGuard, zn as createRunScopeKey, zt as stateBaseOf } from "./stream-BfSwqzPi.js";
8
8
  import { HAND_BACK_STATE_SYMBOL, PARENT_STATE_SYMBOL, PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL, WORKFLOW_CANCELLED_SYMBOL } from "./workflows/constants.js";
9
9
  import { c as MASTRA_THREAD_ID_KEY, d as isReservedRequestContextKey, f as mergeVersionOverrides$1, l as MASTRA_VERSIONS_KEY, n as MASTRA_AUTH_TOKEN_KEY, o as MASTRA_RESOURCE_ID_KEY, p as withoutLiveRequestKeys, r as MASTRA_INHERITED_MEMORY_KEY, s as MASTRA_SCOPES_KEY, t as MASTRA_CONTINUATION_TOOL_CALL_IDS_KEY, u as RequestContext } from "./request-context-COnZHt2-.js";
10
10
  import { _ as resolveObservabilityContext, a as agentLoopTermination, c as compactStopReasonContext, g as createObservabilityContext, h as wrapMastra, i as subtractReportedUsage, m as unwrapMastraTracingProxy, n as extractUsageMetrics, o as executionFailureTermination, r as isUsageIncomplete, s as tripwireTermination, t as calculateObservedUsage } from "./observability-DPDWibyH.js";
@@ -13,9 +13,9 @@ import { a as getOrCreateSpan, f as resolveCurrentSpan, l as getTimeToFirstChunk
13
13
  import { _ as getRequestContextInputValues, a as getModelFacingValidationError, d as validateToolOutput, g as getRequestContextInputSource, l as resolveToolOutputValidationSchema, r as createTool, u as validateToolInput } from "./tool-DIFduuTw.js";
14
14
  import { isStandardSchemaWithJSON, standardSchemaToJSONSchema, toStandardSchema } from "./schema/index.js";
15
15
  import { i as setSpanErrorOrigin, n as getSpanErrorOrigin } from "./error-count-BH-rJW7q.js";
16
- import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-DLnCt6E9.js";
16
+ import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-CnpMuTyD.js";
17
17
  import { h as getWorkflowFGAResourceId, i as MastraFGAPermissions, y as requireFGA } from "./ee-iTj2bRDt-By_B9ngH.js";
18
- import { c as createBackgroundTask, o as resolveBackgroundConfig, s as sanitizeToolArguments, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-HAzB0JtC.js";
18
+ import { c as createBackgroundTask, o as resolveBackgroundConfig, s as sanitizeToolArguments, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-DSMkHpbu.js";
19
19
  import { a as isApprovalExempt, c as isProviderDefinedTool, d as markAgentWorkflowTool, f as markApprovalExempt, l as isProviderTool, n as getNeedsApprovalFn, o as isBuiltBeforeApproval, r as getProviderToolName, s as isMastraTool, t as getBeforeApprovalFn } from "./toolchecks-CRAfUe9H.js";
20
20
  import { t as ToolStream } from "./stream-D9JOykz7.js";
21
21
  import { a as waitDelay, i as getRetryAfterMs, n as DEFAULT_MAX_RETRY_AFTER_MS, r as clampDelayMs } from "./fetchWithRetry-DFSvpYDT.js";
@@ -23,23 +23,23 @@ import { boundedStringify, ensureSerializable, safeStringify } from "./utils/saf
23
23
  import { t as deepEqual$3 } from "./deep-equal-d1xU02ag.js";
24
24
  import { n as resolveDynamicArgument, t as getRequestUser } from "./dynamic-argument-BzPK3qPN.js";
25
25
  import { A as stableStringify$1, E as removeWorkingMemoryTags, P as embed$3, Z as preserveResponseItemIdsOnMerge, a as isTerminalToolInvocationState, c as withUnavailableAttachmentUrls, d as aiV5UIMessagesToAIV5ModelMessages, f as coreContentToString, i as isClientToolInvocationUpdate, l as isDownloadAssetsError, m as filterMessagesForPersistence, n as MessageList, ot as normalizeToolOutput, p as messagesAreEqual, r as advancesToolInvocationState, s as unavailableAttachmentPlaceholder, t as convertMessages, u as MessageMerger } from "./message-list-RgFlLrxG.js";
26
- import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-ccA_1Q-H.js";
26
+ import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-_z1lIfCN.js";
27
27
  import { a as withToolPayloadTransformMetadata, i as transformToolPayloadForTargets, n as hasTransformedToolPayload, o as withToolPayloadTransformProviderMetadata, r as normalizeToolPayloadTransformPolicy, t as getTransformedToolPayload } from "./payload-transform-Dj3HUeD4.js";
28
28
  import { d as signalSpanAttributes, h as signalToXmlMarkup, l as mastraDBMessageToSignal, n as createSignal, o as isMastraSignalMessage, s as isTransientSignalMessage, u as resolveDeliveryAttributes } from "./signals-CqR_iWkg.js";
29
29
  import { h as resolveFilePartMediaTypeAndData, m as parseDataUri, o as categorizeFileData } from "./to-prompt-CMlVGYxC.js";
30
30
  import { c as parsePartialJson, h as tool$1, m as generateId$1, p as asSchema$1, r as embed$4, u as APICallError$1 } from "./dist-TPVqg8oV.js";
31
31
  import { n as embed$5 } from "./dist-D3cKCUe-.js";
32
32
  import { i as hasFreeFormObject } from "./model-DS-b2R-R.js";
33
- import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-BvbEoScB.js";
33
+ import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-C4tv__fr.js";
34
34
  import { t as InMemoryServerCache } from "./inmemory-BK3zLwvM.js";
35
- import { t as MastraLLMV1 } from "./model-BwxfS6T_.js";
35
+ import { t as MastraLLMV1 } from "./model-DmBDBf-q.js";
36
36
  import { MISSING, collectInvalidPredicatePaths, createPredicateEvaluator, derivePredicateLabel, normalizePredicatePath, walk } from "./predicate/index.js";
37
37
  import { Classifier } from "./classifier/index.js";
38
38
  import { initContextStorage, withSpanErrorAttempt } from "./observability/context-storage.js";
39
39
  import { i as executeHook } from "./hooks-Bth8Cjpj.js";
40
40
  import { o as assertValidScheduleDefinition, v as validateScheduleTiming } from "./schedules-DZfSx-7P.js";
41
41
  import { A as writeObjective, D as readObjective, O as resolveEffectiveGoalSettings, T as formatGoalBudgetPausedReason, _ as clearCachedGoalObjective, b as GOAL_SCORER_ID, g as cacheGoalObjective, k as resolveGoalStore, w as clearObjective, x as GOAL_SCORE_WAITING } from "./state-processor-B_KsS82m.js";
42
- import { An as computeTraceStatus, Cr as extractTrajectory, Dr as saveScorePayloadSchema, It as TABLE_SCHEMAS, Lt as TABLE_SCORERS, Nn as extractBranchSpans, Pn as getBranchArgsSchema, Qn as listTracesArgsSchema, Sr as withBufferedReflectionVerified, Tr as extractWorkflowTrajectory, Yn as listBranchesArgsSchema, _r as isAppendOnlySince, ar as spanRecordSchema, br as maxObservationCursor, cr as toTraceSpans, gn as BRANCH_SPAN_TYPE_SET, gr as compareObservationalMemoryHeadOrder, hr as assertActiveObservationsApplied, or as toLightSpanRecord, pn as matchesExpectedWorkflowStatus, qn as isPreviewTruncated, sr as toTraceSpan, vn as TraceStatus, vr as isBufferedChunkCoveredByCursor, wr as extractTrajectoryFromTrace, xr as planReflectionGenerationText, yr as isBufferedReflectionUnchangedSince } from "./constants-Dro9fuhk.js";
42
+ import { An as computeTraceStatus, Cr as extractTrajectory, Dr as saveScorePayloadSchema, It as TABLE_SCHEMAS, Lt as TABLE_SCORERS, Nn as extractBranchSpans, Pn as getBranchArgsSchema, Qn as listTracesArgsSchema, Sr as withBufferedReflectionVerified, Tr as extractWorkflowTrajectory, Yn as listBranchesArgsSchema, _r as isAppendOnlySince, ar as spanRecordSchema, br as maxObservationCursor, cr as toTraceSpans, gn as BRANCH_SPAN_TYPE_SET, gr as compareObservationalMemoryHeadOrder, hr as assertActiveObservationsApplied, or as toLightSpanRecord, pn as matchesExpectedWorkflowStatus, qn as isPreviewTruncated, sr as toTraceSpan, vn as TraceStatus, vr as isBufferedChunkCoveredByCursor, wr as extractTrajectoryFromTrace, xr as planReflectionGenerationText, yr as isBufferedReflectionUnchangedSince } from "./constants-C2Q-ZI5d.js";
43
43
  import { t as GoalSignalProvider } from "./signal-provider-B_mfW-J4.js";
44
44
  import { t as slugify } from "./slugify-BUNmb-Ga.js";
45
45
  import { F as LocalSandbox, at as evaluateReadRecord, c as Workspace, dt as WORKSPACE_TOOLS, g as resolveToolConfig, gt as shellQuote, h as createWorkspaceTools, ht as sliceByTokens, l as createSkillTools, lt as CompositeFilesystem, mt as estimateTokenCount, ot as normalizeReadTrackerPath, pt as sliceByTokensSafe, st as LocalFilesystem } from "./workspace-sqcfdZRR.js";
@@ -58,6 +58,7 @@ import { n as InMemorySkillsStorage, t as FilesystemSkillsStorage } from "./file
58
58
  import { n as InMemoryWorkspacesStorage, t as FilesystemWorkspacesStorage } from "./filesystem-BhYgU8qg.js";
59
59
  import { n as resolveAgentSkills, t as mergeWorkspaceSkills } from "./agent-skills-resolver-D2HktP6Y.js";
60
60
  import { n as DefaultVoice } from "./voice-OS-kmlEA.js";
61
+ import { TTLCache } from "@isaacs/ttlcache";
61
62
  import { any, array, boolean, custom, discriminatedUnion, enum as enum$1, instanceof as instanceof$1, json, lazy, literal, looseObject, never, null as null$1, number, object, record, safeParseAsync, string, union, unknown, z } from "zod/v4";
62
63
  import { createHash, randomUUID } from "crypto";
63
64
  import { jsonSchemaToZod } from "@mastra/schema-compat/json-to-zod";
@@ -70,7 +71,6 @@ import { config, toJSONSchema } from "zod/v4/core";
70
71
  import en from "zod/v4/locales/en.js";
71
72
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
72
73
  import { dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep, win32 } from "path";
73
- import { TTLCache } from "@isaacs/ttlcache";
74
74
  import { AsyncLocalStorage } from "async_hooks";
75
75
  import fastq from "fastq";
76
76
  import { readFile, realpath, stat } from "fs/promises";
@@ -502,6 +502,11 @@ const MASTRA_DURABLE_EXECUTIONS_KEY = "mastra__durableExecutions";
502
502
  */
503
503
  const MASTRA_DURABLE_SEGMENTS_KEY = "mastra__durableSegments";
504
504
  /**
505
+ * Reserved request-context key carrying `Record<runId, boolean>`: the `autoResumeSuspendedTools` a resumed execution
506
+ * runs with, so a step that suspends persists it on whichever worker runs the step. (#30190)
507
+ */
508
+ const MASTRA_DURABLE_AUTO_RESUME_KEY = "mastra__durableAutoResume";
509
+ /**
505
510
  * JSON-safe snapshot of `requestContext.entries()`, for a run that continues
506
511
  * somewhere the live context can't follow: a durable step, or a claimed
507
512
  * thread owner in another process. Best-effort: entries that fail a JSON
@@ -519,6 +524,7 @@ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
519
524
  if (key === "mastra__versions") continue;
520
525
  if (key === "mastra__durableExecutions") continue;
521
526
  if (key === "mastra__durableSegments") continue;
527
+ if (key === "mastra__durableAutoResume") continue;
522
528
  if (key === "__mastra_chat_channel_render") continue;
523
529
  const json = boundedStringify(value);
524
530
  if (json === void 0) {
@@ -12321,6 +12327,15 @@ var EventedExecutionEngine = class extends ExecutionEngine {
12321
12327
  const DOCS_URL = "https://mastra.ai/docs/server/pubsub#evented-workflows-and-agents";
12322
12328
  const warnedHosts = /* @__PURE__ */ new WeakSet();
12323
12329
  const warnedSignalHosts = /* @__PURE__ */ new WeakSet();
12330
+ const warnedCacheHosts = /* @__PURE__ */ new WeakSet();
12331
+ /**
12332
+ * Whether each process keeps its own copy of the run logs `cache` holds while
12333
+ * `pubsub` carries the runs to other processes. Only `InMemoryServerCache` is
12334
+ * known to be process-local; any other cache is assumed to be shared.
12335
+ */
12336
+ function keepsRunLogsInProcess(pubsub, cache) {
12337
+ return cache instanceof InMemoryServerCache && reachesOtherProcesses(pubsub);
12338
+ }
12324
12339
  /**
12325
12340
  * Evented runs spread over several processes need a pubsub that hands a stopped
12326
12341
  * worker's event to another worker, and a store whose step guards let one
@@ -12366,6 +12381,26 @@ function warnUnsharedAgentSignals(mastra, reason) {
12366
12381
  warnedSignalHosts.add(mastra);
12367
12382
  mastra.getLogger()?.warn(`Signals sent to running evented agents aren't supported on several processes with this setup: ${missing}. See ${DOCS_URL}`);
12368
12383
  }
12384
+ /**
12385
+ * An evented agent's steps append their stream frames to the run's log in the
12386
+ * server cache, which also holds the run's ownership record. With a cache each
12387
+ * process keeps to itself, a step in another process publishes its frames
12388
+ * unnumbered, so `observe(runId, { offset })` can't skip them, and another
12389
+ * process can't observe or stop the run. Logs once per Mastra instance, apart
12390
+ * from {@link warnUnsupportedEventedSetup} so that one does not hide this.
12391
+ *
12392
+ * Called when an evented agent is registered, in every process that can run
12393
+ * its steps, including dedicated workers that never start a run.
12394
+ */
12395
+ function warnProcessLocalServerCache(mastra) {
12396
+ if (warnedCacheHosts.has(mastra) || process.env.MASTRA_DISABLE_EVENTED_SETUP_WARNING === "true") return;
12397
+ const pubsub = mastra.pubsub;
12398
+ const wrapped = pubsub instanceof CachingPubSub;
12399
+ if (!keepsRunLogsInProcess(pubsub, wrapped ? pubsub.getCache() : mastra.serverCache)) return;
12400
+ const problem = wrapped ? `the configured CachingPubSub keeps run logs in an InMemoryServerCache, which only this process reads. Give that CachingPubSub a server cache every process shares` : `the server cache is an InMemoryServerCache, which only this process reads. Set \`cache\` on Mastra to a server cache every process shares`;
12401
+ warnedCacheHosts.add(mastra);
12402
+ mastra.getLogger()?.warn(`Evented agents aren't supported on several processes with this setup: ${problem}, such as RedisServerCache. See ${DOCS_URL}`);
12403
+ }
12369
12404
  // src/storage/workflow-step-guard.ts
12370
12405
  var WorkflowStepConflictError = class extends Error {
12371
12406
  reason;
@@ -12571,6 +12606,23 @@ function carrySegmentSpans(target, runId, segment) {
12571
12606
  else target[MASTRA_DURABLE_SEGMENTS_KEY] = next;
12572
12607
  }
12573
12608
  /**
12609
+ * Record the `autoResumeSuspendedTools` a resumed execution of `runId` runs with on the request context it hands the
12610
+ * engine, which carries it to every step of the segment wherever it runs. (#30190)
12611
+ */
12612
+ function carrySegmentAutoResume(requestContext, runId, value) {
12613
+ const current = requestContext.getRaw(MASTRA_DURABLE_AUTO_RESUME_KEY);
12614
+ requestContext.setRaw(MASTRA_DURABLE_AUTO_RESUME_KEY, {
12615
+ ...current && typeof current === "object" ? current : {},
12616
+ [runId]: value
12617
+ });
12618
+ }
12619
+ /** The `autoResumeSuspendedTools` a resume carried for the current execution of `runId`, if any. */
12620
+ function segmentAutoResume(requestContext, runId) {
12621
+ const all = requestContext?.getRaw?.(MASTRA_DURABLE_AUTO_RESUME_KEY);
12622
+ const value = all && typeof all === "object" ? all[runId] : void 0;
12623
+ return typeof value === "boolean" ? value : void 0;
12624
+ }
12625
+ /**
12574
12626
  * The pair the current execution reports under: the one a resume or recovery carried for `runId`,
12575
12627
  * else the run's first pair from `state` (the workflow input or the loop state). A carried `null`
12576
12628
  * means the execution opened no spans, so its steps end none. `carried` tells the two apart.
@@ -14462,7 +14514,7 @@ function closeStoredSignalRun({ mastra, runId, input, requestContext, state, dea
14462
14514
  agentId: input?.agentId,
14463
14515
  threadId: input?.state?.threadId
14464
14516
  });
14465
- return;
14517
+ return false;
14466
14518
  }
14467
14519
  const saved = typeof state === "function" ? await state() : state;
14468
14520
  await queue.store.closeSignalRun({
@@ -14470,11 +14522,13 @@ function closeStoredSignalRun({ mastra, runId, input, requestContext, state, dea
14470
14522
  runId,
14471
14523
  consumedIds: readConsumedSignalIds(saved)
14472
14524
  });
14525
+ return true;
14473
14526
  } catch (error) {
14474
14527
  mastra?.getLogger?.()?.warn?.("Could not close the stored signals of an ended run", {
14475
14528
  runId,
14476
14529
  error
14477
14530
  });
14531
+ return false;
14478
14532
  }
14479
14533
  })();
14480
14534
  }
@@ -15768,7 +15822,7 @@ function createDurableAgentStream(options) {
15768
15822
  armIdleTimer();
15769
15823
  resolveReady();
15770
15824
  releaseTerminalSubscription();
15771
- }).catch((error) => {
15825
+ }).catch(async (error) => {
15772
15826
  pubsub.unsubscribe(topic, subscribedCallback).catch((unsubscribeError) => {
15773
15827
  logError(`[DurableAgentStream] Failed to unsubscribe from ${topic}:`, unsubscribeError);
15774
15828
  });
@@ -15778,6 +15832,11 @@ function createDurableAgentStream(options) {
15778
15832
  markTerminated();
15779
15833
  if ((ctrl.desiredSize ?? 0) > 0) safeError(ctrl, error);
15780
15834
  else pendingRejection = error;
15835
+ try {
15836
+ await onError?.({ error });
15837
+ } catch (callbackError) {
15838
+ logError(`[DurableAgentStream] onError callback error:`, callbackError);
15839
+ }
15781
15840
  });
15782
15841
  },
15783
15842
  pull(ctrl) {
@@ -16318,7 +16377,6 @@ function scopedRunStorage(runId, runStorage) {
16318
16377
  var StepExecutor = class extends MastraBase {
16319
16378
  mastra;
16320
16379
  #stepPubsub;
16321
- #warnedUnnumbered = false;
16322
16380
  constructor({ mastra }) {
16323
16381
  super({
16324
16382
  name: "StepExecutor",
@@ -16351,31 +16409,24 @@ var StepExecutor = class extends MastraBase {
16351
16409
  * numbering the same run from 0 in its own cache would have observers drop
16352
16410
  * its frames as late duplicates. So with a process-local cache behind a
16353
16411
  * cross-process transport, steps only append to logs this process already
16354
- * holds — the caller writes the run's `start` frame before any step runs, so
16412
+ * holds. The caller writes the run's `start` frame before any step runs, so
16355
16413
  * steps in the caller's process are numbered (#28324) and steps on other
16356
- * workers publish unnumbered (live-only).
16414
+ * workers publish unnumbered (live-only). Mastra warns about that setup when
16415
+ * the evented agent is registered (`warnProcessLocalServerCache`).
16357
16416
  */
16358
16417
  #getStepPubsub() {
16359
16418
  if (this.#stepPubsub) return this.#stepPubsub;
16360
16419
  const inner = this.mastra.pubsub;
16361
16420
  const cache = this.mastra?.serverCache;
16362
16421
  if (inner instanceof CachingPubSub) this.#stepPubsub = inner;
16363
- else if (cache) {
16364
- const processLocalLogs = cache instanceof InMemoryServerCache && reachesOtherProcesses(inner);
16365
- this.#stepPubsub = new CachingPubSub(inner, cache, {
16366
- shouldCache: (topic) => !isRunLocalTopic(topic),
16367
- extendExistingLogsOnly: processLocalLogs,
16368
- onUnlogged: (topic) => this.#warnUnnumberedAgentStream(topic),
16369
- logger: this.logger
16370
- });
16371
- } else this.#stepPubsub = inner;
16422
+ else if (cache) this.#stepPubsub = new CachingPubSub(inner, cache, {
16423
+ shouldCache: (topic) => !isRunLocalTopic(topic),
16424
+ extendExistingLogsOnly: keepsRunLogsInProcess(inner, cache),
16425
+ logger: this.logger
16426
+ });
16427
+ else this.#stepPubsub = inner;
16372
16428
  return this.#stepPubsub;
16373
16429
  }
16374
- #warnUnnumberedAgentStream(topic) {
16375
- if (this.#warnedUnnumbered || !topic.startsWith(AGENT_STREAM_TOPIC(""))) return;
16376
- this.#warnedUnnumbered = true;
16377
- this.logger.warn(`Agent stream frames published from this process are not numbered: the run started in another process and the in-memory server cache is process-local, so observe(runId, { offset }) cannot skip these frames. Configure a shared server cache (e.g. RedisServerCache) on Mastra.`, { topic });
16378
- }
16379
16430
  /**
16380
16431
  * Creates an output writer function that publishes chunks to the workflow event stream.
16381
16432
  * @param runId - The workflow run ID
@@ -24756,6 +24807,8 @@ const llmIterationOutputSchema = z.object({
24756
24807
  stepResult: llmIterationStepResultSchema,
24757
24808
  processorRetryCount: z.number().optional(),
24758
24809
  fallbackModelIndex: z.number().optional(),
24810
+ fallbackModelId: z.string().optional(),
24811
+ fallbackModelTriesEarlierEntries: z.boolean().optional(),
24759
24812
  skipUnavailableAttachments: z.boolean().optional(),
24760
24813
  processorRetryFeedback: z.string().optional(),
24761
24814
  isTaskCompleteCheckFailed: z.boolean().optional(),
@@ -25015,7 +25068,7 @@ const RETRYABLE_FAILURE_KINDS = /* @__PURE__ */ new Set([
25015
25068
  const ACCOUNT_REFUSALS = /* @__PURE__ */ new Set(["auth", "quota"]);
25016
25069
  const OPENAI_RETRY_MESSAGE_PATTERN = /you can retry your request/i;
25017
25070
  const DEFAULT_MATCHERS = [isRetryableOpenAIResponsesStreamError];
25018
- function isRecord$7(value) {
25071
+ function isRecord$8(value) {
25019
25072
  return typeof value === "object" && value !== null;
25020
25073
  }
25021
25074
  function getStringProperty(value, key) {
@@ -25024,15 +25077,15 @@ function getStringProperty(value, key) {
25024
25077
  }
25025
25078
  function getObjectCause(error) {
25026
25079
  if (error instanceof Error) return error.cause;
25027
- if (!isRecord$7(error)) return;
25080
+ if (!isRecord$8(error)) return;
25028
25081
  return error.cause;
25029
25082
  }
25030
25083
  function getOpenAIErrorPayload(error) {
25031
- if (!isRecord$7(error)) return;
25032
- if (error.type === "error" && isRecord$7(error.error)) return error.error;
25033
- if (error.type === "response.failed" && isRecord$7(error.response)) {
25084
+ if (!isRecord$8(error)) return;
25085
+ if (error.type === "error" && isRecord$8(error.error)) return error.error;
25086
+ if (error.type === "response.failed" && isRecord$8(error.response)) {
25034
25087
  const responseError = error.response.error;
25035
- return isRecord$7(responseError) ? responseError : void 0;
25088
+ return isRecord$8(responseError) ? responseError : void 0;
25036
25089
  }
25037
25090
  }
25038
25091
  function hasExplicitRetryMessage(payload) {
@@ -25064,12 +25117,12 @@ function isBadRequestError(error) {
25064
25117
  return false;
25065
25118
  }
25066
25119
  function isRetryableProviderMetadata(error) {
25067
- return (APICallError$1.isInstance(error) ? error.isRetryable : isRecord$7(error) && typeof error.isRetryable === "boolean" ? error.isRetryable : void 0) === true;
25120
+ return (APICallError$1.isInstance(error) ? error.isRetryable : isRecord$8(error) && typeof error.isRetryable === "boolean" ? error.isRetryable : void 0) === true;
25068
25121
  }
25069
25122
  function hasDeniedHttpStatus(error) {
25070
25123
  const visited = /* @__PURE__ */ new WeakSet();
25071
25124
  function visit(candidate) {
25072
- if (!isRecord$7(candidate) || visited.has(candidate)) return false;
25125
+ if (!isRecord$8(candidate) || visited.has(candidate)) return false;
25073
25126
  visited.add(candidate);
25074
25127
  if (candidate.status === 401 || candidate.status === 403) return true;
25075
25128
  return visit(candidate.error) || visit(candidate.data) || visit(candidate.cause);
@@ -25091,7 +25144,7 @@ function normalizeEntry(entry) {
25091
25144
  function findMatchingPolicy(error, entries) {
25092
25145
  const visited = /* @__PURE__ */ new WeakSet();
25093
25146
  function visit(candidate) {
25094
- if (isRecord$7(candidate)) {
25147
+ if (isRecord$8(candidate)) {
25095
25148
  if (visited.has(candidate)) return void 0;
25096
25149
  visited.add(candidate);
25097
25150
  }
@@ -30714,7 +30767,7 @@ async function localPathIdentity(path) {
30714
30767
  return toAbsolutePath(path);
30715
30768
  }
30716
30769
  }
30717
- function isRecord$6(value) {
30770
+ function isRecord$7(value) {
30718
30771
  return typeof value === "object" && value !== null;
30719
30772
  }
30720
30773
  function isInstructionFileName(name) {
@@ -30773,9 +30826,9 @@ async function findInstructionFileForPath(candidatePath, pathExists, isDirectory
30773
30826
  }
30774
30827
  }
30775
30828
  function getMessageText(message) {
30776
- const parts = isRecord$6(message.content) ? message.content.parts : void 0;
30829
+ const parts = isRecord$7(message.content) ? message.content.parts : void 0;
30777
30830
  if (!Array.isArray(parts)) return "";
30778
- return parts.filter((part) => isRecord$6(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
30831
+ return parts.filter((part) => isRecord$7(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
30779
30832
  }
30780
30833
  function decodeXmlEntities(value) {
30781
30834
  return value.replaceAll("&quot;", "\"").replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&amp;", "&");
@@ -30797,8 +30850,8 @@ function getReminderMetadata(instructionPath) {
30797
30850
  }
30798
30851
  function extractReminderPathFromMetadata(message) {
30799
30852
  const metadata = message.content.metadata;
30800
- if (!isRecord$6(metadata)) return;
30801
- const reminderMetadata = isRecord$6(metadata.systemReminder) ? metadata.systemReminder : isRecord$6(metadata[LEGACY_REMINDER_METADATA_KEY]) ? metadata[LEGACY_REMINDER_METADATA_KEY] : isRecord$6(metadata.signal) && isRecord$6(metadata.signal.attributes) ? metadata.signal.attributes : metadata;
30853
+ if (!isRecord$7(metadata)) return;
30854
+ const reminderMetadata = isRecord$7(metadata.systemReminder) ? metadata.systemReminder : isRecord$7(metadata[LEGACY_REMINDER_METADATA_KEY]) ? metadata[LEGACY_REMINDER_METADATA_KEY] : isRecord$7(metadata.signal) && isRecord$7(metadata.signal.attributes) ? metadata.signal.attributes : metadata;
30802
30855
  return typeof reminderMetadata.path === "string" ? reminderMetadata.path : void 0;
30803
30856
  }
30804
30857
  function getReminderMarkup(reminderText, instructionPath) {
@@ -30824,10 +30877,10 @@ function truncateToTokenLimit(content, maxTokens) {
30824
30877
  function getCompletedToolCalls(messages) {
30825
30878
  const completed = [];
30826
30879
  for (const message of [...messages].reverse()) {
30827
- const parts = isRecord$6(message.content) ? message.content.parts : void 0;
30880
+ const parts = isRecord$7(message.content) ? message.content.parts : void 0;
30828
30881
  if (!Array.isArray(parts)) continue;
30829
30882
  for (const part of [...parts].reverse()) {
30830
- if (!isRecord$6(part) || part.type !== "tool-invocation") continue;
30883
+ if (!isRecord$7(part) || part.type !== "tool-invocation") continue;
30831
30884
  const invocation = part.toolInvocation;
30832
30885
  if (!invocation || invocation.state !== "result" || typeof invocation.toolCallId !== "string") continue;
30833
30886
  completed.push({
@@ -30839,11 +30892,11 @@ function getCompletedToolCalls(messages) {
30839
30892
  return completed;
30840
30893
  }
30841
30894
  function parseInvocationArgs(args) {
30842
- if (isRecord$6(args)) return args;
30895
+ if (isRecord$7(args)) return args;
30843
30896
  if (typeof args !== "string") return;
30844
30897
  try {
30845
30898
  const parsed = JSON.parse(args);
30846
- return isRecord$6(parsed) ? parsed : void 0;
30899
+ return isRecord$7(parsed) ? parsed : void 0;
30847
30900
  } catch {
30848
30901
  return;
30849
30902
  }
@@ -30949,7 +31002,7 @@ var AgentsMDInjector = class {
30949
31002
  return this.reminderText?.trim() || void 0;
30950
31003
  }
30951
31004
  async *findInstructionPathsInInvocation(invocation, reader, basePath) {
30952
- if (!isRecord$6(invocation)) return;
31005
+ if (!isRecord$7(invocation)) return;
30953
31006
  const args = parseInvocationArgs(invocation.args);
30954
31007
  if (!args) return;
30955
31008
  for (const field of PATH_FIELDS) {
@@ -32489,7 +32542,7 @@ function hashBinary(value) {
32489
32542
  const CYBER_POLICY_ERROR_CODE = "cyber_policy";
32490
32543
  const CYBER_REFUSAL_MESSAGE = "this content was flagged for possible cybersecurity risk";
32491
32544
  const CYBER_STOP_CATEGORY = "cyber";
32492
- function isRecord$5(value) {
32545
+ function isRecord$6(value) {
32493
32546
  return typeof value === "object" && value !== null;
32494
32547
  }
32495
32548
  function parseJson(value) {
@@ -32512,7 +32565,7 @@ function parseJson(value) {
32512
32565
  function isCyberRefusalError(error) {
32513
32566
  const visited = /* @__PURE__ */ new WeakSet();
32514
32567
  function visit(candidate) {
32515
- if (!isRecord$5(candidate) || visited.has(candidate)) return false;
32568
+ if (!isRecord$6(candidate) || visited.has(candidate)) return false;
32516
32569
  visited.add(candidate);
32517
32570
  const { code, message, responseBody } = candidate;
32518
32571
  if (typeof code === "string" && code.toLowerCase() === CYBER_POLICY_ERROR_CODE) return true;
@@ -32532,10 +32585,10 @@ function isCyberRefusalError(error) {
32532
32585
  * still recognized when Claude is reached through another provider.
32533
32586
  */
32534
32587
  function isCyberStopRefusal(finishReason, providerMetadata) {
32535
- if (finishReason !== "content-filter" || !isRecord$5(providerMetadata)) return false;
32588
+ if (finishReason !== "content-filter" || !isRecord$6(providerMetadata)) return false;
32536
32589
  return Object.values(providerMetadata).some((namespace) => {
32537
- const stopDetails = isRecord$5(namespace) ? namespace.stopDetails : void 0;
32538
- return isRecord$5(stopDetails) && typeof stopDetails.category === "string" && stopDetails.category.toLowerCase() === CYBER_STOP_CATEGORY;
32590
+ const stopDetails = isRecord$6(namespace) ? namespace.stopDetails : void 0;
32591
+ return isRecord$6(stopDetails) && typeof stopDetails.category === "string" && stopDetails.category.toLowerCase() === CYBER_STOP_CATEGORY;
32539
32592
  });
32540
32593
  }
32541
32594
  /**
@@ -32801,18 +32854,18 @@ async function checkThreadFGA({ mastra, user, threadId, resourceId, agentId, req
32801
32854
  }
32802
32855
  // src/memory/system-reminders.ts
32803
32856
  const LEGACY_SYSTEM_REMINDER_METADATA_KEY = "dynamicAgentsMdReminder";
32804
- function isRecord$4(value) {
32857
+ function isRecord$5(value) {
32805
32858
  return typeof value === "object" && value !== null;
32806
32859
  }
32807
32860
  function isSystemReminderSignalType(type) {
32808
32861
  return type === "system-reminder" || type === "reactive";
32809
32862
  }
32810
32863
  function isSystemReminderMessage(message) {
32811
- if (!isRecord$4(message.content)) return false;
32864
+ if (!isRecord$5(message.content)) return false;
32812
32865
  const metadata = message.content.metadata;
32813
- if (message.role === "signal") return isRecord$4(metadata) && isRecord$4(metadata.signal) && isSystemReminderSignalType(metadata.signal.type);
32866
+ if (message.role === "signal") return isRecord$5(metadata) && isRecord$5(metadata.signal) && isSystemReminderSignalType(metadata.signal.type);
32814
32867
  if (message.role !== "user") return false;
32815
- if (isRecord$4(metadata) && (isRecord$4(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) return true;
32868
+ if (isRecord$5(metadata) && (isRecord$5(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) return true;
32816
32869
  const firstTextPart = message.content.parts.find((part) => part.type === "text");
32817
32870
  return typeof firstTextPart?.text === "string" && firstTextPart.text.startsWith("<system-reminder");
32818
32871
  }
@@ -32820,10 +32873,10 @@ function isRecallSignalType(type) {
32820
32873
  return type === "user" || type === "state" || type === "reactive" || type === "notification" || type === "user-message" || type === "system-reminder";
32821
32874
  }
32822
32875
  function getRecallSignalType(message) {
32823
- if (!isRecord$4(message.content)) return void 0;
32824
- for (const part of message.content.parts) if ((part.type === "data-signal" || part.type === "data-user-message") && isRecord$4(part.data) && isRecallSignalType(part.data.type)) return part.data.type;
32876
+ if (!isRecord$5(message.content)) return void 0;
32877
+ for (const part of message.content.parts) if ((part.type === "data-signal" || part.type === "data-user-message") && isRecord$5(part.data) && isRecallSignalType(part.data.type)) return part.data.type;
32825
32878
  const metadata = message.content.metadata;
32826
- if (message.role === "signal" && isRecord$4(metadata) && isRecord$4(metadata.signal)) {
32879
+ if (message.role === "signal" && isRecord$5(metadata) && isRecord$5(metadata.signal)) {
32827
32880
  if (isRecallSignalType(metadata.signal.type)) return metadata.signal.type;
32828
32881
  }
32829
32882
  return isSystemReminderMessage(message) ? "system-reminder" : void 0;
@@ -35092,6 +35145,9 @@ var ObservabilityInMemory = class extends ObservabilityStorage {
35092
35145
  entityType: span.entityType,
35093
35146
  entityId: span.entityId,
35094
35147
  entityName: span.entityName,
35148
+ outcome: span.outcome,
35149
+ stopReason: span.stopReason,
35150
+ stopReasonContext: span.stopReasonContext,
35095
35151
  createdAt: span.createdAt,
35096
35152
  updatedAt: span.updatedAt
35097
35153
  }))
@@ -40253,12 +40309,35 @@ var KnowledgeInvalidCursorError = class extends Error {
40253
40309
  }
40254
40310
  };
40255
40311
  /**
40312
+ * A keyword search the store refuses, such as one with a word over
40313
+ * {@link KNOWLEDGE_SEARCH_MAX_WORD_LENGTH} characters. Recognise it by `name`; adapters bundle their
40314
+ * own copy.
40315
+ * @experimental
40316
+ */
40317
+ var KnowledgeInvalidSearchError = class extends Error {
40318
+ constructor(message) {
40319
+ super(message);
40320
+ this.name = "KnowledgeInvalidSearchError";
40321
+ }
40322
+ };
40323
+ /**
40256
40324
  * Keyword-search words: the query split on whitespace, lowercased, deduplicated, keeping the first
40257
40325
  * {@link KNOWLEDGE_SEARCH_MAX_WORDS}. A hit needs at least one of them (as a case-insensitive
40258
- * substring); an empty list means the search returns nothing.
40326
+ * substring); an empty list means the search returns nothing. Throws
40327
+ * {@link KnowledgeInvalidSearchError} for any word over {@link KNOWLEDGE_SEARCH_MAX_WORD_LENGTH}
40328
+ * characters rather than dropping or cutting it, which would match the wrong pages.
40259
40329
  */
40260
40330
  function knowledgeSearchWords(query) {
40261
- return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))].slice(0, 16);
40331
+ const words = [];
40332
+ for (const raw of query.split(/\s+/)) {
40333
+ if (!raw) continue;
40334
+ const length = raw.length > 128 ? [...raw].length : raw.length;
40335
+ if (length > 128) throw new KnowledgeInvalidSearchError(`Knowledge search words can be at most 128 characters; one word has ${length}`);
40336
+ if (words.length === 16) continue;
40337
+ const word = raw.toLowerCase();
40338
+ if (!words.includes(word)) words.push(word);
40339
+ }
40340
+ return words;
40262
40341
  }
40263
40342
  /**
40264
40343
  * Points one matched search word earns on a page, by the best field it appears in: name, then
@@ -41691,6 +41770,13 @@ var InMemoryKnowledgePageStore = class {
41691
41770
  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);
41692
41771
  return sources;
41693
41772
  }
41773
+ async listPageBodyLinkSourcesByRef(input) {
41774
+ const refs = new Set(input.refs);
41775
+ const targets = new Set(input.toPageIds);
41776
+ const sources = [];
41777
+ 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);
41778
+ return sources;
41779
+ }
41694
41780
  /** Every resolved link both of whose ends are live and readable, and not a self-link. */
41695
41781
  #visibleLinks(read, kinds) {
41696
41782
  const wanted = new Set(kinds ?? ["body", "note"]);
@@ -42292,6 +42378,9 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
42292
42378
  findPagesByNames(input) {
42293
42379
  return this.#pageStore.findPagesByNames(input);
42294
42380
  }
42381
+ listPageBodyLinkSourcesByRef(input) {
42382
+ return this.#pageStore.listPageBodyLinkSourcesByRef(input);
42383
+ }
42295
42384
  findPagesByName(input) {
42296
42385
  return this.#pageStore.findPagesByName(input);
42297
42386
  }
@@ -42679,7 +42768,12 @@ var MemoryStorage = class MemoryStorage extends StorageDomain {
42679
42768
  throw pendingSignalsNotSupportedError(this.constructor.name);
42680
42769
  }
42681
42770
  /**
42682
- * Delete the thread's taken rows whose id is in `consumedIds`. Then, if the
42771
+ * Delete the thread's taken rows whose id is in `consumedIds`. A consumed
42772
+ * id never names a queued row: a run consumes a row by claiming it or by
42773
+ * starting with it, a claim never returns a queued row, and a run that
42774
+ * keeps its signals here named itself the signal run through
42775
+ * `setSignalRun` before it started, which made the thread's queued rows
42776
+ * pending. Then, if the
42683
42777
  * thread's signal run is still `runId`, move its other taken rows and its
42684
42778
  * queued rows to pending and clear the signal run. A close that comes after another run
42685
42779
  * became the signal run deletes only what it consumed and leaves the other
@@ -51268,11 +51362,10 @@ function claimFirstReplyLink(requestContext, link) {
51268
51362
  /** Live posts of `reply_in_thread` calls whose text is still streaming in, by tool call id. */
51269
51363
  const STREAMS_KEY = "mastra__channelReplyStreams";
51270
51364
  function replyStreams(requestContext) {
51271
- let streams = requestContext.get(STREAMS_KEY);
51272
- if (!streams) {
51273
- streams = /* @__PURE__ */ new Map();
51274
- requestContext.set(STREAMS_KEY, streams);
51275
- }
51365
+ const stored = requestContext.get(STREAMS_KEY);
51366
+ if (stored instanceof Map) return stored;
51367
+ const streams = /* @__PURE__ */ new Map();
51368
+ requestContext.set(STREAMS_KEY, streams);
51276
51369
  return streams;
51277
51370
  }
51278
51371
  /**
@@ -51284,7 +51377,7 @@ function openReplyStream({ chatThread, logger }) {
51284
51377
  let sent = "";
51285
51378
  let closed = false;
51286
51379
  let wake;
51287
- let done;
51380
+ let posted;
51288
51381
  async function* chunks() {
51289
51382
  while (true) {
51290
51383
  while (queue.length > 0) yield queue.shift();
@@ -51295,12 +51388,16 @@ function openReplyStream({ chatThread, logger }) {
51295
51388
  const push = (text) => {
51296
51389
  if (!text) return;
51297
51390
  queue.push(text);
51298
- done ??= chatThread.post(chunks()).then(() => true, (error) => {
51391
+ posted ??= chatThread.post(chunks()).then((message) => message, (error) => {
51299
51392
  logger?.warn("[channels] streamed reply failed; posting it whole", { error });
51300
- return false;
51301
51393
  });
51302
51394
  wake?.();
51303
51395
  };
51396
+ const end = async () => {
51397
+ closed = true;
51398
+ wake?.();
51399
+ return posted;
51400
+ };
51304
51401
  return {
51305
51402
  update(text) {
51306
51403
  const visible = text.trimStart();
@@ -51310,16 +51407,20 @@ function openReplyStream({ chatThread, logger }) {
51310
51407
  },
51311
51408
  async finish(text, suffix) {
51312
51409
  if (text.startsWith(sent)) push(text.slice(sent.length));
51313
- if (!done) return false;
51410
+ if (!posted) return false;
51314
51411
  push(suffix);
51315
- closed = true;
51316
- wake?.();
51317
- return done;
51412
+ return !!await end();
51318
51413
  },
51319
51414
  async close() {
51320
- closed = true;
51321
- wake?.();
51322
- return done ?? false;
51415
+ return !!await end();
51416
+ },
51417
+ async discard() {
51418
+ const message = await end();
51419
+ try {
51420
+ await message?.delete();
51421
+ } catch (error) {
51422
+ logger?.warn("[channels] could not delete a streamed reply preview", { error });
51423
+ }
51323
51424
  }
51324
51425
  };
51325
51426
  }
@@ -51346,6 +51447,7 @@ var ChannelReplyStreamProcessor = class {
51346
51447
  if (!requestContext) return part;
51347
51448
  await this.#postUnsentAnswer(part, state, requestContext);
51348
51449
  const args = state.args ??= {};
51450
+ const called = state.called ??= {};
51349
51451
  if (part.type === "tool-call-input-streaming-start" && part.payload.toolName === "reply_in_thread") {
51350
51452
  const render = await this.#resolveRender(requestContext);
51351
51453
  if (render?.textDisplay !== "hidden" || !render.streaming?.enabled) return part;
@@ -51356,10 +51458,19 @@ var ChannelReplyStreamProcessor = class {
51356
51458
  if (text !== void 0) replyStreams(requestContext).get(part.payload.toolCallId)?.update(text);
51357
51459
  } else if ((part.type === "tool-error" || part.type === "tool-result") && part.payload.toolCallId in args) {
51358
51460
  delete args[part.payload.toolCallId];
51359
- await closeStream(requestContext, part.payload.toolCallId);
51360
- } else if (RUN_END.has(part.type)) {
51361
- for (const toolCallId of Object.keys(args)) await closeStream(requestContext, toolCallId);
51461
+ delete called[part.payload.toolCallId];
51462
+ await discardStream(requestContext, part.payload.toolCallId);
51463
+ } else if (part.type === "tool-call" && part.payload.toolCallId in args) called[part.payload.toolCallId] = true;
51464
+ else if (part.type === "step-finish") for (const toolCallId of Object.keys(called)) {
51465
+ delete args[toolCallId];
51466
+ delete called[toolCallId];
51467
+ await discardStream(requestContext, toolCallId);
51468
+ }
51469
+ else if (RUN_END.has(part.type)) {
51470
+ for (const toolCallId of Object.keys(args)) if (called[toolCallId]) await discardStream(requestContext, toolCallId);
51471
+ else await closeStream(requestContext, toolCallId);
51362
51472
  state.args = {};
51473
+ state.called = {};
51363
51474
  }
51364
51475
  return part;
51365
51476
  }
@@ -51367,8 +51478,7 @@ var ChannelReplyStreamProcessor = class {
51367
51478
  * Models sometimes end a turn with a plain-text answer and never call
51368
51479
  * `reply_in_thread`, so the thread never hears back. When a run finishes
51369
51480
  * without having replied, post the text written after its last tool call.
51370
- * A reply counts once it posts: a call that fails validation doesn't, unless
51371
- * its streamed post already left text in the thread.
51481
+ * A reply counts once it posts; a failed call's streamed preview is deleted, so it doesn't.
51372
51482
  */
51373
51483
  async #postUnsentAnswer(part, state, requestContext) {
51374
51484
  const answer = state.answer ??= {
@@ -51382,10 +51492,7 @@ var ChannelReplyStreamProcessor = class {
51382
51492
  answer.tail = "";
51383
51493
  if (part.payload.toolName === "reply_in_thread") answer.calls.add(part.payload.toolCallId);
51384
51494
  } else if (part.type === "tool-result" && answer.calls.has(part.payload.toolCallId)) answer.replied = true;
51385
- else if (part.type === "tool-error" && answer.calls.has(part.payload.toolCallId)) {
51386
- const stream = replyStreams(requestContext).get(part.payload.toolCallId);
51387
- if (stream && await stream.close()) answer.replied = true;
51388
- } else if (part.type === "tool-call-approval" || part.type === "tool-call-suspended") answer.held = true;
51495
+ else if (part.type === "tool-call-approval" || part.type === "tool-call-suspended") answer.held = true;
51389
51496
  else if (RUN_END.has(part.type)) {
51390
51497
  state.answer = void 0;
51391
51498
  const text = answer.tail.trim();
@@ -51420,6 +51527,13 @@ async function closeStream(requestContext, toolCallId) {
51420
51527
  streams.delete(toolCallId);
51421
51528
  await stream.close();
51422
51529
  }
51530
+ /** Deletes a streamed post that is only a preview of a reply posted, or failed, elsewhere. */
51531
+ async function discardStream(requestContext, toolCallId) {
51532
+ const streams = replyStreams(requestContext);
51533
+ const stream = streams.get(toolCallId);
51534
+ streams.delete(toolCallId);
51535
+ await stream?.discard();
51536
+ }
51423
51537
  const ESCAPES = {
51424
51538
  "\"": "\"",
51425
51539
  "\\": "\\",
@@ -51889,11 +52003,11 @@ var MastraStateAdapter = class {
51889
52003
  * otherwise reach the agent as just the notification fallback.
51890
52004
  */
51891
52005
  function layoutBlockTexts(raw) {
51892
- const blocks = isRecord$3(raw) ? raw.blocks : void 0;
52006
+ const blocks = isRecord$4(raw) ? raw.blocks : void 0;
51893
52007
  if (!Array.isArray(blocks)) return [];
51894
52008
  const texts = [];
51895
52009
  for (const block of blocks) {
51896
- if (!isRecord$3(block) || typeof block.type !== "string") continue;
52010
+ if (!isRecord$4(block) || typeof block.type !== "string") continue;
51897
52011
  const parts = blockParts(block).map((part) => part.trim()).filter(Boolean);
51898
52012
  if (parts.length) texts.push(parts);
51899
52013
  }
@@ -51906,13 +52020,13 @@ function blockParts(block) {
51906
52020
  const fields = Array.isArray(block.fields) ? block.fields.map(textObject) : [];
51907
52021
  return [textObject(block.text), ...fields];
51908
52022
  }
51909
- case "context": return [(Array.isArray(block.elements) ? block.elements : []).filter((el) => isRecord$3(el) && (el.type === "mrkdwn" || el.type === "plain_text")).map(textObject).filter(Boolean).join(" ")];
52023
+ case "context": return [(Array.isArray(block.elements) ? block.elements : []).filter((el) => isRecord$4(el) && (el.type === "mrkdwn" || el.type === "plain_text")).map(textObject).filter(Boolean).join(" ")];
51910
52024
  case "markdown": return [typeof block.text === "string" ? block.text : ""];
51911
52025
  default: return [];
51912
52026
  }
51913
52027
  }
51914
52028
  function textObject(value) {
51915
- if (!isRecord$3(value) || typeof value.text !== "string") return "";
52029
+ if (!isRecord$4(value) || typeof value.text !== "string") return "";
51916
52030
  const text = value.text.trim();
51917
52031
  return value.type === "mrkdwn" ? slackLinksToMarkdown(text) : text;
51918
52032
  }
@@ -51924,7 +52038,7 @@ function slackLinksToMarkdown(text) {
51924
52038
  return `[${label.replace(/[\\[\]]/g, "\\$&")}](${destination})`;
51925
52039
  });
51926
52040
  }
51927
- function isRecord$3(value) {
52041
+ function isRecord$4(value) {
51928
52042
  return typeof value === "object" && value !== null;
51929
52043
  }
51930
52044
  /**
@@ -55500,6 +55614,11 @@ async function knowledgeSubtree(storage, root) {
55500
55614
  */
55501
55615
  const MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES = 99;
55502
55616
  /**
55617
+ * Most linking pages one batched {@link repairKnowledgeLinks} re-resolves by default, in chunks of
55618
+ * {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES}; it hands back the rest for the caller to repair later.
55619
+ */
55620
+ const MAX_KNOWLEDGE_LINK_REPAIR_SOURCES = 1e3;
55621
+ /**
55503
55622
  * A link refresh that landed but stopped at {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES} linking pages
55504
55623
  * or {@link MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES} namesakes: the rest keep their links until they're
55505
55624
  * next written or `knowledge.reindexLinks()` runs.
@@ -55511,6 +55630,75 @@ var KnowledgeLinkRefreshIncompleteError = class extends Error {
55511
55630
  }
55512
55631
  };
55513
55632
  /**
55633
+ * The pages whose body links may resolve differently now that `affected` answer to what they do:
55634
+ * an unresolved link by a ref one of them answers to, a link resolved to one of them, and a link
55635
+ * resolved to a namesake by one of `names`. A namesake's other linkers name it by id or path, which
55636
+ * a name can't change, so they are left out (an importer re-creating a site's pages would otherwise
55637
+ * re-resolve every page linking to the old copies, on every flush). A store with
55638
+ * `listPageBodyLinkSourcesByRef` tells them apart from its link index; otherwise their bodies are
55639
+ * read once to tell, and a linker with no live page stays in: it keeps no links. `read` holds the
55640
+ * namesake linkers' pages read that way.
55641
+ */
55642
+ async function linkSources(storage, input, maxReads) {
55643
+ const own = new Set(input.affected.map((page) => page.id));
55644
+ const ids = new Set(await storage.listPageBodyLinkSources({
55645
+ refs: [...input.refs],
55646
+ toPageIds: [...own]
55647
+ }));
55648
+ const read = /* @__PURE__ */ new Map();
55649
+ const others = [...input.namesakes].filter((id) => !own.has(id));
55650
+ if (!others.length) return {
55651
+ ids: [...ids],
55652
+ read
55653
+ };
55654
+ const nameKeys = new Set([...input.names].map((name) => knowledgeLinkRefKey(name)));
55655
+ if (storage.listPageBodyLinkSourcesByRef) {
55656
+ if (!nameKeys.size) return {
55657
+ ids: [...ids],
55658
+ read
55659
+ };
55660
+ for (const id of await storage.listPageBodyLinkSourcesByRef({
55661
+ refs: [...nameKeys],
55662
+ toPageIds: others
55663
+ })) ids.add(id);
55664
+ return {
55665
+ ids: [...ids],
55666
+ read
55667
+ };
55668
+ }
55669
+ const candidates = (await storage.listPageBodyLinkSources({ toPageIds: others })).filter((id) => !ids.has(id));
55670
+ if (!candidates.length) return {
55671
+ ids: [...ids],
55672
+ read
55673
+ };
55674
+ if (candidates.length > maxReads - ids.size) {
55675
+ for (const id of candidates) ids.add(id);
55676
+ return {
55677
+ ids: [...ids],
55678
+ read
55679
+ };
55680
+ }
55681
+ for (let i = 0; i < candidates.length; i += 100) for (const page of await storage.getPages({
55682
+ ids: candidates.slice(i, i + 100),
55683
+ read: "all"
55684
+ })) read.set(page.id, page);
55685
+ for (const id of candidates) {
55686
+ const page = read.get(id);
55687
+ if (!page || page.deletedAt) {
55688
+ ids.add(id);
55689
+ continue;
55690
+ }
55691
+ for (const ref of knowledgeBodyLinkRefs(page.body).keys()) if (nameKeys.has(knowledgeLinkRefKey(ref))) {
55692
+ ids.add(id);
55693
+ break;
55694
+ }
55695
+ }
55696
+ return {
55697
+ ids: [...ids],
55698
+ read
55699
+ };
55700
+ }
55701
+ /**
55514
55702
  * Re-resolves the pages whose body links one of `pages` or names a ref one of them answers to now,
55515
55703
  * after they were created, renamed, moved, merged or deleted, in page id order up to
55516
55704
  * {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES}. With `withDescendants`, the pages' subtrees count too
@@ -55520,36 +55708,44 @@ var KnowledgeLinkRefreshIncompleteError = class extends Error {
55520
55708
  async function refreshKnowledgeLinksTo(storage, pages, options = {}) {
55521
55709
  const affected = options.withDescendants ? (await Promise.all(pages.map((page) => knowledgeSubtree(storage, page)))).flat() : pages;
55522
55710
  const refs = /* @__PURE__ */ new Set();
55523
- const targets = new Set(affected.map((page) => page.id));
55524
55711
  const names = /* @__PURE__ */ new Set();
55525
55712
  for (const page of affected) {
55526
55713
  for (const key of await pageRefKeys(storage, page)) refs.add(key);
55527
55714
  if (!page.deletedAt) names.add(page.name);
55528
55715
  }
55529
55716
  const crowded = [];
55717
+ const namesakes = /* @__PURE__ */ new Set();
55530
55718
  for (const name of names) {
55531
- const namesakes = await storage.findPagesByName({
55719
+ const found = await storage.findPagesByName({
55532
55720
  name,
55533
55721
  read: "all",
55534
55722
  limit: 100
55535
55723
  });
55536
- if (namesakes.length > MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES) crowded.push(`"${name}"`);
55537
- for (const namesake of namesakes.slice(0, MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES)) targets.add(namesake.id);
55724
+ if (found.length > MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES) crowded.push(`"${name}"`);
55725
+ for (const namesake of found.slice(0, MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES)) namesakes.add(namesake.id);
55538
55726
  }
55539
- const sources = (await storage.listPageBodyLinkSources({
55540
- refs: [...refs],
55541
- toPageIds: [...targets]
55542
- })).sort();
55727
+ const found = await linkSources(storage, {
55728
+ refs,
55729
+ affected,
55730
+ names,
55731
+ namesakes
55732
+ }, 100);
55733
+ const sources = found.ids.sort();
55543
55734
  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`);
55544
55735
  if (!sources.length) {
55545
55736
  if (crowded.length) throw crowdedError();
55546
55737
  return;
55547
55738
  }
55548
55739
  const batch = sources.slice(0, 100);
55549
- const live = new Map((await storage.getPages({
55550
- ids: batch,
55740
+ const toRead = batch.filter((id) => !found.read.has(id));
55741
+ const live = new Map(toRead.length ? (await storage.getPages({
55742
+ ids: toRead,
55551
55743
  read: "all"
55552
- })).map((page) => [page.id, page]));
55744
+ })).map((page) => [page.id, page]) : []);
55745
+ for (const id of batch) {
55746
+ const page = found.read.get(id);
55747
+ if (page) live.set(id, page);
55748
+ }
55553
55749
  const resolver = new BodyLinkResolver(storage);
55554
55750
  let done = 0;
55555
55751
  for (const id of batch) {
@@ -55616,8 +55812,8 @@ async function reindexKnowledgeLinks(storage) {
55616
55812
  }
55617
55813
  /**
55618
55814
  * A batched link repair that would stop at a cap the op-by-op refreshes enforce one write at a time
55619
- * (linking pages, namesakes, refs looked up, subtree size): the caller saves op by op instead, so the
55620
- * caps apply exactly as they do there.
55815
+ * (namesakes, subtree size): the caller saves op by op instead, so the caps apply exactly as they do
55816
+ * there.
55621
55817
  */
55622
55818
  var KnowledgeLinkRepairUnsupportedError = class extends Error {
55623
55819
  reason;
@@ -55633,13 +55829,19 @@ function canRepairKnowledgeLinksInBatch(storage) {
55633
55829
  }
55634
55830
  /**
55635
55831
  * Every {@link syncKnowledgePageBodyLinks} and {@link refreshKnowledgeLinksTo} of a flush, run once
55636
- * over the store as the flush left it, in a fixed number of statements: each page's links come out
55637
- * as they do when the calls run one after another after the writes. Throws
55638
- * {@link KnowledgeLinkRepairUnsupportedError}, having written nothing, when a cap could bite.
55639
- */
55640
- async function repairKnowledgeLinks(storage, repair) {
55832
+ * over the store as the flush left it, a few statements per chunk of up to
55833
+ * {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES} pages: each page's links come out as they do when the
55834
+ * calls run one after another after the writes. Linking pages past `limit` (default
55835
+ * {@link MAX_KNOWLEDGE_LINK_REPAIR_SOURCES}), in page id order, keep their links and come back in
55836
+ * `deferred`; the synced pages are always written. Throws {@link KnowledgeLinkRepairUnsupportedError},
55837
+ * having written nothing, when a namesake or subtree cap could bite.
55838
+ */
55839
+ async function repairKnowledgeLinks(storage, repair, options = {}) {
55641
55840
  const synced = new Map(repair.synced.map((page) => [page.id, page]));
55642
- if (!synced.size && !repair.refreshed.length) return;
55841
+ if (!synced.size && !repair.refreshed.length) return {
55842
+ rewritten: 0,
55843
+ deferred: []
55844
+ };
55643
55845
  const roots = repair.refreshed.filter((item) => item.withDescendants).map((item) => item.page.id);
55644
55846
  const subtrees = roots.length ? await storage.getPageSubtrees({
55645
55847
  rootIds: [...new Set(roots)],
@@ -55659,40 +55861,51 @@ async function repairKnowledgeLinks(storage, repair) {
55659
55861
  read: "all"
55660
55862
  }) : {};
55661
55863
  const refs = /* @__PURE__ */ new Set();
55662
- const targets = new Set(affected.map((page) => page.id));
55663
55864
  const names = /* @__PURE__ */ new Set();
55664
55865
  for (const page of affected) {
55665
55866
  const parents = !page.isScope && page.key && page.parentId ? chains[page.parentId] ?? [] : [];
55666
55867
  for (const key of refKeysOf(page, parents)) refs.add(key);
55667
55868
  if (!page.deletedAt) names.add(page.name);
55668
55869
  }
55870
+ const namesakes = /* @__PURE__ */ new Set();
55669
55871
  if (names.size) {
55670
- const namesakes = await storage.findPagesByNames({
55872
+ const byName = await storage.findPagesByNames({
55671
55873
  names: [...names],
55672
55874
  read: "all",
55673
55875
  limit: 100
55674
55876
  });
55675
- for (const found of Object.values(namesakes)) {
55877
+ for (const found of Object.values(byName)) {
55676
55878
  if (found.length > MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES) throw new KnowledgeLinkRepairUnsupportedError("a name past the namesake limit");
55677
- for (const namesake of found) targets.add(namesake.id);
55879
+ for (const namesake of found) namesakes.add(namesake.id);
55678
55880
  }
55679
55881
  }
55680
- const sources = affected.length ? await storage.listPageBodyLinkSources({
55681
- refs: [...refs],
55682
- toPageIds: [...targets]
55683
- }) : [];
55684
- if (sources.length > 100) throw new KnowledgeLinkRepairUnsupportedError("linking pages past the refresh limit");
55685
- const unread = sources.filter((id) => !synced.has(id));
55686
- const live = new Map((unread.length ? await storage.getPages({
55687
- ids: unread,
55882
+ const limit = options.limit ?? 1e3;
55883
+ const found = affected.length ? await linkSources(storage, {
55884
+ refs,
55885
+ affected,
55886
+ names,
55887
+ namesakes
55888
+ }, Math.max(0, limit)) : {
55889
+ ids: [],
55890
+ read: /* @__PURE__ */ new Map()
55891
+ };
55892
+ const unread = found.ids.filter((id) => !synced.has(id)).sort();
55893
+ const now = unread.slice(0, Math.max(0, limit));
55894
+ const deferred = unread.slice(now.length);
55895
+ const toRead = now.filter((id) => !found.read.has(id));
55896
+ const live = /* @__PURE__ */ new Map();
55897
+ for (let i = 0; i < toRead.length; i += 100) for (const page of await storage.getPages({
55898
+ ids: toRead.slice(i, i + 100),
55688
55899
  read: "all"
55689
- }) : []).map((page) => [page.id, page]));
55900
+ })) live.set(page.id, page);
55901
+ for (const id of now) {
55902
+ const page = found.read.get(id);
55903
+ if (page && !page.deletedAt) live.set(id, page);
55904
+ }
55690
55905
  const rewrite = /* @__PURE__ */ new Map();
55691
- for (const id of unread) rewrite.set(id, live.get(id) ?? null);
55692
55906
  for (const [id, page] of synced) rewrite.set(id, page);
55693
- const wanted = /* @__PURE__ */ new Map();
55694
- const lookups = [];
55695
- const refreshing = new Set(sources);
55907
+ for (const id of now) rewrite.set(id, live.get(id) ?? null);
55908
+ const chunks = [[]];
55696
55909
  let looked = 0;
55697
55910
  for (const [id, page] of rewrite) {
55698
55911
  const byKey = /* @__PURE__ */ new Map();
@@ -55707,27 +55920,42 @@ async function repairKnowledgeLinks(storage, repair) {
55707
55920
  });
55708
55921
  }
55709
55922
  const entries = [...byKey];
55710
- wanted.set(id, entries);
55711
- if (page) for (const [, { ref }] of entries) lookups.push({
55712
- ref,
55713
- home: page.scopeId
55714
- });
55715
- if (refreshing.has(id)) looked += new Set(entries.map(([, { ref }]) => ref)).size;
55923
+ let chunk = chunks.at(-1);
55924
+ if (chunk.length && (chunk.length >= 100 || looked + entries.length > 1e3)) {
55925
+ chunks.push(chunk = []);
55926
+ looked = 0;
55927
+ }
55928
+ chunk.push([id, entries]);
55929
+ looked += entries.length;
55716
55930
  }
55717
- if (looked >= 1e3) throw new KnowledgeLinkRepairUnsupportedError("refs looked up past the refresh limit");
55718
- const resolved = await resolveKnowledgeBodyLinks(storage, lookups);
55719
- await storage.applyPageWrites({ writes: [...wanted].map(([pageId, entries]) => {
55720
- const home = rewrite.get(pageId)?.scopeId;
55721
- return {
55722
- op: "replace-links",
55723
- pageId,
55724
- links: entries.map(([key, { ref, count }]) => ({
55725
- ref: key,
55726
- toPageId: home === void 0 ? null : resolved.get(`${home}\u0000${ref}`) ?? null,
55727
- count
55728
- }))
55729
- };
55730
- }) });
55931
+ for (const chunk of chunks) {
55932
+ if (!chunk.length) continue;
55933
+ const lookups = [];
55934
+ for (const [id, entries] of chunk) {
55935
+ const page = rewrite.get(id);
55936
+ if (page) for (const [, { ref }] of entries) lookups.push({
55937
+ ref,
55938
+ home: page.scopeId
55939
+ });
55940
+ }
55941
+ const resolved = await resolveKnowledgeBodyLinks(storage, lookups);
55942
+ await storage.applyPageWrites({ writes: chunk.map(([pageId, entries]) => {
55943
+ const home = rewrite.get(pageId)?.scopeId;
55944
+ return {
55945
+ op: "replace-links",
55946
+ pageId,
55947
+ links: entries.map(([key, { ref, count }]) => ({
55948
+ ref: key,
55949
+ toPageId: home === void 0 ? null : resolved.get(`${home}\u0000${ref}`) ?? null,
55950
+ count
55951
+ }))
55952
+ };
55953
+ }) });
55954
+ }
55955
+ return {
55956
+ rewritten: now.length,
55957
+ deferred
55958
+ };
55731
55959
  }
55732
55960
  /** What {@link BodyLinkResolver} answers for each `(home, ref)`, keyed `home\0ref`, in a fixed number of reads. */
55733
55961
  async function resolveKnowledgeBodyLinks(storage, lookups) {
@@ -57064,7 +57292,7 @@ function isBuffer(value) {
57064
57292
  /**
57065
57293
  * Checks whether a value is a non-null, non-array object.
57066
57294
  */
57067
- function isRecord$2(value) {
57295
+ function isRecord$3(value) {
57068
57296
  return value != null && typeof value === "object" && !Array.isArray(value);
57069
57297
  }
57070
57298
  /**
@@ -59058,7 +59286,7 @@ function parseSpeechStreamPart(text) {
59058
59286
  } catch {
59059
59287
  return;
59060
59288
  }
59061
- if (!isRecord$2(value)) return;
59289
+ if (!isRecord$3(value)) return;
59062
59290
  const part = value;
59063
59291
  switch (part.type) {
59064
59292
  case "stream-start": {
@@ -59069,10 +59297,10 @@ function parseSpeechStreamPart(text) {
59069
59297
  warnings
59070
59298
  } : void 0;
59071
59299
  }
59072
- case "audio": return isString$1(part.audio) && isAudioFormat(part.audioFormat) && isOptional$1(part.id, isString$1) && isOptional$1(part.providerMetadata, isRecord$2) ? part : void 0;
59073
- case "finish": return isOptional$1(part.usage, isUsage) && isOptional$1(part.providerMetadata, isRecord$2) ? part : void 0;
59300
+ 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;
59301
+ case "finish": return isOptional$1(part.usage, isUsage) && isOptional$1(part.providerMetadata, isRecord$3) ? part : void 0;
59074
59302
  case "response-metadata": {
59075
- if (!(isOptional$1(part.modelId, isString$1) && isOptional$1(part.headers, isRecord$2))) return;
59303
+ if (!(isOptional$1(part.modelId, isString$1) && isOptional$1(part.headers, isRecord$3))) return;
59076
59304
  const timestamp = part.timestamp;
59077
59305
  if (timestamp == null) return {
59078
59306
  ...part,
@@ -59103,10 +59331,10 @@ const knownWarningTypes = /* @__PURE__ */ new Set([
59103
59331
  "unsupported"
59104
59332
  ]);
59105
59333
  function isUnknownWarningType(value) {
59106
- return isRecord$2(value) && isString$1(value.type) && !knownWarningTypes.has(value.type);
59334
+ return isRecord$3(value) && isString$1(value.type) && !knownWarningTypes.has(value.type);
59107
59335
  }
59108
59336
  function isWarning$1(value) {
59109
- if (!isRecord$2(value)) return false;
59337
+ if (!isRecord$3(value)) return false;
59110
59338
  switch (value.type) {
59111
59339
  case "compatibility":
59112
59340
  case "unsupported": return isString$1(value.feature) && isOptional$1(value.details, isString$1);
@@ -59116,10 +59344,10 @@ function isWarning$1(value) {
59116
59344
  }
59117
59345
  }
59118
59346
  function isAudioFormat(value) {
59119
- return isRecord$2(value) && isString$1(value.type) && value.type.length > 0 && isOptional$1(value.rate, (rate) => typeof rate === "number" && Number.isFinite(rate) && rate > 0);
59347
+ return isRecord$3(value) && isString$1(value.type) && value.type.length > 0 && isOptional$1(value.rate, (rate) => typeof rate === "number" && Number.isFinite(rate) && rate > 0);
59120
59348
  }
59121
59349
  function isUsage(value) {
59122
- return isRecord$2(value) && [
59350
+ return isRecord$3(value) && [
59123
59351
  "inputCharacters",
59124
59352
  "inputTokens",
59125
59353
  "outputTokens"
@@ -59186,12 +59414,12 @@ function parseTranscriptionStreamPart(text) {
59186
59414
  const part = value;
59187
59415
  switch (part.type) {
59188
59416
  case "stream-start": return Array.isArray(part.warnings) && part.warnings.every(isWarning) ? part : void 0;
59189
- case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59190
- case "transcript-partial": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59191
- case "transcript-final": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.endSecond, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59192
- case "finish": return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.usage, isRecord$2) && isOptional(part.providerMetadata, isRecord$2) ? part : void 0;
59417
+ case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isRecord$3) ? part : void 0;
59418
+ 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;
59419
+ 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;
59420
+ case "finish": return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.usage, isRecord$3) && isOptional(part.providerMetadata, isRecord$3) ? part : void 0;
59193
59421
  case "response-metadata": {
59194
- if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isRecord$2))) return;
59422
+ if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isRecord$3))) return;
59195
59423
  const timestamp = part.timestamp;
59196
59424
  if (timestamp == null) return {
59197
59425
  ...part,
@@ -59219,10 +59447,10 @@ function isOptional(value, check) {
59219
59447
  return value === void 0 || check(value);
59220
59448
  }
59221
59449
  function isWarning(value) {
59222
- return isRecord$2(value) && isString(value.type);
59450
+ return isRecord$3(value) && isString(value.type);
59223
59451
  }
59224
59452
  function isSegment(value) {
59225
- return isRecord$2(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
59453
+ return isRecord$3(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
59226
59454
  }
59227
59455
  function withoutTrailingSlash(url) {
59228
59456
  return url?.replace(/\/$/, "");
@@ -72752,6 +72980,50 @@ async function runIdleLoop(agent, streamOptions, deps, firstTurn, streamForConti
72752
72980
  resourceId
72753
72981
  });
72754
72982
  }
72983
+ // src/loop/suspended-run-auto-resume.ts
72984
+ /**
72985
+ * The `autoResumeSuspendedTools` a suspended agentic-loop run executed its latest segment with: the value persisted
72986
+ * with its most recent suspension. A resume can override the run's setting, so a resume in another process (or after
72987
+ * a restart) that leaves the option out keeps the latest one, not the one the first parked tool call recorded.
72988
+ * (#30190)
72989
+ *
72990
+ * Each tool call that suspends persists the segment's value in its own suspend payload, with its `suspendedAt`.
72991
+ * Tool calls that suspend side by side keep one record each, under `__workflow_meta.foreachOutput` or as the step's
72992
+ * `output`. The step's own suspend payload mirrors only the first suspended call, so a step with per-call records is
72993
+ * read through those records. A per-call record is read through its own payload first: on the evented engine its
72994
+ * `output` can hold stale copies of its siblings' records from before it was resumed. A snapshot written before the
72995
+ * value was persisted has none, and this returns `undefined`.
72996
+ */
72997
+ function findLatestSuspendedAutoResume(snapshot) {
72998
+ let latest;
72999
+ /** Records the values persisted at or under `entry`; whether it found one. */
73000
+ const visit = (entry, isToolCall) => {
73001
+ if (!isRecord$2(entry) || entry.status !== "suspended") return false;
73002
+ const suspendPayload = isRecord$2(entry.suspendPayload) ? entry.suspendPayload : void 0;
73003
+ const value = suspendPayload?.__autoResumeSuspendedTools;
73004
+ const record = () => {
73005
+ if (typeof value !== "boolean") return false;
73006
+ const at = typeof entry.suspendedAt === "number" ? entry.suspendedAt : 0;
73007
+ if (!latest || at >= latest.at) latest = {
73008
+ at,
73009
+ value
73010
+ };
73011
+ return true;
73012
+ };
73013
+ if (isToolCall && record()) return true;
73014
+ const meta = isRecord$2(suspendPayload?.__workflow_meta) ? suspendPayload.__workflow_meta : void 0;
73015
+ const perCall = Array.isArray(meta?.foreachOutput) ? meta.foreachOutput : Array.isArray(entry.output) ? entry.output : void 0;
73016
+ let found = false;
73017
+ for (const call of perCall ?? []) found = visit(call, true) || found;
73018
+ return found || !isToolCall && record();
73019
+ };
73020
+ const context = isRecord$2(snapshot) && isRecord$2(snapshot.context) ? snapshot.context : void 0;
73021
+ for (const step of Object.values(context ?? {})) visit(step, false);
73022
+ return latest?.value;
73023
+ }
73024
+ function isRecord$2(value) {
73025
+ return typeof value === "object" && value !== null;
73026
+ }
72755
73027
  // src/tools/provider-tool-utils.ts
72756
73028
  /**
72757
73029
  * Find a provider-defined tool by its model-facing name.
@@ -81203,6 +81475,16 @@ async function processChunkThroughOutputProcessors(chunk, registryEntry, stepReq
81203
81475
  });
81204
81476
  }
81205
81477
  /**
81478
+ * The run's `autoResumeSuspendedTools` for its current segment, persisted with each suspension: a resume can override
81479
+ * the value the run started with, and a later resume in another process that leaves the option out reads the latest
81480
+ * one back from the snapshot. The resume carries its value on the segment's request context, which reaches a step on
81481
+ * any worker; this process's registry entry stands in when user code cleared it. (#30190)
81482
+ */
81483
+ function runAutoResumeSuspendPayload(carried, registryEntry, startOptions) {
81484
+ const value = carried ?? registryEntry?.autoResumeSuspendedTools ?? startOptions?.autoResumeSuspendedTools;
81485
+ return value === void 0 ? {} : { __autoResumeSuspendedTools: value };
81486
+ }
81487
+ /**
81206
81488
  * Create a durable tool call step.
81207
81489
  *
81208
81490
  * This step mirrors the base Agent's createToolCallStep pattern:
@@ -81816,7 +82098,8 @@ function createDurableToolCallStep() {
81816
82098
  type: "approval",
81817
82099
  toolCallId,
81818
82100
  toolName,
81819
- args
82101
+ args,
82102
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
81820
82103
  }, { resumeLabel: toolCallId });
81821
82104
  }
81822
82105
  const isResumableTool = toolName?.startsWith("agent-") || toolName?.startsWith("workflow-");
@@ -82041,7 +82324,8 @@ function createDurableToolCallStep() {
82041
82324
  toolName: approvalToolName,
82042
82325
  args: approvalArgs
82043
82326
  },
82044
- ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
82327
+ ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {},
82328
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
82045
82329
  }, { resumeLabel: toolCallId });
82046
82330
  }
82047
82331
  const suspendedEventData = {
@@ -82095,7 +82379,8 @@ function createDurableToolCallStep() {
82095
82379
  toolCallId,
82096
82380
  toolName,
82097
82381
  resumeLabel: suspendOptions?.resumeLabel,
82098
- ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {}
82382
+ ...delegatedRunId ? { suspendedToolRunId: delegatedRunId } : {},
82383
+ ...runAutoResumeSuspendPayload(segmentAutoResume(requestContext, runId), getRunRegistryEntry(runId, mastra), agentOptions)
82099
82384
  }, { resumeLabel: toolCallId });
82100
82385
  };
82101
82386
  const toolOptions = defineLazyWriter(toolOptionsWithoutWriter, () => new ToolStream({
@@ -84770,6 +85055,8 @@ var DefaultAgentExecutionEngine = class {
84770
85055
  * Close the stored signals of a parked run that was aborted. Call it before
84771
85056
  * the snapshot is deleted and before the abort terminal is published.
84772
85057
  * Returns nothing to wait for when this engine's runs never store signals.
85058
+ * Resolves `false` when the run was left open: its committed state could not
85059
+ * be determined yet, or the close did not commit.
84773
85060
  */
84774
85061
  closeParkedRunSignals(_runId) {}
84775
85062
  /**
@@ -84906,7 +85193,10 @@ var DefaultAgentExecutionEngine = class {
84906
85193
  logger: this.mastra.getLogger(),
84907
85194
  storage: this.mastra.getStorage()
84908
85195
  });
84909
- if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === "evented") this.mastra.__registerInternalWorkflow(this.#workflow, void 0, { distributed: true });
85196
+ if (this.resolveWorkflowEngine(options.workflowEngine, options.logger) === "evented") {
85197
+ this.mastra.__registerInternalWorkflow(this.#workflow, void 0, { distributed: true });
85198
+ warnProcessLocalServerCache(this.mastra);
85199
+ }
84910
85200
  }
84911
85201
  }
84912
85202
  return this.#workflow;
@@ -85207,17 +85497,17 @@ var EventedAgentExecutionEngine = class extends DefaultAgentExecutionEngine {
85207
85497
  workflowName: DurableStepIds.AGENTIC_LOOP,
85208
85498
  runId
85209
85499
  }).catch(() => null);
85210
- if (!snapshot) return;
85500
+ if (!snapshot) return false;
85211
85501
  const context = snapshot.context;
85212
- if (!context?.input?.signalsStored) return;
85502
+ if (!context?.input?.signalsStored) return true;
85213
85503
  const committed = await this.#parkedRunState(workflowsStore, snapshot);
85214
- if (!committed) return;
85215
- await closeStoredSignalRun({
85504
+ if (!committed) return false;
85505
+ return await closeStoredSignalRun({
85216
85506
  mastra: this.mastra,
85217
85507
  runId,
85218
85508
  input: context.input,
85219
85509
  state: committed.state
85220
- });
85510
+ }) ?? false;
85221
85511
  }
85222
85512
  /**
85223
85513
  * The latest committed workflow state of a parked run, or `undefined` when
@@ -85720,7 +86010,7 @@ async function prepareForDurableExecution(options) {
85720
86010
  });
85721
86011
  let tripwireData;
85722
86012
  if (inputProcessors.length > 0) try {
85723
- const { ProcessorRunner } = await import("./stream-D2rv1Ut1.js").then((n) => n.L);
86013
+ const { ProcessorRunner } = await import("./stream-BfSwqzPi.js").then((n) => n.L);
85724
86014
  await new ProcessorRunner({
85725
86015
  inputProcessors,
85726
86016
  outputProcessors,
@@ -94229,9 +94519,30 @@ var Agent = class Agent extends MastraBase {
94229
94519
  if (!this.__usesSharedRunLog()) return void 0;
94230
94520
  return this.#resolveExecutionEngine()?.closeParkedRunSignals(runId);
94231
94521
  }
94232
- /** @internal Close the stored signals of a parked run that an abort requested by another process releases here. */
94233
- __closeParkedRunSignals(runId) {
94234
- return this.#closeParkedRunSignals(runId);
94522
+ /**
94523
+ * @internal Close the stored signals of a parked run that an abort requested by another process releases here.
94524
+ * With `exclusiveOfResume`, the close holds the run's execution claim from its snapshot read through its commit, as
94525
+ * a resume segment does. A resume that starts meanwhile waits for it, instead of consuming a signal that the close,
94526
+ * working from the snapshot it read before, would then return to pending. Resolves `false` while another
94527
+ * execution holds the run.
94528
+ */
94529
+ __closeParkedRunSignals(runId, options) {
94530
+ if (!options?.exclusiveOfResume || !this.__usesSharedRunLog() || !this.#resolveExecutionEngine()) return this.#closeParkedRunSignals(runId);
94531
+ return this.#closeParkedRunSignalsExclusively(runId);
94532
+ }
94533
+ async #closeParkedRunSignalsExclusively(runId) {
94534
+ let executionFence;
94535
+ try {
94536
+ executionFence = await this.#claimExecution(runId, "acquire");
94537
+ } catch (error) {
94538
+ if (error instanceof MastraError && error.id === "DURABLE_AGENT_EXECUTION_CONFLICT") return false;
94539
+ throw error;
94540
+ }
94541
+ let closed = false;
94542
+ await executionFence.settle(async () => {
94543
+ closed = await this.#closeParkedRunSignals(runId) ?? false;
94544
+ });
94545
+ return closed;
94235
94546
  }
94236
94547
  async #cancelAndCloseParkedRun(runId) {
94237
94548
  if (!await this.executionEngine.cancelParkedRun(runId)) return false;
@@ -94623,7 +94934,12 @@ var Agent = class Agent extends MastraBase {
94623
94934
  }
94624
94935
  async resumeStream(resumeData, streamOptions) {
94625
94936
  if (this.#resolveExecutionEngine()) return this.#resumeDurableStream(resumeData, streamOptions);
94626
- return this.#resumeStream(resumeData, streamOptions, false);
94937
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(streamOptions?.runId ?? "", this.getPubSub());
94938
+ try {
94939
+ return await this.#resumeStream(resumeData, streamOptions, false);
94940
+ } finally {
94941
+ releaseResumeHold();
94942
+ }
94627
94943
  }
94628
94944
  async #resumeDurableStream(resumeData, streamOptions) {
94629
94945
  const runId = streamOptions?.runId;
@@ -94653,7 +94969,10 @@ var Agent = class Agent extends MastraBase {
94653
94969
  const actor = mergedStreamOptions.actor;
94654
94970
  delete loopStreamOptions.actor;
94655
94971
  if (mergedStreamOptions.untilIdle) {
94656
- const { untilIdle, ...rest } = mergedStreamOptions ?? {};
94972
+ const { untilIdle, ...rest } = {
94973
+ ...mergedStreamOptions,
94974
+ autoResumeSuspendedTools: streamOptions?.autoResumeSuspendedTools
94975
+ };
94657
94976
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
94658
94977
  return runResumeStreamUntilIdle(this, resumeData, {
94659
94978
  ...rest,
@@ -94674,6 +94993,8 @@ var Agent = class Agent extends MastraBase {
94674
94993
  const snapshotMemoryInfo = this.#getSnapshotMemoryInfo(existingSnapshot);
94675
94994
  const persistedReturnScorerData = streamOptions?.returnScorerData === void 0 ? this.#getSnapshotReturnScorerData(existingSnapshot) : void 0;
94676
94995
  if (persistedReturnScorerData !== void 0) mergedStreamOptions.returnScorerData = loopStreamOptions.returnScorerData = persistedReturnScorerData;
94996
+ const runAutoResume = streamOptions?.autoResumeSuspendedTools ?? findLatestSuspendedAutoResume(existingSnapshot);
94997
+ if (runAutoResume !== void 0) mergedStreamOptions.autoResumeSuspendedTools = loopStreamOptions.autoResumeSuspendedTools = runAutoResume;
94677
94998
  if (snapshotMemoryInfo?.threadId) {
94678
94999
  mergedStreamOptions.memory = {
94679
95000
  ...mergedStreamOptions.memory ?? {},
@@ -94780,7 +95101,10 @@ var Agent = class Agent extends MastraBase {
94780
95101
  text: "An unknown error occurred while streaming"
94781
95102
  });
94782
95103
  }
94783
- await agentThreadStreamRuntime.registerRun(this, result.result, preparedOptions, threadStreamPubSub);
95104
+ await agentThreadStreamRuntime.registerRun(this, result.result, {
95105
+ ...preparedOptions,
95106
+ autoResumeSuspendedTools: runAutoResume
95107
+ }, threadStreamPubSub);
94784
95108
  return result.result;
94785
95109
  } catch (error) {
94786
95110
  await resumeClaim.release();
@@ -94809,6 +95133,17 @@ var Agent = class Agent extends MastraBase {
94809
95133
  async resumeGenerate(...args) {
94810
95134
  if (this.#resolveExecutionEngine()) return this.#resumeDurableGenerate(args);
94811
95135
  const [resumeData, options] = args;
95136
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(options?.runId ?? "", this.getPubSub());
95137
+ let completed = false;
95138
+ try {
95139
+ const output = await this.#resumePlainGenerate(resumeData, options);
95140
+ completed = output.finishReason !== "suspended";
95141
+ return output;
95142
+ } finally {
95143
+ releaseResumeHold({ startQueuedTurn: completed });
95144
+ }
95145
+ }
95146
+ async #resumePlainGenerate(resumeData, options) {
94812
95147
  const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });
94813
95148
  const mergedOptions = deepMerge$1(withDefaultToolCallConcurrencyLimit(defaultOptions, options), withDefinedToolHooks(options) ?? {});
94814
95149
  validateModelTimeoutSettings(mergedOptions.modelSettings?.timeout);
@@ -94822,6 +95157,8 @@ var Agent = class Agent extends MastraBase {
94822
95157
  });
94823
95158
  const persistedReturnScorerData = options?.returnScorerData === void 0 ? this.#getSnapshotReturnScorerData(existingSnapshot) : void 0;
94824
95159
  if (persistedReturnScorerData !== void 0) mergedOptions.returnScorerData = loopOptions.returnScorerData = persistedReturnScorerData;
95160
+ const persistedAutoResume = options?.autoResumeSuspendedTools === void 0 ? findLatestSuspendedAutoResume(existingSnapshot) : void 0;
95161
+ if (persistedAutoResume !== void 0) mergedOptions.autoResumeSuspendedTools = loopOptions.autoResumeSuspendedTools = persistedAutoResume;
94825
95162
  const { options: scopedOptions, resolved: resolvedScopes } = await this.#resolveRunScopes(mergedOptions, {
94826
95163
  callScopes: options?.scopes,
94827
95164
  defaultScopes: defaultOptions?.scopes,
@@ -94955,7 +95292,12 @@ var Agent = class Agent extends MastraBase {
94955
95292
  runId: options.runId
94956
95293
  }
94957
95294
  });
94958
- return this.#resumeStream(void 0, options, true);
95295
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(options.runId, this.getPubSub());
95296
+ try {
95297
+ return await this.#resumeStream(void 0, options, true);
95298
+ } finally {
95299
+ releaseResumeHold();
95300
+ }
94959
95301
  }
94960
95302
  /**
94961
95303
  * Approves a pending tool call and resumes execution.
@@ -96196,10 +96538,11 @@ var Agent = class Agent extends MastraBase {
96196
96538
  if (!this.#unverifiedReaderFences.has(executionFence) && (registryEntry.executionFence?.ownsRunTopics() ?? true)) this.clearPubsubTopic(runId, registryEntry);
96197
96539
  }
96198
96540
  };
96541
+ let cleanupOutput;
96199
96542
  const runCleanup = createRunCleanup({
96200
96543
  scheduleTimer: (cleanup) => this.scheduleReaderCleanup(executionFence, cleanup),
96201
96544
  release: () => {
96202
- agentThreadStreamRuntime.closeRunContinuation(output, this.getPubSub());
96545
+ if (cleanupOutput) agentThreadStreamRuntime.closeRunContinuation(cleanupOutput, this.getPubSub());
96203
96546
  streamCleanup?.();
96204
96547
  cleanupOwnedRegistryState();
96205
96548
  }
@@ -96232,6 +96575,7 @@ var Agent = class Agent extends MastraBase {
96232
96575
  });
96233
96576
  const { output, cleanup: createdStreamCleanup, ready } = stream;
96234
96577
  streamCleanup = createdStreamCleanup;
96578
+ cleanupOutput = output;
96235
96579
  const recoveryPubsub = this.fenceRunPubSub(executionFence, abortController);
96236
96580
  const workflowExecution = executionFence.run(() => this.executionEngine.raceFenceLoss(ready, executionFence).then(async () => {
96237
96581
  const result = await this.executionEngine.restartRun(workflow, executionFence, recoveryPubsub, this.workflowEngine, this.logger, resourceId, requestContext, createObservabilityContext({ currentSpan: recoverAgentSpan }));
@@ -96948,12 +97292,15 @@ var Agent = class Agent extends MastraBase {
96948
97292
  });
96949
97293
  releaseResumeMarker = release;
96950
97294
  }
97295
+ const releaseResumeHold = agentThreadStreamRuntime.holdParkedRunForResume(runId, this.getPubSub());
96951
97296
  try {
96952
97297
  if (await this.#isRunCanceledInStorage(runId)) throw abortedRunError();
96953
97298
  return await this.#resumeRun(runId, resumeData, options, releaseResumeMarker);
96954
97299
  } catch (error) {
96955
97300
  releaseResumeMarker();
96956
97301
  throw error;
97302
+ } finally {
97303
+ releaseResumeHold();
96957
97304
  }
96958
97305
  }
96959
97306
  /**
@@ -96995,6 +97342,7 @@ var Agent = class Agent extends MastraBase {
96995
97342
  let entry = this.executionRunRegistry.get(runId);
96996
97343
  let rehydratedScopes;
96997
97344
  let coldSnapshot;
97345
+ let coldRunAutoResume;
96998
97346
  if (!entry) {
96999
97347
  const workflowsStore = await this.#mastra?.getStorage()?.getStore("workflows");
97000
97348
  const persisted = workflowsStore ? await this.executionEngine.loadPersistedRunSnapshot(workflowsStore, runId) : void 0;
@@ -97093,6 +97441,7 @@ var Agent = class Agent extends MastraBase {
97093
97441
  }
97094
97442
  });
97095
97443
  rehydratedScopes = persistedScopes;
97444
+ coldRunAutoResume = findLatestSuspendedAutoResume(snapshot) ?? workflowInput.options?.autoResumeSuspendedTools;
97096
97445
  const memory = threadId ? {
97097
97446
  ...options?.memory,
97098
97447
  thread: threadId,
@@ -97153,8 +97502,12 @@ var Agent = class Agent extends MastraBase {
97153
97502
  requestContextKeys
97154
97503
  };
97155
97504
  resumeRequestContext = resolvedOptions.requestContext ?? resumeRequestContext;
97505
+ const runAutoResume = options?.autoResumeSuspendedTools ?? (coldSnapshot ? coldRunAutoResume : entry.autoResumeSuspendedTools);
97156
97506
  if (resolvedOptions.untilIdle) {
97157
- const { untilIdle, ...rest } = resolvedOptions;
97507
+ const { untilIdle, ...rest } = {
97508
+ ...resolvedOptions,
97509
+ autoResumeSuspendedTools: runAutoResume
97510
+ };
97158
97511
  const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
97159
97512
  releaseResumeMarker();
97160
97513
  return runResumeDurableStreamUntilIdle({
@@ -97317,6 +97670,7 @@ var Agent = class Agent extends MastraBase {
97317
97670
  globalEntryForContext.requestContext = resumeRequestContext;
97318
97671
  globalEntryForContext.requestContextRebuilt = false;
97319
97672
  }
97673
+ for (const reg of /* @__PURE__ */ new Set([entry, globalEntryForContext])) if (reg && runAutoResume !== void 0) reg.autoResumeSuspendedTools = runAutoResume;
97320
97674
  } catch (error) {
97321
97675
  await executionFence.settle(async () => {});
97322
97676
  throw error;
@@ -97430,6 +97784,7 @@ var Agent = class Agent extends MastraBase {
97430
97784
  this.#mastra?.getLogger?.()?.warn?.(`[DurableAgent] Failed to open resume spans: ${error}`);
97431
97785
  }
97432
97786
  carrySegmentSpans(resumeRequestContext, runId, resumeSegment);
97787
+ if (runAutoResume !== void 0) carrySegmentAutoResume(resumeRequestContext, runId, runAutoResume);
97433
97788
  const resumeSegmentSpan = entry.resumeAgentSpan ?? entry.agentSpan;
97434
97789
  const closeOnSuspend = resolvedOptions.closeOnSuspend ?? false;
97435
97790
  const { output, cleanup: createdStreamCleanup, detach: detachResumeStream, fail: failResumeStream, waitForEventDelivery, ready } = createDurableAgentStream({
@@ -97551,7 +97906,8 @@ var Agent = class Agent extends MastraBase {
97551
97906
  workflowExecution.then(releaseResumeMarker, releaseResumeMarker);
97552
97907
  const resumeStreamOptions = {
97553
97908
  ...resolvedOptions,
97554
- runId
97909
+ runId,
97910
+ autoResumeSuspendedTools: runAutoResume
97555
97911
  };
97556
97912
  if (!agentThreadStreamRuntime.continueRun(this, output, resumeStreamOptions, this.getPubSub(), {
97557
97913
  generation: executionFence.generation,
@@ -102691,33 +103047,56 @@ async function processOutputStream({ collectedChunks = [], tools, messageId, mes
102691
103047
  toolResultTripwire
102692
103048
  };
102693
103049
  }
102694
- function executeStreamWithFallbackModels(models, logger, startIndex = 0, throwIfInterrupted) {
103050
+ /**
103051
+ * What the next step needs to stay on the model serving this generation. A resumed run
103052
+ * resolves its models again, and the list can come back in another order: the id finds the
103053
+ * model again when the caller named it, the first one included.
103054
+ */
103055
+ function carriedFallbackModel(models, index, triesEarlierEntries) {
103056
+ if (models.length < 2) return {};
103057
+ return {
103058
+ ...index > 0 ? { fallbackModelIndex: index } : {},
103059
+ fallbackModelId: models[index]?.id,
103060
+ ...triesEarlierEntries ? { fallbackModelTriesEarlierEntries: true } : {}
103061
+ };
103062
+ }
103063
+ function carriedFallbackModelIndex(models, carried) {
103064
+ const saved = carried.fallbackModelIndex ?? 0;
103065
+ if (models[saved]?.id === carried.fallbackModelId) return saved;
103066
+ const byId = models.findIndex((candidate) => candidate.id === carried.fallbackModelId);
103067
+ return byId >= 0 ? byId : carried.fallbackModelIndex || 0;
103068
+ }
103069
+ /**
103070
+ * True when a resumed run found its model by id at another position than the one it saved: the
103071
+ * list came back in another order, so the entries now ahead of that model were not tried yet.
103072
+ */
103073
+ function resumedInAnotherOrder(models, carried) {
103074
+ const saved = carried.fallbackModelIndex ?? 0;
103075
+ if (carried.fallbackModelId === void 0 || models[saved]?.id === carried.fallbackModelId) return false;
103076
+ return models.some((candidate) => candidate.id === carried.fallbackModelId);
103077
+ }
103078
+ function executeStreamWithFallbackModels(models, logger, startIndex = 0, throwIfInterrupted, tryEntriesBeforeStart = false) {
102695
103079
  return async (callback) => {
102696
- let index = startIndex;
103080
+ const order = [...models.slice(startIndex), ...tryEntriesBeforeStart ? models.slice(0, startIndex) : []];
102697
103081
  let finalResult;
102698
- let done = false;
102699
103082
  let lastError;
102700
- for (const modelConfig of models.slice(startIndex)) {
102701
- index++;
102702
- if (done) break;
102703
- try {
102704
- finalResult = await callback(modelConfig, index === models.length);
102705
- done = true;
102706
- } catch (err) {
102707
- throwIfInterrupted?.();
102708
- if (err instanceof TripWire) throw err;
102709
- if (isMastraTimeoutError(err) && err.timeoutType === "total") throw err;
102710
- lastError = err;
102711
- const nextModel = models[index];
102712
- if (nextModel) logger?.warn(`Model ${modelConfig.model.modelId} failed; falling back to ${nextModel.model.modelId}`, {
102713
- error: err,
102714
- modelId: modelConfig.model.modelId,
102715
- nextModelId: nextModel.model.modelId,
102716
- attempt: index,
102717
- totalModels: models.length
102718
- });
102719
- else logger?.error(`Error executing model ${modelConfig.model.modelId}`, err);
102720
- }
103083
+ for (const [attempt, modelConfig] of order.entries()) try {
103084
+ finalResult = await callback(modelConfig, attempt === order.length - 1);
103085
+ break;
103086
+ } catch (err) {
103087
+ throwIfInterrupted?.();
103088
+ if (err instanceof TripWire) throw err;
103089
+ if (isMastraTimeoutError(err) && err.timeoutType === "total") throw err;
103090
+ lastError = err;
103091
+ const nextModel = order[attempt + 1];
103092
+ if (nextModel) logger?.warn(`Model ${modelConfig.model.modelId} failed; falling back to ${nextModel.model.modelId}`, {
103093
+ error: err,
103094
+ modelId: modelConfig.model.modelId,
103095
+ nextModelId: nextModel.model.modelId,
103096
+ attempt: attempt + 1,
103097
+ totalModels: order.length
103098
+ });
103099
+ else logger?.error(`Error executing model ${modelConfig.model.modelId}`, err);
102721
103100
  }
102722
103101
  if (typeof finalResult === "undefined") {
102723
103102
  const fatalError = lastError ?? /* @__PURE__ */ new Error("Exhausted all fallback models without receiving a result.");
@@ -102984,7 +103363,8 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
102984
103363
  let warnings;
102985
103364
  let request;
102986
103365
  let rawResponse;
102987
- let activeFallbackModelIndex = inputData.fallbackModelIndex || 0;
103366
+ let activeFallbackModelIndex = carriedFallbackModelIndex(models, inputData);
103367
+ const triesEarlierEntries = inputData.fallbackModelTriesEarlierEntries === true || resumedInAnotherOrder(models, inputData);
102988
103368
  let executedStepModel;
102989
103369
  let terminalInputStepFailure;
102990
103370
  let materializeFailedAttempt;
@@ -102996,8 +103376,8 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
102996
103376
  logger
102997
103377
  });
102998
103378
  let settleRequest = () => {};
102999
- const execution = await executeStreamWithFallbackModels(models, logger, activeFallbackModelIndex, throwIfInterrupted)(async (modelConfig, isLastModel) => {
103000
- activeFallbackModelIndex = models.findIndex((candidate) => candidate.id === modelConfig.id);
103379
+ const execution = await executeStreamWithFallbackModels(models, logger, activeFallbackModelIndex, throwIfInterrupted, triesEarlierEntries)(async (modelConfig, isLastModel) => {
103380
+ activeFallbackModelIndex = models.indexOf(modelConfig);
103001
103381
  materializeFailedAttempt = void 0;
103002
103382
  settleRequest();
103003
103383
  settleRequest = startRunStep(options?.stepOwner ?? options?.abortSignal);
@@ -103871,7 +104251,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
103871
104251
  nonUser: []
103872
104252
  },
103873
104253
  processorRetryCount: inputData.processorRetryCount,
103874
- ...activeFallbackModelIndex > 0 ? { fallbackModelIndex: activeFallbackModelIndex } : {},
104254
+ ...carriedFallbackModel(models, activeFallbackModelIndex, triesEarlierEntries),
103875
104255
  ...inputData.skipUnavailableAttachments ? { skipUnavailableAttachments: true } : {}
103876
104256
  };
103877
104257
  if (!aborted) return result;
@@ -104084,7 +104464,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
104084
104464
  },
104085
104465
  messages,
104086
104466
  processorRetryCount: nextProcessorRetryCount,
104087
- ...activeFallbackModelIndex > 0 ? { fallbackModelIndex: activeFallbackModelIndex } : {},
104467
+ ...carriedFallbackModel(models, activeFallbackModelIndex, triesEarlierEntries),
104088
104468
  ...skipUnavailableAttachments ? { skipUnavailableAttachments } : {}
104089
104469
  };
104090
104470
  }
@@ -104266,7 +104646,6 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
104266
104646
  nonUser: messageList.get.response.aiV5.model()
104267
104647
  };
104268
104648
  const stepReason = shouldRetry ? "retry" : tripwireTriggered ? "tripwire" : hasErrored ? "error" : finishReason;
104269
- const nextFallbackModelIndex = shouldContinue ? activeFallbackModelIndex : 0;
104270
104649
  cleanupProviderToolSpans(!shouldContinue || shouldRetry);
104271
104650
  const nextProcessorRetryCount = shouldRetry ? currentProcessorRetryCount + 1 : 0;
104272
104651
  return {
@@ -104300,7 +104679,7 @@ function createLLMExecutionStep({ models, _internal, messageId: messageIdPassed,
104300
104679
  messages,
104301
104680
  processorRetryCount: nextProcessorRetryCount,
104302
104681
  processorRetryFeedback: retryFeedbackText,
104303
- ...nextFallbackModelIndex > 0 ? { fallbackModelIndex: nextFallbackModelIndex } : {}
104682
+ ...shouldContinue ? carriedFallbackModel(models, activeFallbackModelIndex, triesEarlierEntries) : {}
104304
104683
  };
104305
104684
  }
104306
104685
  });
@@ -104770,7 +105149,7 @@ function createLLMMappingStep({ models, _internal, ...rest }, llmExecutionStep)
104770
105149
  });
104771
105150
  }
104772
105151
  // src/loop/workflows/agentic-execution/tool-call-step.ts
104773
- function createToolCallStep({ tools, messageList, options, outputWriter, controller, runId, streamState, modelSpanTracker, _internal, logger, agentId, agentVersionId, resolvedScopes, returnScorerData, mastra, requireToolApproval: requireToolApprovalFromFactory, actor, mcp, agent }) {
105152
+ function createToolCallStep({ tools, messageList, options, outputWriter, controller, runId, streamState, modelSpanTracker, _internal, logger, agentId, agentVersionId, resolvedScopes, returnScorerData, autoResumeSuspendedTools, mastra, requireToolApproval: requireToolApprovalFromFactory, actor, mcp, agent }) {
104774
105153
  const memoryMessageRefs = new MemoryMessageRefs();
104775
105154
  return createStep$1({
104776
105155
  id: "toolCallStep",
@@ -105118,6 +105497,7 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105118
105497
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105119
105498
  __resolvedScopes: resolvedScopes ?? [],
105120
105499
  ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105500
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {},
105121
105501
  suspendedToolRunId: options.runId
105122
105502
  }, { resumeLabel: inputData.toolCallId });
105123
105503
  }
@@ -105158,6 +105538,7 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105158
105538
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105159
105539
  __resolvedScopes: resolvedScopes ?? [],
105160
105540
  ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105541
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {},
105161
105542
  toolCallId: inputData.toolCallId,
105162
105543
  toolName: inputData.toolName,
105163
105544
  resumeLabel: options?.resumeLabel,
@@ -105231,7 +105612,8 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
105231
105612
  __agentId: agentId,
105232
105613
  ...agentVersionId ? { __agentVersionId: agentVersionId } : {},
105233
105614
  __resolvedScopes: resolvedScopes ?? [],
105234
- ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {}
105615
+ ...returnScorerData !== void 0 ? { __returnScorerData: returnScorerData } : {},
105616
+ ...autoResumeSuspendedTools !== void 0 ? { __autoResumeSuspendedTools: autoResumeSuspendedTools } : {}
105235
105617
  }, { resumeLabel: inputData.toolCallId });
105236
105618
  }
105237
105619
  const clearedApproval = await removeToolMetadata({
@@ -106674,6 +107056,15 @@ const AGENT_THREAD_WAKE_OWNER_DISCOVERY_DEADLINE_MS = readPositiveIntEnv("MASTRA
106674
107056
  const AGENT_THREAD_CLAIM_LEASE_PREFIX = "thread-claim:";
106675
107057
  const AGENT_THREAD_OWNER_ACCEPTANCE_TIMEOUT_MS = 5e3;
106676
107058
  const UNSAVED_RUN_TRIM_DELAY_MS = 3e4;
107059
+ /** Waits before a parked storage-backed run tries again to let go of its thread for queued input (#30190). */
107060
+ const PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS = [
107061
+ 100,
107062
+ 200,
107063
+ 400,
107064
+ 800,
107065
+ 1600,
107066
+ 3200
107067
+ ];
106677
107068
  const AGENT_THREAD_PEER_DISCOVERY_TOPIC = "agent.thread-peer-discovery";
106678
107069
  const AGENT_THREAD_PEER_DISCOVERY_TIMEOUT_MS = 100;
106679
107070
  const THREAD_LEASE_OWNER_PREFIX = "mastra:thread-lease:";
@@ -106962,6 +107353,38 @@ function withThreadMemory(memory, resourceId, threadId) {
106962
107353
  thread: memory?.thread ?? threadId
106963
107354
  };
106964
107355
  }
107356
+ /**
107357
+ * The memory a resume that names no thread continues its run with: the run's thread and resource, the run's
107358
+ * settings, and on top of those every setting the resume passes itself (`options` merged key by key, so a resume
107359
+ * that sets only `lastMessages` or `readOnly` keeps the rest).
107360
+ */
107361
+ function resumeMemoryOnOwnThread({ run, resume, threadId, resourceId }) {
107362
+ const options = run?.options || resume?.options ? {
107363
+ ...run?.options,
107364
+ ...resume?.options
107365
+ } : void 0;
107366
+ return {
107367
+ ...run,
107368
+ ...resume,
107369
+ thread: run?.thread ?? threadId,
107370
+ resource: run?.resource ?? resourceId,
107371
+ ...options ? { options } : {}
107372
+ };
107373
+ }
107374
+ /**
107375
+ * The options a resume leaves on its run's record. Resume callers hand over the resume's own
107376
+ * `autoResumeSuspendedTools`, not the agent default merged in, so `undefined` means the resume left it out. The run
107377
+ * then keeps the value it started with: a run that turned auto-resume off keeps holding a queued message for an
107378
+ * explicit resume after it parks again. Callers that resume a run rebuilt from storage pass the run's persisted value
107379
+ * instead, since this process has no record of it. (#30190)
107380
+ */
107381
+ function keepRunAutoResume(resume, run) {
107382
+ if (resume.autoResumeSuspendedTools !== void 0 || run?.autoResumeSuspendedTools === void 0) return resume;
107383
+ return {
107384
+ ...resume,
107385
+ autoResumeSuspendedTools: run.autoResumeSuspendedTools
107386
+ };
107387
+ }
106965
107388
  const CANCELLED_BEFORE_RUN = "The accepted message was cancelled before it ran";
106966
107389
  function toPublicThreadPeer(peer) {
106967
107390
  const { unsubscribe: _unsubscribe, ...publicPeer } = peer;
@@ -106992,6 +107415,7 @@ function createRuntimeState() {
106992
107415
  suspensionMetadataByRunId: /* @__PURE__ */ new Map(),
106993
107416
  signalQueues: createActiveRunSignalQueues(),
106994
107417
  locallyQueuedSignalIdsByThread: /* @__PURE__ */ new Map(),
107418
+ startedSignalIdsByThread: /* @__PURE__ */ new Map(),
106995
107419
  pendingSignalListenersByRunId: /* @__PURE__ */ new Map(),
106996
107420
  lostRunsByThread: /* @__PURE__ */ new Map(),
106997
107421
  pendingIdleSignalsByThread: /* @__PURE__ */ new Map(),
@@ -107039,6 +107463,11 @@ var AgentThreadStreamRuntime = class {
107039
107463
  #stalledLeaseReads = /* @__PURE__ */ new WeakMap();
107040
107464
  /** Per run, the resolution of its signals store in flight (see `#signalsStoreOf`). */
107041
107465
  #storeResolutions = /* @__PURE__ */ new WeakMap();
107466
+ /**
107467
+ * Parked storage-backed runs letting go of their thread for queued input, one release at a time per run. `again`
107468
+ * records a trigger that arrived meanwhile, which checks the run again unless the release let go of the thread.
107469
+ */
107470
+ #releasingParkedStoredRuns = /* @__PURE__ */ new WeakMap();
107042
107471
  #threadlessRunFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(({ state, runId, token }) => {
107043
107472
  if (state.preparedRunsById.get(runId)?.finalizerToken !== token) return;
107044
107473
  this.#cleanupPreparedRun(state, runId);
@@ -107273,7 +107702,7 @@ var AgentThreadStreamRuntime = class {
107273
107702
  }
107274
107703
  const preparedRun = state.preparedRunsById.get(runId);
107275
107704
  const controller = preparedRun?.abortController ?? record.segmentAbortController;
107276
- const stepOwners = [controller?.signal, record.stepOwner?.()].filter((owner) => owner !== void 0);
107705
+ const stepOwners = this.#runStepOwners(state, record);
107277
107706
  const executing = !!preparedRun && record.lifecycle !== "suspended" || stepOwners.some((owner) => hasRunningRunStep(owner));
107278
107707
  const abortController = executing ? controller : void 0;
107279
107708
  if (!state.leaseRenewalTimers.has(runId) || record.registeredElsewhere || record.lateRetakeHandoff) {
@@ -107835,10 +108264,61 @@ var AgentThreadStreamRuntime = class {
107835
108264
  if (!active) return;
107836
108265
  const data = event.data;
107837
108266
  if (data?.type === "signal-enqueued") {
107838
- if (data.sourceId === this.#id && this.#isLocalSignalEcho(state, key, data.signal.id, data.runId) || subscription.admittedSignalIds.has(data.signal.id)) return;
108267
+ if (data.sourceId === this.#id && this.#isLocalSignalEcho(state, key, data.signal.id, data.runId) || subscription.admittedSignalIds.has(data.signal.id) || state.startedSignalIdsByThread.get(key)?.has(data.signal.id)) return;
107839
108268
  const answersTo = (runId) => state.threadKeysByRunId.get(runId) === key || subscription.ownedRunIds.has(runId) || state.storedSignals.endedRun(key)?.run.runId === runId;
107840
108269
  const runId = answersTo(data.runId) ? data.runId : forwardedSignalRunId(data.runId);
107841
108270
  if (!answersTo(runId)) return;
108271
+ if (state.threadRunsById.get(runId)?.registeredElsewhere) return;
108272
+ if (data.senderKeepsCopy && !state.activeThreadRunIds.has(key)) return;
108273
+ const activeRunId = data.queued ? state.activeThreadRunIds.get(key) : void 0;
108274
+ const live = activeRunId ? state.threadRunsById.get(activeRunId) : void 0;
108275
+ if (live && this.#isThreadBlockingRun(state, live)) {
108276
+ const signal = createSignal(data.signal);
108277
+ subscription.admittedSignalIds.add(signal.id);
108278
+ const admit = () => {
108279
+ if (this.#pendingUserMessageChunk(runId, signal, "pending")) this.#publish(pubsub, key, {
108280
+ type: "user-message-admitted",
108281
+ signalId: signal.id,
108282
+ admittedRunId: runId
108283
+ });
108284
+ };
108285
+ const admitStored = () => {
108286
+ this.#publishPendingUserMessage(pubsub, key, live.runId, signal, "queued");
108287
+ admit();
108288
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, live);
108289
+ };
108290
+ if (data.stored) return admitStored();
108291
+ const liveStore = this.#signalsStoreOf(live);
108292
+ if (!liveStore) {
108293
+ this.queueSignal(live.agent, signal, { runId: live.runId }, pubsub);
108294
+ return admit();
108295
+ }
108296
+ const to = {
108297
+ runId: live.runId,
108298
+ agent: live.agent
108299
+ };
108300
+ const written = this.#enqueueStoredSignal(state, key, liveStore, signal, to, true, true);
108301
+ return { settled: (async () => {
108302
+ try {
108303
+ if (await written === "run-closed") {
108304
+ if (subscription.cancelledSignalIds.has(signal.id)) return;
108305
+ this.#announceLeftoverSignal(state, pubsub, key, live, signal);
108306
+ if (live.runId !== runId) admit();
108307
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, live);
108308
+ return;
108309
+ }
108310
+ } catch (error) {
108311
+ if (!subscription.cancelledSignalIds.has(signal.id)) subscription.admittedSignalIds.delete(signal.id);
108312
+ live.agent.__getLogger?.()?.warn?.("Could not store a queued signal forwarded to a running run", {
108313
+ runId,
108314
+ signalId: signal.id,
108315
+ error
108316
+ });
108317
+ throw error;
108318
+ }
108319
+ admitStored();
108320
+ })() };
108321
+ }
107842
108322
  const ended = state.storedSignals.endedRun(key)?.run;
107843
108323
  const run = state.threadRunsById.get(runId) ?? (ended?.runId === runId ? ended : void 0);
107844
108324
  const store = run && this.#signalsStoreOf(run);
@@ -107854,15 +108334,34 @@ var AgentThreadStreamRuntime = class {
107854
108334
  subscription.admittedSignalIds.add(data.signal.id);
107855
108335
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
107856
108336
  this.#notifyPendingSignals(state, key, signal);
108337
+ const record = state.threadRunsById.get(runId);
108338
+ if (record) this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
107857
108339
  } else if (data?.type === "user-message-admitted") this.#settleForwardedIdleSignal(state, key, data.signalId, data.admittedRunId);
107858
108340
  else if (data?.type === "user-message-presentation") {
107859
108341
  const { chunk } = data;
107860
108342
  if (chunk.type === "data-user-message-pending" && chunk.data.metadata?.status === "pending") this.#settleForwardedIdleSignal(state, key, chunk.data.id, chunk.runId);
107861
108343
  } else if (data?.type === "signals-cancelled") {
107862
108344
  for (const id of data.signalIds) this.#settleForwardedIdleSignal(state, key, id);
107863
- for (const id of data.signalIds) subscription.admittedSignalIds.add(id);
108345
+ for (const id of data.signalIds) {
108346
+ subscription.admittedSignalIds.add(id);
108347
+ subscription.cancelledSignalIds.add(id);
108348
+ }
107864
108349
  this.#cancelPendingSignals(state, key, new Set(data.signalIds), pubsub, this.#threadSignalsStore(state, key));
107865
108350
  this.#notifyThreadEvents(state);
108351
+ } else if (data?.type === "queued-input-waiting") {
108352
+ const record = state.threadRunsById.get(data.runId);
108353
+ if (data.sourceId === this.#getSourceId() || !record || state.threadKeysByRunId.get(data.runId) !== key) return;
108354
+ record.queuedInputElsewhere = true;
108355
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
108356
+ } else if (data?.type === "parked-run-released") {
108357
+ if (data.sourceId === this.#getSourceId() || state.activeThreadRunIds.get(key) !== data.runId) return;
108358
+ const record = state.threadRunsById.get(data.runId);
108359
+ if (record && record.registeredElsewhere === void 0) return;
108360
+ if (state.activeThreadStreamIds.get(key) !== data.streamId && record?.registeredElsewhere !== data.streamId) return;
108361
+ state.activeThreadRunIds.delete(key);
108362
+ state.activeThreadStreamIds.delete(key);
108363
+ this.#notifyThreadEvents(state);
108364
+ await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
107866
108365
  } else if (data?.type === "run-abort-requested") {
107867
108366
  const ownsRun = () => active && (state.preparedRunsById.has(data.runId) || state.threadRunsById.has(data.runId)) && state.threadKeysByRunId.get(data.runId) === key && state.activeThreadRunIds.get(key) === data.runId && (data.streamId === void 0 || state.activeThreadStreamIds.get(key) === data.streamId);
107868
108367
  const clearPendingSignals = ownsRun() && data.clearPendingSignals && await this.#holdsThreadLeaseThroughRetake(resolvedPubSub, key, data.runId);
@@ -107884,7 +108383,8 @@ var AgentThreadStreamRuntime = class {
107884
108383
  return;
107885
108384
  }
107886
108385
  const current = state.threadRunsById.get(data.runId);
107887
- if (current?.registrationSeen) current.registeredElsewhere = true;
108386
+ if (current?.registrationSeen) current.registeredElsewhere = data.streamId;
108387
+ if (state.activeThreadRunIds.get(key) === data.runId) this.#requestParkedRunReleaseElsewhere(state, resolvedPubSub, key, { executionChanged: true });
107888
108388
  if (lost?.runId === data.runId && lost.registrationSeen) {
107889
108389
  state.lostRunsByThread.delete(key);
107890
108390
  this.#handOffQueuedSignals(state, resolvedPubSub, key, data.runId, lost.streamId);
@@ -107894,6 +108394,8 @@ var AgentThreadStreamRuntime = class {
107894
108394
  if (data.type === "run-discarded" && !(state.forwardedIdleLeaseChecks.has(key) && await this.#leaseMayStillName(resolvedPubSub, key, data.runId)) && this.#requeueUnadmittedForwards(state, key, data.runId)) await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
107895
108395
  } else if (data?.type === "run-completed" || data?.type === "run-failed") {
107896
108396
  this.#releaseRunSupersededBy(state, resolvedPubSub, key, subscription, data.runId);
108397
+ if (data.type === "run-completed" && data.status === "interrupted" && state.threadRunsById.get(data.runId)?.registeredElsewhere === data.streamId) return;
108398
+ this.#retireRunEndedElsewhere(state, resolvedPubSub, key, data.runId, data.streamId);
107897
108399
  const lostStreamId = subscription.successorRunIds.get(data.runId);
107898
108400
  if (lostStreamId !== void 0 && data.streamId === lostStreamId) return;
107899
108401
  if (lostStreamId === void 0 && data.type === "run-completed" && data.superseded && state.forwardedIdleLeaseChecks.has(key)) return;
@@ -107910,7 +108412,7 @@ var AgentThreadStreamRuntime = class {
107910
108412
  const onEvent = (event, ack) => {
107911
108413
  const type = event.data?.type;
107912
108414
  const awaitingForwards = state.forwardedIdleSignalsByThread.has(key);
107913
- if (type !== "signal-enqueued" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !((type === "user-message-presentation" || type === "user-message-admitted") && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
108415
+ if (type !== "signal-enqueued" && type !== "queued-input-waiting" && type !== "parked-run-released" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !((type === "user-message-presentation" || type === "user-message-admitted") && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
107914
108416
  subscription.references++;
107915
108417
  const handled = tail.then(() => handleEvent(event));
107916
108418
  tail = handled.then(() => {}, () => {});
@@ -107925,6 +108427,7 @@ var AgentThreadStreamRuntime = class {
107925
108427
  observers: 0,
107926
108428
  ownedRunIds,
107927
108429
  admittedSignalIds: /* @__PURE__ */ new Set(),
108430
+ cancelledSignalIds: /* @__PURE__ */ new Set(),
107928
108431
  successorRunIds: /* @__PURE__ */ new Map(),
107929
108432
  supersedingRunIds: /* @__PURE__ */ new Map(),
107930
108433
  unsubscribe: () => {
@@ -107947,7 +108450,9 @@ var AgentThreadStreamRuntime = class {
107947
108450
  if (!subscription || subscription.references > subscription.observers || this.#hasPendingThreadWork(state, key) || state.forwardedIdleSignalsByThread.has(key) || state.drainingPendingSignalsByThread.has(key) || state.drainingIdleSignalsByThread.has(key) || state.recentlyEndedStoredRunTimers.has(key) || [...state.threadKeysByRunId.values()].includes(key) || [...state.preparedRunsById.values()].some((run) => run.threadKey === key)) return;
107948
108451
  subscription.ownedRunIds.clear();
107949
108452
  subscription.admittedSignalIds.clear();
108453
+ subscription.cancelledSignalIds.clear();
107950
108454
  state.locallyQueuedSignalIdsByThread.delete(key);
108455
+ state.startedSignalIdsByThread.delete(key);
107951
108456
  if (subscription.observers) return;
107952
108457
  state.threadControlSubscriptions.delete(key);
107953
108458
  subscription.unsubscribe();
@@ -108642,11 +109147,16 @@ var AgentThreadStreamRuntime = class {
108642
109147
  runId,
108643
109148
  resourceId: owner.resourceId,
108644
109149
  threadId: owner.threadId,
108645
- streamOptions
109150
+ streamOptions,
109151
+ ...waitForIdle ? { queued: true } : {}
108646
109152
  });
108647
109153
  state.pendingIdleSignalsByThread.set(key, idleQueue);
108648
109154
  this.#publishPendingUserMessage(pubsub, key, activeRunId, signal, "queued");
108649
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
109155
+ if (activeRecord) {
109156
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
109157
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, activeRecord);
109158
+ }
109159
+ this.#requestParkedRunReleaseElsewhere(state, pubsub, key);
108650
109160
  settleMessageIdentity?.({ runId });
108651
109161
  return { runId };
108652
109162
  }
@@ -108738,25 +109248,18 @@ var AgentThreadStreamRuntime = class {
108738
109248
  action: "remote",
108739
109249
  runId: ownerRunId
108740
109250
  });
108741
- if (this.#mayStoreForRunHeldElsewhere(state, owner.agent, forwardedSignalRunId(ownerRunId))) {
108742
- if (!await this.#forwardSignal(state, pubsub, key, owner.agent, ownerRunId, signal).catch((error) => {
108743
- releaseMessageIdentity(getErrorFromUnknown(error));
108744
- throw error;
108745
- })) {
108746
- const error = `Thread ${describeThreadKey(key)} is held by run ${ownerRunId}, which ended before it took the message`;
108747
- releaseMessageIdentity(error);
108748
- return {
108749
- runId: ownerRunId,
108750
- error,
108751
- blocked: true
108752
- };
108753
- }
108754
- } else this.#publish(pubsub, key, {
108755
- type: "signal-enqueued",
108756
- runId: ownerRunId,
108757
- signal: this.#serializeSignal(signal),
108758
- sourceId: this.#getSourceId()
108759
- });
109251
+ if (!await this.#forwardToOwner(state, pubsub, key, owner.agent, ownerRunId, signal, waitForIdle).catch((error) => {
109252
+ releaseMessageIdentity(getErrorFromUnknown(error));
109253
+ throw error;
109254
+ })) {
109255
+ const error = `Thread ${describeThreadKey(key)} is held by run ${ownerRunId}, which ended before it took the message`;
109256
+ releaseMessageIdentity(error);
109257
+ return {
109258
+ runId: ownerRunId,
109259
+ error,
109260
+ blocked: true
109261
+ };
109262
+ }
108760
109263
  settleMessageIdentity?.({ runId: ownerRunId }, false);
108761
109264
  return { runId: ownerRunId };
108762
109265
  }
@@ -108847,11 +109350,13 @@ var AgentThreadStreamRuntime = class {
108847
109350
  else if (entry.leaseGone) ended.add(entry.runId);
108848
109351
  else entry.leaseGone = true;
108849
109352
  for (const runId of ended) if (this.#requeueUnadmittedForwards(state, key, runId)) {
109353
+ const executedElsewhere = state.threadRunsById.get(runId)?.registeredElsewhere;
109354
+ if (executedElsewhere !== void 0) this.#retireRunEndedElsewhere(state, this.#getPubSub(pubsub), key, runId, executedElsewhere);
108850
109355
  if (!state.threadRunsById.has(runId) && state.activeThreadStreamIds.get(key) === streamBeforeRead && state.activeThreadRunIds.get(key) === runId) {
108851
109356
  state.activeThreadRunIds.delete(key);
108852
109357
  state.activeThreadStreamIds.delete(key);
108853
109358
  }
108854
- await this.#drainPendingIdleSignals(state, pubsub, key, runId);
109359
+ await this.#drainPendingIdleSignals(state, pubsub, key, executedElsewhere === void 0 ? runId : void 0);
108855
109360
  }
108856
109361
  };
108857
109362
  const check = setInterval(() => {
@@ -108885,6 +109390,21 @@ var AgentThreadStreamRuntime = class {
108885
109390
  state.pendingIdleSignalsByThread.set(key, [...unadmitted.map(([, entry]) => entry.pendingIdle), ...state.pendingIdleSignalsByThread.get(key) ?? []]);
108886
109391
  return true;
108887
109392
  }
109393
+ /** Signals taken from this runtime's queues as a turn's input; `#forgetStartedSignals` undoes it on a requeue. */
109394
+ #recordStartedSignals(state, key, signals) {
109395
+ if (signals.length === 0) return;
109396
+ const ids = state.startedSignalIdsByThread.get(key) ?? /* @__PURE__ */ new Set();
109397
+ for (const signal of signals) {
109398
+ ids.delete(signal.id);
109399
+ ids.add(signal.id);
109400
+ }
109401
+ while (ids.size > MAX_LOCALLY_QUEUED_SIGNAL_IDS_PER_THREAD) ids.delete(ids.values().next().value);
109402
+ state.startedSignalIdsByThread.set(key, ids);
109403
+ }
109404
+ #forgetStartedSignals(state, key, signals) {
109405
+ const ids = state.startedSignalIdsByThread.get(key);
109406
+ for (const signal of signals) ids?.delete(signal.id);
109407
+ }
108888
109408
  #recordLocallyQueuedSignal(state, key, signalId) {
108889
109409
  const ids = state.locallyQueuedSignalIdsByThread.get(key) ?? /* @__PURE__ */ new Map();
108890
109410
  ids.delete(signalId);
@@ -109482,6 +110002,26 @@ var AgentThreadStreamRuntime = class {
109482
110002
  else this.#releaseThreadLease(pubsub, key, runId);
109483
110003
  return true;
109484
110004
  }
110005
+ /**
110006
+ * The execution another process registered for a run parked here has ended, so nothing executes the run any more.
110007
+ * The stale record stops routing the thread's input to it: input sent from now on runs as a new turn here, and
110008
+ * forwards that crossed the end are queued again by the terminal handler. (#30190)
110009
+ */
110010
+ #retireRunEndedElsewhere(state, pubsub, key, runId, streamId) {
110011
+ const record = state.threadRunsById.get(runId);
110012
+ if (!record || streamId === void 0 || record.registeredElsewhere !== streamId) return;
110013
+ record.lifecycle = "completed";
110014
+ this.#clearSuspendedRun(state, runId);
110015
+ this.#stopLeaseRenewal(pubsub, runId);
110016
+ state.threadRunsByStreamId.delete(record.streamId);
110017
+ state.threadRunsById.delete(runId);
110018
+ state.threadKeysByRunId.delete(runId);
110019
+ if (state.activeThreadRunIds.get(key) === runId) {
110020
+ state.activeThreadRunIds.delete(key);
110021
+ state.activeThreadStreamIds.delete(key);
110022
+ }
110023
+ this.#notifyThreadEvents(state);
110024
+ }
109485
110025
  /** Release the local run that `runId` superseded, if it superseded one. */
109486
110026
  #releaseRunSupersededBy(state, pubsub, key, subscription, runId) {
109487
110027
  const supersededRunId = subscription.supersedingRunIds.get(runId);
@@ -109498,12 +110038,162 @@ var AgentThreadStreamRuntime = class {
109498
110038
  */
109499
110039
  #releaseSupersededParkedRun(state, pubsub, key, runId) {
109500
110040
  const record = state.threadRunsById.get(runId);
109501
- if (!record || state.activeThreadRunIds.get(key) !== runId || !this.#isParkedRun(state, runId)) return;
110041
+ if (!record || state.activeThreadRunIds.get(key) !== runId || !this.#isParkedRun(state, runId)) return false;
109502
110042
  state.activeThreadRunIds.delete(key);
109503
110043
  if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key);
109504
110044
  this.#stopReadingDisplacedRun(state, runId);
109505
110045
  if (this.#hasPendingThreadWork(state, key)) this.#drainPendingSignals(state, pubsub, key, record);
109506
110046
  else this.#releaseThreadLease(pubsub, key, runId);
110047
+ return true;
110048
+ }
110049
+ /**
110050
+ * With `autoResumeSuspendedTools`, the next turn is what resumes a run parked on
110051
+ * a tool's suspend(): the model reads the user's answer from the new message.
110052
+ * The parked run itself never drains its queue, so a message queued onto it
110053
+ * would be reported delivered and never run (#30190). Once the run has parked,
110054
+ * queued messages start the next turn the way a stream call on the thread
110055
+ * would; the parked run keeps its record and stays resumable.
110056
+ *
110057
+ * Without auto-resume, the message keeps waiting for the explicit resume (an
110058
+ * AgentController prompt waits for its answer), and a run parked on a tool
110059
+ * approval keeps holding the thread: consent arrives through the approval APIs.
110060
+ *
110061
+ * Any input starts the turn: a sent message, a continuation, or work queued
110062
+ * for after the run (`queueMessage`, `queueSignal`, here, forwarded from
110063
+ * another process, or held by another process that sent `queued-input-waiting`). Queued work waits for the thread's run to end (#32093), and
110064
+ * a run parked with auto-resume on counts as ended: it waits for the next
110065
+ * message and nothing else, so queued work is that message. Every other run
110066
+ * still holds queued work: one in flight, one parked without auto-resume, and
110067
+ * one parked on an approval.
110068
+ */
110069
+ async #startQueuedTurnAfterParkedRun(state, pubsub, key, record) {
110070
+ const options = record.streamOptions;
110071
+ const storageBacked = this.#isStorageBacked(record);
110072
+ 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));
110073
+ if (!canStart()) return;
110074
+ if (!(options.autoResumeSuspendedTools ?? (await record.agent.getDefaultOptions({ requestContext: options.requestContext })).autoResumeSuspendedTools) || !canStart()) return;
110075
+ let owners = this.#runStepOwners(state, record);
110076
+ while (canStart() && owners.some((owner) => hasRunningRunStep(owner))) {
110077
+ await Promise.all(owners.map((owner) => new Promise((resolve) => whenRunStepsSettle(owner, resolve))));
110078
+ owners = this.#runStepOwners(state, record);
110079
+ }
110080
+ if (!canStart()) return;
110081
+ if (storageBacked ? await this.#releaseParkedStoredRunForInput(state, pubsub, key, record, canStart) : this.#releaseSupersededParkedRun(state, this.#getPubSub(pubsub), key, record.runId)) {
110082
+ record.queuedInputElsewhere = false;
110083
+ this.#publish(pubsub, key, {
110084
+ type: "parked-run-released",
110085
+ runId: record.runId,
110086
+ streamId: record.streamId,
110087
+ sourceId: this.#getSourceId()
110088
+ });
110089
+ }
110090
+ }
110091
+ /**
110092
+ * Whether the thread of a storage-backed run has input for it: a pending or queued row (`listPendingSignals` returns
110093
+ * both), or a continuation or queued work held here.
110094
+ */
110095
+ async #hasStoredRunInput(state, key, record) {
110096
+ if (this.#hasPendingThreadWork(state, key)) return true;
110097
+ const store = await this.#signalsStoreOf(record);
110098
+ if (!store) return false;
110099
+ return (await store.store.listPendingSignals({ threadId: store.threadId })).length > 0;
110100
+ }
110101
+ /**
110102
+ * `#releaseSupersededParkedRun` for a storage-backed run: its input waits in its store, so the thread is checked
110103
+ * as at the end of a run, which starts the next turn with the oldest pending row. The run's signals are closed first,
110104
+ * as when a parked run is aborted, so rows it took and never consumed are pending again for that turn. The run keeps
110105
+ * its record and stays resumable; a resume keeps the thread's signal run as it finds it. (#30190)
110106
+ */
110107
+ async #releaseParkedStoredRunForInput(state, pubsub, key, record, canStart) {
110108
+ const inFlight = this.#releasingParkedStoredRuns.get(record);
110109
+ if (inFlight) {
110110
+ inFlight.again = true;
110111
+ return false;
110112
+ }
110113
+ const release = { again: false };
110114
+ this.#releasingParkedStoredRuns.set(record, release);
110115
+ let released = false;
110116
+ const { runId } = record;
110117
+ const holds = () => canStart() && state.activeThreadRunIds.get(key) === runId && this.#isParkedRun(state, runId);
110118
+ try {
110119
+ for (let attempt = 0;; attempt++) {
110120
+ const outcome = await state.storedSignals.runWrite(key, async () => {
110121
+ if (!holds() || !(record.queuedInputElsewhere || await this.#hasStoredRunInput(state, key, record))) return "kept";
110122
+ if (!holds()) return "kept";
110123
+ if (await record.agent.__closeParkedRunSignals?.(runId, { exclusiveOfResume: true }) === false) return "retry";
110124
+ if (!holds()) return "kept";
110125
+ state.activeThreadRunIds.delete(key);
110126
+ if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key);
110127
+ this.#stopReadingDisplacedRun(state, runId);
110128
+ return "released";
110129
+ }).catch((error) => {
110130
+ this.#logParkedRunReleaseFailure(record, error);
110131
+ return "retry";
110132
+ });
110133
+ if (outcome === "kept") return false;
110134
+ if (outcome === "released") {
110135
+ released = true;
110136
+ break;
110137
+ }
110138
+ if (attempt >= PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS.length) {
110139
+ this.#logParkedRunReleaseFailure(record, /* @__PURE__ */ new Error("The parked run kept the thread after every retry"));
110140
+ return false;
110141
+ }
110142
+ await new Promise((resolve) => setTimeout(resolve, PARKED_STORED_RUN_RELEASE_RETRY_DELAYS_MS[attempt]));
110143
+ }
110144
+ } finally {
110145
+ this.#releasingParkedStoredRuns.delete(record);
110146
+ if (release.again && !released) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
110147
+ }
110148
+ const queued = this.#hasPendingThreadWork(state, key);
110149
+ if (!queued) this.#releaseEndedStoredRun(state, pubsub, key, record);
110150
+ this.#drainPendingSignals(state, pubsub, key, record, { freshLease: !queued });
110151
+ return true;
110152
+ }
110153
+ /**
110154
+ * Holds a parked run for a resume that is setting up, so input queued meanwhile stays the resumed run's next model
110155
+ * input, as it was before parked runs were released for queued input, instead of starting a turn beside the resumed
110156
+ * tool. The returned function ends the hold; if the run is still parked then, for example because the resume
110157
+ * failed, queued input starts the next turn, unless `startQueuedTurn` is false: a caller whose resume this record
110158
+ * doesn't follow, and that left the run parked again, marks the record so queued input keeps waiting. (#30190)
110159
+ */
110160
+ holdParkedRunForResume(runId, pubsub) {
110161
+ const state = this.#getState(pubsub);
110162
+ const record = state.threadRunsById.get(runId);
110163
+ if (!record) return () => {};
110164
+ record.resumeHolds = (record.resumeHolds ?? 0) + 1;
110165
+ let held = true;
110166
+ return ({ startQueuedTurn = true } = {}) => {
110167
+ if (!held) return;
110168
+ held = false;
110169
+ record.resumeHolds = (record.resumeHolds ?? 1) - 1;
110170
+ if (!startQueuedTurn) record.resumedUntracked = true;
110171
+ if (record.resumeHolds > 0 || !startQueuedTurn) return;
110172
+ const key = this.#threadKey(record.resourceId, record.threadId);
110173
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110174
+ };
110175
+ }
110176
+ #startQueuedTurnAfterParkedRunLater(state, pubsub, key, record) {
110177
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110178
+ }
110179
+ /**
110180
+ * The message that triggered the release was already answered `deliver`, so a failure here would otherwise
110181
+ * leave it queued on the parked run with no trace.
110182
+ */
110183
+ #logParkedRunReleaseFailure(record, error) {
110184
+ record.agent.__getLogger?.()?.error("Could not start the queued turn for a run parked on a suspended tool", {
110185
+ runId: record.runId,
110186
+ threadId: record.threadId,
110187
+ resourceId: record.resourceId,
110188
+ error
110189
+ });
110190
+ }
110191
+ /**
110192
+ * The objects the steps of a run register under while they run: the abort signal of its prepared run or current
110193
+ * segment, and a durable run's registry entry.
110194
+ */
110195
+ #runStepOwners(state, record) {
110196
+ return [(state.preparedRunsById.get(record.runId)?.abortController ?? record.segmentAbortController)?.signal, record.stepOwner?.()].filter((owner) => owner !== void 0);
109507
110197
  }
109508
110198
  /**
109509
110199
  * A parked run no longer holds its thread, so its answer resumes it on a new
@@ -109701,6 +110391,7 @@ var AgentThreadStreamRuntime = class {
109701
110391
  state.suspensionMetadataByRunId.clear();
109702
110392
  state.signalQueues.clear();
109703
110393
  state.locallyQueuedSignalIdsByThread.clear();
110394
+ state.startedSignalIdsByThread.clear();
109704
110395
  state.lostRunsByThread.clear();
109705
110396
  state.pendingIdleSignalsByThread.clear();
109706
110397
  state.forwardedIdleSignalsByThread.clear();
@@ -109771,11 +110462,43 @@ var AgentThreadStreamRuntime = class {
109771
110462
  /**
109772
110463
  * Queues a signal for in-loop draining by a same-agent run that is already in
109773
110464
  * flight here, so it becomes that run's next model input instead of waiting for
109774
- * the run to finish.
110465
+ * the run to finish. If the run is parked on a suspension that auto-resume
110466
+ * answers, the signal starts the next turn instead.
109775
110467
  */
109776
110468
  #queueForActiveRun(state, pubsub, key, record, signal) {
109777
- state.signalQueues.enqueue("pending", key, signal);
109778
110469
  this.#recordLocallyQueuedSignal(state, key, signal.id);
110470
+ if (record.registeredElsewhere) {
110471
+ const senderKeepsCopy = !!this.#pendingUserMessageChunk(record.runId, signal, "pending");
110472
+ if (senderKeepsCopy) {
110473
+ const forwarded = state.forwardedIdleSignalsByThread.get(key) ?? /* @__PURE__ */ new Map();
110474
+ forwarded.set(signal.id, {
110475
+ pendingIdle: {
110476
+ agent: record.agent,
110477
+ signal,
110478
+ runId: globalThis.crypto.randomUUID(),
110479
+ resourceId: record.resourceId ?? "",
110480
+ threadId: record.threadId,
110481
+ streamOptions: {
110482
+ ...record.streamOptions,
110483
+ abortSignal: void 0
110484
+ }
110485
+ },
110486
+ runId: record.runId
110487
+ });
110488
+ state.forwardedIdleSignalsByThread.set(key, forwarded);
110489
+ this.#ensureThreadControlSubscription(state, pubsub, key);
110490
+ this.#watchForwardedIdleLease(state, pubsub, key);
110491
+ }
110492
+ this.#publish(pubsub, key, {
110493
+ type: "signal-enqueued",
110494
+ runId: record.runId,
110495
+ signal: this.#serializeSignal(signal),
110496
+ sourceId: this.#getSourceId(),
110497
+ ...senderKeepsCopy ? { senderKeepsCopy } : {}
110498
+ });
110499
+ return;
110500
+ }
110501
+ state.signalQueues.enqueue("pending", key, signal);
109779
110502
  this.#publishPendingUserMessage(pubsub, key, record.runId, signal, "pending");
109780
110503
  this.#notifyPendingSignals(state, key, signal);
109781
110504
  this.#publish(pubsub, key, {
@@ -109785,6 +110508,7 @@ var AgentThreadStreamRuntime = class {
109785
110508
  sourceId: this.#getSourceId()
109786
110509
  });
109787
110510
  this.#watchThreadRunCompletion(state, pubsub, key, record);
110511
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109788
110512
  }
109789
110513
  /**
109790
110514
  * `#queueForActiveRun` for a run that keeps its signals in storage. Resolves
@@ -109796,13 +110520,14 @@ var AgentThreadStreamRuntime = class {
109796
110520
  this.#recordLocallyQueuedSignal(state, key, signal.id);
109797
110521
  let written;
109798
110522
  try {
109799
- written = await this.#enqueueStoredSignal(state, key, store, signal, record);
110523
+ written = await this.#enqueueStoredSignal(state, key, store, signal, record, false, true);
109800
110524
  } catch (error) {
109801
110525
  this.#forgetLocallyQueuedSignal(state, key, signal.id);
109802
110526
  throw error;
109803
110527
  }
109804
110528
  if (written === "run-closed") {
109805
- await this.#storeLeftoverSignal(state, pubsub, key, record, signal, store);
110529
+ this.#announceLeftoverSignal(state, pubsub, key, record, signal);
110530
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109806
110531
  return;
109807
110532
  }
109808
110533
  this.#publishSignalAvailable(record.agent, record.runId, signal.id);
@@ -109816,6 +110541,7 @@ var AgentThreadStreamRuntime = class {
109816
110541
  stored: true
109817
110542
  });
109818
110543
  this.#watchThreadRunCompletion(state, pubsub, key, record);
110544
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
109819
110545
  }
109820
110546
  /**
109821
110547
  * `signal-enqueued` for a run this runtime holds that keeps its signals in
@@ -109829,12 +110555,16 @@ var AgentThreadStreamRuntime = class {
109829
110555
  const signal = createSignal(data.signal);
109830
110556
  if (!data.stored) {
109831
110557
  try {
109832
- if (await this.#enqueueStoredSignal(state, key, store, signal, run) === "run-closed") {
109833
- await this.#storeLeftoverSignal(state, pubsub, key, run, signal, store);
110558
+ if (await this.#enqueueStoredSignal(state, key, store, signal, run, false, true) === "run-closed") {
110559
+ if (!subscription.cancelledSignalIds.has(signal.id)) {
110560
+ this.#announceLeftoverSignal(state, pubsub, key, run, signal);
110561
+ const parked = state.threadRunsById.get(runId);
110562
+ if (parked) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, parked);
110563
+ }
109834
110564
  return;
109835
110565
  }
109836
110566
  } catch (error) {
109837
- subscription.admittedSignalIds.delete(data.signal.id);
110567
+ if (!subscription.cancelledSignalIds.has(data.signal.id)) subscription.admittedSignalIds.delete(data.signal.id);
109838
110568
  run.agent.__getLogger?.()?.warn?.("Could not store a signal forwarded to a running run", {
109839
110569
  runId,
109840
110570
  signalId: signal.id,
@@ -109851,7 +110581,9 @@ var AgentThreadStreamRuntime = class {
109851
110581
  });
109852
110582
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
109853
110583
  this.#notifyPendingSignals(state, key, signal, runId);
109854
- if (!state.threadRunsById.has(runId)) this.#drainPendingSignals(state, pubsub, key, run, { freshLease: true });
110584
+ const record = state.threadRunsById.get(runId);
110585
+ if (record) this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, record);
110586
+ else this.#drainPendingSignals(state, pubsub, key, run, { freshLease: true });
109855
110587
  }
109856
110588
  /**
109857
110589
  * Move the signals this runtime queued for a run that is only reserved into
@@ -109875,10 +110607,8 @@ var AgentThreadStreamRuntime = class {
109875
110607
  return this.#enqueueStoredSignal(state, key, store, signal, {
109876
110608
  runId,
109877
110609
  agent
109878
- }).then((written) => {
109879
- if (written !== "run-closed") return;
109880
- leftForNextRun = true;
109881
- return this.#enqueueStoredSignal(state, key, store, signal);
110610
+ }, false, true).then((written) => {
110611
+ if (written === "run-closed") leftForNextRun = true;
109882
110612
  }).then(() => waiter?.resolve(), (error) => {
109883
110613
  if (waiter) {
109884
110614
  this.#forgetLocallyQueuedSignal(state, key, signal.id);
@@ -110019,17 +110749,12 @@ var AgentThreadStreamRuntime = class {
110019
110749
  return this.#getState(pubsub).storedSignals.writesSettled(this.#threadKey(store.resourceId, store.threadId));
110020
110750
  }
110021
110751
  /**
110022
- * Keep a signal whose run closed before it was stored, in the process that
110023
- * started that run: as a pending row of the thread, then run the end-of-run
110024
- * check again, since the run's own check may have found nothing.
110752
+ * After a signal whose run closed first was kept as a pending row of the
110753
+ * thread (`#enqueueStoredSignal` with `keepWhenClosed`), in the process that
110754
+ * started that run: present it, then run the end-of-run check again, since
110755
+ * the run's own check may have found nothing.
110025
110756
  */
110026
- async #storeLeftoverSignal(state, pubsub, key, endedRun, signal, store) {
110027
- try {
110028
- await this.#enqueueStoredSignal(state, key, store, signal);
110029
- } catch (error) {
110030
- this.#forgetLocallyQueuedSignal(state, key, signal.id);
110031
- throw error;
110032
- }
110757
+ #announceLeftoverSignal(state, pubsub, key, endedRun, signal) {
110033
110758
  this.#publishPendingUserMessage(pubsub, key, endedRun.runId, signal, "pending");
110034
110759
  this.#drainPendingSignals(state, pubsub, key, endedRun, { freshLease: true });
110035
110760
  }
@@ -110040,15 +110765,15 @@ var AgentThreadStreamRuntime = class {
110040
110765
  * when the event arrives. Returns `false` when the store reports that run
110041
110766
  * closed.
110042
110767
  */
110043
- async #forwardSignal(state, pubsub, key, agent, runId, signal) {
110768
+ async #forwardSignal(state, pubsub, key, agent, runId, signal, queued = false) {
110044
110769
  const target = forwardedSignalRunId(runId);
110045
110770
  const store = await this.#runSignalsStore(state, agent, target, key);
110046
110771
  if (store) {
110047
110772
  if (await this.#enqueueStoredSignal(state, key, store, signal, {
110048
110773
  runId: target,
110049
110774
  agent
110050
- }) === "run-closed") return false;
110051
- this.#publishSignalAvailable(agent, target, signal.id);
110775
+ }, queued) === "run-closed") return false;
110776
+ if (!queued) this.#publishSignalAvailable(agent, target, signal.id);
110052
110777
  this.#recordLocallyQueuedSignal(state, key, signal.id);
110053
110778
  state.locallyQueuedSignalIdsByThread.get(key)?.set(signal.id, target);
110054
110779
  }
@@ -110057,8 +110782,11 @@ var AgentThreadStreamRuntime = class {
110057
110782
  runId,
110058
110783
  signal: this.#serializeSignal(signal),
110059
110784
  sourceId: this.#getSourceId(),
110060
- ...store ? { stored: true } : {}
110061
- }).catch(() => {});
110785
+ ...store ? { stored: true } : {},
110786
+ ...queued ? { queued: true } : {}
110787
+ }).catch((error) => {
110788
+ if (queued && !store) throw error;
110789
+ });
110062
110790
  return true;
110063
110791
  }
110064
110792
  /**
@@ -110073,6 +110801,26 @@ var AgentThreadStreamRuntime = class {
110073
110801
  return state.remoteAgentIdsByRunId.get(runId) === agent.id && state.storedSignals.isRemoteRunStored(runId) && maySignalsBeStored(agent) && agent.__hasFixedMemory?.() === true;
110074
110802
  }
110075
110803
  /**
110804
+ * Hand `signal` to `ownerRunId`, a run another process holds. Queued input must wait for that run to end, so it is
110805
+ * never a row the run would claim: for a storage-backed run it is stored as a queued row, otherwise it travels as a
110806
+ * marked event its holder queues, and a failed publish of that event rejects. Other input is stored for a
110807
+ * storage-backed run and published otherwise, ignoring publish failure. Answers false only when the storage-backed
110808
+ * run ended before it took the row.
110809
+ */
110810
+ async #forwardToOwner(state, pubsub, key, agent, ownerRunId, signal, queued) {
110811
+ const target = forwardedSignalRunId(ownerRunId);
110812
+ if (this.#mayStoreForRunHeldElsewhere(state, agent, target)) return this.#forwardSignal(state, pubsub, key, agent, ownerRunId, signal, queued);
110813
+ const published = this.#publishAndWait(pubsub, key, {
110814
+ type: "signal-enqueued",
110815
+ runId: ownerRunId,
110816
+ signal: this.#serializeSignal(signal),
110817
+ sourceId: this.#getSourceId(),
110818
+ ...queued ? { queued: true } : {}
110819
+ });
110820
+ await (queued ? published : published.catch(() => {}));
110821
+ return true;
110822
+ }
110823
+ /**
110076
110824
  * Where `runId` keeps its signals as far as this process knows: the
110077
110825
  * decision on its record here (none for a run only reserved here), or, for
110078
110826
  * a run another process holds that passes `#mayStoreForRunHeldElsewhere`,
@@ -110114,17 +110862,23 @@ var AgentThreadStreamRuntime = class {
110114
110862
  /**
110115
110863
  * Insert a signal as a pending row of the thread, behind this process's
110116
110864
  * earlier writes for it. With `to` the row is only inserted while that run
110117
- * is the thread's signal run, and a thread without a row rejects.
110865
+ * is the thread's signal run, and a thread without a row rejects. With
110866
+ * `keepWhenClosed`, a run that closed first leaves the signal as a pending
110867
+ * row for the thread's next turn, inserted in the same write: a cancel
110868
+ * handled after this call is ordered after that insert too, so it deletes
110869
+ * the row. The answer is still `run-closed`.
110118
110870
  */
110119
- #enqueueStoredSignal(state, key, storeRef, signal, to) {
110871
+ #enqueueStoredSignal(state, key, storeRef, signal, to, queued = false, keepWhenClosed = false) {
110120
110872
  return state.storedSignals.runWrite(key, async () => {
110121
110873
  const store = storeRef instanceof Promise ? await storeRef : storeRef;
110122
110874
  if (!store) throw new Error(`The memory storage that keeps the signals of ${describeThreadKey(key)} could not be resolved, so the signal was not stored`);
110123
- return this.#insertStoredSignal(state, key, store, signal, to);
110875
+ const written = await this.#insertStoredSignal(state, key, store, signal, to, queued);
110876
+ if (written === "run-closed" && keepWhenClosed) await this.#insertStoredSignal(state, key, store, signal);
110877
+ return written;
110124
110878
  });
110125
110879
  }
110126
110880
  /** The insert of `#enqueueStoredSignal`, for a caller already inside a write of the thread's stored signals. */
110127
- async #insertStoredSignal(state, key, store, signal, to) {
110881
+ async #insertStoredSignal(state, key, store, signal, to, queued = false) {
110128
110882
  const message = signal.toDBMessage({
110129
110883
  threadId: store.threadId,
110130
110884
  resourceId: store.resourceId
@@ -110132,7 +110886,8 @@ var AgentThreadStreamRuntime = class {
110132
110886
  const recordAccepted = state.storedSignals.stampNewRow(key, message);
110133
110887
  const written = await store.store.enqueuePendingSignal({
110134
110888
  message,
110135
- ...to ? { toRunId: to.runId } : {}
110889
+ ...to ? { toRunId: to.runId } : {},
110890
+ ...queued ? { queued: true } : {}
110136
110891
  });
110137
110892
  if (written === "thread-not-found") throw new Error(`Thread ${store.threadId} of resource ${store.resourceId} was not found in the memory storage of agent ${to?.agent.id}, so the signal was not stored`);
110138
110893
  if (written === "accepted") recordAccepted();
@@ -110348,18 +111103,29 @@ var AgentThreadStreamRuntime = class {
110348
111103
  }
110349
111104
  }
110350
111105
  continueRun(agent, output, streamOptions, pubsub, claim) {
110351
- const { threadId, resourceId } = this.#getThreadTarget(streamOptions);
110352
- if (!threadId) return false;
110353
111106
  const state = this.#getState(pubsub);
110354
111107
  this.#sweepStaleSuspendedRecords(state, pubsub);
110355
- const key = this.#threadKey(resourceId, threadId);
110356
111108
  const existing = state.threadRunsById.get(output.runId);
111109
+ const named = this.#getThreadTarget(streamOptions);
111110
+ const continuesOwnThread = !named.threadId && existing !== void 0 && (named.resourceId === void 0 || named.resourceId === existing.resourceId);
111111
+ const { threadId, resourceId } = continuesOwnThread ? existing : named;
111112
+ if (!threadId) return false;
111113
+ const key = this.#threadKey(resourceId, threadId);
110357
111114
  if (!existing?.continuation?.canContinue() || existing.agent !== agent || existing.threadId !== threadId || existing.resourceId !== resourceId || state.activeThreadRunIds.get(key) !== output.runId || state.activeThreadStreamIds.get(key) !== existing.streamId || output.status !== "running" && output.status !== "suspended" || existing.lifecycle === "completed" || existing.lifecycle === "failed" || existing.lifecycle === "aborted") return false;
110358
111115
  const resumedToolCallId = streamOptions.toolCallId;
110359
111116
  if (resumedToolCallId) this.#clearSuspendedToolCall(state, output.runId, resumedToolCallId);
110360
111117
  else this.#clearSuspendedRun(state, output.runId);
110361
111118
  existing.lifecycle = "running";
110362
- existing.streamOptions = streamOptions;
111119
+ const resumeOptions = keepRunAutoResume(streamOptions, existing.streamOptions);
111120
+ existing.streamOptions = continuesOwnThread ? {
111121
+ ...resumeOptions,
111122
+ memory: resumeMemoryOnOwnThread({
111123
+ run: existing.streamOptions.memory,
111124
+ resume: streamOptions.memory,
111125
+ threadId,
111126
+ resourceId
111127
+ })
111128
+ } : resumeOptions;
110363
111129
  existing.currentSegmentOutput = output;
110364
111130
  if (claim?.generation !== void 0) existing.generation = claim.generation;
110365
111131
  if (claim?.ownershipLost) existing.ownershipLost = claim.ownershipLost;
@@ -110438,7 +111204,8 @@ var AgentThreadStreamRuntime = class {
110438
111204
  sourceOutput: output,
110439
111205
  canContinue: broadcast.canContinueBroadcast,
110440
111206
  didPublishTerminal: broadcast.didPublishTerminal
110441
- } : void 0
111207
+ } : void 0,
111208
+ queuedInputElsewhere: state.threadRunsById.get(output.runId)?.queuedInputElsewhere
110442
111209
  };
110443
111210
  return {
110444
111211
  record,
@@ -110473,7 +111240,8 @@ var AgentThreadStreamRuntime = class {
110473
111240
  const state = this.#getState(pubsub);
110474
111241
  this.#sweepStaleSuspendedRecords(state, pubsub);
110475
111242
  const key = this.#threadKey(resourceId, threadId);
110476
- const { record, streamId, streamSeq, startBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput(state, agent, output, streamOptions, pubsub, threadId, resourceId, registrationOptions);
111243
+ const runOptions = keepRunAutoResume(streamOptions, state.threadRunsById.get(output.runId)?.streamOptions);
111244
+ const { record, streamId, streamSeq, startBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput(state, agent, output, runOptions, pubsub, threadId, resourceId, registrationOptions);
110477
111245
  const activeRunId = state.activeThreadRunIds.get(key);
110478
111246
  const takesLeaseFrom = activeRunId !== void 0 && activeRunId !== output.runId && state.threadKeysByRunId.get(activeRunId) === key && this.#isParkedRun(state, activeRunId) ? activeRunId : void 0;
110479
111247
  state.threadRunsById.set(output.runId, record);
@@ -110621,6 +111389,7 @@ var AgentThreadStreamRuntime = class {
110621
111389
  runId: record.runId,
110622
111390
  streamId: record.streamId
110623
111391
  });
111392
+ this.#startQueuedTurnAfterParkedRun(this.#getState(pubsub), pubsub, key, record).catch((error) => this.#logParkedRunReleaseFailure(record, error));
110624
111393
  }
110625
111394
  #watchThreadRunCompletion(state, pubsub, key, record, registered, isDisabled) {
110626
111395
  if (state.watchedThreadStreamIds.has(record.streamId)) return;
@@ -110754,6 +111523,7 @@ var AgentThreadStreamRuntime = class {
110754
111523
  try {
110755
111524
  signal = state.signalQueues.takeNextPending(key);
110756
111525
  if (signal) {
111526
+ this.#recordStartedSignals(state, key, [signal]);
110757
111527
  nextRunId = globalThis.crypto.randomUUID();
110758
111528
  const reservedRunId = nextRunId;
110759
111529
  state.activeThreadRunIds.set(key, reservedRunId);
@@ -110783,6 +111553,7 @@ var AgentThreadStreamRuntime = class {
110783
111553
  state.threadKeysByRunId.delete(nextRunId);
110784
111554
  state.storedSignals.settlePreRunWaiters(nextRunId);
110785
111555
  state.signalQueues.discardPreRunQueue(key);
111556
+ this.#forgetStartedSignals(state, key, [signal]);
110786
111557
  if (owns.owner && !isRetakeLeaseOwner(owns.owner)) {
110787
111558
  const ownerRunId = threadLeaseRunId(owns.owner);
110788
111559
  const ids = state.locallyQueuedSignalIdsByThread.get(key);
@@ -110818,6 +111589,7 @@ var AgentThreadStreamRuntime = class {
110818
111589
  if (state.activeThreadRunIds.get(key) === nextRunId) state.activeThreadRunIds.delete(key);
110819
111590
  }
110820
111591
  state.signalQueues.restoreAfterFailedStart(key, draining?.cancelled ? void 0 : signal);
111592
+ if (signal) this.#forgetStartedSignals(state, key, [signal]);
110821
111593
  this.#publish(pubsub, key, {
110822
111594
  type: "run-failed",
110823
111595
  runId: failedRunId,
@@ -110861,7 +111633,11 @@ var AgentThreadStreamRuntime = class {
110861
111633
  * with its oldest pending row as input, else a queued continuation, else a
110862
111634
  * queued message, else release the lease. Rows are neither moved nor
110863
111635
  * deleted here: the follow-up's first model request claims every pending
110864
- * row of the thread.
111636
+ * row of the thread. A row still queued at this read, because the ended
111637
+ * run's close has not landed, is not delivered twice: saving the
111638
+ * follow-up's input under the row's id moves the row into the thread in
111639
+ * every store, and a follow-up that keeps its signals in storage counts the
111640
+ * id as consumed, so its claims never return it.
110865
111641
  *
110866
111642
  * `freshLease` is for a check that a late send triggered after the run's own
110867
111643
  * check: the ended run's lease may be gone, so it is acquired fresh, and
@@ -111060,7 +111836,10 @@ var AgentThreadStreamRuntime = class {
111060
111836
  const queue = state.pendingContinuationsByThread.get(key) ?? [];
111061
111837
  queue.push(pending);
111062
111838
  state.pendingContinuationsByThread.set(key, queue);
111063
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
111839
+ if (activeRecord) {
111840
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
111841
+ this.#startQueuedTurnAfterParkedRun(state, pubsub, key, activeRecord).catch((error) => this.#logParkedRunReleaseFailure(activeRecord, error));
111842
+ }
111064
111843
  return {
111065
111844
  accepted: true,
111066
111845
  runId
@@ -111072,6 +111851,27 @@ var AgentThreadStreamRuntime = class {
111072
111851
  runId
111073
111852
  };
111074
111853
  }
111854
+ /**
111855
+ * Queued work waits for the thread's run to end (#32093), and a run parked with auto-resume on counts as ended
111856
+ * (#30190). Only the process executing a run knows how it parked, so a runtime holding queued work behind a parked
111857
+ * run it doesn't execute asks that run's holder to let go of the thread. A holder whose run counts as ended releases
111858
+ * it and announces `parked-run-released`, and this runtime starts its queued work as after the run's end. The work
111859
+ * stays queued here meanwhile, with its own agent, options and queue owner, so it can still be cancelled here.
111860
+ */
111861
+ #requestParkedRunReleaseElsewhere(state, pubsub, key, { executionChanged = false } = {}) {
111862
+ const runId = state.activeThreadRunIds.get(key);
111863
+ if (!runId) return;
111864
+ const record = state.threadRunsById.get(runId);
111865
+ if (record && record.registeredElsewhere === void 0) return;
111866
+ if (!executionChanged && !this.#isSuspendedRun(state, runId) && record?.lifecycle !== "suspended") return;
111867
+ if (!state.pendingIdleSignalsByThread.get(key)?.some((entry) => entry.queued)) return;
111868
+ this.#ensureThreadControlSubscription(state, pubsub, key);
111869
+ this.#publish(pubsub, key, {
111870
+ type: "queued-input-waiting",
111871
+ runId,
111872
+ sourceId: this.#getSourceId()
111873
+ });
111874
+ }
111075
111875
  async #drainPendingIdleSignals(state, pubsub, key, fromRunId) {
111076
111876
  if (state.activeThreadRunIds.has(key)) return false;
111077
111877
  const idleQueue = state.pendingIdleSignalsByThread.get(key);
@@ -111141,9 +111941,9 @@ var AgentThreadStreamRuntime = class {
111141
111941
  this.#watchForwardedIdleLease(state, pubsub, key);
111142
111942
  }
111143
111943
  this.#notifyThreadEvents(state);
111144
- if (ownerRunId && this.#mayStoreForRunHeldElsewhere(state, pendingIdle.agent, forwardedSignalRunId(ownerRunId))) {
111145
- if (!await this.#forwardSignal(state, pubsub, key, pendingIdle.agent, ownerRunId, pendingIdle.signal).catch((error) => {
111146
- pendingIdle.agent.__getLogger?.()?.warn?.("Could not store a queued message for the run holding its thread", {
111944
+ if (ownerRunId) {
111945
+ if (!await this.#forwardToOwner(state, pubsub, key, pendingIdle.agent, ownerRunId, pendingIdle.signal, pendingIdle.queued === true).catch((error) => {
111946
+ pendingIdle.agent.__getLogger?.()?.warn?.("Could not forward a queued message to the run holding its thread", {
111147
111947
  runId: ownerRunId,
111148
111948
  signalId: pendingIdle.signal.id,
111149
111949
  error
@@ -111155,12 +111955,7 @@ var AgentThreadStreamRuntime = class {
111155
111955
  this.#notifyThreadEvents(state);
111156
111956
  return true;
111157
111957
  }
111158
- } else if (ownerRunId) await this.#publishAndWait(pubsub, key, {
111159
- type: "signal-enqueued",
111160
- runId: ownerRunId,
111161
- signal: this.#serializeSignal(pendingIdle.signal),
111162
- sourceId: this.#getSourceId()
111163
- }).catch(() => {});
111958
+ }
111164
111959
  const drained = await this.#drainPendingIdleSignals(state, pubsub, key, owns.acquired ? pendingIdle.runId : fromRunId);
111165
111960
  if (owns.acquired && !drained) this.#releaseThreadLease(pubsub, key, pendingIdle.runId);
111166
111961
  return drained || owns.acquired;
@@ -111257,7 +112052,9 @@ var AgentThreadStreamRuntime = class {
111257
112052
  const record = state.threadRunsById.get(runId);
111258
112053
  const key = record ? this.#threadKey(record.resourceId, record.threadId) : state.threadKeysByRunId.get(runId);
111259
112054
  if (!key) return [];
111260
- return state.signalQueues.take(scope, key);
112055
+ const queue = state.signalQueues.take(scope, key);
112056
+ this.#recordStartedSignals(state, key, queue);
112057
+ return queue;
111261
112058
  }
111262
112059
  /**
111263
112060
  * Resolves `'reserved'` when this call reserved the thread for `runId`; the
@@ -111979,6 +112776,7 @@ var AgentThreadStreamRuntime = class {
111979
112776
  state.suspendedRunIds.add(data.runId);
111980
112777
  const record = state.threadRunsByStreamId.get(eventStreamId) ?? state.threadRunsById.get(data.runId);
111981
112778
  if (record) record.lifecycle = "suspended";
112779
+ this.#requestParkedRunReleaseElsewhere(state, resolvedPubSub, key);
111982
112780
  } else clearActiveIfCurrent(data.runId, data.streamId);
111983
112781
  if (data.type !== "run-suspended" || suspendedRunEnded) this.#clearSuspendedRun(state, data.runId);
111984
112782
  const remoteRun = remoteRuns.get(eventStreamId);
@@ -112604,13 +113402,18 @@ var AgentThreadStreamRuntime = class {
112604
113402
  resourceId,
112605
113403
  threadId,
112606
113404
  streamOptions: queuedStreamOptions,
112607
- queueOwnerId: target.queueOwnerId
113405
+ queueOwnerId: target.queueOwnerId,
113406
+ queued: true
112608
113407
  });
112609
113408
  state.pendingIdleSignalsByThread.set(key, idleQueue);
112610
113409
  const control = this.#ensureThreadControlSubscription(state, pubsub, key);
112611
113410
  this.#publishPendingUserMessage(pubsub, key, runId ?? queuedRunId, queuedSignal, "queued");
112612
113411
  this.#notifyThreadEvents(state);
112613
- if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
113412
+ if (activeRecord) {
113413
+ this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
113414
+ this.#startQueuedTurnAfterParkedRunLater(state, pubsub, key, activeRecord);
113415
+ }
113416
+ this.#requestParkedRunReleaseElsewhere(state, pubsub, key);
112614
113417
  return {
112615
113418
  signal: queuedSignal,
112616
113419
  accepted: control.ready.then(() => ({
@@ -112949,7 +113752,8 @@ var AgentThreadStreamRuntime = class {
112949
113752
  runId,
112950
113753
  resourceId,
112951
113754
  threadId,
112952
- streamOptions: target.ifIdle?.streamOptions
113755
+ streamOptions: target.ifIdle?.streamOptions,
113756
+ ...waitForIdle ? { queued: true } : {}
112953
113757
  });
112954
113758
  state.pendingIdleSignalsByThread.set(key, idleQueue);
112955
113759
  if (activeRecord) this.#watchThreadRunCompletion(state, pubsub, key, activeRecord);
@@ -113067,18 +113871,11 @@ var AgentThreadStreamRuntime = class {
113067
113871
  reason: "scope-mismatch",
113068
113872
  runId: winnerRunId
113069
113873
  };
113070
- if (winnerRunId && this.#mayStoreForRunHeldElsewhere(state, agent, forwardedSignalRunId(winnerRunId))) {
113071
- if (!await this.#forwardSignal(state, pubsub, reservedKey, agent, winnerRunId, signal)) return {
113072
- action: "blocked",
113073
- reason: "thread-blocked",
113074
- runId: winnerRunId
113075
- };
113076
- } else if (winnerRunId) await this.#publishAndWait(pubsub, reservedKey, {
113077
- type: "signal-enqueued",
113078
- runId: winnerRunId,
113079
- signal: this.#serializeSignal(signal),
113080
- sourceId: this.#getSourceId()
113081
- }).catch(() => {});
113874
+ if (winnerRunId && !await this.#forwardToOwner(state, pubsub, reservedKey, agent, winnerRunId, signal, waitForIdle)) return {
113875
+ action: "blocked",
113876
+ reason: "thread-blocked",
113877
+ runId: winnerRunId
113878
+ };
113082
113879
  return {
113083
113880
  action: "deliver",
113084
113881
  runId: winnerRunId ?? reservedRunId
@@ -114778,4 +115575,4 @@ function withExecutionFence(step) {
114778
115575
  }
114779
115576
  };
114780
115577
  }
114781
- export { modelConfigSchema as $, spanQueryResponseSchema as $a, createConcurrencyLimiter as $c, ChannelsStorage as $i, ProcessorOutputStreamPhaseSchema as $l, assertKnowledgeCeilingRaised as $n, TokenLimiterProcessor as $o, KnowledgeImporterBindingConflictError as $r, resolveAgentById as $s, KnowledgeLinkRepairUnsupportedError as $t, detachFullStreamOnEnd as A, THREAD_QUERY_DEFAULT_LIMIT as Aa, getStepEntry as Ac, knowledgeLinkRefKey as Ai, validateStepRequestContext as Al, renderBuiltInToolEvent as An, MemoryProcessor as Ao, ScoresInMemory as Ar, EventedWorkflow as As, runDefaultCompletionCheck as At, serializeToolsMetadata as B, SPAN_QUERY_MAX_LIMIT as Ba, createNestedRunParentStatusLookup as Bc, ExperimentsInMemory as Bi, hasDurableExecution as Bl, toChatLogger as Bn, ResponseCache as Bo, notificationSignalAttributes as Br, emitChunkEvent as Bs, KnowledgeRunScopesError as Bt, mergeAgentPersona as C, validateStorageMetadataFilter as Ca, AgentControlEventTypes as Cc, MAX_KNOWLEDGE_PAGE_LINKS as Ci, isSingleStepEntry as Cl, MastraStateAdapter as Cn, buildMessageEmbeddingRows as Co, createEmptyWorkflowSnapshot as Cr, isRetryableOpenAIResponsesStreamError as Cs, formatCompletionFeedback as Ct, prepareForDurableExecution as D, tracePageNodeSchema as Da, isWorkflowStepConflictError as Dc, assertKnowledgeNoteTextWithinBound as Di, runCountDeprecationMessage as Dl, markNewChannelThread as Dn, resolveMaxChunkChars as Do, WorkflowDefinitionsStorage as Dr, createEventedWorkflow as Ds, generateStructuredFinalResult as Dt, normalizeResumeGenerateArgs as E, tracePageIdSchema as Ea, assertWorkflowStepGuard as Ec, MAX_KNOWLEDGE_PIN_LIST_DEPTH as Ei, resolveForeachConcurrency as El, NEW_CHANNEL_THREAD_KEY as En, messageVectorId as Eo, InMemoryWorkflowDefinitionsStorage as Er, cloneWorkflow as Es, generateFinalResult as Et, createDurableToolCallStep as F, threadQueryRequestSchema as Fa, isProcessor$1 as Fc, parseKnowledgePageRef as Fi, getEntryId as Fl, DEFAULT_CHANNEL_TOOLS_SETTINGS as Fn, getStorageSource as Fo, InMemoryNotificationsStorage as Fr, WorkflowEventProcessor as Fs, PINNED_READ_MEMO_KEY as Ft, resolveDurableToolCallConcurrency as G, encodeSpanQueryCursor as Ga, SCORING_PREDICATE_ROOTS as Gc, SchemaValidator as Gi, MessageContentSchema as Gl, WorkingMemory as Gn, formatSkillsCatalog as Go, readNotificationRoutingRequirement as Gr, emitSuspendedEvent as Gs, moveKnowledgePage as Gt, MessagePartSpans as H, SPAN_QUERY_ORDER_FIELDS as Ha, nestedRunRecoveryAction as Hc, DatasetsInMemory as Hi, isDurableAgentLike as Hl, MemoryInputFilter as Hn, WorkspaceInstructionsProcessor as Ho, notificationSummaryContents as Hr, emitFinishEvent as Hs, knowledgeAgentScopes as Ht, createWorkflowInput as I, threadQueryResponseSchema as Ia, mapVariable as Ic, KnowledgeInvalidCursorError as Ii, getEntryWorkflow as Il, channelToolScopeResolver as In, createBackgroundWorkSignalProcessor as Io, NotificationsStorage as Ir, StepExecutor as Is, knowledgeDeliveredPins as It, createBaseIterationStateUpdate as J, resolveSpanQueryCost as Ja, WORKFLOW_RUN_LEASE_TTL_MS as Jc, getSchemaValidator as Ji, ProcessorInputStepPhaseSchema as Jl, getMemoryRunState as Jn, ToolCallFilter as Jo, resolveDeliveryFailureUpdate as Jr, resolveInternalState as Js, updateKnowledgeNote as Jt, buildStepRecord as K, parseSpanQueryRequest as Ka, evaluateScoringPredicate as Kc, assertSupportedPatterns as Ki, MessagePartSchema as Kl, MessageHistory as Kn, ToolSearchProcessor as Ko, MAX_NOTIFICATION_DELIVERY_ATTEMPTS as Kr, diffResponseMessages as Ks, removeKnowledgeNote as Kt, serializeDurableOptions as L, threadQueryRowSchema as La, predicateToCondition as Lc, knowledgePageKeyProblem as Li, assertDrainTimeout as Ll, createChannelToolScope as Ln, CyberRefusalHandler as Lo, dispatchDueNotifications as Lr, computeScheduleDefinitionHash as Ls, buildKnowledgePageTools as Lt, createDurableGoalStep as M, encodeThreadQueryCursor as Ma, Workflow as Mc, knowledgePinDepth as Mi, validateStepStateData as Ml, CONTINUE_RUN_MESSAGE as Mn, filterSystemReminderMessages as Mo, InMemorySchedulesStorage as Mr, cloneWorkflow$1 as Ms, runValidation as Mt, createDurableIsTaskCompleteStep as N, planThreadRowsQuery as Na, cloneStep$1 as Nc, knowledgePositionBetween as Ni, validateStepSuspendData as Nl, formatToolApproval as Nn, isSystemReminderMessage as No, SchedulesStorage as Nr, createStep as Ns, loop as Nt, applyReservedMemoryContextKeys as O, tracePageRequestSchema as Oa, EventedExecutionEngine as Oc, assertKnowledgePageDescriptionWithinBound as Oi, setLongTimeout as Ol, ChatChannelProcessor as On, upsertMessageVectors as Oo, InMemoryToolProviderConnectionsStorage as Or, createWorkflow as Os, runChecks as Ot, createDurableLLMMappingStep as P, threadQueryIdentitySchema as Pa, createStep$1 as Pc, knowledgeScopeReadable as Pi, waitForSuspendedSnapshot as Pl, ChannelSessionRejectedError as Pn, augmentWithInit as Po, normalizeScheduleTarget as Pr, createWorkflow$1 as Ps, validateModelTimeoutSettings as Pt, durableAgenticOutputSchema as Q, spanQueryRequestSchema as Qa, ExecutionEngine as Qc, InMemoryChannelsStorage as Qi, ProcessorOutputStepPhaseSchema as Ql, MAX_KNOWLEDGE_SCOPE_TAGS as Qn, SystemPromptScrubber as Qo, InMemoryKnowledgeStorage as Qr, toolRequiresApproval as Qs, KnowledgeLinkRefreshIncompleteError as Qt, serializeDurableState as R, SPAN_QUERY_MAX_COST_METRICS as Ra, evaluatePredicate as Rc, InMemoryHarness as Ri, waitMs as Rl, createChannelTools as Rn, DEFAULT_RESPONSE_CACHE_TTL_SECONDS as Ro, createNotificationSignal as Rr, createDurableAgentStream as Rs, heldScopes as Rt, MAX_FS_SUBAGENT_DEPTH as S, transformScoreRow as Sa, AGENT_STREAM_TOPIC as Sc, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS as Si, isEntryFinished as Sl, resolveChannelRenderContext as Sn, MESSAGE_EMBEDDING_CHARS_PER_TOKEN as So, WorkflowsStorage as Sr, isBadRequestError as Ss, formatCheckFeedback as St, Agent as T, readTracePage as Ta, WorkflowStepConflictError as Tc, MAX_KNOWLEDGE_PAGE_LIST_LIMIT as Ti, omitPriorSuspensionFields as Tl, ChannelThreadLinkProcessor as Tn, extractMessageEmbeddingText as To, mergeWorkflowStepResult as Tr, getGoalActivityDurationMs as Ts, formatValidationFeedback as Tt, isSpanChunk as U, buildSpanQueryResponse as Ua, nestedRunStatusOf as Uc, DatasetsStorage as Ui, FilePartSchema as Ul, SemanticRecall as Un, SkillSearchProcessor as Uo, notificationSummarySignalMetadata as Ur, emitStepFinishEvent as Us, knowledgePersonaScopes as Ut, createDurableLLMExecutionStep as V, SPAN_QUERY_MAX_PREVIEW_CHARACTERS as Va, nestedRunParentOf as Vc, ExperimentsStorage as Vi, hasResumableStreams as Vl, BaseProcessor as Vn, buildResponseCacheKey as Vo, notificationSignalMetadata as Vr, emitErrorEvent as Vs, knowledgeRunPrincipals as Vt, createDurableBackgroundTaskCheckStep as W, createSpanQueryPreview as Wa, DefaultExecutionEngine as Wc, DatasetItemIdentityConflictError as Wi, ImagePartSchema as Wl, globalEmbeddingCache as Wn, SkillsProcessor as Wo, summarizeNotifications as Wr, emitStepStartEvent as Ws, addKnowledgeNote as Wt, baseDurableAgenticInputSchema as X, spanQueryIdentityKey as Xa, repeatAfterSettled as Xc, SchemaUpdateValidationError as Xi, ProcessorMessageSchema as Xl, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH as Xn, CostGuardProcessor as Xo, InMemoryMemory as Xr, resolveRuntimeDependencies as Xs, KnowledgeSemanticIndex as Xt, accumulatedUsageSchema as Y, spanQueryCostSchema as Ya, renewWorkflowLease as Yc, UnsupportedSchemaPatternError as Yi, ProcessorMessageContentSchema as Yl, MockMemory as Yn, RegexFilterProcessor as Yo, resolveNotificationDeliveryDecision as Yr, resolveModel as Ys, upsertKnowledgePage as Yt, baseIterationStateSchema as Z, spanQueryIdentitySchema as Za, runFenceConflictOf as Zc, SchemaValidationError as Zi, ProcessorOutputResultPhaseSchema as Zl, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH as Zn, TokenCostControl as Zo, MemoryStorage as Zr, resolveTool$1 as Zs, embed$2 as Zt, isNotScorable as _, parseDuration as _a, segmentSpanData as _c, KnowledgePageKeyConflictError as _i, getRestartStartIndex as _l, encodeKnowledgeScopeId as _n, ObservabilityStorage as _o, FilesystemDB as _r, isMalformedFunctionCallError as _s, untilIdleHandlesBackgroundTask as _t, matchesRunFence as _u, AGENTIC_EXECUTION_WORKFLOW_ID as a, resolveRetentionTargets as aa, endRunSpansWithError as ac, KnowledgeNotFoundError$1 as ai, createStepFromTool as al, syncKnowledgePageBodyLinks as an, planTraceQuery as ao, expandKnowledgeScope as ar, normalizeMessageHistoryConfig as as, runResumeDurableStreamUntilIdle as at, StepStartPartSchema as au, agentInstructions as b, storageMessageMatchesMetadataFilter as ba, DurableStepIds as bc, MAX_KNOWLEDGE_PAGE_BODY_LINKS as bi, getStepIds as bl, resolveWaitUntil as bn, UniqueViolationError as bo, WorkflowsInMemory as br, FILE_UPLOAD_ERROR_CODES as bs, resolveDeclineReason as bt, runOutsideRunFenceScope as bu, runEvals as c, createStorageErrorId as ca, getRunRegistryEntry as cc, KnowledgeTransactionDeadlineError as ci, abortableSleep as cl, knowledgeReadScopeFor as cn, buildLogRecord as co, knowledgeSemanticDocumentId as cr, ClassifierProcessor as cs, readRunDeadline as ct, isAgentCompatible as cu, validateAndSaveScore as d, ensureDate as da, setRunRegistryEntry as dc, createKnowledgeUlid as di, cleanStepResult as dl, compileKnowledgeScopes as dn, buildUpdateSpanRecord as do, parseKnowledgeNodeCursor as dr, PIIDetector as ds, requestAcknowledgedAbort as dt, RUN_FENCE_CONFLICT_ERROR_ID as du, InMemoryBlobStore as ea, DURABLE_CONTEXT_SEGMENT_KEY as ec, KnowledgeImporterRunStateError as ei, normalizeConcurrency as el, canRepairKnowledgeLinksInBatch as en, spanQueryRowSchema as eo, assertKnowledgeDescriptionWithinBound as er, groupLinkedToolMessages as es, modelListEntrySchema as et, ProcessorStepInputSchema as eu, createClassifierScorer as f, filterByDateRange as fa, takeRunScorerInstances as fc, inspectKnowledgeSchema as fi, createDeprecationProxy as fl, knowledgeMemoryScopes as fn, getObjectOrNull as fo, StoreOperationsInMemory as fr, PromptInjectionDetector as fs, subscribeToAbortRequests as ft, RUN_FENCING_NOT_SUPPORTED_ERROR_ID as fu, filterRun as g, jsonValueEquals as ga, segmentEndedBySuspension as gc, KnowledgePageHasChildrenError as gi, defineStateAccessors as gl, decodeKnowledgeScopeId as gn, ObservabilityInMemory as go, FilesystemStore as gr, defaultStabilityErrorProcessors as gs, getScopeStreamSlot as gt, isRunFenceConflictError as gu, createScorer as h, hasErrorCode as ha, liveSegmentSpan as hc, KnowledgePageDepthError as hi, defineLazyWriter as hl, strongerKnowledgeRole as hn, toEntityType as ho, createGitHubSourceControlProviderFromEnv as hr, STABILITY_ERROR_PROCESSOR_IDS as hs, getRunStreamSlot as ht, currentRunGeneration as hu, agentThreadStreamRuntime as i, executeRetentionPrune as ia, deleteRunRegistryEntry as ic, KnowledgeConflictError as ii, createStepFromClassifier as il, repairKnowledgeLinks as in, planThreadQuery as io, createKnowledgeNodeCursor as ir, isAfterMemoryTokenBoundary as is, runDurableStreamUntilIdle as it, SourcePartSchema as iu, createDurableAgenticWorkflow as j, THREAD_QUERY_MAX_LIMIT as ja, Run as jc, knowledgePagePath as ji, validateStepResumeData as jl, CONTINUE_RUN_ACTION_ID as jn, memoryDefaultOptions as jo, ScoresStorage as jr, cloneStep as js, runStreamCompletionScorers as jt, persistDurableRunInput as k, tracePageResponseSchema as ka, getNestedWorkflow as kc, canonicalKnowledgeName as ki, validateStepInput as kl, CHAT_CHANNEL_RENDER_CONTEXT_KEY as kn, MastraMemory as ko, ToolProviderConnectionsStorage as kr, EventedRun as ks, runCompletionScorers as kt, flushBeforeTraceRead as l, createStoreErrorId as la, globalRunRegistry as lc, KnowledgeUnsupportedCapabilityError as li, applyStateDelta as ll, knowledgeRoleOn as ln, buildMetricRecord as lo, knowledgeSemanticIdempotencyKey as lr, StructuredOutputProcessor as ls, AgentStreamBus as lt, CONTROLLER_RUN_BINDING_KEY as lu, ScorerRunError as m, getSqlType as ma, endFailedSegmentSpans as mc, KnowledgeMoveTooLargeError as mi, createTimeTravelExecutionParams as ml, knowledgeScopeAddress as mn, serializeSpanAttributes as mo, GitHubSourceControlProvider as mr, UnicodeNormalizer as ms, __registerMastraCtor as mt, coverNestedRun as mu, getExecutionClaimScope as n, BackgroundTasksInMemory as na, RunRegistry as nc, KNOWLEDGE_STORAGE_CONTRACT_VERSION as ni, createMappingStep as nl, refreshKnowledgeLinksTo as nn, encodeTraceQueryDeltaCursor as no, assertKnowledgeScopeWithinCeiling as nr, advanceMemoryTokenBoundary as ns, runDurableFinishSideEffects as nt, ProcessorStepSchema as nu, AGENTIC_LOOP_WORKFLOW_ID as o, retentionCutoffMs as oa, getActiveDurableAgentWorkflowExecutions as oc, KnowledgeSchemaResetRequiredError as oi, RESUME_SNAPSHOT_POLL_INTERVAL_MS as ol, updateKnowledgeLinks as on, buildCreateSpanRecord as oo, isKnowledgeScopeVisible as or, BatchPartsProcessor as os, RUN_DEADLINE_KEY as ot, TextPartSchema as ou, MastraScorer as p, getDefaultValue as pa, carrySegmentSpans as pc, parseKnowledgeWikilinks as pi, createRestartExecutionParams as pl, knowledgeRunScopes as pn, getStringOrNull as po, StoreOperations as pr, ModerationProcessor as ps, createRunAbortController as pt, RunFenceConflictError as pu, calculateAccumulatedUsage as q, planSpanQuery as qa, validateScoringPredicate as qc, createValidator as qi, ProcessorInputPhaseSchema as ql, MemoryRunState as qn, AgentsMDInjector as qo, defaultNotificationDeliveryDecision as qr, rebuildRunToolsFromMastra as qs, removeKnowledgePage as qt, AgentThreadLeaseLostError as r, BackgroundTasksStorage as ra, abandonDurableAgentExecutions as rc, KNOWLEDGE_STORAGE_SCHEMA_VERSION as ri, createStepFromAgent$1 as rl, reindexKnowledgeLinks as rn, getTraceQueryDeltaWatermark as ro, canonicalizeKnowledgeScope as rr, getMemoryTokenBoundary as rs, loadRunStoredMessages as rt, ReasoningPartSchema as ru, describeNonSuccessFinishReason as s, runRetentionBatches as sa, getExecutingInstances as sc, KnowledgeStorage as si, RESUME_SNAPSHOT_WAIT_STATUSES as sl, knowledgeAccessGrants as sn, buildFeedbackRecord as so, knowledgeScopeKey as sr, ModelSelectionProcessor as ss, ensureRemoteAbortListener as st, ToolInvocationPartSchema as su, __resetExecutionFencesForTests as t, BlobStore as ta, ExtendedRunRegistry as tc, KnowledgeImportersStorage as ti, runWithConcurrency as tl, knowledgeSubtree as tn, encodeTraceQueryCursor as to, assertKnowledgeRecordTextWithinBound as tr, loadMessageHistory as ts, executeDurableAgentScorers as tt, ProcessorStepOutputSchema as tu, createOnScorerHook as u, createVectorErrorId as ua, isDurableAgentExecutionDetached as uc, assertKnowledgeSchemaCompatible as ui, assertTimeTravelGraphMatchesSnapshot as ul, KnowledgeDeclarationError as un, buildScoreRecord as uo, knowledgeVisibleScopeKeys as ur, LanguageDetector as us, publishAbortRequest as ut, restoredWorkerControllerContexts as uu, notScorable as v, safelyParseJSON as va, DURABLE_STOP_WHEN_ERROR_ID as vc, MAX_KNOWLEDGE_MOVE_PAGES as vi, getResumeLabelsByStepId as vl, buildKnowledgeInstructions as vn, FactoryStorage as vo, InMemoryStore as vr, UnsupportedFileHandler as vs, pruneAgentLoopSnapshot as vt, resolveRunFence as vu, AGENT_RESUME_CLAIM_STALE_MS as w, TracePageError as wa, AgentStreamEventTypes as wc, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH as wi, omitPriorCompletionFields as wl, REPLY_TOOL_NAME as wn, chunkMessageText as wo, mergeStepResult as wr, PrefillErrorHandler as ws, formatStreamCompletionFeedback as wt, assembleAgentFromFsEntry as x, transformRow as xa, AGENT_CONTROL_TOPIC as xc, MAX_KNOWLEDGE_PAGE_DEPTH as xi, hydrateSerializedStepErrors as xl, defaultTypingStatus as xn, DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS as xo, cloneRunData as xr, StreamErrorRetryProcessor as xs, getServerSideFallbackInfo as xt, setRunFenceContext as xu, agentConfig as y, serializeDate as ya, DurableAgentDefaults as yc, MAX_KNOWLEDGE_NOTE_TOKENS as yi, getSingleStepEntryId as yl, AgentChannels as yn, FactoryStorageDomain as yo, MockStore as yr, FileUploadProcessor as ys, DEFAULT_TOOL_DECLINE_REASON as yt, runFencingNotSupportedError as yu, serializeModelConfig as z, SPAN_QUERY_MAX_CURSOR_BYTES as za, cancelNestedRun as zc, HarnessStorage as zi, workflowTermination as zl, resolveChannelToolsSettings as zn, RESPONSE_CACHE_CONTEXT_KEY as zo, createNotificationSummarySignal as zr, emitAbortEvent as zs, KnowledgeRun as zt };
115578
+ export { modelConfigSchema as $, spanQueryIdentitySchema as $a, runFenceConflictOf as $c, SchemaValidationError as $i, ProcessorOutputResultPhaseSchema as $l, MAX_KNOWLEDGE_SCOPE_TAGS as $n, TokenCostControl as $o, InMemoryKnowledgeStorage as $r, resolveTool$1 as $s, KnowledgeLinkRepairUnsupportedError as $t, detachFullStreamOnEnd as A, tracePageRequestSchema as Aa, EventedExecutionEngine as Ac, canonicalKnowledgeName as Ai, setLongTimeout as Al, CHAT_CHANNEL_RENDER_CONTEXT_KEY as An, upsertMessageVectors as Ao, ToolProviderConnectionsStorage as Ar, createWorkflow as As, runDefaultCompletionCheck as At, serializeToolsMetadata as B, SPAN_QUERY_MAX_COST_METRICS as Ba, evaluatePredicate as Bc, InMemoryHarness as Bi, waitMs as Bl, resolveChannelToolsSettings as Bn, DEFAULT_RESPONSE_CACHE_TTL_SECONDS as Bo, createNotificationSummarySignal as Br, createDurableAgentStream as Bs, KnowledgeRunScopesError as Bt, mergeAgentPersona as C, transformRow as Ca, AGENT_CONTROL_TOPIC as Cc, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS as Ci, hydrateSerializedStepErrors as Cl, resolveChannelRenderContext as Cn, DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS as Co, WorkflowsStorage as Cr, StreamErrorRetryProcessor as Cs, formatCompletionFeedback as Ct, setRunFenceContext as Cu, prepareForDurableExecution as D, readTracePage as Da, WorkflowStepConflictError as Dc, MAX_KNOWLEDGE_PIN_LIST_DEPTH as Di, omitPriorSuspensionFields as Dl, NEW_CHANNEL_THREAD_KEY as Dn, extractMessageEmbeddingText as Do, InMemoryWorkflowDefinitionsStorage as Dr, getGoalActivityDurationMs as Ds, generateStructuredFinalResult as Dt, normalizeResumeGenerateArgs as E, TracePageError as Ea, AgentStreamEventTypes as Ec, MAX_KNOWLEDGE_PAGE_LIST_LIMIT as Ei, omitPriorCompletionFields as El, ChannelThreadLinkProcessor as En, chunkMessageText as Eo, mergeWorkflowStepResult as Er, PrefillErrorHandler as Es, generateFinalResult as Et, createDurableToolCallStep as F, planThreadRowsQuery as Fa, cloneStep$1 as Fc, knowledgeScopeReadable as Fi, validateStepSuspendData as Fl, ChannelSessionRejectedError as Fn, isSystemReminderMessage as Fo, normalizeScheduleTarget as Fr, createStep as Fs, PINNED_READ_MEMO_KEY as Ft, resolveDurableToolCallConcurrency as G, buildSpanQueryResponse as Ga, nestedRunStatusOf as Gc, DatasetsStorage as Gi, FilePartSchema as Gl, globalEmbeddingCache as Gn, SkillSearchProcessor as Go, summarizeNotifications as Gr, emitStepFinishEvent as Gs, moveKnowledgePage as Gt, MessagePartSpans as H, SPAN_QUERY_MAX_LIMIT as Ha, createNestedRunParentStatusLookup as Hc, ExperimentsInMemory as Hi, hasDurableExecution as Hl, BaseProcessor as Hn, ResponseCache as Ho, notificationSignalMetadata as Hr, emitChunkEvent as Hs, knowledgeAgentScopes as Ht, createWorkflowInput as I, threadQueryIdentitySchema as Ia, createStep$1 as Ic, parseKnowledgePageRef as Ii, waitForSuspendedSnapshot as Il, DEFAULT_CHANNEL_TOOLS_SETTINGS as In, augmentWithInit as Io, InMemoryNotificationsStorage as Ir, createWorkflow$1 as Is, knowledgeDeliveredPins as It, createBaseIterationStateUpdate as J, parseSpanQueryRequest as Ja, evaluateScoringPredicate as Jc, assertSupportedPatterns as Ji, MessagePartSchema as Jl, MemoryRunState as Jn, ToolSearchProcessor as Jo, defaultNotificationDeliveryDecision as Jr, diffResponseMessages as Js, updateKnowledgeNote as Jt, buildStepRecord as K, createSpanQueryPreview as Ka, DefaultExecutionEngine as Kc, DatasetItemIdentityConflictError as Ki, ImagePartSchema as Kl, WorkingMemory as Kn, SkillsProcessor as Ko, readNotificationRoutingRequirement as Kr, emitStepStartEvent as Ks, removeKnowledgeNote as Kt, serializeDurableOptions as L, threadQueryRequestSchema as La, isProcessor$1 as Lc, KnowledgeInvalidCursorError as Li, getEntryId as Ll, channelToolScopeResolver as Ln, getStorageSource as Lo, NotificationsStorage as Lr, WorkflowEventProcessor as Ls, buildKnowledgePageTools as Lt, createDurableGoalStep as M, THREAD_QUERY_DEFAULT_LIMIT as Ma, getStepEntry as Mc, knowledgePagePath as Mi, validateStepRequestContext as Ml, CONTINUE_RUN_ACTION_ID as Mn, MemoryProcessor as Mo, ScoresStorage as Mr, EventedWorkflow as Ms, runValidation as Mt, createDurableIsTaskCompleteStep as N, THREAD_QUERY_MAX_LIMIT as Na, Run as Nc, knowledgePinDepth as Ni, validateStepResumeData as Nl, CONTINUE_RUN_MESSAGE as Nn, memoryDefaultOptions as No, InMemorySchedulesStorage as Nr, cloneStep as Ns, loop as Nt, applyReservedMemoryContextKeys as O, tracePageIdSchema as Oa, assertWorkflowStepGuard as Oc, assertKnowledgeNoteTextWithinBound as Oi, resolveForeachConcurrency as Ol, markNewChannelThread as On, messageVectorId as Oo, WorkflowDefinitionsStorage as Or, cloneWorkflow as Os, runChecks as Ot, createDurableLLMMappingStep as P, encodeThreadQueryCursor as Pa, Workflow as Pc, knowledgePositionBetween as Pi, validateStepStateData as Pl, formatToolApproval as Pn, filterSystemReminderMessages as Po, SchedulesStorage as Pr, cloneWorkflow$1 as Ps, validateModelTimeoutSettings as Pt, durableAgenticOutputSchema as Q, spanQueryIdentityKey as Qa, repeatAfterSettled as Qc, SchemaUpdateValidationError as Qi, ProcessorMessageSchema as Ql, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH as Qn, CostGuardProcessor as Qo, MemoryStorage as Qr, resolveRuntimeDependencies as Qs, KnowledgeLinkRefreshIncompleteError as Qt, serializeDurableState as R, threadQueryResponseSchema as Ra, mapVariable as Rc, KnowledgeInvalidSearchError as Ri, getEntryWorkflow as Rl, createChannelToolScope as Rn, createBackgroundWorkSignalProcessor as Ro, dispatchDueNotifications as Rr, StepExecutor as Rs, heldScopes as Rt, MAX_FS_SUBAGENT_DEPTH as S, storageMessageMatchesMetadataFilter as Sa, DurableStepIds as Sc, MAX_KNOWLEDGE_PAGE_DEPTH as Si, getStepIds as Sl, defaultTypingStatus as Sn, UniqueViolationError as So, cloneRunData as Sr, FILE_UPLOAD_ERROR_CODES as Ss, formatCheckFeedback as St, runOutsideRunFenceScope as Su, Agent as T, validateStorageMetadataFilter as Ta, AgentControlEventTypes as Tc, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH as Ti, isSingleStepEntry as Tl, REPLY_TOOL_NAME as Tn, buildMessageEmbeddingRows as To, mergeStepResult as Tr, isRetryableOpenAIResponsesStreamError as Ts, formatValidationFeedback as Tt, isSpanChunk as U, SPAN_QUERY_MAX_PREVIEW_CHARACTERS as Ua, nestedRunParentOf as Uc, ExperimentsStorage as Ui, hasResumableStreams as Ul, MemoryInputFilter as Un, buildResponseCacheKey as Uo, notificationSummaryContents as Ur, emitErrorEvent as Us, knowledgePersonaScopes as Ut, createDurableLLMExecutionStep as V, SPAN_QUERY_MAX_CURSOR_BYTES as Va, cancelNestedRun as Vc, HarnessStorage as Vi, workflowTermination as Vl, toChatLogger as Vn, RESPONSE_CACHE_CONTEXT_KEY as Vo, notificationSignalAttributes as Vr, emitAbortEvent as Vs, knowledgeRunPrincipals as Vt, createDurableBackgroundTaskCheckStep as W, SPAN_QUERY_ORDER_FIELDS as Wa, nestedRunRecoveryAction as Wc, DatasetsInMemory as Wi, isDurableAgentLike as Wl, SemanticRecall as Wn, WorkspaceInstructionsProcessor as Wo, notificationSummarySignalMetadata as Wr, emitFinishEvent as Ws, addKnowledgeNote as Wt, baseDurableAgenticInputSchema as X, resolveSpanQueryCost as Xa, WORKFLOW_RUN_LEASE_TTL_MS as Xc, getSchemaValidator as Xi, ProcessorInputStepPhaseSchema as Xl, MockMemory as Xn, ToolCallFilter as Xo, resolveNotificationDeliveryDecision as Xr, resolveInternalState as Xs, KnowledgeSemanticIndex as Xt, accumulatedUsageSchema as Y, planSpanQuery as Ya, validateScoringPredicate as Yc, createValidator as Yi, ProcessorInputPhaseSchema as Yl, getMemoryRunState as Yn, AgentsMDInjector as Yo, resolveDeliveryFailureUpdate as Yr, rebuildRunToolsFromMastra as Ys, upsertKnowledgePage as Yt, baseIterationStateSchema as Z, spanQueryCostSchema as Za, renewWorkflowLease as Zc, UnsupportedSchemaPatternError as Zi, ProcessorMessageContentSchema as Zl, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH as Zn, RegexFilterProcessor as Zo, InMemoryMemory as Zr, resolveModel as Zs, embed$2 as Zt, isNotScorable as _, hasErrorCode as _a, liveSegmentSpan as _c, KnowledgePageHasChildrenError as _i, defineLazyWriter as _l, decodeKnowledgeScopeId as _n, toEntityType as _o, FilesystemStore as _r, STABILITY_ERROR_PROCESSOR_IDS as _s, untilIdleHandlesBackgroundTask as _t, currentRunGeneration as _u, AGENTIC_EXECUTION_WORKFLOW_ID as a, BackgroundTasksStorage as aa, abandonDurableAgentExecutions as ac, KnowledgeConflictError as ai, createStepFromAgent$1 as al, repairKnowledgeLinks as an, getTraceQueryDeltaWatermark as ao, createKnowledgeNodeCursor as ar, getMemoryTokenBoundary as as, runResumeDurableStreamUntilIdle as at, ReasoningPartSchema as au, agentInstructions as b, safelyParseJSON as ba, DURABLE_STOP_WHEN_ERROR_ID as bc, MAX_KNOWLEDGE_NOTE_TOKENS as bi, getResumeLabelsByStepId as bl, AgentChannels as bn, FactoryStorage as bo, MockStore as br, UnsupportedFileHandler as bs, resolveDeclineReason as bt, resolveRunFence as bu, runEvals as c, retentionCutoffMs as ca, getActiveDurableAgentWorkflowExecutions as cc, KnowledgeStorage as ci, RESUME_SNAPSHOT_POLL_INTERVAL_MS as cl, knowledgeAccessGrants as cn, buildCreateSpanRecord as co, knowledgeScopeKey as cr, BatchPartsProcessor as cs, readRunDeadline as ct, TextPartSchema as cu, validateAndSaveScore as d, createStoreErrorId as da, globalRunRegistry as dc, assertKnowledgeSchemaCompatible as di, applyStateDelta as dl, KnowledgeDeclarationError as dn, buildMetricRecord as do, knowledgeVisibleScopeKeys as dr, StructuredOutputProcessor as ds, requestAcknowledgedAbort as dt, CONTROLLER_RUN_BINDING_KEY as du, InMemoryChannelsStorage as ea, toolRequiresApproval as ec, KnowledgeImporterBindingConflictError as ei, ExecutionEngine as el, MAX_KNOWLEDGE_LINK_REPAIR_SOURCES as en, spanQueryRequestSchema as eo, assertKnowledgeCeilingRaised as er, SystemPromptScrubber as es, modelListEntrySchema as et, ProcessorOutputStepPhaseSchema as eu, createClassifierScorer as f, createVectorErrorId as fa, isDurableAgentExecutionDetached as fc, createKnowledgeUlid as fi, assertTimeTravelGraphMatchesSnapshot as fl, compileKnowledgeScopes as fn, buildScoreRecord as fo, parseKnowledgeNodeCursor as fr, LanguageDetector as fs, subscribeToAbortRequests as ft, restoredWorkerControllerContexts as fu, filterRun as g, getSqlType as ga, endFailedSegmentSpans as gc, KnowledgePageDepthError as gi, createTimeTravelExecutionParams as gl, strongerKnowledgeRole as gn, serializeSpanAttributes as go, createGitHubSourceControlProviderFromEnv as gr, UnicodeNormalizer as gs, getScopeStreamSlot as gt, coverNestedRun as gu, createScorer as h, getDefaultValue as ha, carrySegmentSpans as hc, KnowledgeMoveTooLargeError as hi, createRestartExecutionParams as hl, knowledgeScopeAddress as hn, getStringOrNull as ho, GitHubSourceControlProvider as hr, ModerationProcessor as hs, getRunStreamSlot as ht, RunFenceConflictError as hu, agentThreadStreamRuntime as i, BackgroundTasksInMemory as ia, RunRegistry as ic, KNOWLEDGE_STORAGE_SCHEMA_VERSION as ii, createMappingStep as il, reindexKnowledgeLinks as in, encodeTraceQueryDeltaCursor as io, canonicalizeKnowledgeScope as ir, advanceMemoryTokenBoundary as is, runDurableStreamUntilIdle as it, ProcessorStepSchema as iu, createDurableAgenticWorkflow as j, tracePageResponseSchema as ja, getNestedWorkflow as jc, knowledgeLinkRefKey as ji, validateStepInput as jl, renderBuiltInToolEvent as jn, MastraMemory as jo, ScoresInMemory as jr, EventedRun as js, runStreamCompletionScorers as jt, persistDurableRunInput as k, tracePageNodeSchema as ka, isWorkflowStepConflictError as kc, assertKnowledgePageDescriptionWithinBound as ki, runCountDeprecationMessage as kl, ChatChannelProcessor as kn, resolveMaxChunkChars as ko, InMemoryToolProviderConnectionsStorage as kr, createEventedWorkflow as ks, runCompletionScorers as kt, flushBeforeTraceRead as l, runRetentionBatches as la, getExecutingInstances as lc, KnowledgeTransactionDeadlineError as li, RESUME_SNAPSHOT_WAIT_STATUSES as ll, knowledgeReadScopeFor as ln, buildFeedbackRecord as lo, knowledgeSemanticDocumentId as lr, ModelSelectionProcessor as ls, AgentStreamBus as lt, ToolInvocationPartSchema as lu, ScorerRunError as m, filterByDateRange as ma, takeRunScorerInstances as mc, parseKnowledgeWikilinks as mi, createDeprecationProxy as ml, knowledgeRunScopes as mn, getObjectOrNull as mo, StoreOperations as mr, PromptInjectionDetector as ms, __registerMastraCtor as mt, RUN_FENCING_NOT_SUPPORTED_ERROR_ID as mu, getExecutionClaimScope as n, InMemoryBlobStore as na, DURABLE_CONTEXT_SEGMENT_KEY as nc, KnowledgeImportersStorage as ni, normalizeConcurrency as nl, knowledgeSubtree as nn, spanQueryRowSchema as no, assertKnowledgeRecordTextWithinBound as nr, groupLinkedToolMessages as ns, runDurableFinishSideEffects as nt, ProcessorStepInputSchema as nu, AGENTIC_LOOP_WORKFLOW_ID as o, executeRetentionPrune as oa, deleteRunRegistryEntry as oc, KnowledgeNotFoundError$1 as oi, createStepFromClassifier as ol, syncKnowledgePageBodyLinks as on, planThreadQuery as oo, expandKnowledgeScope as or, isAfterMemoryTokenBoundary as os, RUN_DEADLINE_KEY as ot, SourcePartSchema as ou, MastraScorer as p, ensureDate as pa, setRunRegistryEntry as pc, inspectKnowledgeSchema as pi, cleanStepResult as pl, knowledgeMemoryScopes as pn, buildUpdateSpanRecord as po, StoreOperationsInMemory as pr, PIIDetector as ps, createRunAbortController as pt, RUN_FENCE_CONFLICT_ERROR_ID as pu, calculateAccumulatedUsage as q, encodeSpanQueryCursor as qa, SCORING_PREDICATE_ROOTS as qc, SchemaValidator as qi, MessageContentSchema as ql, MessageHistory as qn, formatSkillsCatalog as qo, MAX_NOTIFICATION_DELIVERY_ATTEMPTS as qr, emitSuspendedEvent as qs, removeKnowledgePage as qt, AgentThreadLeaseLostError as r, BlobStore as ra, ExtendedRunRegistry as rc, KNOWLEDGE_STORAGE_CONTRACT_VERSION as ri, runWithConcurrency as rl, refreshKnowledgeLinksTo as rn, encodeTraceQueryCursor as ro, assertKnowledgeScopeWithinCeiling as rr, loadMessageHistory as rs, loadRunStoredMessages as rt, ProcessorStepOutputSchema as ru, describeNonSuccessFinishReason as s, resolveRetentionTargets as sa, endRunSpansWithError as sc, KnowledgeSchemaResetRequiredError as si, createStepFromTool as sl, updateKnowledgeLinks as sn, planTraceQuery as so, isKnowledgeScopeVisible as sr, normalizeMessageHistoryConfig as ss, ensureRemoteAbortListener as st, StepStartPartSchema as su, __resetExecutionFencesForTests as t, ChannelsStorage as ta, resolveAgentById as tc, KnowledgeImporterRunStateError as ti, createConcurrencyLimiter as tl, canRepairKnowledgeLinksInBatch as tn, spanQueryResponseSchema as to, assertKnowledgeDescriptionWithinBound as tr, TokenLimiterProcessor as ts, executeDurableAgentScorers as tt, ProcessorOutputStreamPhaseSchema as tu, createOnScorerHook as u, createStorageErrorId as ua, getRunRegistryEntry as uc, KnowledgeUnsupportedCapabilityError as ui, abortableSleep as ul, knowledgeRoleOn as un, buildLogRecord as uo, knowledgeSemanticIdempotencyKey as ur, ClassifierProcessor as us, publishAbortRequest as ut, isAgentCompatible as uu, notScorable as v, jsonValueEquals as va, segmentEndedBySuspension as vc, KnowledgePageKeyConflictError as vi, defineStateAccessors as vl, encodeKnowledgeScopeId as vn, ObservabilityInMemory as vo, FilesystemDB as vr, defaultStabilityErrorProcessors as vs, pruneAgentLoopSnapshot as vt, isRunFenceConflictError as vu, AGENT_RESUME_CLAIM_STALE_MS as w, transformScoreRow as wa, AGENT_STREAM_TOPIC as wc, MAX_KNOWLEDGE_PAGE_LINKS as wi, isEntryFinished as wl, MastraStateAdapter as wn, MESSAGE_EMBEDDING_CHARS_PER_TOKEN as wo, createEmptyWorkflowSnapshot as wr, isBadRequestError as ws, formatStreamCompletionFeedback as wt, assembleAgentFromFsEntry as x, serializeDate as xa, DurableAgentDefaults as xc, MAX_KNOWLEDGE_PAGE_BODY_LINKS as xi, getSingleStepEntryId as xl, resolveWaitUntil as xn, FactoryStorageDomain as xo, WorkflowsInMemory as xr, FileUploadProcessor as xs, getServerSideFallbackInfo as xt, runFencingNotSupportedError as xu, agentConfig as y, parseDuration as ya, segmentSpanData as yc, MAX_KNOWLEDGE_MOVE_PAGES as yi, getRestartStartIndex as yl, buildKnowledgeInstructions as yn, ObservabilityStorage as yo, InMemoryStore as yr, isMalformedFunctionCallError as ys, DEFAULT_TOOL_DECLINE_REASON as yt, matchesRunFence as yu, serializeModelConfig as z, threadQueryRowSchema as za, predicateToCondition as zc, knowledgePageKeyProblem as zi, assertDrainTimeout as zl, createChannelTools as zn, CyberRefusalHandler as zo, createNotificationSignal as zr, computeScheduleDefinitionHash as zs, KnowledgeRun as zt };