@mastra/core 1.87.0-alpha.0 → 1.87.0-alpha.10

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 (503) hide show
  1. package/dist/_types/@ai-sdk_anthropic@3.0.137/dist/index.d.ts +2 -2
  2. package/dist/_types/@ai-sdk_google@3.0.140/dist/index.d.ts +2 -2
  3. package/dist/_types/@ai-sdk_openai@3.0.135/dist/index.d.ts +2 -2
  4. package/dist/_types/@ai-sdk_openai@4.0.106/dist/index.d.ts +2034 -0
  5. package/dist/_types/@ai-sdk_openai@4.0.106/package.json +1 -0
  6. package/dist/a2a/index.cjs +1 -1
  7. package/dist/a2a/index.js +1 -1
  8. package/dist/agent/agent.d.ts +3 -1
  9. package/dist/agent/durable/index.cjs +2 -1
  10. package/dist/agent/durable/index.d.ts +1 -0
  11. package/dist/agent/durable/index.js +2 -2
  12. package/dist/agent/durable/run-message-refs.d.ts +3 -2
  13. package/dist/agent/durable/run-registry.d.ts +12 -1
  14. package/dist/agent/durable/types.d.ts +2 -0
  15. package/dist/agent/durable/workflows/finalize-run.d.ts +2 -1
  16. package/dist/agent/index.cjs +5 -4
  17. package/dist/agent/index.d.ts +2 -0
  18. package/dist/agent/index.js +5 -5
  19. package/dist/agent/merge-persona.d.ts +15 -0
  20. package/dist/agent/message-list/adapters/AIV5Adapter.d.ts +15 -1
  21. package/dist/agent/message-list/index.cjs +2 -2
  22. package/dist/agent/message-list/index.js +2 -2
  23. package/dist/agent/message-list/state/types.d.ts +5 -1
  24. package/dist/agent/message-list/types.d.ts +1 -1
  25. package/dist/agent/message-list/utils/provider-compat.d.ts +9 -1
  26. package/dist/agent/thread-stream-runtime.d.ts +3 -1
  27. package/dist/agent-builder/ee/index.cjs +1 -1
  28. package/dist/agent-builder/ee/index.js +1 -1
  29. package/dist/agent-controller/agent-controller.d.ts +6 -0
  30. package/dist/agent-controller/index.cjs +2 -2
  31. package/dist/agent-controller/index.js +2 -2
  32. package/dist/agent-controller/worker-run-binding.d.ts +15 -0
  33. package/dist/{agent-controller-B8LoFdtu.js → agent-controller--gKWI81G.js} +50 -8
  34. package/dist/{agent-controller-DSnFynpa.cjs → agent-controller-BolLBwDm.cjs} +50 -8
  35. package/dist/background-tasks/index.cjs +2 -1
  36. package/dist/background-tasks/index.d.ts +1 -1
  37. package/dist/background-tasks/index.js +1 -1
  38. package/dist/background-tasks/resolve-config.d.ts +30 -1
  39. package/dist/background-tasks/system-prompt.d.ts +8 -2
  40. package/dist/background-tasks/types.d.ts +47 -1
  41. package/dist/{background-tasks-IW7M4iD2.js → background-tasks-CgzXjBfE.js} +156 -33
  42. package/dist/{background-tasks-Ci5h0dhj.cjs → background-tasks-DYtlijQ1.cjs} +167 -32
  43. package/dist/browser/index.cjs +2 -2
  44. package/dist/browser/index.js +2 -2
  45. package/dist/{builder-14Uptu8y.cjs → builder-Dz-g-9CZ.cjs} +2 -2
  46. package/dist/{builder-DI2c2xjy.js → builder-emNPaIaC.js} +2 -2
  47. package/dist/capabilities/302ai.json +202 -202
  48. package/dist/capabilities/abliteratedllm.json +36 -27
  49. package/dist/capabilities/abliteration-ai.json +12 -12
  50. package/dist/capabilities/above.json +14 -14
  51. package/dist/capabilities/adaption.json +9 -9
  52. package/dist/capabilities/adzuki.json +26 -26
  53. package/dist/capabilities/agentrouter.json +4 -4
  54. package/dist/capabilities/agnes.json +2 -2
  55. package/dist/capabilities/ai-router.json +5 -5
  56. package/dist/capabilities/aiand.json +11 -11
  57. package/dist/capabilities/aigrow.json +14 -14
  58. package/dist/capabilities/aimlapi.json +154 -158
  59. package/dist/capabilities/aixy.json +21 -21
  60. package/dist/capabilities/aki-io.json +14 -14
  61. package/dist/capabilities/alibaba-cn.json +107 -101
  62. package/dist/capabilities/alibaba-coding-plan-cn.json +3 -3
  63. package/dist/capabilities/alibaba-coding-plan.json +3 -3
  64. package/dist/capabilities/alibaba-token-plan-cn.json +53 -53
  65. package/dist/capabilities/alibaba-token-plan.json +53 -53
  66. package/dist/capabilities/alibaba.json +99 -65
  67. package/dist/capabilities/ambient.json +14 -7
  68. package/dist/capabilities/amd.json +8 -8
  69. package/dist/capabilities/anthropic.json +47 -47
  70. package/dist/capabilities/anyapi.json +19 -19
  71. package/dist/capabilities/apiko.json +2 -2
  72. package/dist/capabilities/arcee.json +4 -4
  73. package/dist/capabilities/augure.json +5 -5
  74. package/dist/capabilities/auriko.json +22 -22
  75. package/dist/capabilities/bailing.json +3 -3
  76. package/dist/capabilities/baseten.json +25 -25
  77. package/dist/capabilities/bee.json +5 -5
  78. package/dist/capabilities/berget.json +14 -1
  79. package/dist/capabilities/bothub.json +17 -17
  80. package/dist/capabilities/boundless.json +31 -31
  81. package/dist/capabilities/bumo.json +40 -40
  82. package/dist/capabilities/byteplus.json +29 -29
  83. package/dist/capabilities/cheapaimodel.json +9 -9
  84. package/dist/capabilities/cheapest-token.json +30 -30
  85. package/dist/capabilities/chutes.json +9 -9
  86. package/dist/capabilities/claudinio.json +10 -1
  87. package/dist/capabilities/cline-pass.json +40 -40
  88. package/dist/capabilities/cloudcode.json +8 -15
  89. package/dist/capabilities/cloudflare-workers-ai.json +8 -8
  90. package/dist/capabilities/commandcode.json +145 -145
  91. package/dist/capabilities/concentrate.json +272 -289
  92. package/dist/capabilities/cortecs.json +110 -110
  93. package/dist/capabilities/crossmodel.json +182 -182
  94. package/dist/capabilities/crusoe.json +37 -8
  95. package/dist/capabilities/daoxe.json +8 -8
  96. package/dist/capabilities/databricks.json +130 -130
  97. package/dist/capabilities/deepinfra.json +92 -83
  98. package/dist/capabilities/digitalocean.json +112 -112
  99. package/dist/capabilities/dothoosh.json +31 -31
  100. package/dist/capabilities/doubleword.json +22 -22
  101. package/dist/capabilities/edenai.json +898 -1743
  102. package/dist/capabilities/empiriolabs.json +168 -168
  103. package/dist/capabilities/engy.json +19 -19
  104. package/dist/capabilities/entrim.json +2 -2
  105. package/dist/capabilities/evroc.json +12 -12
  106. package/dist/capabilities/ezkielyna.json +11 -11
  107. package/dist/capabilities/fastrouter.json +82 -82
  108. package/dist/capabilities/fireworks-ai.json +125 -64
  109. package/dist/capabilities/fortytwo.json +9 -3
  110. package/dist/capabilities/freemodel.json +19 -19
  111. package/dist/capabilities/friendli.json +8 -8
  112. package/dist/capabilities/frogbot.json +100 -100
  113. package/dist/capabilities/gisoo.json +20 -20
  114. package/dist/capabilities/gmicloud.json +23 -23
  115. package/dist/capabilities/google.json +50 -50
  116. package/dist/capabilities/graphn.json +13 -13
  117. package/dist/capabilities/greenpt.json +35 -35
  118. package/dist/capabilities/groq.json +3 -3
  119. package/dist/capabilities/helicone.json +84 -84
  120. package/dist/capabilities/hetzner.json +35 -3
  121. package/dist/capabilities/hostinger-router.json +15 -15
  122. package/dist/capabilities/hpc-ai.json +12 -12
  123. package/dist/capabilities/huawei-maas.json +14 -14
  124. package/dist/capabilities/hubris.json +33 -33
  125. package/dist/capabilities/huggingface.json +108 -158
  126. package/dist/capabilities/humain.json +2 -2
  127. package/dist/capabilities/hyper.json +20 -28
  128. package/dist/capabilities/impossibl.json +152 -152
  129. package/dist/capabilities/inception.json +2 -2
  130. package/dist/capabilities/inceptron.json +6 -6
  131. package/dist/capabilities/inco.json +5 -5
  132. package/dist/capabilities/infer.json +20 -20
  133. package/dist/capabilities/inferall.json +10 -10
  134. package/dist/capabilities/inference-coop.json +15 -15
  135. package/dist/capabilities/inferenceapis.json +11 -11
  136. package/dist/capabilities/inferris.json +3 -3
  137. package/dist/capabilities/infersia.json +11 -11
  138. package/dist/capabilities/infomaniak.json +2 -2
  139. package/dist/capabilities/iteracompute.json +48 -48
  140. package/dist/capabilities/jad-ai.json +2 -2
  141. package/dist/capabilities/jalapeno.json +12 -12
  142. package/dist/capabilities/jiekou.json +58 -58
  143. package/dist/capabilities/jzstoken.json +53 -54
  144. package/dist/capabilities/keln.json +13 -13
  145. package/dist/capabilities/kenari.json +119 -127
  146. package/dist/capabilities/kilo.json +643 -647
  147. package/dist/capabilities/kimi-code-plan-cn.json +6 -6
  148. package/dist/capabilities/kimi-code-plan-global.json +6 -6
  149. package/dist/capabilities/kitani.json +6 -6
  150. package/dist/capabilities/klavo.json +14 -14
  151. package/dist/capabilities/korouter.json +34 -34
  152. package/dist/capabilities/kunavo.json +7 -7
  153. package/dist/capabilities/liquid.json +11 -11
  154. package/dist/capabilities/lithosai.json +3 -3
  155. package/dist/capabilities/llmgateway-providers.json +949 -880
  156. package/dist/capabilities/llmgateway.json +344 -343
  157. package/dist/capabilities/llmtr.json +29 -29
  158. package/dist/capabilities/longcat.json +2 -2
  159. package/dist/capabilities/lowrouter.json +53 -53
  160. package/dist/capabilities/lyceum.json +17 -9
  161. package/dist/capabilities/melious.json +14 -14
  162. package/dist/capabilities/merge-gateway.json +303 -301
  163. package/dist/capabilities/meta.json +9 -9
  164. package/dist/capabilities/mistral.json +20 -20
  165. package/dist/capabilities/mixlayer.json +2 -2
  166. package/dist/capabilities/modal.json +10 -10
  167. package/dist/capabilities/model-oracle-ai.json +23 -23
  168. package/dist/capabilities/modelis.json +22 -22
  169. package/dist/capabilities/modular.json +31 -9
  170. package/dist/capabilities/moneo.json +13 -13
  171. package/dist/capabilities/moonshotai-cn.json +6 -6
  172. package/dist/capabilities/moonshotai.json +6 -6
  173. package/dist/capabilities/morph.json +15 -15
  174. package/dist/capabilities/munito.json +2 -2
  175. package/dist/capabilities/nan.json +24 -24
  176. package/dist/capabilities/nano-gpt.json +595 -580
  177. package/dist/capabilities/nearai.json +101 -101
  178. package/dist/capabilities/nebius.json +26 -26
  179. package/dist/capabilities/neon.json +125 -125
  180. package/dist/capabilities/neuralwatt.json +43 -43
  181. package/dist/capabilities/nokeep.json +4 -4
  182. package/dist/capabilities/novita-ai.json +123 -123
  183. package/dist/capabilities/nvidia.json +39 -22
  184. package/dist/capabilities/oathbreaker.json +26 -3
  185. package/dist/capabilities/obscurify.json +22 -22
  186. package/dist/capabilities/oci.json +5 -5
  187. package/dist/capabilities/ofox.json +327 -327
  188. package/dist/capabilities/ollama-cloud.json +58 -58
  189. package/dist/capabilities/openai.json +57 -57
  190. package/dist/capabilities/opencode-go.json +90 -90
  191. package/dist/capabilities/openreason.json +5 -5
  192. package/dist/capabilities/openrouter.json +561 -557
  193. package/dist/capabilities/opper.json +30 -30
  194. package/dist/capabilities/orcarouter.json +238 -238
  195. package/dist/capabilities/outerlabs.json +29 -29
  196. package/dist/capabilities/ovhcloud.json +20 -20
  197. package/dist/capabilities/pareto.json +4 -4
  198. package/dist/capabilities/pendra.json +4 -4
  199. package/dist/capabilities/perplexity-agent.json +63 -63
  200. package/dist/capabilities/phala.json +22 -22
  201. package/dist/capabilities/pioneer.json +26 -26
  202. package/dist/capabilities/poe.json +134 -134
  203. package/dist/capabilities/poolside.json +3 -3
  204. package/dist/capabilities/powerspring.json +8 -8
  205. package/dist/capabilities/primalabs.json +8 -8
  206. package/dist/capabilities/prime.json +133 -123
  207. package/dist/capabilities/privatemode-ai.json +13 -13
  208. package/dist/capabilities/proxystacks.json +6 -6
  209. package/dist/capabilities/qiniu-ai.json +15 -15
  210. package/dist/capabilities/refuseless.json +6 -6
  211. package/dist/capabilities/regolo-ai.json +9 -9
  212. package/dist/capabilities/requesty.json +386 -171
  213. package/dist/capabilities/ruapi.json +29 -13
  214. package/dist/capabilities/runcrate.json +8 -8
  215. package/dist/capabilities/runinfra.json +9 -9
  216. package/dist/capabilities/sakana.json +3 -3
  217. package/dist/capabilities/sambanova.json +5 -5
  218. package/dist/capabilities/sandbase.json +17 -17
  219. package/dist/capabilities/sarvam.json +14 -14
  220. package/dist/capabilities/scaleway.json +13 -13
  221. package/dist/capabilities/scnet-token-plan.json +12 -12
  222. package/dist/capabilities/scx-ai.json +22 -22
  223. package/dist/capabilities/sensenova.json +10 -10
  224. package/dist/capabilities/siliconflow-cn.json +49 -49
  225. package/dist/capabilities/siliconflow.json +54 -54
  226. package/dist/capabilities/snowflake-cortex.json +17 -17
  227. package/dist/capabilities/sokkan.json +5 -5
  228. package/dist/capabilities/sparrowcodes.json +23 -23
  229. package/dist/capabilities/standardcompute.json +94 -94
  230. package/dist/capabilities/steadyrouter.json +40 -40
  231. package/dist/capabilities/stepfun-ai-step-plan.json +5 -5
  232. package/dist/capabilities/stepfun-ai.json +5 -5
  233. package/dist/capabilities/stepfun-step-plan.json +5 -5
  234. package/dist/capabilities/stepfun.json +5 -5
  235. package/dist/capabilities/stepping-stone.json +9 -9
  236. package/dist/capabilities/subconscious.json +2 -2
  237. package/dist/capabilities/synthetic.json +10 -10
  238. package/dist/capabilities/synthorai.json +22 -22
  239. package/dist/capabilities/teamorouter.json +23 -23
  240. package/dist/capabilities/teapot-router.json +12 -12
  241. package/dist/capabilities/tencent-token-plan-intl.json +126 -0
  242. package/dist/capabilities/tencent-token-plan.json +35 -35
  243. package/dist/capabilities/tencent-tokenhub.json +51 -36
  244. package/dist/capabilities/tensorx.json +44 -44
  245. package/dist/capabilities/tenstorrent.json +6 -6
  246. package/dist/capabilities/the-grid-ai.json +32 -32
  247. package/dist/capabilities/thinkingmachines.json +48 -48
  248. package/dist/capabilities/tinfoil.json +11 -11
  249. package/dist/capabilities/toapis.json +2 -2
  250. package/dist/capabilities/togetherai.json +40 -40
  251. package/dist/capabilities/tokengo.json +25 -25
  252. package/dist/capabilities/tokenify.json +9 -9
  253. package/dist/capabilities/tokenwatt.json +10 -2
  254. package/dist/capabilities/trustedrouter.json +6 -6
  255. package/dist/capabilities/trustedtokens.json +13 -13
  256. package/dist/capabilities/umans-ai-coding-plan.json +14 -14
  257. package/dist/capabilities/umans-ai.json +12 -12
  258. package/dist/capabilities/uncensuredai.json +2 -2
  259. package/dist/capabilities/unrestricted.json +8 -8
  260. package/dist/capabilities/uplinkswitch.json +18 -18
  261. package/dist/capabilities/upstage.json +6 -6
  262. package/dist/capabilities/vancine.json +18 -18
  263. package/dist/capabilities/vercel.json +590 -587
  264. package/dist/capabilities/vivgrid.json +87 -78
  265. package/dist/capabilities/volcengine-coding-plan.json +32 -23
  266. package/dist/capabilities/volcengine.json +31 -30
  267. package/dist/capabilities/vultr.json +26 -26
  268. package/dist/capabilities/wafer.ai.json +18 -18
  269. package/dist/capabilities/wallaby.json +5 -5
  270. package/dist/capabilities/wally.json +10 -10
  271. package/dist/capabilities/wandb.json +10 -10
  272. package/dist/capabilities/watt.json +26 -26
  273. package/dist/capabilities/xai.json +4 -4
  274. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -2
  275. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -2
  276. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -2
  277. package/dist/capabilities/xiaomi.json +2 -2
  278. package/dist/capabilities/xpersona.json +13 -13
  279. package/dist/capabilities/xxapi.json +28 -28
  280. package/dist/capabilities/zai-coding-plan.json +18 -18
  281. package/dist/capabilities/zai.json +30 -30
  282. package/dist/capabilities/zenifra.json +30 -30
  283. package/dist/capabilities/zenmux.json +205 -205
  284. package/dist/capabilities/zerogpu.json +11 -11
  285. package/dist/capabilities/zhipuai-coding-plan.json +2 -2
  286. package/dist/capabilities/zhipuai.json +30 -30
  287. package/dist/capabilities/zro.json +4 -4
  288. package/dist/channels/agent-channels.d.ts +29 -0
  289. package/dist/channels/attach-file-tool.d.ts +22 -0
  290. package/dist/channels/index.cjs +11 -2
  291. package/dist/channels/index.d.ts +10 -0
  292. package/dist/channels/index.js +3 -3
  293. package/dist/channels/output-processor.d.ts +12 -0
  294. package/dist/channels/reply-guidance-processor.d.ts +26 -0
  295. package/dist/channels/reply-mode.d.ts +66 -0
  296. package/dist/channels/reply-reminder-processor.d.ts +23 -0
  297. package/dist/channels/reply-tool.d.ts +43 -0
  298. package/dist/channels/state-adapter.d.ts +3 -1
  299. package/dist/channels/stream-helpers.d.ts +17 -0
  300. package/dist/channels/thread-link-processor.d.ts +48 -0
  301. package/dist/channels/thread-lookup.d.ts +16 -0
  302. package/dist/channels/tool-announcement-processor.d.ts +29 -0
  303. package/dist/channels/types.d.ts +25 -0
  304. package/dist/{channels-tVV_de9Q.cjs → channels-BVnDIsZS.cjs} +122 -1
  305. package/dist/{channels-Wh32drgu.js → channels-CndspFXP.js} +99 -2
  306. package/dist/coding-agent/index.cjs +2 -2
  307. package/dist/coding-agent/index.js +2 -2
  308. package/dist/{constants-B9ZDvXZ4.cjs → constants-Bou0hEgY.cjs} +4 -0
  309. package/dist/{constants-BmdTvEYN.js → constants-CFWgIaqA.js} +4 -0
  310. package/dist/datasets/experiment/index.d.ts +1 -1
  311. package/dist/datasets/experiment/item.d.ts +4 -3
  312. package/dist/datasets/experiment/scorer.d.ts +45 -11
  313. package/dist/datasets/index.cjs +3 -2
  314. package/dist/datasets/index.js +3 -3
  315. package/dist/{dist-ByO0vuJJ-BjMue5_p.cjs → dist-CufwpBZM-CwERFaas.cjs} +4 -4
  316. package/dist/{dist-ByO0vuJJ-CCXLBnvJ.js → dist-CufwpBZM-DK14Qe0Z.js} +4 -4
  317. package/dist/docs/SKILL.md +3 -1
  318. package/dist/docs/assets/SOURCE_MAP.json +1070 -1055
  319. package/dist/docs/references/docs-agents-code-mode.md +36 -0
  320. package/dist/docs/references/docs-agents-networks.md +1 -1
  321. package/dist/docs/references/docs-agents-tools.md +6 -0
  322. package/dist/docs/references/docs-auth-simple-auth.md +8 -8
  323. package/dist/docs/references/docs-browser.md +3 -1
  324. package/dist/docs/references/docs-channels.md +43 -0
  325. package/dist/docs/references/docs-evals-custom-scorers.md +1 -1
  326. package/dist/docs/references/docs-evals-experiments.md +13 -3
  327. package/dist/docs/references/docs-harness-background-tasks.md +38 -0
  328. package/dist/docs/references/docs-knowledge-agents-and-tools.md +2 -0
  329. package/dist/docs/references/docs-mastra-platform-observability-overview.md +3 -189
  330. package/dist/docs/references/docs-memory-message-history.md +25 -0
  331. package/dist/docs/references/docs-sandbox-lsp.md +5 -6
  332. package/dist/docs/references/docs-sandbox-overview.md +20 -0
  333. package/dist/docs/references/docs-sandbox-skills.md +2 -0
  334. package/dist/docs/references/docs-signals-sending-signals.md +1 -1
  335. package/dist/docs/references/integrations.md +1 -0
  336. package/dist/docs/references/reference-agent-controller-session.md +1 -1
  337. package/dist/docs/references/reference-agents-durable-agent.md +2 -0
  338. package/dist/docs/references/reference-agents-generate.md +1 -1
  339. package/dist/docs/references/reference-agents-network.md +1 -1
  340. package/dist/docs/references/reference-channels-thread-link.md +67 -0
  341. package/dist/docs/references/reference-configuration.md +8 -8
  342. package/dist/docs/references/reference-core-getWorkspaceById.md +37 -0
  343. package/dist/docs/references/reference-evals-create-scorer.md +5 -5
  344. package/dist/docs/references/reference-evals-run-evals.md +1 -1
  345. package/dist/docs/references/reference-knowledge-knowledge-tools.md +3 -3
  346. package/dist/docs/references/reference-manual-install.md +1 -1
  347. package/dist/docs/references/reference-memory-observational-memory.md +8 -0
  348. package/dist/docs/references/reference-observability-tracing-interfaces.md +10 -6
  349. package/dist/docs/references/reference-processors-processor-interface.md +3 -2
  350. package/dist/docs/references/reference-processors-system-prompt-scrubber.md +1 -1
  351. package/dist/docs/references/reference-processors-tool-search-processor.md +3 -3
  352. package/dist/docs/references/reference-pubsub-base.md +5 -3
  353. package/dist/docs/references/reference-pubsub-caching-pubsub.md +3 -1
  354. package/dist/docs/references/reference-storage-overview.md +1 -1
  355. package/dist/docs/references/reference-storage-retention.md +20 -20
  356. package/dist/docs/references/reference-tools-create-code-mode.md +22 -0
  357. package/dist/docs/references/reference-tools-vector-query-tool.md +8 -0
  358. package/dist/docs/references/reference-voice-overview.md +11 -26
  359. package/dist/docs/references/reference-voice-speech-to-speech.md +1 -1
  360. package/dist/docs/references/reference-voice-voice.listen.md +1 -0
  361. package/dist/docs/references/reference-voice-voice.speak.md +1 -3
  362. package/dist/docs/references/reference-workspace-factory-sandbox.md +8 -7
  363. package/dist/docs/references/reference-workspace-sandbox.md +14 -0
  364. package/dist/docs/references/reference.md +2 -0
  365. package/dist/evals/index.cjs +2 -2
  366. package/dist/evals/index.js +2 -2
  367. package/dist/evals/scoreTraces/index.cjs +2 -2
  368. package/dist/evals/scoreTraces/index.js +2 -2
  369. package/dist/events/index.cjs +1 -1
  370. package/dist/events/index.js +1 -1
  371. package/dist/harness/index.cjs +2 -2
  372. package/dist/harness/index.js +2 -2
  373. package/dist/index.cjs +1 -1
  374. package/dist/index.js +1 -1
  375. package/dist/knowledge/agent-scopes.d.ts +17 -0
  376. package/dist/knowledge/declarations.d.ts +2 -0
  377. package/dist/knowledge/held-scopes-state-processor.d.ts +50 -0
  378. package/dist/knowledge/importers/host.d.ts +7 -1
  379. package/dist/knowledge/importers/runner.d.ts +12 -0
  380. package/dist/knowledge/importers/types.d.ts +4 -0
  381. package/dist/knowledge/index.cjs +209 -38
  382. package/dist/knowledge/index.d.ts +12 -2
  383. package/dist/knowledge/index.js +208 -39
  384. package/dist/knowledge/page-tools.d.ts +23 -0
  385. package/dist/knowledge/pinned-state-processor.d.ts +2 -2
  386. package/dist/knowledge/run.d.ts +5 -0
  387. package/dist/knowledge/scope-runtime.d.ts +6 -0
  388. package/dist/llm/index.cjs +3 -3
  389. package/dist/llm/index.js +3 -3
  390. package/dist/llm/model/base.types.d.ts +3 -1
  391. package/dist/llm/model/mastra-gateway-provider-tools.d.ts +9 -6
  392. package/dist/llm/model/model.d.ts +1 -1
  393. package/dist/llm/model/model.loop.d.ts +1 -1
  394. package/dist/llm/model/model.loop.types.d.ts +3 -1
  395. package/dist/llm/model/provider-options.d.ts +4 -3
  396. package/dist/llm/model/provider-types.generated.d.ts +7091 -7163
  397. package/dist/{llm-BAiOsNAP.cjs → llm-B1semiTO.cjs} +38 -78
  398. package/dist/{llm-B1zaFLYZ.js → llm-CytL7cpw.js} +38 -78
  399. package/dist/loop/index.cjs +2 -2
  400. package/dist/loop/index.js +2 -2
  401. package/dist/{manager-BVX9nVrM.cjs → manager-BwyfS4ha.cjs} +220 -93
  402. package/dist/{manager-ChK9GdGz.js → manager-DnTzA9GL.js} +215 -94
  403. package/dist/mastra/index.cjs +1 -1
  404. package/dist/mastra/index.js +1 -1
  405. package/dist/{mastra-CUGfgEpZ.js → mastra-DTkZPpch.js} +17 -17
  406. package/dist/{mastra-HSmofHEJ.cjs → mastra-Dj35Lj_J.cjs} +17 -17
  407. package/dist/memory/index.cjs +3 -3
  408. package/dist/memory/index.js +3 -3
  409. package/dist/{message-list-KRbg-TnI.js → message-list-BGm1DCiG.js} +231 -130
  410. package/dist/{message-list-Cj0Sq_JP.cjs → message-list-vR3uLAHL.cjs} +351 -250
  411. package/dist/{model-C47BJRtR.js → model-DyQ07rPH.js} +4 -3
  412. package/dist/{model-WahorgzJ.cjs → model-eDfetuno.cjs} +4 -3
  413. package/dist/{netlify-D99AnEhW.cjs → netlify-BC4v7Ufv.cjs} +41377 -30474
  414. package/dist/{netlify-CfDXkuLf.js → netlify-BUvdxfHe.js} +41373 -30476
  415. package/dist/notifications/index.cjs +1 -1
  416. package/dist/notifications/index.js +1 -1
  417. package/dist/observability/types/tracing.d.ts +1 -1
  418. package/dist/processor-provider/index.cjs +1 -1
  419. package/dist/processor-provider/index.js +1 -1
  420. package/dist/processors/index.cjs +2 -2
  421. package/dist/processors/index.js +2 -2
  422. package/dist/processors/processors/tool-search.d.ts +2 -2
  423. package/dist/processors/runner.d.ts +12 -0
  424. package/dist/{provider-registry-CO1NVbO5.cjs → provider-registry-Bn01gq9y.cjs} +22180 -22242
  425. package/dist/{provider-registry-CR385GJ4.js → provider-registry-CP_5SNiw.js} +22181 -22243
  426. package/dist/provider-registry.json +22417 -22539
  427. package/dist/{registry-generator-B3erRqYS.js → registry-generator-CDPyxbzt.js} +1 -1
  428. package/dist/{registry-generator-Cvp34qcB.cjs → registry-generator-CNFKGRFQ.cjs} +1 -1
  429. package/dist/{rehydrate-CJBLrZxs.js → rehydrate-CnGNY2zq.js} +2 -2
  430. package/dist/{rehydrate-Da4hNuaK.cjs → rehydrate-DExpzlNS.cjs} +2 -2
  431. package/dist/relevance/index.cjs +2 -2
  432. package/dist/relevance/index.js +2 -2
  433. package/dist/{run-registry-DdeEBsVW.js → run-registry-BL_kKvFE.js} +1559 -298
  434. package/dist/{run-registry-TOOfO3hT.cjs → run-registry-CibQoN6K.cjs} +1637 -298
  435. package/dist/storage/constants.cjs +1 -1
  436. package/dist/storage/constants.js +1 -1
  437. package/dist/storage/domains/knowledge/base.d.ts +16 -1
  438. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +1 -0
  439. package/dist/storage/domains/knowledge/importers.d.ts +8 -0
  440. package/dist/storage/domains/knowledge/inmemory.d.ts +1 -0
  441. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +5 -1
  442. package/dist/storage/index.cjs +3 -3
  443. package/dist/storage/index.js +3 -3
  444. package/dist/storage/types.d.ts +8 -0
  445. package/dist/stream/index.cjs +2 -2
  446. package/dist/stream/index.js +2 -2
  447. package/dist/{stream-C5PagEDs.js → stream-1DGoEkG2.js} +37 -14
  448. package/dist/{stream-DH7Qgz8l.cjs → stream-D_7tMaJe.cjs} +37 -14
  449. package/dist/test-utils/llm-mock.cjs +1 -1
  450. package/dist/test-utils/llm-mock.js +1 -1
  451. package/dist/{to-prompt-B9eZo2U5.cjs → to-prompt-CG-LyaBY.cjs} +9 -0
  452. package/dist/{to-prompt-BsDtVXrf.js → to-prompt-CMlVGYxC.js} +9 -0
  453. package/dist/tool-loop-agent/index.cjs +1 -1
  454. package/dist/tool-loop-agent/index.js +1 -1
  455. package/dist/{tool-loop-agent-DVYJXlQJ.js → tool-loop-agent-BXya_RYj.js} +4 -4
  456. package/dist/{tool-loop-agent-CJTs4T8b.cjs → tool-loop-agent-CLB1r3X3.cjs} +4 -4
  457. package/dist/tools/code-mode/index.d.ts +2 -0
  458. package/dist/tools/code-mode/log-collector.d.ts +49 -0
  459. package/dist/tools/code-mode/types.d.ts +71 -0
  460. package/dist/tools/index.cjs +3 -1
  461. package/dist/tools/index.js +2 -2
  462. package/dist/{tools-CGF5Ik6j.cjs → tools-BEYxowf0.cjs} +429 -61
  463. package/dist/{tools-CDfyMpzN.js → tools-tPy2FwMI.js} +418 -62
  464. package/dist/{utils-xJi_N6Tx.cjs → utils-B-KOMA_Q.cjs} +7 -6
  465. package/dist/{utils-D8upuTwy.js → utils-C55ZdVaj.js} +7 -6
  466. package/dist/utils.cjs +1 -1
  467. package/dist/utils.js +1 -1
  468. package/dist/{validate-DTkW3Vlp.js → validate-BDfYr72F.js} +1 -1
  469. package/dist/{validate-6eZ8Wssn.cjs → validate-CmZhnsmX.cjs} +1 -1
  470. package/dist/vector/index.cjs +2 -2
  471. package/dist/vector/index.js +2 -2
  472. package/dist/worker/index.cjs +1 -1
  473. package/dist/worker/index.js +1 -1
  474. package/dist/worker/workers/orchestration-worker.d.ts +1 -0
  475. package/dist/{worker-DbcFkKJO.js → worker-BG1rw_dg.js} +5 -5
  476. package/dist/{worker-24ORi-wV.cjs → worker-BoybIUTI.cjs} +10 -4
  477. package/dist/{worker-Dqubrnf8.js → worker-CuK2RaC0.js} +2 -2
  478. package/dist/{worker-BO3u_WjZ.cjs → worker-D2B-x7Le.cjs} +2 -2
  479. package/dist/{workflow-wXOf72fO.js → workflow-Bt09PcH1.js} +3 -3
  480. package/dist/{workflow-D5Fc5ieC.cjs → workflow-CTKqeRXU.cjs} +3 -3
  481. package/dist/workflows/builder/index.cjs +1 -1
  482. package/dist/workflows/builder/index.js +1 -1
  483. package/dist/workflows/evented/index.cjs +1 -1
  484. package/dist/workflows/evented/index.js +1 -1
  485. package/dist/workflows/index.cjs +4 -4
  486. package/dist/workflows/index.js +4 -4
  487. package/dist/workflows/step.d.ts +2 -0
  488. package/dist/workflows/workflow.d.ts +2 -0
  489. package/dist/workspace/index.cjs +3 -1
  490. package/dist/workspace/index.d.ts +1 -1
  491. package/dist/workspace/index.js +2 -2
  492. package/dist/workspace/lsp/manager.d.ts +19 -4
  493. package/dist/workspace/sandbox/mastra-sandbox.d.ts +17 -0
  494. package/dist/workspace/sandbox/teardown-context.d.ts +74 -0
  495. package/dist/workspace/tools/index.d.ts +1 -0
  496. package/dist/workspace/tools/media.d.ts +20 -1
  497. package/dist/workspace/tools/recreate-sandbox.d.ts +24 -0
  498. package/dist/{workspace-X2RHJZU9.cjs → workspace-C8Zo5_qK.cjs} +387 -109
  499. package/dist/{workspace-DY2Nxiyi.js → workspace-DOAil8mG.js} +376 -110
  500. package/package.json +8 -8
  501. package/src/llm/model/provider-types.generated.d.ts +7091 -7163
  502. /package/dist/_types/{@ai-sdk_provider-utils@4.0.66 → @ai-sdk_provider-utils@4.0.67}/dist/index.d.ts +0 -0
  503. /package/dist/_types/{@ai-sdk_provider-utils@4.0.66 → @ai-sdk_provider-utils@4.0.67}/package.json +0 -0
@@ -4,18 +4,18 @@ const require_base = require("./base-BIzR1D3_.cjs");
4
4
  const require_observability = require("./observability-B0R_D1PZ.cjs");
5
5
  const require_error = require("./error-D90lJ6M7.cjs");
6
6
  const require_error$1 = require("./error-L1V4uUbd.cjs");
7
- const require_stream = require("./stream-DH7Qgz8l.cjs");
7
+ const require_stream = require("./stream-D_7tMaJe.cjs");
8
8
  const require_request_context = require("./request-context-D9RXYCy8.cjs");
9
9
  const require_output_helpers = require("./output-helpers-DgsH4aTb.cjs");
10
- const require_message_list = require("./message-list-Cj0Sq_JP.cjs");
10
+ const require_message_list = require("./message-list-vR3uLAHL.cjs");
11
11
  const require_storage = require("./storage-CfG0I2aF.cjs");
12
12
  const require_utils = require("./utils-D-eNsgDM.cjs");
13
13
  const require_error_count = require("./error-count-DeDpeWU2.cjs");
14
- const require_llm = require("./llm-BAiOsNAP.cjs");
14
+ const require_llm = require("./llm-B1semiTO.cjs");
15
15
  const require_payload_transform = require("./payload-transform-CWgnsO9w.cjs");
16
16
  const require_utils_safe_stringify = require("./utils/safe-stringify.cjs");
17
17
  const require_signals = require("./signals-CWxAMEmE.cjs");
18
- const require_to_prompt = require("./to-prompt-B9eZo2U5.cjs");
18
+ const require_to_prompt = require("./to-prompt-CG-LyaBY.cjs");
19
19
  const require_dist = require("./dist-P2rjrlmj.cjs");
20
20
  const require_dist$1 = require("./dist-CXeCeeW7.cjs");
21
21
  const require_deep_equal = require("./deep-equal-TMDmByBC.cjs");
@@ -23,13 +23,13 @@ const require_tool = require("./tool-CYlT2UA-.cjs");
23
23
  const require_toolchecks = require("./toolchecks-MFU48cit.cjs");
24
24
  const require_fetchWithRetry = require("./fetchWithRetry-f5k4p7_1.cjs");
25
25
  const require_model = require("./model-jBymoqGa.cjs");
26
- const require_provider_registry = require("./provider-registry-CO1NVbO5.cjs");
26
+ const require_provider_registry = require("./provider-registry-Bn01gq9y.cjs");
27
27
  const require_inmemory = require("./inmemory-Dc86VWGB.cjs");
28
28
  const require_dynamic_argument = require("./dynamic-argument-CUc1BBOS.cjs");
29
- const require_model$1 = require("./model-WahorgzJ.cjs");
30
- const require_utils$1 = require("./utils-xJi_N6Tx.cjs");
29
+ const require_model$1 = require("./model-eDfetuno.cjs");
30
+ const require_utils$1 = require("./utils-B-KOMA_Q.cjs");
31
31
  const require_ee_iTj2bRDt = require("./ee-iTj2bRDt-D3-QLGDF.cjs");
32
- const require_background_tasks = require("./background-tasks-Ci5h0dhj.cjs");
32
+ const require_background_tasks = require("./background-tasks-DYtlijQ1.cjs");
33
33
  const require_stream$1 = require("./stream-BGbj9jAU.cjs");
34
34
  const require_predicate_index = require("./predicate/index.cjs");
35
35
  const require_classifier_index = require("./classifier/index.cjs");
@@ -38,11 +38,11 @@ const require_workflows_constants = require("./workflows/constants.cjs");
38
38
  const require_hooks = require("./hooks-D7VDBETj.cjs");
39
39
  const require_schedules = require("./schedules-BZS8McF7.cjs");
40
40
  const require_state_processor = require("./state-processor-kRNZ38Nf.cjs");
41
- const require_constants = require("./constants-B9ZDvXZ4.cjs");
41
+ const require_constants = require("./constants-Bou0hEgY.cjs");
42
42
  const require_signal_provider = require("./signal-provider-BFAvh_AJ.cjs");
43
43
  const require_slugify = require("./slugify-B_WzG9IY.cjs");
44
- const require_workspace = require("./workspace-X2RHJZU9.cjs");
45
- const require_tools = require("./tools-CGF5Ik6j.cjs");
44
+ const require_workspace = require("./workspace-C8Zo5_qK.cjs");
45
+ const require_tools = require("./tools-BEYxowf0.cjs");
46
46
  const require_workspace_skills = require("./workspace-skills-BcquhPDn.cjs");
47
47
  const require_filesystem_versioned = require("./filesystem-versioned-BavRtYWJ.cjs");
48
48
  const require_features_index = require("./features/index.cjs");
@@ -65,12 +65,12 @@ let stream_web = require("stream/web");
65
65
  let _ai_sdk_provider_utils_v6 = require("@ai-sdk/provider-utils-v6");
66
66
  let zod = require("zod");
67
67
  let crypto$1 = require("crypto");
68
- let _mastra_schema_compat = require("@mastra/schema-compat");
69
- let fs = require("fs");
70
- let path = require("path");
71
68
  let zod_v4_core = require("zod/v4/core");
72
69
  let zod_v4_locales_en_js = require("zod/v4/locales/en.js");
73
70
  zod_v4_locales_en_js = require_rolldown_runtime.__toESM(zod_v4_locales_en_js, 1);
71
+ let _mastra_schema_compat = require("@mastra/schema-compat");
72
+ let fs = require("fs");
73
+ let path = require("path");
74
74
  let _mastra_schema_compat_json_to_zod = require("@mastra/schema-compat/json-to-zod");
75
75
  let async_hooks = require("async_hooks");
76
76
  let fastq = require("fastq");
@@ -7617,6 +7617,7 @@ function createStepFromProcessor$1(processor) {
7617
7617
  };
7618
7618
  const step = {
7619
7619
  id: `processor:${processor.id}`,
7620
+ processorId: processor.id,
7620
7621
  description: processor.name ?? `Processor ${processor.id}`,
7621
7622
  inputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepInputSchema),
7622
7623
  outputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepOutputSchema),
@@ -8262,7 +8263,8 @@ function cloneStep$1(step, opts) {
8262
8263
  retries: step.retries,
8263
8264
  scorers: step.scorers,
8264
8265
  component: step.component,
8265
- metadata: step.metadata
8266
+ metadata: step.metadata,
8267
+ processorId: step.processorId
8266
8268
  };
8267
8269
  }
8268
8270
  /**
@@ -11712,6 +11714,21 @@ function warnUnsupportedEventedSetup(mastra, workflowsStore) {
11712
11714
  warnedHosts.add(mastra);
11713
11715
  mastra.getLogger()?.warn(`Evented workflows and agents aren't supported on several processes with this setup: ${missing}. See ${DOCS_URL}`);
11714
11716
  }
11717
+ // src/agent-controller/worker-run-binding.ts
11718
+ const CONTROLLER_RUN_BINDING_KEY = "mastra__controllerRunBinding";
11719
+ const controllerRunBindingSchema = zod_v4.z.object({
11720
+ controllerId: zod_v4.z.string().min(1),
11721
+ agentId: zod_v4.z.string().min(1),
11722
+ sessionId: zod_v4.z.string().min(1),
11723
+ ownerId: zod_v4.z.string(),
11724
+ resourceId: zod_v4.z.string().min(1),
11725
+ threadId: zod_v4.z.string().min(1),
11726
+ modeId: zod_v4.z.string().min(1)
11727
+ });
11728
+ const restoredWorkerControllerContexts = /* @__PURE__ */ new WeakSet();
11729
+ function isRestoredWorkerControllerContext(value) {
11730
+ return typeof value === "object" && value !== null && restoredWorkerControllerContexts.has(value);
11731
+ }
11715
11732
  // src/agent/scopes.ts
11716
11733
  /**
11717
11734
  * Scope types Memory reads as the run's identity. Every other scope type is
@@ -12000,6 +12017,7 @@ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
12000
12017
  if (key === "mastra__versions") continue;
12001
12018
  if (key === "mastra__durableExecutions") continue;
12002
12019
  if (key === "mastra__durableSegments") continue;
12020
+ if (key === "__mastra_chat_channel_render") continue;
12003
12021
  const json = require_utils_safe_stringify.boundedStringify(value);
12004
12022
  if (json === void 0) {
12005
12023
  onEntryOmitted?.();
@@ -12026,6 +12044,8 @@ function restoreRequestContext(entries, runLevel, liveRunContext) {
12026
12044
  if (liveRunContext) return liveRunContext;
12027
12045
  if (entries) {
12028
12046
  const restored = new require_request_context.RequestContext([...Object.entries(require_request_context.withoutLiveRequestKeys(entries)), ...liveRequestEntries(runLevel)]);
12047
+ const controller = runLevel?.get("controller");
12048
+ if (isRestoredWorkerControllerContext(controller)) restored.set("controller", controller);
12029
12049
  restoreRunAgentScopes(restored);
12030
12050
  return restored;
12031
12051
  }
@@ -12038,6 +12058,118 @@ function liveRequestEntries(runLevel) {
12038
12058
  const kept = require_request_context.withoutLiveRequestKeys(live);
12039
12059
  return Object.entries(live).filter(([key]) => !(key in kept));
12040
12060
  }
12061
+ // src/agent/streams/constants.ts
12062
+ /**
12063
+ * Topics and event types of an agent's resumable run stream.
12064
+ */
12065
+ /**
12066
+ * Generate the pubsub topic name for agent streaming events
12067
+ * @param runId - The unique run identifier
12068
+ * @returns The topic name for subscribing/publishing agent stream events
12069
+ */
12070
+ const AGENT_STREAM_TOPIC = (runId) => `agent.stream.${runId}`;
12071
+ /**
12072
+ * Generate the pubsub topic name for agent control messages.
12073
+ *
12074
+ * Separate from {@link AGENT_STREAM_TOPIC} because control messages travel the
12075
+ * opposite direction: stream events flow worker -> consumer, control messages
12076
+ * flow caller -> worker. Keeping them apart means stream consumers never see
12077
+ * control traffic and vice versa.
12078
+ *
12079
+ * @param runId - The unique run identifier
12080
+ * @returns The topic name for publishing/subscribing agent control events
12081
+ */
12082
+ const AGENT_CONTROL_TOPIC = (runId) => `agent.control.${runId}`;
12083
+ /**
12084
+ * Event type constants for agent control events
12085
+ */
12086
+ const AgentControlEventTypes = {
12087
+ /**
12088
+ * Request that a run abort itself. Published by `abort()` in whichever
12089
+ * process the caller lives in; handled by whichever process is actually
12090
+ * executing the run's steps.
12091
+ */
12092
+ ABORT_REQUEST: "abort-request" };
12093
+ /**
12094
+ * Event type constants for agent stream events
12095
+ */
12096
+ const AgentStreamEventTypes = {
12097
+ /** Chunk of streaming data (text, tool call, etc.) */
12098
+ CHUNK: "chunk",
12099
+ /** Internal boundary preceding all output from an LLM execution step. */
12100
+ ITERATION_START: "iteration-start",
12101
+ /** Start of a new step in the agentic loop */
12102
+ STEP_START: "step-start",
12103
+ /** End of a step in the agentic loop */
12104
+ STEP_FINISH: "step-finish",
12105
+ /** Agent execution completed successfully */
12106
+ FINISH: "finish",
12107
+ /** Error occurred during execution */
12108
+ ERROR: "error",
12109
+ /** Workflow suspended (e.g., for tool approval) */
12110
+ SUSPENDED: "suspended",
12111
+ /** Execution aborted by abortSignal */
12112
+ ABORT: "abort",
12113
+ /** Single agentic-loop iteration completed (observability hook) */
12114
+ ITERATION_COMPLETE: "iteration-complete",
12115
+ /**
12116
+ * A new execution claimed the run. Carries no chunk: consumers only raise
12117
+ * their generation so events the superseded execution still publishes are
12118
+ * dropped.
12119
+ */
12120
+ OWNERSHIP_CLAIMED: "ownership-claimed"
12121
+ };
12122
+ // src/agent/durable/constants.ts
12123
+ const DURABLE_STOP_WHEN_ERROR_ID = "DURABLE_AGENT_STOP_WHEN_FAILED";
12124
+ const REJECT_STREAM_ERROR = Symbol("mastra.durable.rejectStreamError");
12125
+ function markErrorForStreamRejection(error) {
12126
+ error[REJECT_STREAM_ERROR] = true;
12127
+ return error;
12128
+ }
12129
+ function shouldRejectStream(error) {
12130
+ return error[REJECT_STREAM_ERROR] === true;
12131
+ }
12132
+ /**
12133
+ * Default values for durable agent execution
12134
+ */
12135
+ const DurableAgentDefaults = {
12136
+ /** Default maximum number of agentic loop iterations */
12137
+ MAX_STEPS: 5,
12138
+ /**
12139
+ * Default tool call concurrency.
12140
+ * Applied by `resolveDurableToolCallConcurrency` when a run doesn't
12141
+ * configure `toolCallConcurrency`. Approval / suspend-capable tool sets
12142
+ * always run sequentially (concurrency: 1) regardless of this value.
12143
+ */
12144
+ TOOL_CALL_CONCURRENCY: 10
12145
+ };
12146
+ /**
12147
+ * Step IDs used in the durable agentic workflow
12148
+ */
12149
+ const DurableStepIds = {
12150
+ /** LLM execution step */
12151
+ LLM_EXECUTION: "durable-llm-execution",
12152
+ /** Tool call step */
12153
+ TOOL_CALL: "durable-tool-call",
12154
+ /** LLM mapping step (combines results) */
12155
+ LLM_MAPPING: "durable-llm-mapping",
12156
+ /** Agentic execution workflow (one iteration) */
12157
+ AGENTIC_EXECUTION: "durable-agentic-execution",
12158
+ /** Full agentic loop workflow */
12159
+ AGENTIC_LOOP: "durable-agentic-loop",
12160
+ /** Scorer execution step */
12161
+ SCORER_EXECUTION: "durable-scorer-execution",
12162
+ /** isTaskComplete evaluation step */
12163
+ IS_TASK_COMPLETE: "durable-is-task-complete"
12164
+ };
12165
+ /** The loop's last step, which ends the run's spans when it succeeds. */
12166
+ const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
12167
+ const RECOVER_ALREADY_IN_PROGRESS_ERROR_ID = "DURABLE_AGENT_RECOVER_ALREADY_IN_PROGRESS";
12168
+ const RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID = "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND";
12169
+ const RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID = "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE";
12170
+ const RECOVER_RUN_SUSPENDED_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_SUSPENDED";
12171
+ const RECOVER_RUN_NOT_ACTIVE_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_NOT_ACTIVE";
12172
+ const RECOVER_SHUTDOWN_ERROR_ID = "DURABLE_AGENT_RECOVER_SHUTDOWN";
12041
12173
  // src/agent/durable/execution-ownership-guard.ts
12042
12174
  /** One step's observation of its immutable driver's claim. Never renews it. */
12043
12175
  var ExecutionOwnershipGuard = class {
@@ -12155,67 +12287,6 @@ var ExecutionOwnershipGuard = class {
12155
12287
  this.#unsubscribe?.();
12156
12288
  }
12157
12289
  };
12158
- // src/agent/streams/constants.ts
12159
- /**
12160
- * Topics and event types of an agent's resumable run stream.
12161
- */
12162
- /**
12163
- * Generate the pubsub topic name for agent streaming events
12164
- * @param runId - The unique run identifier
12165
- * @returns The topic name for subscribing/publishing agent stream events
12166
- */
12167
- const AGENT_STREAM_TOPIC = (runId) => `agent.stream.${runId}`;
12168
- /**
12169
- * Generate the pubsub topic name for agent control messages.
12170
- *
12171
- * Separate from {@link AGENT_STREAM_TOPIC} because control messages travel the
12172
- * opposite direction: stream events flow worker -> consumer, control messages
12173
- * flow caller -> worker. Keeping them apart means stream consumers never see
12174
- * control traffic and vice versa.
12175
- *
12176
- * @param runId - The unique run identifier
12177
- * @returns The topic name for publishing/subscribing agent control events
12178
- */
12179
- const AGENT_CONTROL_TOPIC = (runId) => `agent.control.${runId}`;
12180
- /**
12181
- * Event type constants for agent control events
12182
- */
12183
- const AgentControlEventTypes = {
12184
- /**
12185
- * Request that a run abort itself. Published by `abort()` in whichever
12186
- * process the caller lives in; handled by whichever process is actually
12187
- * executing the run's steps.
12188
- */
12189
- ABORT_REQUEST: "abort-request" };
12190
- /**
12191
- * Event type constants for agent stream events
12192
- */
12193
- const AgentStreamEventTypes = {
12194
- /** Chunk of streaming data (text, tool call, etc.) */
12195
- CHUNK: "chunk",
12196
- /** Internal boundary preceding all output from an LLM execution step. */
12197
- ITERATION_START: "iteration-start",
12198
- /** Start of a new step in the agentic loop */
12199
- STEP_START: "step-start",
12200
- /** End of a step in the agentic loop */
12201
- STEP_FINISH: "step-finish",
12202
- /** Agent execution completed successfully */
12203
- FINISH: "finish",
12204
- /** Error occurred during execution */
12205
- ERROR: "error",
12206
- /** Workflow suspended (e.g., for tool approval) */
12207
- SUSPENDED: "suspended",
12208
- /** Execution aborted by abortSignal */
12209
- ABORT: "abort",
12210
- /** Single agentic-loop iteration completed (observability hook) */
12211
- ITERATION_COMPLETE: "iteration-complete",
12212
- /**
12213
- * A new execution claimed the run. Carries no chunk: consumers only raise
12214
- * their generation so events the superseded execution still publishes are
12215
- * dropped.
12216
- */
12217
- OWNERSHIP_CLAIMED: "ownership-claimed"
12218
- };
12219
12290
  // src/agent/streams/run-records.ts
12220
12291
  /**
12221
12292
  * Lifetime of a running or suspended run's record. Deliberately much longer
@@ -14227,26 +14298,97 @@ var ExecutionFence = class ExecutionFence {
14227
14298
  if (!claim.agentId) return void 0;
14228
14299
  const executionBackend = await resolveRemoteBackend(mastra, claim.agentId, runId, claim);
14229
14300
  if (!executionBackend) return void 0;
14230
- const holdsThreadLease = async (threadId) => {
14231
- const lease = [
14232
- mastra.pubsub,
14233
- runId,
14234
- threadId,
14235
- claim.resourceId,
14236
- claim.generation,
14237
- claim.executionId
14238
- ];
14239
- if (claim.generation === void 0) return agentThreadStreamRuntime.renewDurableThreadLease(...lease);
14301
+ const details = {
14302
+ agentId: claim.agentId,
14303
+ runId,
14304
+ executionId: claim.executionId
14305
+ };
14306
+ const threadId = claim.threadId;
14307
+ const lease = threadId ? [
14308
+ mastra.pubsub,
14309
+ runId,
14310
+ threadId,
14311
+ claim.resourceId,
14312
+ claim.generation,
14313
+ claim.executionId
14314
+ ] : void 0;
14315
+ let heartbeatRenewal;
14316
+ let participant;
14317
+ const verifyCurrent = async () => {
14318
+ await executionBackend.verify(claim, details);
14319
+ if (participant?.isLost()) throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details);
14320
+ };
14321
+ const checkThread = async (threadLease, heartbeatWorker) => {
14322
+ const stopped = () => heartbeatWorker && (!heartbeatWorker.#heartbeat || heartbeatWorker.isLost());
14323
+ let timedOut = false;
14324
+ let timer;
14325
+ const check = async () => {
14326
+ let renewed;
14327
+ try {
14328
+ renewed = await agentThreadStreamRuntime.renewDurableThreadLease(...threadLease);
14329
+ } catch (error) {
14330
+ if (agentThreadStreamRuntime.isThreadLeaseBackendUnavailableToAll(mastra.pubsub, error)) return true;
14331
+ throw error;
14332
+ }
14333
+ if (renewed) return true;
14334
+ if (timedOut || stopped()) return void 0;
14335
+ await verifyCurrent();
14336
+ if (timedOut || stopped()) return void 0;
14337
+ let acquired;
14338
+ try {
14339
+ acquired = await agentThreadStreamRuntime.reclaimDurableThreadLease(...threadLease);
14340
+ } catch (error) {
14341
+ if (agentThreadStreamRuntime.isThreadLeaseBackendUnavailableToAll(mastra.pubsub, error)) return true;
14342
+ throw error;
14343
+ }
14344
+ if (acquired) try {
14345
+ await verifyCurrent();
14346
+ } catch (error) {
14347
+ if (error instanceof DurableExecutionFenceError && error.id === "DURABLE_AGENT_EXECUTION_SUPERSEDED") (async () => {
14348
+ const snapshot = await (await mastra.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
14349
+ workflowName: DurableStepIds.AGENTIC_LOOP,
14350
+ runId
14351
+ });
14352
+ if (!(snapshot?.status === "suspended" || snapshot?.status === "waiting") || await executionBackend.isSuperseded(claim)) await agentThreadStreamRuntime.releaseDurableThreadLease(...threadLease);
14353
+ })().catch(() => {});
14354
+ throw error;
14355
+ }
14356
+ else if (heartbeatWorker) {
14357
+ if (timedOut || stopped()) return void 0;
14358
+ const [pubsub, , threadId, resourceId] = threadLease;
14359
+ if (!await agentThreadStreamRuntime.isDurableThreadLeaseHeldByAnotherRun(pubsub, runId, threadId, resourceId)) return;
14360
+ }
14361
+ return acquired;
14362
+ };
14240
14363
  try {
14241
- return await agentThreadStreamRuntime.renewDurableThreadLease(...lease) || await agentThreadStreamRuntime.reclaimDurableThreadLease(...lease);
14242
- } catch (error) {
14243
- if (!agentThreadStreamRuntime.isThreadLeaseBackendUnavailableToAll(mastra.pubsub, error)) throw error;
14244
- mastra.getLogger()?.warn(`[DurableAgent] run ${runId}: thread lease backend unavailable, relying on run ownership`, { error });
14245
- return true;
14364
+ return await Promise.race([check(), new Promise((resolve) => {
14365
+ timer = setTimeout(() => {
14366
+ timedOut = true;
14367
+ resolve(void 0);
14368
+ }, EXECUTION_LEASE_RENEW_INTERVAL_MS);
14369
+ timer.unref?.();
14370
+ })]);
14371
+ } finally {
14372
+ clearTimeout(timer);
14246
14373
  }
14247
14374
  };
14248
14375
  const backend = {
14249
14376
  ...executionBackend,
14377
+ verify: async () => {
14378
+ await verifyCurrent();
14379
+ if (!lease || claim.generation === void 0) return;
14380
+ for (;;) {
14381
+ const held = await checkThread(lease);
14382
+ await verifyCurrent();
14383
+ if (held === true) return;
14384
+ if (held === false) {
14385
+ ExecutionFence.releaseSharedClaim(mastra, runId, claim, "abandoned").catch(() => {});
14386
+ throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details);
14387
+ }
14388
+ await sleep(VERIFY_RETRY_DELAY_MS);
14389
+ await verifyCurrent();
14390
+ }
14391
+ },
14250
14392
  renew: async (current) => {
14251
14393
  const result = await executionBackend.renew(current);
14252
14394
  if (!result.renewed) {
@@ -14257,20 +14399,22 @@ var ExecutionFence = class ExecutionFence {
14257
14399
  });
14258
14400
  return result;
14259
14401
  }
14260
- if (claim.threadId && !await holdsThreadLease(claim.threadId)) throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, {
14261
- agentId: claim.agentId,
14262
- runId,
14263
- executionId: claim.executionId
14264
- });
14402
+ if (lease) {
14403
+ if (claim.generation === void 0) {
14404
+ if (!await agentThreadStreamRuntime.renewDurableThreadLease(...lease)) throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details);
14405
+ } else if (participant && !heartbeatRenewal) {
14406
+ const worker = participant;
14407
+ heartbeatRenewal = checkThread(lease, worker).then(async (held) => {
14408
+ if (held !== false || !worker.#heartbeat || worker.isLost()) return;
14409
+ worker.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details));
14410
+ await ExecutionFence.releaseSharedClaim(mastra, runId, claim, "abandoned");
14411
+ }).catch(() => {}).finally(() => heartbeatRenewal = void 0);
14412
+ }
14413
+ }
14265
14414
  return result;
14266
14415
  }
14267
14416
  };
14268
14417
  const startedAt = Date.now();
14269
- const details = {
14270
- agentId: claim.agentId,
14271
- runId,
14272
- executionId: claim.executionId
14273
- };
14274
14418
  let deadline;
14275
14419
  try {
14276
14420
  await Promise.race([(async () => {
@@ -14288,7 +14432,7 @@ var ExecutionFence = class ExecutionFence {
14288
14432
  } finally {
14289
14433
  if (deadline) clearTimeout(deadline);
14290
14434
  }
14291
- const fence = new ExecutionFence({
14435
+ const fence = participant = new ExecutionFence({
14292
14436
  ...details,
14293
14437
  backend,
14294
14438
  generation: claim.generation,
@@ -15365,7 +15509,8 @@ var StepExecutor = class extends require_base.MastraBase {
15365
15509
  return require_stream.storageV2StepResultAccessors((step) => require_stream.getHydratedStepResult(stepResults, step, hydrate));
15366
15510
  }
15367
15511
  async execute(params) {
15368
- const { entry, stepResults, runId, requestContext, retryCount = 0, perStep } = params;
15512
+ const { entry, stepResults, runId, retryCount = 0, perStep } = params;
15513
+ let { requestContext } = params;
15369
15514
  const stepId = getEntryId(entry);
15370
15515
  const errorAttemptId = `${runId}:${stepId}:${params.foreachIdx ?? ""}:attempt:${retryCount}`;
15371
15516
  const schemas = getEntrySchemas(entry, this.mastra);
@@ -15421,6 +15566,18 @@ var StepExecutor = class extends require_base.MastraBase {
15421
15566
  const stepTracingContext = workflowStepSpan ? { currentSpan: workflowStepSpan } : params.tracingContext ?? {};
15422
15567
  try {
15423
15568
  if (validationError) throw validationError;
15569
+ if (params.workflowId === DurableStepIds.AGENTIC_LOOP || params.workflowId === DurableStepIds.AGENTIC_EXECUTION) {
15570
+ const live = requestContext.get("controller");
15571
+ const initial = stepResults.input;
15572
+ const binding = initial?.requestContextEntries?.[CONTROLLER_RUN_BINDING_KEY];
15573
+ if (initial && binding !== void 0 && typeof live?.getState !== "function") {
15574
+ const parsed = controllerRunBindingSchema.parse(binding);
15575
+ if (initial.agentId !== parsed.agentId || initial.state?.threadId !== parsed.threadId || initial.state.resourceId !== parsed.resourceId) throw new Error("Controller binding does not match this durable run");
15576
+ const controller = this.mastra?.getAgentControllerById(parsed.controllerId);
15577
+ if (!controller) throw new Error("Controller is not registered on this worker");
15578
+ requestContext = await controller.__restoreWorkerRequestContext(requestContext, parsed, abortController.signal, initial.runId);
15579
+ }
15580
+ }
15424
15581
  const callId = globalThis.crypto.randomUUID();
15425
15582
  const outputWriter = this.createOutputWriter(runId);
15426
15583
  const stepOutput = await require_utils.executeWithContext({
@@ -21217,7 +21374,8 @@ function cloneStep(step, opts) {
21217
21374
  retries: step.retries,
21218
21375
  scorers: step.scorers,
21219
21376
  metadata: step.metadata,
21220
- component: step.component
21377
+ component: step.component,
21378
+ processorId: step.processorId
21221
21379
  };
21222
21380
  }
21223
21381
  function isToolStep(input) {
@@ -21477,6 +21635,7 @@ function createStepFromProcessor(processor) {
21477
21635
  };
21478
21636
  return {
21479
21637
  id: `processor:${processor.id}`,
21638
+ processorId: processor.id,
21480
21639
  description: processor.name ?? `Processor ${processor.id}`,
21481
21640
  inputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepSchema),
21482
21641
  outputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepOutputSchema),
@@ -27626,12 +27785,14 @@ async function partitionMessages(messagesDescending, limits, tokenCounter, initi
27626
27785
  if (maxTokens !== void 0 && !tokenCounter) throw new Error("A token counter is required to load token-limited message history");
27627
27786
  let messageCount = 0;
27628
27787
  let tokenCount = initialTokens;
27788
+ let loadedTokens = initialTokens;
27629
27789
  let reachedLimit = false;
27630
27790
  let overflowReason;
27631
27791
  const retainedIds = /* @__PURE__ */ new Set();
27632
27792
  for (const group of groupLinkedToolMessages(messagesDescending)) {
27633
27793
  let groupTokens = 0;
27634
27794
  if (tokenCounter) for (const message of group) groupTokens += await tokenCounter.countMessage(message);
27795
+ loadedTokens += groupTokens;
27635
27796
  const exceedsMessageLimit = limits.maxMessages !== void 0 && messageCount + group.length > limits.maxMessages;
27636
27797
  const exceedsTokenLimit = maxTokens !== void 0 && tokenCount + groupTokens > maxTokens;
27637
27798
  if (reachedLimit || exceedsMessageLimit || exceedsTokenLimit) {
@@ -27646,7 +27807,8 @@ async function partitionMessages(messagesDescending, limits, tokenCounter, initi
27646
27807
  return {
27647
27808
  messages: messagesDescending.filter((message) => retainedIds.has(message.id)).reverse(),
27648
27809
  overflow: messagesDescending.filter((message) => !retainedIds.has(message.id)).reverse(),
27649
- overflowReason
27810
+ overflowReason,
27811
+ loadedTokens
27650
27812
  };
27651
27813
  }
27652
27814
  function laterDate(left, right) {
@@ -27708,15 +27870,15 @@ async function loadMessageHistory(args) {
27708
27870
  const newestOverflow = partitioned.overflow.at(-1);
27709
27871
  if (newestOverflow) cutoffTimestamp = newestOverflow.createdAt.getTime();
27710
27872
  const oldestTimestamp = result.messages.at(-1)?.createdAt.getTime();
27711
- const crossedCutoff = cutoffTimestamp !== void 0 && oldestTimestamp !== void 0 && oldestTimestamp < cutoffTimestamp;
27873
+ const crossedCutoff = cutoffTimestamp !== void 0 && oldestTimestamp !== void 0 && oldestTimestamp < cutoffTimestamp && (!args.includeOverflow || partitioned.overflowReason !== "tokens" || partitioned.loadedTokens > (args.maxTokens ?? 0));
27712
27874
  const reachedBoundary = args.boundary !== void 0 && oldestTimestamp !== void 0 && oldestTimestamp < new Date(args.boundary.createdAt).getTime();
27713
- if (!result.hasMore || crossedCutoff || reachedBoundary || result.messages.length === 0) return args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned : {
27875
+ if (!result.hasMore || crossedCutoff || reachedBoundary || result.messages.length === 0) return {
27714
27876
  messages: partitioned.messages,
27715
- overflow: []
27877
+ overflow: args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned.overflow : []
27716
27878
  };
27717
- if (oldestTimestamp === void 0) return args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned : {
27879
+ if (oldestTimestamp === void 0) return {
27718
27880
  messages: partitioned.messages,
27719
- overflow: []
27881
+ overflow: args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned.overflow : []
27720
27882
  };
27721
27883
  if (end?.getTime() === oldestTimestamp && added === 0) page++;
27722
27884
  else {
@@ -30211,19 +30373,24 @@ var ToolSearchProcessor = class {
30211
30373
  });
30212
30374
  }
30213
30375
  async processInputStep(args) {
30214
- const { tools, messageList } = args;
30376
+ const { tools, messageList, activeTools } = args;
30215
30377
  const catalog = this.catalogForStep(tools);
30216
30378
  const storeContext = this.makeStoreContext(args);
30217
30379
  const loadedToolNames = await this.store.getLoadedNames(storeContext);
30218
30380
  const autoLoad = this.searchConfig.autoLoad;
30219
- messageList.addSystem(autoLoad ? "To discover available tools, call search_tools with a keyword query. Matching tools are loaded automatically and become available on your next turn \u2014 there is no separate load step. After searching, use the tool directly." : "To discover available tools, call search_tools with a keyword query. To add one or more tools to the conversation, call load_tool with a toolName or toolNames array. Tools must be loaded before they can be used.");
30220
- if (this.injectCatalog) {
30381
+ const searchAvailable = !activeTools || activeTools.includes("search_tools");
30382
+ const loadAvailable = !autoLoad && (!activeTools || activeTools.includes("load_tool"));
30383
+ const instructionParts = [];
30384
+ if (searchAvailable) instructionParts.push(autoLoad ? "To discover available tools, call search_tools with a keyword query. Matching tools are loaded automatically and become available on your next turn \u2014 there is no separate load step. After searching, use the tool directly." : "To discover available tools, call search_tools with a keyword query.");
30385
+ if (loadAvailable) instructionParts.push("To add one or more tools to the conversation, call load_tool with a toolName or toolNames array. Tools must be loaded before they can be used.");
30386
+ if (instructionParts.length > 0) messageList.addSystem(instructionParts.join(" "));
30387
+ if (this.injectCatalog && (autoLoad ? searchAvailable : loadAvailable)) {
30221
30388
  const catalogList = await this.formatCatalog(catalog, args.requestContext);
30222
- if (catalogList) messageList.addSystem((autoLoad ? "The following tools are available. Call search_tools with a keyword to load one \u2014 matching tools are loaded automatically and become available on your next turn." : "The following tools are available to load. Call load_tool with a toolName or toolNames array to add one or more before using them \u2014 no search step is required. search_tools is also available if you need to rediscover tools by keyword.") + "\n\nAvailable tools:\n" + catalogList);
30389
+ if (catalogList) messageList.addSystem((autoLoad ? "The following tools are available. Call search_tools with a keyword to load one \u2014 matching tools are loaded automatically and become available on your next turn." : "The following tools are available to load. Call load_tool with a toolName or toolNames array to add one or more before using them \u2014 no search step is required." + (searchAvailable ? " search_tools is also available if you need to rediscover tools by keyword." : "")) + "\n\nAvailable tools:\n" + catalogList);
30223
30390
  }
30224
30391
  const searchTool = require_tool.createTool({
30225
30392
  id: "search_tools",
30226
- description: autoLoad ? "Search for available tools by keyword. Use this when you need a capability you don't currently have. Returns a list of matching tools, which are loaded automatically and become available on your next turn \u2014 no separate load step is required." : "Search for available tools by keyword. Use this when you need a capability you don't currently have. Returns a list of matching tools with their names and descriptions. After finding a useful tool, use load_tool to make it available.",
30393
+ description: autoLoad ? "Search for available tools by keyword. Use this when you need a capability you don't currently have. Returns a list of matching tools, which are loaded automatically and become available on your next turn \u2014 no separate load step is required." : "Search for available tools by keyword. Use this when you need a capability you don't currently have. Returns a list of matching tools with their names and descriptions." + (loadAvailable ? " After finding a useful tool, use load_tool to make it available." : ""),
30227
30394
  inputSchema: zod_v4.z.object({ query: zod_v4.z.string().describe("Search keywords (e.g., \"weather\", \"github issue\", \"database query\")") }),
30228
30395
  outputSchema: zod_v4.z.object({
30229
30396
  results: zod_v4.z.array(zod_v4.z.object({
@@ -30253,13 +30420,13 @@ var ToolSearchProcessor = class {
30253
30420
  }
30254
30421
  return {
30255
30422
  results,
30256
- message: `Found ${results.length} tool(s). Use load_tool with an exact toolName or a toolNames array to make them available.`
30423
+ message: loadAvailable ? `Found ${results.length} tool(s). Use load_tool with an exact toolName or a toolNames array to make them available.` : `Found ${results.length} tool(s): ${results.map((r) => r.name).join(", ")}.`
30257
30424
  };
30258
30425
  }
30259
30426
  });
30260
30427
  const loadTool = require_tool.createTool({
30261
30428
  id: "load_tool",
30262
- description: "Load one or more tools into your context. Call this after finding tools with search_tools. Once loaded, tools will be available for use. Pass a single toolName or an array of toolNames to load multiple tools at once.",
30429
+ description: "Load one or more tools into your context. " + (searchAvailable ? "Call this after finding tools with search_tools. " : "") + "Once loaded, tools will be available for use. Pass a single toolName or an array of toolNames to load multiple tools at once.",
30263
30430
  inputSchema: zod_v4.z.object({
30264
30431
  toolName: zod_v4.z.string().optional().describe("The exact name of a tool to load (from search results)"),
30265
30432
  toolNames: zod_v4.z.array(zod_v4.z.string()).optional().describe("Array of exact tool names to load in one call (from search results)")
@@ -30316,7 +30483,7 @@ var ToolSearchProcessor = class {
30316
30483
  const suggestions = await this.getSuggestedToolNames(catalog, name, args.requestContext);
30317
30484
  let message = `Tool "${name}" not found.`;
30318
30485
  if (suggestions.length > 0) message += ` Did you mean: ${suggestions.slice(0, 3).join(", ")}?`;
30319
- else message += " Use search_tools to find available tools.";
30486
+ else if (searchAvailable) message += " Use search_tools to find available tools.";
30320
30487
  return {
30321
30488
  success: false,
30322
30489
  message,
@@ -30350,8 +30517,8 @@ var ToolSearchProcessor = class {
30350
30517
  });
30351
30518
  const loadedTools = await this.getLoadedTools(catalog, loadedToolNames, args.requestContext);
30352
30519
  return { tools: {
30353
- search_tools: searchTool,
30354
- ...autoLoad ? {} : { load_tool: loadTool },
30520
+ ...searchAvailable ? { search_tools: searchTool } : {},
30521
+ ...loadAvailable ? { load_tool: loadTool } : {},
30355
30522
  ...this.includeResolvedTools ? unsearchableResolvedTools(tools) : tools ?? {},
30356
30523
  ...loadedTools
30357
30524
  } };
@@ -30713,7 +30880,7 @@ var SkillSearchProcessor = class {
30713
30880
  return this.cleanupStaleState();
30714
30881
  }
30715
30882
  async processInputStep(args) {
30716
- const { tools, messageList } = args;
30883
+ const { tools, messageList, activeTools } = args;
30717
30884
  const threadId = this.getThreadId(args);
30718
30885
  const threadState = this.getThreadState(threadId);
30719
30886
  const configuredSkills = this.skills;
@@ -30723,10 +30890,18 @@ var SkillSearchProcessor = class {
30723
30890
  if (this.blockingRefresh) await skills.maybeRefresh({ requestContext: args.requestContext })?.catch(this.warnRefreshFailed);
30724
30891
  else skills.maybeRefresh({ requestContext: args.requestContext })?.catch(this.warnRefreshFailed);
30725
30892
  }
30726
- messageList.addSystem("To discover available skills, call search_skills with a keyword query. To load a skill's instructions, call load_skill with the skill name. Loaded skills provide context and instructions for the conversation.");
30893
+ const searchAvailable = !activeTools || activeTools.includes("search_skills");
30894
+ const loadAvailable = !activeTools || activeTools.includes("load_skill");
30895
+ const instructionParts = [];
30896
+ if (searchAvailable) instructionParts.push("To discover available skills, call search_skills with a keyword query.");
30897
+ if (loadAvailable) instructionParts.push("To load a skill's instructions, call load_skill with the skill name.");
30898
+ if (instructionParts.length > 0) {
30899
+ instructionParts.push("Loaded skills provide context and instructions for the conversation.");
30900
+ messageList.addSystem(instructionParts.join(" "));
30901
+ }
30727
30902
  const searchSkillTool = require_tool.createTool({
30728
30903
  id: "search_skills",
30729
- description: "Search for available skills by keyword. Returns a list of matching skills with their names and descriptions. After finding a useful skill, use load_skill to load its instructions.",
30904
+ description: "Search for available skills by keyword. Returns a list of matching skills with their names and descriptions." + (loadAvailable ? " After finding a useful skill, use load_skill to load its instructions." : ""),
30730
30905
  inputSchema: zod_v4.z.object({ query: zod_v4.z.string().trim().min(1, "Query is required").describe("Search keywords (e.g., \"api design\", \"testing\", \"deployment\")") }),
30731
30906
  outputSchema: zod_v4.z.object({
30732
30907
  results: zod_v4.z.array(zod_v4.z.object({
@@ -30763,13 +30938,13 @@ var SkillSearchProcessor = class {
30763
30938
  });
30764
30939
  return {
30765
30940
  results,
30766
- message: `Found ${results.length} skill(s). Use load_skill with the exact skill name to load its instructions.`
30941
+ message: loadAvailable ? `Found ${results.length} skill(s). Use load_skill with the exact skill name to load its instructions.` : `Found ${results.length} skill(s): ${results.map((r) => r.name).join(", ")}.`
30767
30942
  };
30768
30943
  }
30769
30944
  });
30770
30945
  const loadSkillTool = require_tool.createTool({
30771
30946
  id: "load_skill",
30772
- description: "Load a skill's full instructions into the conversation. Call this after finding a skill with search_skills. The skill's instructions will be available as context.",
30947
+ description: "Load a skill's full instructions into the conversation. " + (searchAvailable ? "Call this after finding a skill with search_skills. " : "") + "The skill's instructions will be available as context.",
30773
30948
  inputSchema: zod_v4.z.object({ skillName: zod_v4.z.string().describe("The exact name of the skill to load (from search results)") }),
30774
30949
  outputSchema: zod_v4.z.object({
30775
30950
  success: zod_v4.z.boolean(),
@@ -30787,7 +30962,7 @@ var SkillSearchProcessor = class {
30787
30962
  const suggestions = (await skills.list()).filter((s) => s.name.toLowerCase().includes(skillName.toLowerCase()) || skillName.toLowerCase().includes(s.name.toLowerCase())).slice(0, 3);
30788
30963
  let message = `Skill "${skillName}" not found.`;
30789
30964
  if (suggestions.length > 0) message += ` Did you mean: ${suggestions.map((s) => s.name).join(", ")}?`;
30790
- else message += " Use search_skills to find available skills.";
30965
+ else if (searchAvailable) message += " Use search_skills to find available skills.";
30791
30966
  return {
30792
30967
  success: false,
30793
30968
  message
@@ -30803,8 +30978,8 @@ var SkillSearchProcessor = class {
30803
30978
  });
30804
30979
  for (const [skillName, instructions] of threadState.skills) messageList.addSystem(`[Skill: ${skillName}]\n\n${instructions}`);
30805
30980
  const metaTools = {
30806
- search_skills: searchSkillTool,
30807
- load_skill: loadSkillTool
30981
+ ...searchAvailable ? { search_skills: searchSkillTool } : {},
30982
+ ...loadAvailable ? { load_skill: loadSkillTool } : {}
30808
30983
  };
30809
30984
  if (tools) {
30810
30985
  for (const key of Object.keys(tools)) if (key in metaTools) console.warn(`[SkillSearchProcessor] User tool "${key}" conflicts with meta-tool and will be shadowed.`);
@@ -38605,6 +38780,7 @@ var ExperimentsInMemory = class extends ExperimentsStorage {
38605
38780
  targetType: input.targetType ?? null,
38606
38781
  targetId: input.targetId ?? null,
38607
38782
  scorerIds: input.scorerIds ?? null,
38783
+ scorerVersions: input.scorerVersions ?? null,
38608
38784
  name: input.name,
38609
38785
  description: input.description,
38610
38786
  metadata: input.metadata,
@@ -39511,6 +39687,31 @@ var KnowledgeStorage = class extends require_filesystem_versioned.StorageDomain
39511
39687
  getPages(_input) {
39512
39688
  return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPages"));
39513
39689
  }
39690
+ /**
39691
+ * The page `parentId` and its ancestors, nearest first: for each row what {@link getPage} would
39692
+ * return with the same `read`, deleted rows included. Stops after the first scope page, before
39693
+ * the first row `getPage` would return null for, or after {@link MAX_KNOWLEDGE_PAGE_DEPTH} + 1
39694
+ * rows. Lets a caller holding a page walk its parents in one call instead of one per level.
39695
+ *
39696
+ * The base class reads one {@link getPage} per level; adapters that can read the chain in one
39697
+ * query override it.
39698
+ *
39699
+ * @experimental
39700
+ */
39701
+ async getPageParents(input) {
39702
+ const parents = [];
39703
+ let id = input.parentId;
39704
+ while (id && parents.length <= 10) {
39705
+ const page = await this.getPage({
39706
+ id,
39707
+ read: input.read
39708
+ });
39709
+ if (!page) break;
39710
+ parents.push(page);
39711
+ id = page.isScope ? null : page.parentId;
39712
+ }
39713
+ return parents;
39714
+ }
39514
39715
  getPageByPath(_input) {
39515
39716
  return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPageByPath"));
39516
39717
  }
@@ -39828,6 +40029,12 @@ var InMemoryKnowledgeImportersStorage = class extends KnowledgeImportersStorage
39828
40029
  const node = this.#s.nodes.get(key(bindingId, sourceId));
39829
40030
  return node ? structuredClone(node) : null;
39830
40031
  }
40032
+ async getNodes(bindingId, sourceIds) {
40033
+ return [...new Set(sourceIds)].flatMap((sourceId) => {
40034
+ const node = this.#s.nodes.get(key(bindingId, sourceId));
40035
+ return node ? [structuredClone(node)] : [];
40036
+ });
40037
+ }
39831
40038
  async getNodeByPage(pageId) {
39832
40039
  const node = [...this.#s.nodes.values()].find((n) => n.pageId === pageId);
39833
40040
  return node ? structuredClone(node) : null;
@@ -40218,6 +40425,15 @@ var InMemoryKnowledgePageStore = class {
40218
40425
  const page = this.#pages.get(input.id);
40219
40426
  return page && this.#pageReadable(page, input.read) ? clone$1(page) : null;
40220
40427
  }
40428
+ async getPageParents(input) {
40429
+ const parents = [];
40430
+ let page = this.#pages.get(input.parentId);
40431
+ while (page && this.#pageReadable(page, input.read) && parents.length <= 10) {
40432
+ parents.push(clone$1(page));
40433
+ page = page.isScope || !page.parentId ? void 0 : this.#pages.get(page.parentId);
40434
+ }
40435
+ return parents;
40436
+ }
40221
40437
  async getPages(input) {
40222
40438
  return [...new Set(input.ids)].map((id) => this.#pages.get(id)).filter((page) => !!page && !page.deletedAt && this.#pageReadable(page, input.read)).map(clone$1);
40223
40439
  }
@@ -40725,6 +40941,9 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40725
40941
  getPage(input) {
40726
40942
  return this.#pageStore.getPage(input);
40727
40943
  }
40944
+ getPageParents(input) {
40945
+ return this.#pageStore.getPageParents(input);
40946
+ }
40728
40947
  listScopeDeclarations() {
40729
40948
  return this.#pageStore.listScopeDeclarations();
40730
40949
  }
@@ -47766,6 +47985,32 @@ function chunkToFallbackMessage(chunk) {
47766
47985
  if (chunk.type === "plan_update") return chunk.title && chunk.title.length > 0 ? chunk.title : null;
47767
47986
  return null;
47768
47987
  }
47988
+ /** Whitespace plus the meaningful joiners ZWNJ (U+200C) and ZWJ (U+200D). */
47989
+ const EDGE_PADDING = /[\s\u200C\u200D]/;
47990
+ /**
47991
+ * Sanitize a buffered channel reply before posting.
47992
+ *
47993
+ * Zero-width space (U+200B) and the byte-order mark (U+FEFF) are invisible
47994
+ * padding and are removed everywhere. Whitespace and the joiners ZWNJ
47995
+ * (U+200C) / ZWJ (U+200D) are trimmed only at the edges, so internal joiners
47996
+ * in compound emoji (🏄🏼‍♂️, 👨‍👩‍👧) and scripts such as Persian (می‌خواهم)
47997
+ * survive — the bug behind #31205. Invisible-only input collapses to '' so
47998
+ * callers skip posting it entirely.
47999
+ *
48000
+ * The edge trim is a single-pass scan rather than
48001
+ * `.replace(/^[\s\u200C\u200D]+|[\s\u200C\u200D]+$/g, '')`: that anchored
48002
+ * alternation backtracks quadratically over a long interior run of the class
48003
+ * (a 300k-character run of model-controlled output took ~80s), while this
48004
+ * scan is O(n).
48005
+ */
48006
+ function cleanBufferedText(input) {
48007
+ const stripped = input.replace(/[\u200B\uFEFF]/g, "");
48008
+ let start = 0;
48009
+ let end = stripped.length;
48010
+ while (start < end && EDGE_PADDING.test(stripped.charAt(start))) start++;
48011
+ while (end > start && EDGE_PADDING.test(stripped.charAt(end - 1))) end--;
48012
+ return start === 0 && end === stripped.length ? stripped : stripped.slice(start, end);
48013
+ }
47769
48014
  // src/channels/chat-driver-static.ts
47770
48015
  /**
47771
48016
  * Static (non-streaming) driver: consumes `AgentChunkType<any>` chunks and
@@ -47810,7 +48055,7 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47810
48055
  let textBuffer = "";
47811
48056
  const toolMessageIds = /* @__PURE__ */ new Map();
47812
48057
  const flushText = async () => {
47813
- const cleaned = textBuffer.replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
48058
+ const cleaned = cleanBufferedText(textBuffer);
47814
48059
  if (cleaned) try {
47815
48060
  await chatThread.post(textFormat === "plain" ? cleaned : { markdown: cleaned });
47816
48061
  } catch (e) {
@@ -48145,7 +48390,7 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
48145
48390
  if (closed) break;
48146
48391
  await waitForNext();
48147
48392
  }
48148
- const cleaned = fallback.replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
48393
+ const cleaned = cleanBufferedText(fallback);
48149
48394
  if (cleaned) try {
48150
48395
  await chatThread.post(textFormat === "plain" ? cleaned : { markdown: cleaned });
48151
48396
  } catch (postErr) {
@@ -48628,6 +48873,20 @@ const TEXT_CHUNK_TYPES = /* @__PURE__ */ new Set([
48628
48873
  /** Key the processor reads off `requestContext` to locate its render deps. */
48629
48874
  const CHAT_CHANNEL_RENDER_CONTEXT_KEY = "__mastra_chat_channel_render";
48630
48875
  /**
48876
+ * Whether a `requestContext` entry is a live render context rather than the
48877
+ * method-less husk a JSON snapshot round-trip leaves behind (issue #31310).
48878
+ * `wrapStream` is the first method the session calls, so its presence is the
48879
+ * signal that the object is usable.
48880
+ *
48881
+ * Every reader that treats a stashed render context as a live object (the
48882
+ * output processor, `resolveChannelRenderContext`, `AgentChannels.resolveRunRender`
48883
+ * and the generative-UI processor) guards with this, so a husk on a replica's
48884
+ * restored `requestContext` always falls through to a rebuild from the thread.
48885
+ */
48886
+ function isUsableRenderContext(value) {
48887
+ return typeof value === "object" && value !== null && typeof value.wrapStream === "function";
48888
+ }
48889
+ /**
48631
48890
  * Single-producer / single-consumer async queue. The processor pushes chunks
48632
48891
  * synchronously from `processOutputStream`; the driver consumes them via the
48633
48892
  * async iterable. `close()` ends the iteration after pending items are drained.
@@ -48761,7 +49020,7 @@ var ChatChannelOutputProcessor = class {
48761
49020
  async #resolveRenderContext(state, requestContext) {
48762
49021
  if (state.render !== void 0) return state.render;
48763
49022
  const fromRequest = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
48764
- if (fromRequest) {
49023
+ if (isUsableRenderContext(fromRequest)) {
48765
49024
  state.render = fromRequest;
48766
49025
  return fromRequest;
48767
49026
  }
@@ -48934,7 +49193,7 @@ var ChatChannelGenerativeUIProcessor = class {
48934
49193
  }
48935
49194
  async #resolve(requestContext, state) {
48936
49195
  const inbound = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
48937
- if (inbound) return inbound;
49196
+ if (isUsableRenderContext(inbound)) return inbound;
48938
49197
  if (state && "render" in state) return state.render ?? void 0;
48939
49198
  const threadId = require_stream.parseMemoryRequestContext(requestContext)?.thread?.id;
48940
49199
  const render = threadId && this.#channels ? await this.#channels.buildRenderContextForThread(threadId) : null;
@@ -49088,6 +49347,8 @@ async function headContentType(url, logger) {
49088
49347
  }
49089
49348
  }
49090
49349
  // src/channels/processor.ts
49350
+ /** Per-run `state` key caching a thread's display mode recovered without a render context. */
49351
+ const RECOVERED_DISPLAY_KEY = "threadTextHidden";
49091
49352
  /**
49092
49353
  * Input processor that injects channel context (platform, bot identity, DM vs.
49093
49354
  * public-channel guidance) into the agent's system prompt on every step.
@@ -49121,19 +49382,37 @@ var ChatChannelProcessor = class {
49121
49382
  }
49122
49383
  async #resolve(requestContext, state) {
49123
49384
  const channel = requestContext?.get("channel");
49124
- if (channel) return {
49125
- channel,
49126
- textHidden: (requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY))?.textDisplay === "hidden"
49127
- };
49385
+ if (channel) {
49386
+ const render = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
49387
+ return {
49388
+ channel,
49389
+ textHidden: isUsableRenderContext(render) ? render.textDisplay === "hidden" : await this.#recoverTextHidden(requestContext, state)
49390
+ };
49391
+ }
49128
49392
  if (state && "thread" in state) return state.thread ?? void 0;
49393
+ const resolved = await this.#resolveThread(requestContext);
49394
+ if (state) state.thread = resolved;
49395
+ return resolved ?? void 0;
49396
+ }
49397
+ /** The channel-backed context of the run's memory thread, or `null` when it has none. */
49398
+ async #resolveThread(requestContext) {
49129
49399
  const threadId = require_stream.parseMemoryRequestContext(requestContext)?.thread?.id;
49130
49400
  const found = threadId && this.#channels ? await this.#channels.buildChannelContextForThread(threadId) : null;
49131
- const resolved = found ? {
49401
+ return found ? {
49132
49402
  channel: found.channel,
49133
49403
  textHidden: found.render.textDisplay === "hidden"
49134
49404
  } : null;
49135
- if (state) state.thread = resolved;
49136
- return resolved ?? void 0;
49405
+ }
49406
+ /**
49407
+ * Display mode of a channel-backed thread whose render context is no longer on the
49408
+ * restored request context. Cached per run like the thread lookup above, so later
49409
+ * steps of the same run read the thread once.
49410
+ */
49411
+ async #recoverTextHidden(requestContext, state) {
49412
+ if (state && RECOVERED_DISPLAY_KEY in state) return state[RECOVERED_DISPLAY_KEY] === true;
49413
+ const textHidden = (await this.#resolveThread(requestContext))?.textHidden ?? false;
49414
+ if (state) state[RECOVERED_DISPLAY_KEY] = textHidden;
49415
+ return textHidden;
49137
49416
  }
49138
49417
  };
49139
49418
  function channelLines(ctx, textHidden, tools) {
@@ -49161,6 +49440,488 @@ function channelLines(ctx, textHidden, tools) {
49161
49440
  if (tools && "add_reaction" in tools) lines.push(`If you want to acknowledge a message without ${textHidden ? "posting" : "speaking"}, use the \`add_reaction\` tool to react with an emoji instead of replying with text.`);
49162
49441
  return lines;
49163
49442
  }
49443
+ // src/channels/thread-link-processor.ts
49444
+ /**
49445
+ * Request-context marker for a run that opened a new channel thread. `AgentChannels` sets it when
49446
+ * it creates the thread; a host that decides "new" itself can call {@link markNewChannelThread}.
49447
+ */
49448
+ const NEW_CHANNEL_THREAD_KEY = "__mastra_new_channel_thread";
49449
+ function markNewChannelThread(requestContext) {
49450
+ requestContext.set(NEW_CHANNEL_THREAD_KEY, true);
49451
+ }
49452
+ /** Text-part id of the link delta; never collides with a model block id. */
49453
+ const LINK_PART_ID = "mastra-channel-thread-link";
49454
+ const EMITTED_SUFFIX_KEY = "mastra__channelThreadLinkSuffix";
49455
+ /**
49456
+ * Posts a link to the thread in the host's web UI right after the first reply of a new channel
49457
+ * thread, so the link closes the reply rather than leading it. The channel driver ends a post at
49458
+ * `text-end`, so the link shows as its own short message after the reply.
49459
+ *
49460
+ * "End of the reply" is not `text-end`: a reply with citations is several text blocks, each with
49461
+ * its own `text-end`. The reply ends at the first `tool-call` (an opener before tools run) or at
49462
+ * `step-finish` (a reply with no tools), whichever comes first after some text. A processor
49463
+ * returns one part, so on that chunk this returns a `text-delta` carrying the link and stashes the
49464
+ * chunk under `REPROCESS_PART_KEY`, which the runner re-drives through the chain right after.
49465
+ *
49466
+ * The link is a channel display detail. Saved to memory it would show the model its own link on
49467
+ * later turns (inviting it to fabricate links) and render a self-link in the web transcript, so
49468
+ * `processOutputStep` drops the link's text part before the message is saved.
49469
+ *
49470
+ * No-op unless the run opened a new thread, the reply text is shown, and `link` returns a URL.
49471
+ */
49472
+ var ChannelThreadLinkProcessor = class {
49473
+ id = "channel-thread-link";
49474
+ #options;
49475
+ /** Pass options, or a function picking them per run (e.g. by the run's platform). */
49476
+ constructor(options) {
49477
+ this.#options = typeof options === "function" ? options : () => options;
49478
+ }
49479
+ async processOutputStream({ part, state, requestContext }) {
49480
+ if (state.linked || !linksThisRun(requestContext)) return part;
49481
+ if (part.type === "text-delta") {
49482
+ if (part.payload.text.trim()) state.textStarted = true;
49483
+ return part;
49484
+ }
49485
+ if (part.type !== "tool-call" && part.type !== "step-finish" || !state.textStarted) return part;
49486
+ state.linked = true;
49487
+ const suffix = this.#suffix(requestContext);
49488
+ if (!suffix) return part;
49489
+ requestContext.set(EMITTED_SUFFIX_KEY, suffix);
49490
+ state[require_stream.REPROCESS_PART_KEY] = part;
49491
+ return {
49492
+ type: "text-delta",
49493
+ runId: part.runId,
49494
+ from: part.from,
49495
+ payload: {
49496
+ id: LINK_PART_ID,
49497
+ text: suffix
49498
+ }
49499
+ };
49500
+ }
49501
+ processOutputStep({ messageList, requestContext }) {
49502
+ const suffix = requestContext?.get(EMITTED_SUFFIX_KEY);
49503
+ if (!suffix) return messageList;
49504
+ for (const message of messageList.get.response.db()) {
49505
+ if (message.role !== "assistant") continue;
49506
+ const index = message.content.parts.findIndex((part) => part.type === "text" && part.text === suffix);
49507
+ if (index === -1) continue;
49508
+ message.content.parts.splice(index, 1);
49509
+ if (typeof message.content.content === "string" && message.content.content.endsWith(suffix)) message.content.content = message.content.content.slice(0, -suffix.length);
49510
+ return messageList;
49511
+ }
49512
+ return messageList;
49513
+ }
49514
+ #suffix(requestContext) {
49515
+ const options = this.#options(requestContext);
49516
+ if (!options) return void 0;
49517
+ const memory = require_stream.parseMemoryRequestContext(requestContext);
49518
+ const link = options.link({
49519
+ requestContext,
49520
+ threadId: memory?.thread?.id,
49521
+ resourceId: memory?.resourceId
49522
+ });
49523
+ return link && `\n\n[${options.label ?? "Open thread \u2197"}](${link})`;
49524
+ }
49525
+ };
49526
+ function linksThisRun(requestContext) {
49527
+ if (!requestContext?.get("__mastra_new_channel_thread")) return false;
49528
+ return requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY)?.textDisplay !== "hidden";
49529
+ }
49530
+ // src/channels/reply-tool.ts
49531
+ const REPLY_TOOL_NAME = "reply_in_thread";
49532
+ /**
49533
+ * Which reply carries the session link: `claimed` while that reply is posting,
49534
+ * `posted` once it landed. Claimed before any await, so overlapping replies
49535
+ * can't both take it; a failed post hands it back to the next reply.
49536
+ */
49537
+ const LINKED_KEY = "mastra__channelReplyLinked";
49538
+ const replyInput = zod.z.object({ text: zod.z.string().trim().min(1).max(12e3).describe("The message to post, in markdown.") }).strict();
49539
+ /** @internal */
49540
+ function createChannelReplyTool(requestContext, options) {
49541
+ const { resolveRender } = options;
49542
+ return { [REPLY_TOOL_NAME]: require_tool.createTool({
49543
+ id: REPLY_TOOL_NAME,
49544
+ description: "Post a message in this chat thread. Nothing you write outside this tool reaches the thread, so use it for anything the people there should see: a short note that you are starting a longer job, a question you need answered, and the outcome when you finish. Post when you have something new; do not repeat yourself or post that nothing changed. To stay quiet, do not call it.",
49545
+ inputSchema: replyInput,
49546
+ execute: async (input, context) => {
49547
+ const link = claimFirstReplyLink(requestContext, options.link);
49548
+ const suffix = link ? `\n\n[${options.link?.label ?? "Open thread \u2197"}](${link})` : "";
49549
+ const toolCallId = context?.agent?.toolCallId;
49550
+ const streamed = toolCallId ? replyStreams(requestContext).get(toolCallId) : void 0;
49551
+ if (toolCallId) replyStreams(requestContext).delete(toolCallId);
49552
+ try {
49553
+ if (!streamed || !await streamed.finish(input.text, suffix)) {
49554
+ const render = await resolveRender(requestContext);
49555
+ if (!render) throw new Error("This session is no longer linked to a chat thread.");
49556
+ await render.chatThread.post({ markdown: `${input.text}${suffix}` });
49557
+ }
49558
+ } catch (error) {
49559
+ if (link) requestContext.set(LINKED_KEY, void 0);
49560
+ throw error;
49561
+ }
49562
+ if (link) requestContext.set(LINKED_KEY, "posted");
49563
+ return { posted: true };
49564
+ }
49565
+ }) };
49566
+ }
49567
+ /**
49568
+ * The session link the first reply of a new session ends with, claimed for
49569
+ * this reply. With reply text hidden, the session-link processor's text delta
49570
+ * never reaches the thread, so the tool carries the link instead.
49571
+ */
49572
+ function claimFirstReplyLink(requestContext, link) {
49573
+ if (!link || !requestContext.get("__mastra_new_channel_thread") || requestContext.get(LINKED_KEY)) return;
49574
+ const memory = require_stream.parseMemoryRequestContext(requestContext);
49575
+ const url = link.link({
49576
+ requestContext,
49577
+ threadId: memory?.thread?.id,
49578
+ resourceId: memory?.resourceId
49579
+ });
49580
+ if (url) requestContext.set(LINKED_KEY, "claimed");
49581
+ return url;
49582
+ }
49583
+ /** Live posts of `reply_in_thread` calls whose text is still streaming in, by tool call id. */
49584
+ const STREAMS_KEY = "mastra__channelReplyStreams";
49585
+ function replyStreams(requestContext) {
49586
+ let streams = requestContext.get(STREAMS_KEY);
49587
+ if (!streams) {
49588
+ streams = /* @__PURE__ */ new Map();
49589
+ requestContext.set(STREAMS_KEY, streams);
49590
+ }
49591
+ return streams;
49592
+ }
49593
+ /**
49594
+ * One streamed post, opened on the first visible text so an abandoned
49595
+ * call never leaves an empty message behind.
49596
+ */
49597
+ function openReplyStream({ chatThread, logger }) {
49598
+ const queue = [];
49599
+ let sent = "";
49600
+ let closed = false;
49601
+ let wake;
49602
+ let done;
49603
+ async function* chunks() {
49604
+ while (true) {
49605
+ while (queue.length > 0) yield queue.shift();
49606
+ if (closed) return;
49607
+ await new Promise((resolve) => wake = resolve);
49608
+ }
49609
+ }
49610
+ const push = (text) => {
49611
+ if (!text) return;
49612
+ queue.push(text);
49613
+ done ??= chatThread.post(chunks()).then(() => true, (error) => {
49614
+ logger?.warn("[channels] streamed reply failed; posting it whole", { error });
49615
+ return false;
49616
+ });
49617
+ wake?.();
49618
+ };
49619
+ return {
49620
+ update(text) {
49621
+ const visible = text.trimStart();
49622
+ if (!visible.startsWith(sent)) return;
49623
+ push(visible.slice(sent.length));
49624
+ sent = visible;
49625
+ },
49626
+ async finish(text, suffix) {
49627
+ if (text.startsWith(sent)) push(text.slice(sent.length));
49628
+ if (!done) return false;
49629
+ push(suffix);
49630
+ closed = true;
49631
+ wake?.();
49632
+ return done;
49633
+ },
49634
+ async close() {
49635
+ closed = true;
49636
+ wake?.();
49637
+ return done ?? false;
49638
+ }
49639
+ };
49640
+ }
49641
+ /**
49642
+ * Streams a `reply_in_thread` call's `text` into the thread while the model is
49643
+ * still writing it, so a long reply appears as it is written instead of all at
49644
+ * once when the call completes. The tool finishes the post with the validated
49645
+ * text. Runs whose adapter doesn't stream, or that show reply text, are left
49646
+ * alone.
49647
+ */
49648
+ var ChannelReplyStreamProcessor = class {
49649
+ id = "channel-reply-stream";
49650
+ #resolveRender;
49651
+ constructor(resolveRender) {
49652
+ this.#resolveRender = resolveRender;
49653
+ }
49654
+ async processOutputStream({ part, state, requestContext }) {
49655
+ if (!requestContext) return part;
49656
+ const args = state.args ??= {};
49657
+ if (part.type === "tool-call-input-streaming-start" && part.payload.toolName === "reply_in_thread") {
49658
+ const render = await this.#resolveRender(requestContext);
49659
+ if (render?.textDisplay !== "hidden" || !render.streaming?.enabled) return part;
49660
+ args[part.payload.toolCallId] = "";
49661
+ replyStreams(requestContext).set(part.payload.toolCallId, openReplyStream(render));
49662
+ } else if (part.type === "tool-call-delta" && part.payload.toolCallId in args) {
49663
+ const text = partialStringField(args[part.payload.toolCallId] += part.payload.argsTextDelta, "text");
49664
+ if (text !== void 0) replyStreams(requestContext).get(part.payload.toolCallId)?.update(text);
49665
+ } else if ((part.type === "tool-error" || part.type === "tool-result") && part.payload.toolCallId in args) {
49666
+ delete args[part.payload.toolCallId];
49667
+ await closeStream(requestContext, part.payload.toolCallId);
49668
+ } else if (RUN_END.has(part.type)) {
49669
+ for (const toolCallId of Object.keys(args)) await closeStream(requestContext, toolCallId);
49670
+ state.args = {};
49671
+ }
49672
+ return part;
49673
+ }
49674
+ };
49675
+ /** Chunks after which no `reply_in_thread` call of this run will still execute. */
49676
+ const RUN_END = /* @__PURE__ */ new Set([
49677
+ "finish",
49678
+ "abort",
49679
+ "error",
49680
+ "tripwire"
49681
+ ]);
49682
+ /**
49683
+ * Ends a streamed post whose call will never reach `execute`, keeping the text
49684
+ * shown so far, so the platform isn't left with a message that never finishes.
49685
+ */
49686
+ async function closeStream(requestContext, toolCallId) {
49687
+ const streams = replyStreams(requestContext);
49688
+ const stream = streams.get(toolCallId);
49689
+ if (!stream) return;
49690
+ streams.delete(toolCallId);
49691
+ await stream.close();
49692
+ }
49693
+ const ESCAPES = {
49694
+ "\"": "\"",
49695
+ "\\": "\\",
49696
+ "/": "/",
49697
+ b: "\b",
49698
+ f: "\f",
49699
+ n: "\n",
49700
+ r: "\r",
49701
+ t: " "
49702
+ };
49703
+ /** The decoded value of a top-level string field in JSON that may still be cut off mid-string. */
49704
+ function partialStringField(json, field) {
49705
+ const start = new RegExp(`"${field}"\\s*:\\s*"`).exec(json);
49706
+ if (!start) return void 0;
49707
+ let out = "";
49708
+ for (let i = start.index + start[0].length; i < json.length; i++) {
49709
+ const ch = json[i];
49710
+ if (ch === "\"") return out;
49711
+ if (ch !== "\\") {
49712
+ out += ch;
49713
+ continue;
49714
+ }
49715
+ const next = json[i + 1];
49716
+ if (next === void 0) return out;
49717
+ if (next === "u") {
49718
+ const hex = json.slice(i + 2, i + 6);
49719
+ if (hex.length < 4) return out;
49720
+ out += String.fromCharCode(parseInt(hex, 16));
49721
+ i += 5;
49722
+ } else {
49723
+ out += ESCAPES[next] ?? next;
49724
+ i += 1;
49725
+ }
49726
+ }
49727
+ return out;
49728
+ }
49729
+ // src/channels/reply-guidance-processor.ts
49730
+ const ID$1 = "channel-reply-guidance";
49731
+ /** Chat surfaces show what the agent writes as-is, so a bare id is a dead end for the reader. */
49732
+ const LINK_REFERENCES = "Write every pull request, issue, commit, ticket or other reference you mention in the thread as a markdown link to its page, with the id as plain link text, e.g. [#28467](https://github.com/<owner>/<repo>/pull/28467). Never leave one as a bare id or wrap it in code formatting. Build links from URLs your tools returned; don't guess a URL, and leave a reference unlinked only when you can't work out its URL.";
49733
+ /** Agents tend to write the way they report to other agents: names, ids and shorthand only they follow. */
49734
+ const WRITE_FOR_PEOPLE = [
49735
+ "Write for the people in the thread, not for another agent. A teammate who knows the product and programming, but has not read this code or this conversation, should follow your message on first read.",
49736
+ "Lead with the answer or the outcome and anything you need from them, in plain sentences. Keep it short: a few sentences answer most questions, and when there is more, offer it rather than writing it all out. Say what code does rather than naming the function, file, field, error class or tool that does it; name one only when they need it to find the code. Use the project\u2019s real terms, not invented analogies.",
49737
+ "Leave out tool names and run ids unless someone asks for them, and always leave out agent shorthand. When you pass on what another agent reported, say what it means for the people here in your own words; never paste its report."
49738
+ ].join(" ");
49739
+ /**
49740
+ * Tells the agent how to speak in a chat channel: open a long job with one line that names it,
49741
+ * finish with the outcome, write for people, and link references. With `reply_in_thread` on the
49742
+ * run, that advice becomes advice on when to call it. A run outside the channel that can still
49743
+ * post there (a web prompt on a linked thread) gets a short note on when to. Runs with neither
49744
+ * get nothing.
49745
+ */
49746
+ var ChannelReplyGuidanceProcessor = class {
49747
+ id = ID$1;
49748
+ #instructions;
49749
+ constructor(options = {}) {
49750
+ this.#instructions = options.instructions;
49751
+ }
49752
+ processInputStep({ messageList, requestContext, tools }) {
49753
+ const canReply = !!tools && "reply_in_thread" in tools;
49754
+ let content;
49755
+ if (!requestContext?.get("channel")) {
49756
+ if (!canReply) return void 0;
49757
+ content = [`Post to that thread with \`${REPLY_TOOL_NAME}\`. This request came from outside it, so don't post an opener or progress there; post the outcome when the people in the thread asked for this work or are waiting on it, or when you're asked to. Don't write a note about what you posted.`];
49758
+ } else if (canReply) content = [
49759
+ `Only messages you send with \`${REPLY_TOOL_NAME}\` reach this thread; your other text stays out of it. Don't write a note about what you posted. After a reply, either keep working or end your turn with an empty message; any text you write after posting is wasted.`,
49760
+ "When a request will take tools or more than a moment, post one short line first that says what you are about to do, then do the work and post the outcome when you finish \u2014 not a replay of the steps.",
49761
+ "Post again in between only when you need an answer or have news the people in the thread would want. When a message that doesn't mention you needs nothing from you, don't call it."
49762
+ ];
49763
+ else content = ["When a request will take tools or more than a moment to answer, reply first with one short line that says what you are about to do \u2014 \"On it \u2014 <the task in a few words>.\" \u2014 then do the work; the opener posts as its own message before any progress is shown. Give direct answers and trivial replies without an opener.", "Finish with the outcome, not a replay of the steps."];
49764
+ const extra = typeof this.#instructions === "function" ? this.#instructions({ canReply }) : this.#instructions ?? [];
49765
+ messageList.addSystem({
49766
+ role: "system",
49767
+ content: [
49768
+ ...content,
49769
+ ...extra,
49770
+ LINK_REFERENCES,
49771
+ WRITE_FOR_PEOPLE
49772
+ ].join("\n")
49773
+ }, ID$1);
49774
+ return { messageList };
49775
+ }
49776
+ };
49777
+ // src/channels/reply-reminder-processor.ts
49778
+ const ID = "channel-reply-reminder";
49779
+ /** How long a run may work without posting before it is nudged. */
49780
+ const REPLY_REMINDER_AFTER_MS = 3e5;
49781
+ /**
49782
+ * With reply text hidden, a long job can run silently for an hour while the
49783
+ * person who asked has no idea whether anything is happening. Once a run has
49784
+ * gone `afterMs` without calling `reply_in_thread`, this sends the agent one
49785
+ * signal suggesting a status update, then restarts the clock. Ignoring it is
49786
+ * how the agent stays quiet. A signal joins the end of the transcript, so the
49787
+ * cached prompt prefix is untouched. Only runs that have the reply tool are
49788
+ * touched.
49789
+ */
49790
+ var ChannelReplyReminderProcessor = class {
49791
+ id = ID;
49792
+ #afterMs;
49793
+ #now;
49794
+ constructor({ afterMs = REPLY_REMINDER_AFTER_MS, now = Date.now } = {}) {
49795
+ this.#afterMs = afterMs;
49796
+ this.#now = now;
49797
+ }
49798
+ async processInputStep({ messageList, tools, state, sendSignal }) {
49799
+ if (!tools || !("reply_in_thread" in tools) || !sendSignal) return void 0;
49800
+ const reminder = state;
49801
+ const now = this.#now();
49802
+ reminder.quietSince ??= now;
49803
+ const seen = new Set(reminder.seenCalls ?? []);
49804
+ const calls = replyCalls(messageList.get.response.db());
49805
+ if (calls.some((id) => !seen.has(id))) reminder.quietSince = now;
49806
+ reminder.seenCalls = calls;
49807
+ const silentFor = now - reminder.quietSince;
49808
+ if (silentFor < this.#afterMs) return void 0;
49809
+ const minutes = Math.floor(silentFor / 6e4);
49810
+ await sendSignal({
49811
+ type: "reactive",
49812
+ contents: `It has been ${minutes} minute${minutes === 1 ? "" : "s"} since you last posted in this thread. If the people there would want to know where things stand, post a short status with \`${REPLY_TOOL_NAME}\`. Otherwise keep working.`
49813
+ });
49814
+ reminder.quietSince = now;
49815
+ }
49816
+ };
49817
+ /** Ids of the `reply_in_thread` calls this run has finished. */
49818
+ function replyCalls(messages) {
49819
+ const ids = [];
49820
+ for (const message of messages) {
49821
+ if (message.role !== "assistant") continue;
49822
+ for (const part of message.content.parts ?? []) {
49823
+ if (part.type !== "tool-invocation") continue;
49824
+ const { toolName, toolCallId, state } = part.toolInvocation;
49825
+ if (toolName === "reply_in_thread" && state === "result") ids.push(toolCallId);
49826
+ }
49827
+ }
49828
+ return ids;
49829
+ }
49830
+ // src/channels/reply-mode.ts
49831
+ /**
49832
+ * Slack renders the status inline next to the app name, and rejects a status
49833
+ * (sent as its loading message) of 51 characters or more. Other platforms get
49834
+ * the same cap; reply mode has only been tested on Slack.
49835
+ */
49836
+ const MAX_STATUS_LENGTH = 50;
49837
+ /**
49838
+ * Turns a tool's `description` arg ("Listing the repo root") into a status
49839
+ * line that reads after the app name ("<App> is listing the repo root…").
49840
+ * Only the first line counts: issue/PR creators carry whole bodies there.
49841
+ */
49842
+ function describeToolCall(args) {
49843
+ if (!args || typeof args !== "object") return void 0;
49844
+ const { description } = args;
49845
+ if (typeof description !== "string") return void 0;
49846
+ const line = description.split("\n").map((part) => part.replace(/\s+/g, " ").trim()).find(Boolean);
49847
+ if (!line) return void 0;
49848
+ const status = `is ${/^[A-Z][a-z]/.test(line) ? line.charAt(0).toLowerCase() + line.slice(1) : line}`;
49849
+ return status.length > MAX_STATUS_LENGTH ? `${status.slice(0, 49)}\u2026` : status;
49850
+ }
49851
+ /**
49852
+ * Progress as a status line rather than posts: "is thinking...", the current
49853
+ * tool's `description`, "is typing..." while a reply is written. With reply
49854
+ * text hidden, streamed text never reaches the thread, so it gets no status:
49855
+ * an "is typing..." set after the reply tool's post would sit on the thread
49856
+ * with nothing coming, and race the clear at the end of the run.
49857
+ *
49858
+ * @internal
49859
+ */
49860
+ function channelReplyTypingStatus(textDisplay = "hidden") {
49861
+ return (chunk) => {
49862
+ switch (chunk.type) {
49863
+ case "reasoning-delta": return "is thinking...";
49864
+ case "text-delta": return textDisplay === "show" ? "is typing..." : void 0;
49865
+ case "tool-call-input-streaming-start": return chunk.payload.toolName === "reply_in_thread" ? "is typing..." : void 0;
49866
+ case "tool-call":
49867
+ if (chunk.payload.toolName === "reply_in_thread") return "is typing...";
49868
+ return describeToolCall(chunk.payload.args) ?? "is working...";
49869
+ default: return;
49870
+ }
49871
+ };
49872
+ }
49873
+ function threadLinkOptions(link) {
49874
+ if (!link) return void 0;
49875
+ return typeof link === "function" ? { link } : link;
49876
+ }
49877
+ /**
49878
+ * Installed by `AgentChannels` when an adapter sets `replyMode`. On runs whose chat
49879
+ * thread is on that adapter (including runs started elsewhere whose thread is linked
49880
+ * to it) it adds the `reply_in_thread` tool, the reply guidance prompt, and the
49881
+ * nudge after a quiet stretch. Other runs are untouched.
49882
+ *
49883
+ * @internal
49884
+ */
49885
+ var ChannelReplyModeProcessor = class {
49886
+ id = "channel-reply-mode";
49887
+ #deps;
49888
+ constructor(deps) {
49889
+ this.#deps = deps;
49890
+ }
49891
+ async processInputStep(args) {
49892
+ const { requestContext, state } = args;
49893
+ const render = await this.#deps.resolveRender(requestContext, state);
49894
+ const adapter = render && this.#deps.adapter(render.platform);
49895
+ if (!requestContext || !render || !adapter?.replyMode) return void 0;
49896
+ const config = adapter.replyMode === "tool" ? {} : adapter.replyMode;
49897
+ if (render.textDisplay !== "hidden") {
49898
+ new ChannelReplyGuidanceProcessor({ instructions: config.instructions }).processInputStep(args);
49899
+ return { messageList: args.messageList };
49900
+ }
49901
+ const tools = {
49902
+ ...args.tools,
49903
+ ...createChannelReplyTool(requestContext, {
49904
+ resolveRender: async () => render,
49905
+ link: threadLinkOptions(adapter.threadLink)
49906
+ })
49907
+ };
49908
+ const withTools = {
49909
+ ...args,
49910
+ tools
49911
+ };
49912
+ new ChannelReplyGuidanceProcessor({ instructions: config.instructions }).processInputStep(withTools);
49913
+ await new ChannelReplyReminderProcessor({
49914
+ afterMs: config.reminderAfterMs,
49915
+ now: this.#deps.now
49916
+ }).processInputStep(withTools);
49917
+ const activeTools = args.activeTools && !args.activeTools.includes("reply_in_thread") ? [...args.activeTools, REPLY_TOOL_NAME] : void 0;
49918
+ return {
49919
+ tools,
49920
+ messageList: args.messageList,
49921
+ ...activeTools ? { activeTools } : {}
49922
+ };
49923
+ }
49924
+ };
49164
49925
  // src/channels/state-adapter.ts
49165
49926
  /**
49166
49927
  * Chat SDK StateAdapter backed by Mastra storage.
@@ -49174,15 +49935,17 @@ function channelLines(ctx, textHidden, tools) {
49174
49935
  var MastraStateAdapter = class {
49175
49936
  memoryStore;
49176
49937
  getOwnerId;
49938
+ logger;
49177
49939
  connected = false;
49178
49940
  connectPromise = null;
49179
49941
  cache = /* @__PURE__ */ new Map();
49180
49942
  locks = /* @__PURE__ */ new Map();
49181
49943
  lists = /* @__PURE__ */ new Map();
49182
49944
  queues = /* @__PURE__ */ new Map();
49183
- constructor(memoryStore, getOwnerId) {
49945
+ constructor(memoryStore, getOwnerId, logger) {
49184
49946
  this.memoryStore = memoryStore;
49185
49947
  this.getOwnerId = getOwnerId;
49948
+ this.logger = logger;
49186
49949
  }
49187
49950
  async connect() {
49188
49951
  if (this.connected) return;
@@ -49201,7 +49964,10 @@ var MastraStateAdapter = class {
49201
49964
  }
49202
49965
  async subscribe(threadId) {
49203
49966
  const thread = await this.findThreadByExternalId(threadId);
49204
- if (!thread) return;
49967
+ if (!thread) {
49968
+ this.logger?.warn(`subscribe(${threadId}) ignored: no Mastra thread is mapped to this chat thread. Use AgentChannels.subscribeThread() for threads the bot started itself.`);
49969
+ return;
49970
+ }
49205
49971
  await this.memoryStore.patchThread({
49206
49972
  id: thread.id,
49207
49973
  metadata: {
@@ -49580,6 +50346,24 @@ function formatLegacyHistoryBlock(history, chatThread, platform) {
49580
50346
  for (const msg of history.recent) lines.push(line(msg));
49581
50347
  return lines.join("\n");
49582
50348
  }
50349
+ // src/channels/thread-lookup.ts
50350
+ /**
50351
+ * The chat thread this run posts into, if any.
50352
+ *
50353
+ * A run started by a platform message has the render context on `requestContext`. A run
50354
+ * started elsewhere (web UI, schedule, signal wake) on a thread linked to a chat thread does
50355
+ * not, so rebuild it from the thread's persisted channel coordinates. The thread id comes from
50356
+ * the agent controller when there is one, else from the run's memory context. A forked
50357
+ * subagent's thread carries no channel metadata, so forks resolve nothing.
50358
+ */
50359
+ async function resolveChannelRenderContext(requestContext, channels) {
50360
+ if (!requestContext) return void 0;
50361
+ const stashed = requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
50362
+ if (isUsableRenderContext(stashed)) return stashed;
50363
+ const threadId = requestContext.get("controller")?.threadId ?? require_stream.parseMemoryRequestContext(requestContext)?.thread?.id;
50364
+ if (!threadId) return void 0;
50365
+ return await channels?.()?.buildRenderContextForThread(threadId) ?? void 0;
50366
+ }
49583
50367
  // src/channels/typing-status.ts
49584
50368
  /**
49585
50369
  * Built-in typing-status resolver. Used when `typingStatus: true` (the default)
@@ -49825,7 +50609,7 @@ var AgentChannels = class {
49825
50609
  for (const [name, value] of Object.entries(config.adapters)) if (value && typeof value === "object" && "adapter" in value) {
49826
50610
  const cfg = value;
49827
50611
  adapters[name] = cfg.adapter;
49828
- adapterConfigs[name] = cfg;
50612
+ adapterConfigs[name] = cfg.replyMode ? withReplyModeDefaults(cfg) : cfg;
49829
50613
  } else {
49830
50614
  adapters[name] = value;
49831
50615
  adapterConfigs[name] = { adapter: value };
@@ -49846,6 +50630,7 @@ var AgentChannels = class {
49846
50630
  this.channelConfig = config;
49847
50631
  this.channelToolNames = new Set(Object.keys(this.getTools()));
49848
50632
  if (this.generativeUIEnabled) this.channelToolNames.add(RENDER_CARD_TOOL_NAME);
50633
+ if (this.replyModeEnabled) this.channelToolNames.add(REPLY_TOOL_NAME);
49849
50634
  }
49850
50635
  /**
49851
50636
  * Bind the owning agent used for webhook paths and stored-thread ownership.
@@ -50018,7 +50803,7 @@ var AgentChannels = class {
50018
50803
  const storage = mastra.getStorage();
50019
50804
  const memoryStore = storage ? await storage.getStore("memory") : void 0;
50020
50805
  if (!memoryStore) throw new Error("Channels require storage to be configured on the Mastra instance. Configure a storage provider like LibSQLStore.");
50021
- this.stateAdapter = new MastraStateAdapter(memoryStore, () => this.getOwnerId());
50806
+ this.stateAdapter = new MastraStateAdapter(memoryStore, () => this.getOwnerId(), this.logger);
50022
50807
  this.log("info", "Using MastraStateAdapter (subscriptions persist across restarts)");
50023
50808
  }
50024
50809
  const { Chat, Message: ChatMessage, ThreadImpl } = await getChatModule();
@@ -50246,25 +51031,30 @@ var AgentChannels = class {
50246
51031
  runId = stashed.runId;
50247
51032
  toolName = stashed.toolName;
50248
51033
  toolArgs = stashed.args;
50249
- } else {
51034
+ }
51035
+ if (!requesterId) {
50250
51036
  const { result: lookup } = await this.lookupPersistedApproval({
50251
51037
  mastra,
50252
51038
  card,
50253
51039
  platform
50254
51040
  });
50255
- if (lookup.status === "answered") {
50256
- this.log("info", "Tool approval already answered", actionEventContext);
50257
- return;
51041
+ if (!stashed?.runId) {
51042
+ if (lookup.status === "answered") {
51043
+ this.log("info", "Tool approval already answered", actionEventContext);
51044
+ return;
51045
+ }
51046
+ if (lookup.status === "pending") {
51047
+ runId = lookup.runId;
51048
+ toolName = lookup.toolName;
51049
+ toolArgs = lookup.args;
51050
+ }
50258
51051
  }
50259
51052
  if (lookup.status === "pending") {
50260
- runId = lookup.runId;
50261
- toolName = lookup.toolName;
50262
- toolArgs = lookup.args;
50263
- if (adapterConfig?.toolApprovers !== "anyone" && !requesterId && lookup.authors.length > 1) {
51053
+ if (adapterConfig?.toolApprovers !== "anyone" && lookup.authors.length > 1) {
50264
51054
  this.log("info", "Ignoring tool approval action: requester is ambiguous", actionEventContext);
50265
51055
  return;
50266
51056
  }
50267
- requesterId ??= lookup.authors[0];
51057
+ requesterId = lookup.authors[0];
50268
51058
  }
50269
51059
  }
50270
51060
  if (!runId) {
@@ -50553,8 +51343,28 @@ var AgentChannels = class {
50553
51343
  const processors = [];
50554
51344
  if (this.channelConfig.threadContext?.addSystemMessage !== false && !has("chat-channel-context")) processors.push(new ChatChannelProcessor(this));
50555
51345
  if (this.generativeUIEnabled && !has("chat-channel-generative-ui")) processors.push(new ChatChannelGenerativeUIProcessor(this));
51346
+ if (this.replyModeEnabled && !has(REPLY_MODE_PROCESSOR_ID)) processors.push(new ChannelReplyModeProcessor({
51347
+ resolveRender: (requestContext, state) => this.resolveRunRender(requestContext, state),
51348
+ adapter: (platform) => this.adapterConfigs[platform]
51349
+ }));
50556
51350
  return processors;
50557
51351
  }
51352
+ get replyModeEnabled() {
51353
+ return Object.values(this.adapterConfigs).some((cfg) => cfg.replyMode);
51354
+ }
51355
+ /**
51356
+ * The chat thread a run posts to: the one it came in on, else the one its
51357
+ * thread (the controller's, or memory's) is linked to. Cached on `state`
51358
+ * when given; `null` remembers a thread that isn't channel-backed.
51359
+ */
51360
+ async resolveRunRender(requestContext, state) {
51361
+ const inbound = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
51362
+ if (isUsableRenderContext(inbound)) return inbound;
51363
+ if (state && "render" in state) return state.render ?? void 0;
51364
+ const render = await resolveChannelRenderContext(requestContext, () => this);
51365
+ if (state) state.render = render ?? null;
51366
+ return render;
51367
+ }
50558
51368
  /** Whether the Slack adapter opted into `generativeUI` (the only platform it supports). */
50559
51369
  get generativeUIEnabled() {
50560
51370
  return this.adapterConfigs.slack?.generativeUI === true;
@@ -50575,8 +51385,15 @@ var AgentChannels = class {
50575
51385
  */
50576
51386
  close() {}
50577
51387
  getOutputProcessors(configuredProcessors = []) {
50578
- if (configuredProcessors.some((p) => !require_stream.isProcessorWorkflow(p) && p.id === "chat-channel-render")) return [];
50579
- return [new ChatChannelOutputProcessor(this)];
51388
+ const has = (id) => configuredProcessors.some((p) => !require_stream.isProcessorWorkflow(p) && p.id === id);
51389
+ const processors = [];
51390
+ if (Object.values(this.adapterConfigs).some((cfg) => cfg.threadLink) && !has(THREAD_LINK_PROCESSOR_ID)) processors.push(new ChannelThreadLinkProcessor((requestContext) => {
51391
+ const platform = requestContext.get("channel")?.platform ?? requestContext.get("__mastra_chat_channel_render")?.platform;
51392
+ return platform ? threadLinkOptions(this.adapterConfigs[platform]?.threadLink) : void 0;
51393
+ }));
51394
+ if (!has("chat-channel-render")) processors.push(new ChatChannelOutputProcessor(this));
51395
+ if (this.replyModeEnabled && !has(REPLY_STREAM_PROCESSOR_ID)) processors.push(new ChannelReplyStreamProcessor((requestContext) => this.resolveRunRender(requestContext)));
51396
+ return processors;
50580
51397
  }
50581
51398
  /**
50582
51399
  * Returns generic channel tools (add_reaction, remove_reaction) that resolve
@@ -50851,6 +51668,7 @@ var AgentChannels = class {
50851
51668
  defaultThreadId,
50852
51669
  requestContext
50853
51670
  }) : void 0,
51671
+ onCreate: () => markNewChannelThread(requestContext),
50854
51672
  mastra
50855
51673
  });
50856
51674
  const threadResourceId = mastraThread.resourceId;
@@ -51753,9 +52571,39 @@ var AgentChannels = class {
51753
52571
  };
51754
52572
  }
51755
52573
  /**
52574
+ * Map a chat thread to a Mastra thread (creating the mapping if needed) and
52575
+ * subscribe to it, so follow-up replies reach the agent without a mention.
52576
+ *
52577
+ * Use this for threads the bot started itself, e.g. a scheduled digest posted
52578
+ * to Slack. Inbound messages create the mapping automatically, but a thread
52579
+ * the bot opened has none until someone mentions it. An existing mapping is
52580
+ * reused and keeps its original owner.
52581
+ *
52582
+ * @example
52583
+ * ```ts
52584
+ * const sent = await channel.post('Daily digest');
52585
+ * await agent.getChannels()!.subscribeThread({ thread: sent.thread, resourceId: 'digest-bot' });
52586
+ * ```
52587
+ */
52588
+ async subscribeThread({ thread, resourceId, threadId }) {
52589
+ const mastra = this.getMastra();
52590
+ if (!mastra) throw new Error("subscribeThread requires the agent to be registered with a Mastra instance.");
52591
+ await this.initialize(mastra);
52592
+ const mastraThread = await this.getOrCreateThread({
52593
+ externalThreadId: thread.id,
52594
+ channelId: thread.channelId,
52595
+ platform: thread.adapter.name,
52596
+ resourceId,
52597
+ threadId: threadId ? () => threadId : void 0,
52598
+ mastra
52599
+ });
52600
+ await this.stateAdapter.subscribe(thread.id);
52601
+ return mastraThread;
52602
+ }
52603
+ /**
51756
52604
  * Resolves an existing Mastra thread for the given external IDs, or creates one.
51757
52605
  */
51758
- async getOrCreateThread({ externalThreadId, channelId, platform, resourceId, threadId, mastra }) {
52606
+ async getOrCreateThread({ externalThreadId, channelId, platform, resourceId, threadId, onCreate, mastra }) {
51759
52607
  const { thread: existingThread, memoryStore, metadata } = await this.findThreadMapping({
51760
52608
  externalThreadId,
51761
52609
  channelId,
@@ -51763,6 +52611,7 @@ var AgentChannels = class {
51763
52611
  mastra
51764
52612
  });
51765
52613
  if (existingThread) return existingThread;
52614
+ onCreate?.();
51766
52615
  const resolvedResourceId = typeof resourceId === "function" ? await resourceId() : resourceId;
51767
52616
  const defaultThreadId = crypto.randomUUID();
51768
52617
  let resolvedThreadId = threadId ? await threadId(resolvedResourceId, defaultThreadId) : defaultThreadId;
@@ -51964,6 +52813,147 @@ async function storedAttachmentBytes(fs, dir, root = true) {
51964
52813
  }
51965
52814
  return total;
51966
52815
  }
52816
+ const REPLY_MODE_PROCESSOR_ID = "channel-reply-mode";
52817
+ const REPLY_STREAM_PROCESSOR_ID = "channel-reply-stream";
52818
+ const THREAD_LINK_PROCESSOR_ID = "channel-thread-link";
52819
+ /** Reply mode keeps reply text and tool calls out of the thread and shows progress in the status, unless set. */
52820
+ function withReplyModeDefaults(cfg) {
52821
+ const legacyCards = "cards" in cfg && cfg.cards !== void 0;
52822
+ const set = Object.fromEntries(Object.entries(cfg).filter(([, value]) => value !== void 0));
52823
+ const textDisplay = cfg.textDisplay ?? "hidden";
52824
+ return {
52825
+ textDisplay,
52826
+ ...legacyCards ? {} : { toolDisplay: "hidden" },
52827
+ typingStatus: channelReplyTypingStatus(textDisplay),
52828
+ ...set
52829
+ };
52830
+ }
52831
+ // src/knowledge/held-scopes-state-processor.ts
52832
+ const HELD_SCOPES_STATE_ID = "knowledge-scopes";
52833
+ const HELD_SCOPES_SNAPSHOT_TAG = "knowledge-scopes";
52834
+ const HELD_SCOPES_DELTA_TAG = "knowledge-scopes-update";
52835
+ function lp$1(value) {
52836
+ return `${value.length}:${value}`;
52837
+ }
52838
+ function fingerprint$1(scope) {
52839
+ return `${lp$1(scope.address)}${lp$1(scope.role)}`;
52840
+ }
52841
+ function cacheKey(scopes) {
52842
+ return `scopes:${scopes.map(fingerprint$1).join("|")}`;
52843
+ }
52844
+ function scopesFromSnapshot(snapshot) {
52845
+ const value = (snapshot?.metadata)?.value?.scopes;
52846
+ return Array.isArray(value) ? value : [];
52847
+ }
52848
+ function opsFromDelta(delta) {
52849
+ const ops = delta.metadata?.delta?.ops;
52850
+ return Array.isArray(ops) ? ops : [];
52851
+ }
52852
+ function applyOps(scopes, ops) {
52853
+ const next = scopes.slice();
52854
+ for (const op of ops) {
52855
+ const address = op.op === "remove" ? op.address : op.scope.address;
52856
+ const idx = next.findIndex((scope) => scope.address === address);
52857
+ if (op.op === "remove") {
52858
+ if (idx >= 0) next.splice(idx, 1);
52859
+ } else if (idx >= 0) next[idx] = op.scope;
52860
+ else next.push(op.scope);
52861
+ }
52862
+ return next;
52863
+ }
52864
+ function diffScopes(prior, current) {
52865
+ const ops = [];
52866
+ const before = new Map(prior.map((scope) => [scope.address, fingerprint$1(scope)]));
52867
+ const currentAddresses = new Set(current.map((scope) => scope.address));
52868
+ for (const scope of prior) if (!currentAddresses.has(scope.address)) ops.push({
52869
+ op: "remove",
52870
+ address: scope.address
52871
+ });
52872
+ for (const scope of current) {
52873
+ const was = before.get(scope.address);
52874
+ if (was === void 0) ops.push({
52875
+ op: "add",
52876
+ scope
52877
+ });
52878
+ else if (was !== fingerprint$1(scope)) ops.push({
52879
+ op: "change",
52880
+ scope
52881
+ });
52882
+ }
52883
+ return ops;
52884
+ }
52885
+ function line(scope) {
52886
+ return `${scope.address} (${scope.role})`;
52887
+ }
52888
+ function renderSnapshot(scopes) {
52889
+ if (scopes.length === 0) return "\n Your session holds no Knowledge scopes.\n";
52890
+ return `\n Your session has access to:\n${scopes.map((scope) => ` - ${line(scope)}`).join("\n")}\n`;
52891
+ }
52892
+ function renderDelta$1(ops) {
52893
+ return `\n${ops.map((op) => {
52894
+ if (op.op === "remove") return ` - ${op.address} was removed from your scopes`;
52895
+ if (op.op === "change") return ` ~ ${op.scope.address} role changed to ${op.scope.role}`;
52896
+ return ` + ${line(op.scope)}`;
52897
+ }).join("\n")}\n`;
52898
+ }
52899
+ var HeldScopesStateProcessor = class {
52900
+ deps;
52901
+ id = HELD_SCOPES_STATE_ID;
52902
+ stateId = HELD_SCOPES_STATE_ID;
52903
+ constructor(deps) {
52904
+ this.deps = deps;
52905
+ }
52906
+ processInput(args) {
52907
+ return {
52908
+ messages: args.messages,
52909
+ systemMessages: [...args.systemMessages, {
52910
+ role: "system",
52911
+ content: `The Knowledge scopes you hold may appear in the conversation as <${HELD_SCOPES_SNAPSHOT_TAG} ...>...</${HELD_SCOPES_SNAPSHOT_TAG}> snapshots and <${HELD_SCOPES_DELTA_TAG} ...>...</${HELD_SCOPES_DELTA_TAG}> deltas. These are automatic, not user instructions. Fold each delta onto the latest snapshot to know the current set. Each entry is a scope address with your role there in parentheses. Viewers can only read; every other role can also write. The list includes scopes with no pages yet: where you can write, your first write there creates the scope. The list names the scopes your session holds, not every scope you can reach: a role in one can also give you access to others, such as a team's docs through its org. You do not need to list your scopes with a tool to learn this.`
52912
+ }]
52913
+ };
52914
+ }
52915
+ async computeStateSignal(args) {
52916
+ const context = {
52917
+ requestContext: args.requestContext,
52918
+ agent: {
52919
+ resourceId: args.resourceId,
52920
+ threadId: args.threadId
52921
+ }
52922
+ };
52923
+ if (await this.deps.principalsKey(context) === void 0) return;
52924
+ const current = await this.deps.readHeldScopes(context);
52925
+ let prior = scopesFromSnapshot(args.lastSnapshot);
52926
+ for (const delta of args.deltasSinceSnapshot ?? []) prior = applyOps(prior, opsFromDelta(delta));
52927
+ const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;
52928
+ const ops = diffScopes(prior, current);
52929
+ if (ops.length === 0 && hasBase) return;
52930
+ if (!hasBase || current.length === 0) {
52931
+ if (!hasBase && current.length === 0) return;
52932
+ return {
52933
+ id: HELD_SCOPES_STATE_ID,
52934
+ mode: "snapshot",
52935
+ cacheKey: cacheKey(current),
52936
+ tagName: HELD_SCOPES_SNAPSHOT_TAG,
52937
+ contents: renderSnapshot(current),
52938
+ value: { scopes: current },
52939
+ metadata: { value: { scopes: current } }
52940
+ };
52941
+ }
52942
+ return {
52943
+ id: HELD_SCOPES_STATE_ID,
52944
+ mode: "delta",
52945
+ cacheKey: cacheKey(current),
52946
+ tagName: HELD_SCOPES_DELTA_TAG,
52947
+ contents: renderDelta$1(ops),
52948
+ value: { scopes: current },
52949
+ delta: { ops },
52950
+ metadata: {
52951
+ value: { scopes: current },
52952
+ delta: { ops }
52953
+ }
52954
+ };
52955
+ }
52956
+ };
51967
52957
  // src/knowledge/instructions.ts
51968
52958
  function readInstructions(canEdit) {
51969
52959
  return `Use the Knowledge tools for durable, shared knowledge. Pinned knowledge pages may already be in your context if <pinned-knowledge> tags are present in the visible conversation history: answer from their bodies without searching for or reading them again${canEdit ? ", and edit one straight from its body and the version shown, unless its body was cut off: then read it first, since a write replaces the whole body" : ""}. Read a pinned page with knowledge_read only when the answer depends on what its notes say, or on its child pages; a note count alone is no reason to read it. For anything else, search with knowledge_search before answering from Knowledge, and read a page with knowledge_read before relying on it. To see how a scope or section is organized, list it with knowledge_list and read pages by the refs it gives. Read a page whole first; when its body is too long, it comes back as its headings with line numbers and the first lines under each: read the section you need, or match the terms you are looking for. A result's more says what it left out: follow it only when what you need is not already in what you have read, and answer as soon as you have it. Cite the page or note you used. When nothing is found, say so plainly instead of guessing. When notes disagree, show both with their dates.`;
@@ -52254,6 +53244,16 @@ function compileKnowledgeScopes(declarations) {
52254
53244
  const concreteEntries = [];
52255
53245
  for (const [key, declaration] of Object.entries(declarations)) {
52256
53246
  const pattern = parsePattern(key, "Knowledge scope key");
53247
+ if (declaration.mint !== void 0) {
53248
+ if (declaration.mint !== "run-identity" || pattern.type !== "agent" || pattern.params.length === 0) throw new KnowledgeDeclarationError(`Knowledge scope "${key}" can mint only an agent pattern with mint: 'run-identity'.`);
53249
+ for (const param of pattern.params) if (![
53250
+ "agentId",
53251
+ "orgId",
53252
+ "resourceId",
53253
+ "role",
53254
+ "teamId"
53255
+ ].includes(param)) throw new KnowledgeDeclarationError(`Knowledge scope "${key}" cannot mint unknown parameter $${param}.`);
53256
+ }
52257
53257
  if (pattern.params.length === 0) {
52258
53258
  concreteEntries.push([key, declaration]);
52259
53259
  continue;
@@ -52722,17 +53722,19 @@ async function pageRefKeys(storage, page) {
52722
53722
  if (page.address) keys.push(knowledgeLinkRefKey(page.address));
52723
53723
  return keys;
52724
53724
  }
53725
+ if (!page.key || !page.parentId) return keys;
52725
53726
  const path = [];
52726
- let current = page;
52727
- while (current && !current.isScope) {
53727
+ for (const current of [page, ...await storage.getPageParents({
53728
+ parentId: page.parentId,
53729
+ read: "all"
53730
+ })]) {
53731
+ if (current.isScope) {
53732
+ if (current.address) keys.push(knowledgeLinkRefKey(`${current.address}#${path.join("/")}`));
53733
+ return keys;
53734
+ }
52728
53735
  if (!current.key || !current.parentId) return keys;
52729
53736
  path.unshift(current.key);
52730
- current = await storage.getPage({
52731
- id: current.parentId,
52732
- read: "all"
52733
- });
52734
53737
  }
52735
- if (current?.address) keys.push(knowledgeLinkRefKey(`${current.address}#${path.join("/")}`));
52736
53738
  return keys;
52737
53739
  }
52738
53740
  /** The page and its live ordinary descendants, at most {@link MAX_KNOWLEDGE_MOVE_PAGES} + 1. */
@@ -62225,6 +63227,94 @@ async function removeKnowledgeNote(host, input) {
62225
63227
  await embed$1(host, (index) => index.remove([`note:${note.id}`]), UNEMBED_FAILED$1);
62226
63228
  return removed;
62227
63229
  }
63230
+ // src/knowledge/agent-scopes.ts
63231
+ /** Agent identity declarations. Identities grant nothing until an access rule names them. @experimental */
63232
+ function knowledgeAgentScopes() {
63233
+ return Object.fromEntries([
63234
+ "agent:$agentId",
63235
+ "agent:$agentId:org:$orgId",
63236
+ "agent:$agentId:user:$resourceId",
63237
+ "agent:persona:role:$role",
63238
+ "agent:persona:role:$role:org:$orgId",
63239
+ "agent:persona:role:$role:user:$resourceId",
63240
+ "agent:persona:team:$teamId"
63241
+ ].map((key) => [key, {
63242
+ mint: "run-identity",
63243
+ access: []
63244
+ }]));
63245
+ }
63246
+ /**
63247
+ * {@link knowledgeAgentScopes} plus a read-only persona convention: each agent reads and pins its own
63248
+ * `#persona` page, and every agent of a role or team reads and pins that scope's `#rules` page. The
63249
+ * `:edit` forms give editor on one role or team scope and are never minted; host code passes them.
63250
+ * @experimental
63251
+ */
63252
+ function knowledgePersonaScopes() {
63253
+ const scopes = knowledgeAgentScopes();
63254
+ for (const [key, page, name, edit] of [
63255
+ [
63256
+ "agent:$agentId",
63257
+ "persona",
63258
+ "Persona",
63259
+ false
63260
+ ],
63261
+ [
63262
+ "agent:persona:role:$role",
63263
+ "rules",
63264
+ "Role rules",
63265
+ true
63266
+ ],
63267
+ [
63268
+ "agent:persona:team:$teamId",
63269
+ "rules",
63270
+ "Team rules",
63271
+ true
63272
+ ]
63273
+ ]) {
63274
+ scopes[key] = {
63275
+ ...scopes[key],
63276
+ access: [{
63277
+ principal: "self",
63278
+ role: "viewer"
63279
+ }, ...edit ? [{
63280
+ principal: `${key}:edit`,
63281
+ role: "editor"
63282
+ }] : []],
63283
+ pages: [{
63284
+ key: page,
63285
+ name
63286
+ }],
63287
+ pinnedContext: [`${key}#${page}`]
63288
+ };
63289
+ if (edit) scopes[`${key}:edit`] = { access: [] };
63290
+ }
63291
+ return scopes;
63292
+ }
63293
+ /** @internal */
63294
+ function mintKnowledgeAgentScopes(compiled, scopes, agent) {
63295
+ const params = {};
63296
+ if (agent?.agentId) params.agentId = agent.agentId;
63297
+ if (agent?.resourceId) params.resourceId = agent.resourceId;
63298
+ const persona = agent?.persona;
63299
+ if (persona && typeof persona === "object") for (const [field, param] of [["role", "role"], ["teamId", "teamId"]]) {
63300
+ const value = persona[field];
63301
+ if (typeof value === "string" && value.length > 0) params[param] = value;
63302
+ }
63303
+ const orgs = scopes.filter((scope) => /^org:[^:]+$/.test(scope)).map((scope) => decodeKnowledgeScopeValue(scope.slice(4))).filter((value) => value !== null);
63304
+ const minted = [];
63305
+ for (const declaration of compiled.declarations.values()) {
63306
+ if (declaration.declaration.mint !== "run-identity") continue;
63307
+ const bindings = declaration.pattern.params.includes("orgId") ? orgs.map((orgId) => ({
63308
+ ...params,
63309
+ orgId
63310
+ })) : [params];
63311
+ for (const binding of bindings) {
63312
+ const address = bindKnowledgePattern(declaration.pattern, binding);
63313
+ if (address) minted.push(address);
63314
+ }
63315
+ }
63316
+ return minted;
63317
+ }
62228
63318
  // src/knowledge/run.ts
62229
63319
  /** A page reference the run can't resolve; identical for missing and unreadable pages. */
62230
63320
  var KnowledgeNotFoundError = class extends Error {
@@ -62233,6 +63323,13 @@ var KnowledgeNotFoundError = class extends Error {
62233
63323
  this.name = "KnowledgeNotFoundError";
62234
63324
  }
62235
63325
  };
63326
+ /** A run with no scopes and no Memory identity: it has no Knowledge view. @internal */
63327
+ var KnowledgeRunScopesError = class extends Error {
63328
+ constructor() {
63329
+ super("Knowledge tools need run scopes: give the agent or the call `scopes`, or run it with Memory.");
63330
+ this.name = "KnowledgeRunScopesError";
63331
+ }
63332
+ };
62236
63333
  const NAME_CANDIDATES = 5;
62237
63334
  const CLOSE_MATCHES = 3;
62238
63335
  /**
@@ -62384,9 +63481,15 @@ function knowledgeRunPrincipals(runtime, context) {
62384
63481
  const memory = [];
62385
63482
  if (context?.agent?.resourceId) memory.push(knowledgeScopeAddress("resource:$resourceId", { resourceId: context.agent.resourceId }));
62386
63483
  if (context?.agent?.threadId) memory.push(knowledgeScopeAddress("thread:$threadId", { threadId: context.agent.threadId }));
62387
- if (raw.length === 0 && memory.length === 0) throw new Error("Knowledge tools need run scopes: give the agent or the call `scopes`, or run it with Memory.");
63484
+ if (raw.length === 0 && memory.length === 0) throw new KnowledgeRunScopesError();
62388
63485
  for (const address of memory) if (!runtime.compiled.match(address)) throw new KnowledgeDeclarationError(`Knowledge run scope "${address}" does not match a declared scope type. Declare it in Knowledge \`scopes\` (for Memory's resource:/thread: scopes, spread \`...knowledgeMemoryScopes()\`).`);
62389
- return [.../* @__PURE__ */ new Set([...knowledgeRunScopes(runtime.compiled, raw), ...memory])];
63486
+ const scopes = knowledgeRunScopes(runtime.compiled, raw);
63487
+ const minted = mintKnowledgeAgentScopes(runtime.compiled, scopes, context?.agent);
63488
+ return [.../* @__PURE__ */ new Set([
63489
+ ...scopes,
63490
+ ...memory,
63491
+ ...minted
63492
+ ])];
62390
63493
  }
62391
63494
  /** Longest heading line a hit shows ahead of its excerpt; a longer one is cut with `…`. */
62392
63495
  const HEADING_CHARS = 120;
@@ -62760,6 +63863,30 @@ async function noteSummaries(run, notes, cache = /* @__PURE__ */ new Map()) {
62760
63863
  for (const note of notes) summaries.push(noteSummary(note, await noteMentions(run, note, cache)));
62761
63864
  return summaries;
62762
63865
  }
63866
+ /**
63867
+ * Every scope the run holds, in principal order, with its role and what it can do there. A held scope
63868
+ * gets its page on the first write, so before that its role comes from the declarations and the parent
63869
+ * that write would link it under: without it a model sees no scopes on its first turn and concludes it
63870
+ * has nowhere to write. A stored scope it can't read keeps only its address.
63871
+ */
63872
+ async function heldScopes(run) {
63873
+ const stored = await run.storage.getScopesByAddress(run.principals);
63874
+ return Promise.all(run.principals.map(async (address) => {
63875
+ const found = stored.find((scope) => scope.address === address);
63876
+ const page = found && knowledgeScopeReadable(found, run.read) ? found : void 0;
63877
+ const role = found ? await run.roleOn(found) : knowledgeRoleOn(run.runtime.compiled, run.principals, {
63878
+ address,
63879
+ parentAddress: run.runtime.firstWriteParentAddress(address, run.principals)
63880
+ });
63881
+ const can = !role ? "none" : knowledgeRoleAtLeast(role, "contributor") ? "write" : "read";
63882
+ return {
63883
+ address,
63884
+ ...page ? { page } : {},
63885
+ role,
63886
+ can
63887
+ };
63888
+ }));
63889
+ }
62763
63890
  /** Scope pages for addresses the run names; each must be readable. */
62764
63891
  async function readableScopes(run, addresses) {
62765
63892
  const page = addresses.find((address) => address.includes("#"));
@@ -62796,11 +63923,13 @@ async function visibleNote(run, id) {
62796
63923
  page
62797
63924
  };
62798
63925
  }
62799
- /** Pin authority over an audience entry: the run holds it, or rules give it editor+ there. */
63926
+ /** Shared persona audiences need editor authority even when the run holds them. */
62800
63927
  async function requireAudienceAuthority(run, audience) {
62801
63928
  for (const address of audience) {
62802
- if (run.principals.includes(address)) continue;
62803
- if (!run.runtime.compiled.match(address)) throw new Error(`Pin audience "${address}" does not match a declared scope type.`);
63929
+ const match = run.runtime.compiled.match(address);
63930
+ const sharedPersona = match?.compiled.declaration.mint === "run-identity" && match.compiled.pattern.params.some((param) => param === "role" || param === "teamId");
63931
+ if (run.principals.includes(address) && !sharedPersona) continue;
63932
+ if (!match) throw new Error(`Pin audience "${address}" does not match a declared scope type.`);
62804
63933
  const [scope] = await run.storage.getScopesByAddress([address]);
62805
63934
  if (!knowledgeRoleAtLeast(scope ? await run.roleOn(scope) : knowledgeRoleOn(run.runtime.compiled, run.principals, { address }), "editor")) throw new Error(`Pinning for "${address}" needs holding it or editor on it; this run has neither.`);
62806
63935
  }
@@ -63040,7 +64169,7 @@ function bodyView(body, input) {
63040
64169
  function readTool(host, canEdit) {
63041
64170
  return require_tool.createTool({
63042
64171
  id: "knowledge_read",
63043
- description: `Read a page: its body, its notes, its child pages and the notes on other pages that mention it. Read a scope address (org:acme) to browse that scope. Without \`page\`, lists the scopes this run holds. When a page's notes, or the notes mentioning it, come to more than ${KNOWLEDGE_READ_INLINE_TOKENS.toLocaleString("en-US")} tokens, a whole read leaves them out and counts them in \`more\`; read them on their own with \`notes\` or \`mentionedIn\`. A body returns at most ${maxTokensOf(host).toLocaleString("en-US")} tokens at a time. A body that fits comes whole as \`body\`; a longer one comes as numbered \`lines\` (\`12\u2502text\`) with the \`range\` they cover, and \`more\` says where to read on; a first read of a long page shows every heading with its line number and the first lines under it, so you can pick the part to read. For a long page, ask for its \`outline\` of headings with their line numbers, read one \`section\`, or \`match\` terms to see only the lines that contain them, with \`context\` lines around each. Those part reads return just that part of the body.` + (canEdit ? " To edit part of a long body, pass the `range` a read gave you to knowledge_page." : ""),
64172
+ description: `Read a page: its body, its notes, its child pages and the notes on other pages that mention it. Read a scope address (org:acme) to browse that scope. Without \`page\`, lists every scope this run holds, with its role and whether it can read or write there, including scopes with no page this run can read yet (\`empty\`). When a page's notes, or the notes mentioning it, come to more than ${KNOWLEDGE_READ_INLINE_TOKENS.toLocaleString("en-US")} tokens, a whole read leaves them out and counts them in \`more\`; read them on their own with \`notes\` or \`mentionedIn\`. A body returns at most ${maxTokensOf(host).toLocaleString("en-US")} tokens at a time. A body that fits comes whole as \`body\`; a longer one comes as numbered \`lines\` (\`12\u2502text\`) with the \`range\` they cover, and \`more\` says where to read on; a first read of a long page shows every heading with its line number and the first lines under it, so you can pick the part to read. For a long page, ask for its \`outline\` of headings with their line numbers, read one \`section\`, or \`match\` terms to see only the lines that contain them, with \`context\` lines around each. Those part reads return just that part of the body.` + (canEdit ? " To edit part of a long body, pass the `range` a read gave you to knowledge_page." : ""),
63044
64173
  inputSchema: {
63045
64174
  type: "object",
63046
64175
  properties: {
@@ -63122,10 +64251,13 @@ function readTool(host, canEdit) {
63122
64251
  if (outline && from) throw new Error("knowledge_read: an outline covers the whole body; pass it without from.");
63123
64252
  const run = await start(host, context);
63124
64253
  const limit = limitOf(requested);
63125
- if (!ref) return { scopes: (await run.storage.getScopesByAddress(run.principals)).filter((scope) => knowledgeScopeReadable(scope, run.read)).map((scope) => ({
63126
- address: scope.address,
63127
- name: scope.name,
63128
- ...scope.description ? { description: scope.description } : {}
64254
+ if (!ref) return { scopes: (await heldScopes(run)).map(({ address, page, role, can }) => ({
64255
+ address,
64256
+ name: page?.name ?? address,
64257
+ ...page?.description ? { description: page.description } : {},
64258
+ ...role ? { role } : {},
64259
+ can,
64260
+ ...page ? {} : { empty: true }
63129
64261
  })) };
63130
64262
  const page = await run.pageOrCloseMatches(ref);
63131
64263
  if (outline || section || match || from) {
@@ -63339,12 +64471,13 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
63339
64471
  let scopes = [];
63340
64472
  if (!origin) {
63341
64473
  if (cursor?.startsWith("p")) throw new Error("knowledge_list: a page cursor needs the `from` it came from.");
63342
- const held = await run.storage.getScopesByAddress(run.principals);
63343
- const order = (scope) => run.principals.indexOf(scope.address ?? "");
63344
- scopes = held.filter((scope) => knowledgeScopeReadable(scope, run.read)).sort((a, b) => order(a) - order(b));
64474
+ scopes = (await heldScopes(run)).map((held) => ({
64475
+ ...held.page ? { page: held.page } : {},
64476
+ held
64477
+ }));
63345
64478
  } else {
63346
64479
  originRef = (await pageRefs(run, [origin])).refs.get(origin.id) ?? origin.id;
63347
- if (origin.isScope && !cursor?.startsWith("p")) scopes = await childScopes(origin.id);
64480
+ if (origin.isScope && !cursor?.startsWith("p")) scopes = (await childScopes(origin.id)).map((page) => ({ page }));
63348
64481
  }
63349
64482
  const shownScopes = scopes.slice(scopeOffset, scopeOffset + limit);
63350
64483
  let roots = shownScopes;
@@ -63354,7 +64487,7 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
63354
64487
  const room = limit - shownScopes.length;
63355
64488
  if (room > 0) {
63356
64489
  const pages = await childPages(origin.id, room, pageCursor);
63357
- roots = [...shownScopes, ...pages.pages];
64490
+ roots = [...shownScopes, ...pages.pages.map((page) => ({ page }))];
63358
64491
  if (pages.nextCursor) nextCursor = `p${pages.nextCursor}`;
63359
64492
  } else if ((await run.storage.countChildPages({
63360
64493
  parentIds: [origin.id],
@@ -63368,10 +64501,19 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
63368
64501
  children: 0,
63369
64502
  below: []
63370
64503
  });
63371
- const top = roots.map((page) => nodeOf(page, origin && originRef ? childRef(origin, originRef, page) : page.address ?? page.id, 1));
64504
+ const top = roots.map(({ page, held }) => page ? {
64505
+ ...nodeOf(page, origin && originRef ? childRef(origin, originRef, page) : page.address ?? page.id, 1),
64506
+ ...held ? { held } : {}
64507
+ } : {
64508
+ held,
64509
+ ref: held.address,
64510
+ depth: 1,
64511
+ children: 0,
64512
+ below: []
64513
+ });
63372
64514
  let budget = Math.max(limit - top.length, 0);
63373
64515
  let truncated = false;
63374
- let level = top;
64516
+ let level = top.filter((node) => node.page);
63375
64517
  for (let current = 1; current <= depth && level.length; current++) {
63376
64518
  const parentIds = level.map((node) => node.page.id);
63377
64519
  const scopeParents = level.filter((node) => node.page.isScope).map((node) => node.page.id);
@@ -63395,22 +64537,30 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
63395
64537
  budget -= scopes.length;
63396
64538
  const pages = budget > 0 ? (await childPages(node.page.id, budget)).pages : [];
63397
64539
  budget -= pages.length;
63398
- node.below = [...scopes, ...pages].map((child) => nodeOf(child, childRef(node.page, node.ref, child), current + 1));
63399
- if (node.below.length < node.children) truncated = true;
63400
- nextLevel.push(...node.below);
64540
+ const below = [...scopes, ...pages].map((child) => ({
64541
+ ...nodeOf(child, childRef(node.page, node.ref, child), current + 1),
64542
+ page: child
64543
+ }));
64544
+ node.below = below;
64545
+ if (below.length < node.children) truncated = true;
64546
+ nextLevel.push(...below);
63401
64547
  }
63402
64548
  level = nextLevel;
63403
64549
  }
63404
64550
  const entries = [];
63405
64551
  const flatten = (nodes) => {
63406
64552
  for (const node of nodes) {
64553
+ const { page, held } = node;
63407
64554
  entries.push({
63408
64555
  ref: node.ref,
63409
- name: node.page.name,
63410
- ...descriptions && node.page.description ? { description: node.page.description } : {},
64556
+ name: page?.name ?? node.ref,
64557
+ ...descriptions && page?.description ? { description: page.description } : {},
63411
64558
  depth: node.depth,
63412
64559
  children: node.children,
63413
- ...node.page.isScope ? { scope: true } : {}
64560
+ ...!page || page.isScope ? { scope: true } : {},
64561
+ ...held?.role ? { role: held.role } : {},
64562
+ ...held ? { can: held.can } : {},
64563
+ ...page ? {} : { empty: true }
63414
64564
  });
63415
64565
  flatten(node.below);
63416
64566
  }
@@ -63427,7 +64577,7 @@ function listTool(host) {
63427
64577
  const maxTokens = maxTokensOf(host);
63428
64578
  return require_tool.createTool({
63429
64579
  id: "knowledge_list",
63430
- description: `List the page tree under a starting point: each child with its ref (pass it to knowledge_read or knowledge_list), name and how many children it has. Pass \`descriptions: true\` to include page descriptions too. Without \`from\`, lists the scopes this run can read. Use it to find your way around a scope before searching or reading. One result holds at most \`limit\` entries and about ${maxTokens.toLocaleString("en-US")} tokens of them; when it stops early, \`more\` says how many entries were left out and gives the \`cursor\` to list the rest (pass the same \`from\`).`,
64580
+ description: `List the page tree under a starting point: each child with its ref (pass it to knowledge_read or knowledge_list), name and how many children it has. Pass \`descriptions: true\` to include page descriptions too. Without \`from\`, lists every scope this run holds, with its role and whether it can read or write there, including scopes with no page this run can read yet (\`empty\`). Use it to find your way around a scope before searching or reading. One result holds at most \`limit\` entries and about ${maxTokens.toLocaleString("en-US")} tokens of them; when it stops early, \`more\` says how many entries were left out and gives the \`cursor\` to list the rest (pass the same \`from\`).`,
63431
64581
  inputSchema: {
63432
64582
  type: "object",
63433
64583
  properties: {
@@ -64599,12 +65749,8 @@ var PinnedStateProcessor = class {
64599
65749
  threadId: args.threadId
64600
65750
  }
64601
65751
  };
64602
- let key;
64603
- try {
64604
- key = this.deps.principalsKey(context);
64605
- } catch {
64606
- return;
64607
- }
65752
+ const key = await this.deps.principalsKey(context);
65753
+ if (key === void 0) return void 0;
64608
65754
  if (memo && memo.key === key && stepNumber > memo.atStep) return memo.entries;
64609
65755
  const entries = await this.deps.readPins(context);
64610
65756
  args.requestContext?.set?.(MEMO_KEY, {
@@ -66524,7 +67670,7 @@ var MastraLLMVNext = class extends require_base.MastraBase {
66524
67670
  content: messages
66525
67671
  }];
66526
67672
  }
66527
- stream({ resumeContext, runId, stopWhen, maxSteps, tools = {}, modelSettings, toolChoice = "auto", threadId, resourceId, structuredOutput, options, inputProcessors, llmRequestInputProcessors, outputProcessors, errorProcessors, hasConfiguredErrorProcessors, returnScorerData, providerOptions, messageList, requireToolApproval, toolCallConcurrency, eagerToolExecution, streamPublisher, _internal, onTracingTripwire, onTracingTerminalError, tracingScope = require_stream.createRunScope(), agentId, agentVersionId, resolvedScopes, agentName, toolCallId, requestContext, actor, mcp, methodType, includeRawChunks, experimentalTransform, hideSignals, autoResumeSuspendedTools, maxProcessorRetries, processorStates, activeTools, isTaskComplete, goal, onIterationComplete, workspace, agentRunSpan, agent, ...rest }) {
67673
+ stream({ resumeContext, runId, stopWhen, maxSteps, tools = {}, modelSettings, toolChoice = "auto", threadId, resourceId, structuredOutput, options, inputProcessors, llmRequestInputProcessors, outputProcessors, errorProcessors, hasConfiguredErrorProcessors, returnScorerData, providerOptions, messageList, requireToolApproval, toolCallConcurrency, eagerToolExecution, streamPublisher, _internal, onTracingTripwire, onTracingTerminalError, tracingScope = require_stream.createRunScope(), agentId, agentVersionId, resolvedScopes, agentName, toolCallId, requestContext, actor, mcp, methodType, includeRawChunks, experimentalTransform, hideSignals, autoResumeSuspendedTools, maxProcessorRetries, processorStates, activeTools, isTaskComplete, goal, onIterationComplete, workspace, agentRunSpan, agent, resultType, ...rest }) {
66528
67674
  const observabilityContext = require_observability.resolveObservabilityContext(rest);
66529
67675
  let stopWhenToUse;
66530
67676
  if (maxSteps && typeof maxSteps === "number") {
@@ -66550,7 +67696,8 @@ var MastraLLMVNext = class extends require_base.MastraBase {
66550
67696
  provider: firstModel.provider,
66551
67697
  streaming: true,
66552
67698
  parameters: modelSettings,
66553
- ...toolDefinitions ? { tools: toolDefinitions } : {}
67699
+ ...toolDefinitions ? { tools: toolDefinitions } : {},
67700
+ ...resultType ? { resultType } : {}
66554
67701
  },
66555
67702
  metadata: {
66556
67703
  runId,
@@ -71359,57 +72506,6 @@ function armRunDeadline(controller, deadline) {
71359
72506
  timer.unref?.();
71360
72507
  return timer;
71361
72508
  }
71362
- // src/agent/durable/constants.ts
71363
- const DURABLE_STOP_WHEN_ERROR_ID = "DURABLE_AGENT_STOP_WHEN_FAILED";
71364
- const REJECT_STREAM_ERROR = Symbol("mastra.durable.rejectStreamError");
71365
- function markErrorForStreamRejection(error) {
71366
- error[REJECT_STREAM_ERROR] = true;
71367
- return error;
71368
- }
71369
- function shouldRejectStream(error) {
71370
- return error[REJECT_STREAM_ERROR] === true;
71371
- }
71372
- /**
71373
- * Default values for durable agent execution
71374
- */
71375
- const DurableAgentDefaults = {
71376
- /** Default maximum number of agentic loop iterations */
71377
- MAX_STEPS: 5,
71378
- /**
71379
- * Default tool call concurrency.
71380
- * Applied by `resolveDurableToolCallConcurrency` when a run doesn't
71381
- * configure `toolCallConcurrency`. Approval / suspend-capable tool sets
71382
- * always run sequentially (concurrency: 1) regardless of this value.
71383
- */
71384
- TOOL_CALL_CONCURRENCY: 10
71385
- };
71386
- /**
71387
- * Step IDs used in the durable agentic workflow
71388
- */
71389
- const DurableStepIds = {
71390
- /** LLM execution step */
71391
- LLM_EXECUTION: "durable-llm-execution",
71392
- /** Tool call step */
71393
- TOOL_CALL: "durable-tool-call",
71394
- /** LLM mapping step (combines results) */
71395
- LLM_MAPPING: "durable-llm-mapping",
71396
- /** Agentic execution workflow (one iteration) */
71397
- AGENTIC_EXECUTION: "durable-agentic-execution",
71398
- /** Full agentic loop workflow */
71399
- AGENTIC_LOOP: "durable-agentic-loop",
71400
- /** Scorer execution step */
71401
- SCORER_EXECUTION: "durable-scorer-execution",
71402
- /** isTaskComplete evaluation step */
71403
- IS_TASK_COMPLETE: "durable-is-task-complete"
71404
- };
71405
- /** The loop's last step, which ends the run's spans when it succeeds. */
71406
- const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
71407
- const RECOVER_ALREADY_IN_PROGRESS_ERROR_ID = "DURABLE_AGENT_RECOVER_ALREADY_IN_PROGRESS";
71408
- const RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID = "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND";
71409
- const RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID = "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE";
71410
- const RECOVER_RUN_SUSPENDED_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_SUSPENDED";
71411
- const RECOVER_RUN_NOT_ACTIVE_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_NOT_ACTIVE";
71412
- const RECOVER_SHUTDOWN_ERROR_ID = "DURABLE_AGENT_RECOVER_SHUTDOWN";
71413
72509
  // src/agent/durable/durable-stream-until-idle.ts
71414
72510
  /**
71415
72511
  * Run `DurableAgent.streamUntilIdle` (or `DurableAgent.stream({ untilIdle })`).
@@ -72953,8 +74049,9 @@ function releaseRunMessageRefs(runId) {
72953
74049
  /**
72954
74050
  * A `SaveQueueManager` `onSaved` callback that records the rows a run saved,
72955
74051
  * so its persisted transcript references them instead of repeating them. Only
72956
- * runs that store refs hold an entry (the transcript store creates it), so saves
72957
- * for other runs, or landing after the run released its entry, are not kept.
74052
+ * runs that store refs hold an entry (created before the run saves its input,
74053
+ * else by the transcript store), so saves for other runs, or landing after the
74054
+ * run released its entry, are not kept.
72958
74055
  */
72959
74056
  function recordRunSavedMessages(runId) {
72960
74057
  return (rows) => {
@@ -72976,6 +74073,15 @@ function recordRunSavedMessages(runId) {
72976
74073
  };
72977
74074
  }
72978
74075
  // src/agent/durable/utils/resolve-runtime.ts
74076
+ async function restoreWorkerToolsets(mastra, context, names) {
74077
+ const controller = context.get("controller");
74078
+ if (!isRestoredWorkerControllerContext(controller) || !names?.length) return;
74079
+ const toolsets = await mastra.getAgentControllerById(controller.controllerId)?.__restoreWorkerToolsets(context);
74080
+ if (!toolsets) return;
74081
+ const allowed = new Set(names);
74082
+ for (const [key, tools] of Object.entries(toolsets)) if (tools) toolsets[key] = Object.fromEntries(Object.entries(tools).filter(([name]) => allowed.has(name)));
74083
+ return toolsets;
74084
+ }
72979
74085
  /**
72980
74086
  * Build a SaveQueueManager for a run's memory, or `undefined` when no memory
72981
74087
  * is configured. Shared by `resolveRuntimeDependencies` and
@@ -73138,6 +74244,7 @@ async function resolveRuntimeDependencies(options) {
73138
74244
  backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
73139
74245
  tools = await agent.getToolsForExecution({
73140
74246
  runId,
74247
+ toolsets: await restoreWorkerToolsets(mastra, resolveRequestContext, input.options?.toolsetToolNames),
73141
74248
  threadId: input.state.threadId,
73142
74249
  resourceId: input.state.resourceId,
73143
74250
  requestContext: resolveRequestContext,
@@ -73259,6 +74366,7 @@ async function rebuildRunToolsFromMastra(options) {
73259
74366
  const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
73260
74367
  const tools = await agent.getToolsForExecution({
73261
74368
  runId,
74369
+ toolsets: await restoreWorkerToolsets(mastra, resolveRequestContext, execOptions?.toolsetToolNames),
73262
74370
  threadId: state.threadId,
73263
74371
  resourceId: state.resourceId,
73264
74372
  requestContext: resolveRequestContext,
@@ -73705,7 +74813,7 @@ function runTranscriptRefs(params) {
73705
74813
  async function runMemory(params, run) {
73706
74814
  const entry = run.runId ? getRunRegistryEntry(run.runId, params.mastra) : void 0;
73707
74815
  if (entry?.memory || !params.mastra || !run.agentId) return entry?.memory;
73708
- return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: restoreRequestContext(run.requestContextEntries, params.requestContext, getLiveRunRequestContext(entry)) });
74816
+ return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: restoreRequestContext(run.requestContextEntries, params.requestContext, getLiveRunRequestContext(entry, run.runId, params.requestContext)) });
73709
74817
  }
73710
74818
  /** The most recent transcript in a snapshot: workflow state, else the last step output carrying one. */
73711
74819
  function latestMessageListState(snapshot) {
@@ -73728,7 +74836,11 @@ function mergeRequestContextForFinalization(entries, fallback, liveRunContext) {
73728
74836
  if (liveRunContext) return liveRunContext;
73729
74837
  if (!entries) return fallback ?? new require_request_context.RequestContext();
73730
74838
  const restored = new require_request_context.RequestContext(fallback?.entries());
73731
- for (const [key, value] of Object.entries(require_request_context.withoutLiveRequestKeys(entries))) restored.set(key, value);
74839
+ const controller = fallback?.get("controller");
74840
+ for (const [key, value] of Object.entries(require_request_context.withoutLiveRequestKeys(entries))) {
74841
+ if (key === "controller" && isRestoredWorkerControllerContext(controller)) continue;
74842
+ restored.set(key, value);
74843
+ }
73732
74844
  restoreRunAgentScopes(restored);
73733
74845
  return restored;
73734
74846
  }
@@ -73769,6 +74881,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73769
74881
  ...initData,
73770
74882
  messageListState
73771
74883
  },
74884
+ requestContext,
73772
74885
  logger: effectiveLogger
73773
74886
  });
73774
74887
  rebuiltSaveQueueManager = resolved.saveQueueManager;
@@ -73781,7 +74894,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73781
74894
  error
73782
74895
  });
73783
74896
  }
73784
- const effectiveRequestContext = mergeRequestContextForFinalization(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry));
74897
+ const effectiveRequestContext = mergeRequestContextForFinalization(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext));
73785
74898
  if (!effectiveRequestContext.has("MastraMemory") && durableState?.threadId) effectiveRequestContext.set("MastraMemory", {
73786
74899
  thread: { id: durableState.threadId },
73787
74900
  resourceId: durableState.resourceId,
@@ -74078,9 +75191,9 @@ function deadlineMessageListState(entry, fallback) {
74078
75191
  * durable run. The run never reaches its finish step, so this runs over what the deadline saves
74079
75192
  * (see `deadlineMessageListState`), as the default loop's deadline pass does.
74080
75193
  */
74081
- async function runDurableDeadlineOutputPass({ runId, initData, messageListState, cutOffText, entry, mastra, tracingContext, logger }) {
75194
+ async function runDurableDeadlineOutputPass({ runId, initData, messageListState, cutOffText, entry, executionId, mastra, tracingContext, logger }) {
74082
75195
  const durableState = initData.state;
74083
- const requestContext = mergeRequestContextForFinalization(initData.requestContextEntries, void 0, getLiveRunRequestContext(entry));
75196
+ const requestContext = mergeRequestContextForFinalization(initData.requestContextEntries, void 0, getLiveRunRequestContext(entry, runId, void 0, executionId));
74084
75197
  if (!requestContext.has("MastraMemory") && durableState?.threadId) requestContext.set("MastraMemory", {
74085
75198
  thread: { id: durableState.threadId },
74086
75199
  resourceId: durableState.resourceId,
@@ -75773,6 +76886,15 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
75773
76886
  });
75774
76887
  break;
75775
76888
  }
76889
+ case "custom": {
76890
+ const p = chunk.payload;
76891
+ parts.push({
76892
+ type: "custom",
76893
+ kind: p.kind,
76894
+ ...p.providerMetadata ? { providerMetadata: p.providerMetadata } : {}
76895
+ });
76896
+ break;
76897
+ }
75776
76898
  case "tool-call": {
75777
76899
  const p = chunk.payload;
75778
76900
  const toolDef = tools?.[p.toolName] || findProviderToolByName(tools, p.toolName);
@@ -76098,7 +77220,7 @@ function createDurableLLMExecutionStep(_options) {
76098
77220
  const typedInput = inputData;
76099
77221
  const { agentId, messageId, options: execOptions } = typedInput;
76100
77222
  const runId = typedInput.runId;
76101
- const requestContext = getLiveRunRequestContext(getRunRegistryEntry(runId, mastra)) ?? params.requestContext;
77223
+ const requestContext = getLiveRunRequestContext(getRunRegistryEntry(runId, mastra), runId, params.requestContext) ?? params.requestContext;
76102
77224
  const logger = mastra?.getLogger?.();
76103
77225
  if (pubsub) await emitIterationStartEvent(pubsub, runId, inputData.stepIndex ?? 0);
76104
77226
  const { messageList, tools, model: resolvedModel, modelList: resolvedModelList, inputProcessors: resolvedInputProcessors, llmRequestInputProcessors: resolvedLlmRequestInputProcessors, outputProcessors: resolvedOutputProcessors } = await resolveRuntimeDependencies({
@@ -78995,6 +80117,15 @@ async function flushMessagesBeforeSuspension({ saveQueueManager, messageList, me
78995
80117
  return false;
78996
80118
  }
78997
80119
  }
80120
+ /**
80121
+ * Context for output processors on a tool result. A live context is reused only for the execution that
80122
+ * owns it. A context rebuilt from the run snapshot is returned as before; whether a rebuilt entry can
80123
+ * outlive a resume by another caller is tracked in COR-1660.
80124
+ */
80125
+ function toolResultRequestContext(registryEntry, runId, stepRequestContext) {
80126
+ if (registryEntry?.requestContextRebuilt) return registryEntry.requestContext;
80127
+ return getLiveRunRequestContext(registryEntry, runId, stepRequestContext) ?? stepRequestContext;
80128
+ }
78998
80129
  var DurableOutputProcessorError = class extends Error {
78999
80130
  constructor(error) {
79000
80131
  super(error instanceof Error ? error.message : String(error), { cause: error });
@@ -79016,7 +80147,7 @@ var DurableChunkPublishError = class extends Error {
79016
80147
  * Thin glue over the shared per-chunk pipeline core; mirrors the regular
79017
80148
  * agent's `processAndEnqueueChunk` in llm-mapping-step.ts.
79018
80149
  */
79019
- async function processChunkThroughOutputProcessors(chunk, registryEntry, pubsub, runId, agentName, logger, messageList, observabilityContext, collectDataPart, onEmit) {
80150
+ async function processChunkThroughOutputProcessors(chunk, registryEntry, stepRequestContext, pubsub, runId, agentName, logger, messageList, observabilityContext, collectDataPart, onEmit) {
79020
80151
  const runner = registryEntry?.outputProcessors?.length && registryEntry.processorStates ? new require_stream.ProcessorRunner({
79021
80152
  inputProcessors: [],
79022
80153
  outputProcessors: registryEntry.outputProcessors,
@@ -79029,7 +80160,7 @@ async function processChunkThroughOutputProcessors(chunk, registryEntry, pubsub,
79029
80160
  runner,
79030
80161
  processorStates: registryEntry?.processorStates,
79031
80162
  observabilityContext,
79032
- requestContext: registryEntry?.requestContext,
80163
+ requestContext: toolResultRequestContext(registryEntry, runId, stepRequestContext),
79033
80164
  messageList,
79034
80165
  streamWriter: pubsub ? { custom: async (data, writerOptions) => {
79035
80166
  if (data.type.startsWith("data-") && !data.transient) collectDataPart?.({
@@ -79303,6 +80434,12 @@ function createDurableToolCallStep() {
79303
80434
  error
79304
80435
  };
79305
80436
  }
80437
+ if (typeof args === "object" && args !== null) args = require_background_tasks.sanitizeToolArguments({
80438
+ args,
80439
+ toolName,
80440
+ toolConfig: tool?.backgroundConfig,
80441
+ agentConfig: registryEntry?.backgroundTasksConfig
80442
+ });
79306
80443
  const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;
79307
80444
  const memory = registryEntry?.memory ?? rebuiltMemory;
79308
80445
  const workspace = registryEntry?.workspace ?? rebuiltWorkspace;
@@ -79380,7 +80517,7 @@ function createDurableToolCallStep() {
79380
80517
  }).add(invocation, "memory");
79381
80518
  }
79382
80519
  if (saveQueueManager && messagesToFlush && memory && state?.threadId && state.resourceId && !state.memoryConfig?.readOnly) {
79383
- const authorizationRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext);
80520
+ const authorizationRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext));
79384
80521
  const authorizeMemory = (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
79385
80522
  mastra,
79386
80523
  user: authorizationRequestContext.get("user"),
@@ -79424,10 +80561,10 @@ function createDurableToolCallStep() {
79424
80561
  };
79425
80562
  const registryRequireToolApproval = registryEntry?.requireToolApproval;
79426
80563
  const effectiveRequireToolApproval = registryRequireToolApproval !== void 0 ? registryRequireToolApproval : agentOptions.requireToolApproval;
79427
- const approvalRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext);
80564
+ const approvalRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext));
79428
80565
  const requiresApproval = await toolRequiresApproval(tool, effectiveRequireToolApproval, args, {
79429
80566
  toolName,
79430
- requestContext: Object.fromEntries([...approvalRequestContext.entries()].filter(([key]) => !INTERNAL_APPROVAL_KEYS.has(key))),
80567
+ requestContext: Object.fromEntries([...approvalRequestContext.entries()].filter(([key]) => key !== "__mastra_durableContextSegment" && !INTERNAL_APPROVAL_KEYS.has(key))),
79431
80568
  workspace
79432
80569
  });
79433
80570
  const addToolMetadata = (opts) => {
@@ -79607,7 +80744,7 @@ function createDurableToolCallStep() {
79607
80744
  toolTransform: tool?.transform,
79608
80745
  tools: toolsForTransform,
79609
80746
  logger
79610
- }), registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
80747
+ }), registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
79611
80748
  } catch (emitError) {
79612
80749
  if (emitError instanceof DurableOutputProcessorError) throw emitError;
79613
80750
  logger?.warn?.(`[DurableAgent] Failed to emit tool-result chunk for ${toolName}: ${emitError}`);
@@ -79709,7 +80846,7 @@ function createDurableToolCallStep() {
79709
80846
  policy: toolPayloadTransform,
79710
80847
  tools: toolsForTransform,
79711
80848
  logger
79712
- }), registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
80849
+ }), registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
79713
80850
  } catch (emitError) {
79714
80851
  if (emitError instanceof DurableOutputProcessorError) throw emitError;
79715
80852
  logger?.warn?.(`[DurableAgent] Failed to emit tool-output-denied chunk for ${toolName}: ${emitError}`);
@@ -80149,7 +81286,7 @@ function createDurableToolCallStep() {
80149
81286
  toolCallId: params.toolCallId,
80150
81287
  toolName: params.toolName,
80151
81288
  status: params.status === "failed" ? "failed" : "completed",
80152
- requestContext: restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext)
81289
+ requestContext: restoreRequestContext(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext))
80153
81290
  });
80154
81291
  } catch (error) {
80155
81292
  resolveReconciliation({ error });
@@ -80448,7 +81585,7 @@ function createDurableToolCallStep() {
80448
81585
  result,
80449
81586
  modelOutput: require_stream.readModelOutput(providerMetadata),
80450
81587
  ...processorObservabilityContext ?? {},
80451
- requestContext: registryEntry.requestContext,
81588
+ requestContext: toolResultRequestContext(registryEntry, runId, requestContext),
80452
81589
  retryCount: 0,
80453
81590
  writer: pubsub ? { custom: async (data, writerOptions) => {
80454
81591
  if (data.type.startsWith("data-") && !data.transient) collectProcessorDataPart({
@@ -80553,7 +81690,7 @@ function createDurableToolCallStep() {
80553
81690
  logger
80554
81691
  });
80555
81692
  transformMetadata = resultChunk.metadata;
80556
- await processChunkThroughOutputProcessors(resultChunk, registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart, (chunk) => {
81693
+ await processChunkThroughOutputProcessors(resultChunk, registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart, (chunk) => {
80557
81694
  if (chunk.type === "tool-result" && chunk.payload.toolCallId === toolCallId) resultEmitted = true;
80558
81695
  });
80559
81696
  } catch (emitError) {
@@ -80625,7 +81762,7 @@ function createDurableToolCallStep() {
80625
81762
  logger
80626
81763
  });
80627
81764
  errorTransformMetadata = errorChunk.metadata;
80628
- await processChunkThroughOutputProcessors(errorChunk, registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
81765
+ await processChunkThroughOutputProcessors(errorChunk, registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
80629
81766
  } catch (emitError) {
80630
81767
  ownership?.throwIfLost();
80631
81768
  if (emitError instanceof DurableOutputProcessorError) throw emitError;
@@ -81213,7 +82350,7 @@ function createDurableIsTaskCompleteStep(defaultMaxSteps = DurableAgentDefaults.
81213
82350
  const restored = await restoreCompletionPolicy({
81214
82351
  agent,
81215
82352
  persisted: initData.options.isTaskComplete,
81216
- requestContext: restoreRequestContext(initData.requestContextEntries, registryEntry?.requestContext, getLiveRunRequestContext(registryEntry)),
82353
+ requestContext: restoreRequestContext(initData.requestContextEntries, params.requestContext, getLiveRunRequestContext(registryEntry, state.runId, params.requestContext)),
81217
82354
  runId: state.runId,
81218
82355
  logger: mastra?.getLogger?.()
81219
82356
  });
@@ -81249,7 +82386,7 @@ function createDurableIsTaskCompleteStep(defaultMaxSteps = DurableAgentDefaults.
81249
82386
  agentName: initData.agentName,
81250
82387
  threadId: initData.state?.threadId,
81251
82388
  resourceId: initData.state?.resourceId,
81252
- customContext: restoreCustomContext(initData.requestContextEntries, registryEntry?.requestContext ?? params.requestContext),
82389
+ customContext: restoreCustomContext(initData.requestContextEntries, getLiveRunRequestContext(registryEntry, state.runId, params.requestContext) ?? params.requestContext),
81253
82390
  generateId: () => mastra?.generateId?.(),
81254
82391
  emitChunk: (chunk) => {
81255
82392
  if (!pubsub) return;
@@ -81297,7 +82434,7 @@ function createDurableGoalStep() {
81297
82434
  const registryEntry = getRunRegistryEntry(state.runId, mastra);
81298
82435
  let goalConfig = registryEntry?.goal;
81299
82436
  if (!goalConfig && initData.agentId) goalConfig = mastra?.getAgentById?.(initData.agentId)?.__getGoalConfig?.();
81300
- const liveRunContext = getLiveRunRequestContext(registryEntry);
82437
+ const liveRunContext = getLiveRunRequestContext(registryEntry, state.runId, params.requestContext);
81301
82438
  const currentRequestContext = liveRunContext ?? params.requestContext;
81302
82439
  const requestContext = restoreRequestContext(initData.requestContextEntries, params.requestContext, liveRunContext);
81303
82440
  const customContext = restoreCustomContext(initData.requestContextEntries, currentRequestContext);
@@ -83098,15 +84235,21 @@ async function persistDurableRunInput(runId, workflowInput, mastra, beforeSave)
83098
84235
  await beforeSave();
83099
84236
  }
83100
84237
  const inputCopy = entry.messageList.clone();
83101
- await entry.saveQueueManager.flushMessages(inputCopy, state.threadId, state.memoryConfig, {
83102
- throwOnError: true,
83103
- beforePersist: () => assertExecutionOwned({
83104
- runId,
83105
- agentId: workflowInput.agentId,
83106
- mastra,
83107
- requestContext
83108
- })
83109
- });
84238
+ if (state.fixedMemory) getRunMessageRefs(runId);
84239
+ try {
84240
+ await entry.saveQueueManager.flushMessages(inputCopy, state.threadId, state.memoryConfig, {
84241
+ throwOnError: true,
84242
+ beforePersist: () => assertExecutionOwned({
84243
+ runId,
84244
+ agentId: workflowInput.agentId,
84245
+ mastra,
84246
+ requestContext
84247
+ })
84248
+ });
84249
+ } catch (error) {
84250
+ if (state.fixedMemory) releaseRunMessageRefs(runId);
84251
+ throw error;
84252
+ }
83110
84253
  const embedded = entry.messageList.getEmbeddedMessages();
83111
84254
  for (const [messageId, textHash] of inputCopy.getEmbeddedMessages()) embedded.set(messageId, textHash);
83112
84255
  }
@@ -83433,7 +84576,7 @@ async function prepareForDurableExecution(options) {
83433
84576
  });
83434
84577
  let tripwireData;
83435
84578
  if (inputProcessors.length > 0) try {
83436
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-DH7Qgz8l.cjs")).then((n) => n.runner_exports);
84579
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-D_7tMaJe.cjs")).then((n) => n.runner_exports);
83437
84580
  await new ProcessorRunner({
83438
84581
  inputProcessors,
83439
84582
  outputProcessors,
@@ -86193,6 +87336,11 @@ var Agent = class Agent extends require_base.MastraBase {
86193
87336
  const processors = [];
86194
87337
  const instructions = knowledge.getInstructions();
86195
87338
  if (instructions && !configuredIds.has("knowledge-instructions-processor")) processors.push(new KnowledgeInstructionsProcessor(instructions));
87339
+ const toolGroups = knowledge.__toolGroups;
87340
+ if (hasMemory && (toolGroups.read || toolGroups.write) && !hasConfiguredProcessor(configuredProcessors, (processor) => processor.id === "knowledge-scopes")) processors.push(new HeldScopesStateProcessor({
87341
+ principalsKey: (context) => knowledge.__principalsKey(context),
87342
+ readHeldScopes: (context) => knowledge.__heldScopes(context)
87343
+ }));
86196
87344
  if (knowledge.pinnedContextEnabled && !configuredIds.has("knowledge")) {
86197
87345
  if (!hasMemory) {
86198
87346
  if (!this.#warnedPinsWithoutMemory) {
@@ -86201,9 +87349,26 @@ var Agent = class Agent extends require_base.MastraBase {
86201
87349
  }
86202
87350
  return processors;
86203
87351
  }
87352
+ const contexts = /* @__PURE__ */ new WeakMap();
87353
+ const pinContext = (context) => {
87354
+ let resolved = contexts.get(context);
87355
+ if (!resolved) {
87356
+ const requestContext = context.requestContext instanceof require_request_context.RequestContext ? context.requestContext : void 0;
87357
+ resolved = this.resolveKnowledgePersona(knowledge, requestContext).then((persona) => ({
87358
+ ...context,
87359
+ agent: {
87360
+ ...context.agent,
87361
+ agentId: this.id,
87362
+ persona
87363
+ }
87364
+ }));
87365
+ contexts.set(context, resolved);
87366
+ }
87367
+ return resolved;
87368
+ };
86204
87369
  processors.push(new PinnedStateProcessor({
86205
- principalsKey: (context) => knowledge.__principalsKey(context),
86206
- readPins: (context) => knowledge.__deliveredPins(context),
87370
+ principalsKey: async (context) => knowledge.__principalsKey(await pinContext(context)),
87371
+ readPins: async (context) => knowledge.__deliveredPins(await pinContext(context)),
86207
87372
  ...knowledge.__toolGroups
86208
87373
  }));
86209
87374
  }
@@ -87160,7 +88325,8 @@ var Agent = class Agent extends require_base.MastraBase {
87160
88325
  }
87161
88326
  /**
87162
88327
  * Gets the metadata for this agent, resolving function-based metadata if necessary.
87163
- * Metadata is a classification bag for clients and is never read by the agent runtime.
88328
+ * Metadata is a classification bag for clients. The agent runtime reads only `metadata.persona`, to mint
88329
+ * Knowledge persona scopes; it reads nothing else in metadata.
87164
88330
  *
87165
88331
  * @example
87166
88332
  * ```typescript
@@ -87898,11 +89064,13 @@ var Agent = class Agent extends require_base.MastraBase {
87898
89064
  ...observabilityContext,
87899
89065
  messageList,
87900
89066
  agentId: this.id,
87901
- agentName: this.name
89067
+ agentName: this.name,
89068
+ resultType: "title_generation"
87902
89069
  }).text;
87903
89070
  } else text = (await llm.__text({
87904
89071
  requestContext,
87905
89072
  ...observabilityContext,
89073
+ resultType: "title_generation",
87906
89074
  messages: [{
87907
89075
  role: "system",
87908
89076
  content: systemInstructions
@@ -88049,10 +89217,34 @@ var Agent = class Agent extends require_base.MastraBase {
88049
89217
  backgroundConfig: tool.background,
88050
89218
  agentBackgroundConfig: this.#backgroundTasks
88051
89219
  };
88052
- converted[toolName] = require_utils$1.makeCoreTool(tool, options, void 0, autoResumeSuspendedTools, backgroundTaskEnabled);
89220
+ const execute = tool.execute;
89221
+ const agentTool = execute ? {
89222
+ ...tool,
89223
+ execute: async (input, context) => {
89224
+ const persona = await this.resolveKnowledgePersona(knowledge, requestContext);
89225
+ const runContext = {
89226
+ ...context,
89227
+ agent: context?.agent ? {
89228
+ ...context.agent,
89229
+ agentId: this.id,
89230
+ persona
89231
+ } : void 0
89232
+ };
89233
+ return execute(input, runContext);
89234
+ }
89235
+ } : tool;
89236
+ converted[toolName] = require_utils$1.makeCoreTool(agentTool, options, void 0, autoResumeSuspendedTools, backgroundTaskEnabled);
88053
89237
  }
88054
89238
  return converted;
88055
89239
  }
89240
+ async resolveKnowledgePersona(knowledge, requestContext) {
89241
+ if (!await knowledge.__needsAgentPersona()) return void 0;
89242
+ try {
89243
+ return (await this.getMetadata({ requestContext }))?.persona;
89244
+ } catch {
89245
+ return;
89246
+ }
89247
+ }
88056
89248
  /**
88057
89249
  * Lists workspace tools if a workspace is configured.
88058
89250
  * @internal
@@ -93536,6 +94728,7 @@ var Agent = class Agent extends require_base.MastraBase {
93536
94728
  initData: runInput,
93537
94729
  ...deadlineMessageListState(runInputEntry, runInput.messageListState),
93538
94730
  entry: runInputEntry,
94731
+ executionId: fence.executionId,
93539
94732
  mastra: this.#mastra,
93540
94733
  tracingContext: deadlineSpan ? { currentSpan: deadlineSpan } : void 0,
93541
94734
  logger: this.logger
@@ -94069,7 +95262,7 @@ var Agent = class Agent extends require_base.MastraBase {
94069
95262
  const threadId = workflowInput.state?.threadId ?? memoryInfo?.threadId;
94070
95263
  const resourceId = workflowInput.state?.resourceId ?? memoryInfo?.resourceId;
94071
95264
  if (sharedExecution && pubsub && entry?.requestContext && executionFence && threadId) {
94072
- await agentThreadStreamRuntime.claimDurableThreadLease(pubsub, runId, threadId, resourceId, executionFence.generation, executionFence.executionId);
95265
+ await agentThreadStreamRuntime.claimDurableThreadLease(pubsub, runId, threadId, resourceId, executionFence.generation, executionFence.executionId, true);
94073
95266
  try {
94074
95267
  await executionFence.verify();
94075
95268
  } catch (error) {
@@ -94343,7 +95536,13 @@ var Agent = class Agent extends require_base.MastraBase {
94343
95536
  messageListFollowsStream: () => !this.executionEngine.executesStepsLocally
94344
95537
  });
94345
95538
  streamCleanup = createdStreamCleanup;
94346
- const workflowExecution = executionFence.run(() => ready.then(async () => {
95539
+ const threadRegistration = agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
95540
+ continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
95541
+ generation: executionFence.generation,
95542
+ ownershipLost: () => executionFence.isLost(),
95543
+ stepOwner: () => getRunRegistryEntry(runId, this.#mastra)
95544
+ });
95545
+ const workflowExecution = executionFence.run(() => Promise.all([ready, threadRegistration]).then(async () => {
94347
95546
  if (await this.redeliverDeadlineError(registryEntry, executionFence)) return;
94348
95547
  await emitChunkEvent(fencePubSub(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, executionFence), runId, {
94349
95548
  type: "start",
@@ -94384,12 +95583,7 @@ var Agent = class Agent extends require_base.MastraBase {
94384
95583
  }).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })));
94385
95584
  const trackedEntry = getRunRegistryEntry(runId, this.#mastra);
94386
95585
  if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
94387
- await agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
94388
- continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
94389
- generation: executionFence.generation,
94390
- ownershipLost: () => executionFence.isLost(),
94391
- stepOwner: () => getRunRegistryEntry(runId, this.#mastra)
94392
- });
95586
+ await threadRegistration;
94393
95587
  const cleanup = () => {
94394
95588
  if (methodType === "generate" || runCleanup.done || output.status !== "running") return performCleanup();
94395
95589
  Promise.race([workflowExecution, executionFence.whenSettled]).then(() => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush()).then(() => waitForEventDelivery()).catch(() => {}).finally(performCleanup);
@@ -95791,6 +96985,29 @@ var Agent = class Agent extends require_base.MastraBase {
95791
96985
  };
95792
96986
  }
95793
96987
  };
96988
+ // src/agent/merge-persona.ts
96989
+ function merge(metadata, persona) {
96990
+ const code = metadata?.persona;
96991
+ const base = code && typeof code === "object" && !Array.isArray(code) ? code : {};
96992
+ const set = Object.fromEntries(Object.entries(persona).filter(([, value]) => value !== void 0));
96993
+ return {
96994
+ ...metadata,
96995
+ persona: {
96996
+ ...base,
96997
+ ...set
96998
+ }
96999
+ };
97000
+ }
97001
+ /**
97002
+ * Overrides an Agent's `metadata.persona` field by field: a field `persona` sets wins, a field it leaves
97003
+ * unset keeps the code's value, and keys outside `persona` stay as they are. Function-form metadata is
97004
+ * wrapped so the override applies to whatever it resolves to.
97005
+ * @experimental
97006
+ */
97007
+ function mergeAgentPersona(metadata, persona) {
97008
+ if (typeof metadata !== "function") return merge(metadata, persona);
97009
+ return async (context) => merge(await metadata(context), persona);
97010
+ }
95794
97011
  // ../_internal-core/dist/fs-routing/index.js
95795
97012
  /**
95796
97013
  * Maximum nesting depth for declared subagents. A top-level agent is depth 0;
@@ -102457,6 +103674,12 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
102457
103674
  args = argsFromInput;
102458
103675
  resumeDataFromArgs = resumeDataFromInput;
102459
103676
  }
103677
+ if (typeof args === "object" && args !== null) args = require_background_tasks.sanitizeToolArguments({
103678
+ args,
103679
+ toolName: inputData.toolName,
103680
+ toolConfig: tool?.backgroundConfig,
103681
+ agentConfig: readScoped(scopeCtx, AGENT_BACKGROUND_CONFIG_KEY, "agentBackgroundConfig")
103682
+ });
102460
103683
  const resumeData = resumeDataFromArgs ?? workflowResumeData;
102461
103684
  const isResumeToolCall = resumeDataFromArgs != null;
102462
103685
  const approvalVerdicts = readScoped(scopeCtx, TOOL_APPROVAL_VERDICTS_KEY, "toolApprovalVerdicts");
@@ -104246,7 +105469,7 @@ var AgentThreadStreamRuntime = class {
104246
105469
  return state.leaseOwners.get(runId) ?? threadLeaseOwner(runId, state.threadRunsById.get(runId)?.generation);
104247
105470
  }
104248
105471
  /** @internal Qualify a shared thread lease before dispatching this execution. */
104249
- async claimDurableThreadLease(pubsub, runId, threadId, resourceId, generation, executionId) {
105472
+ async claimDurableThreadLease(pubsub, runId, threadId, resourceId, generation, executionId, workerFenced = false) {
104250
105473
  const key = this.#threadKey(resourceId, threadId);
104251
105474
  const owner = threadLeaseOwner(runId, generation, executionId);
104252
105475
  let lease = await this.#acquireThreadLease(pubsub, key, runId, owner);
@@ -104264,7 +105487,7 @@ var AgentThreadStreamRuntime = class {
104264
105487
  if (!lease.acquired) throw new AgentThreadLeaseConflictError(runId, lease.owner ?? "another owner");
104265
105488
  if (this.#getState(pubsub).leaseRenewalTimers.has(runId)) {
104266
105489
  this.#stopLeaseRenewal(pubsub, runId);
104267
- this.#startLeaseRenewal(pubsub, key, runId, owner);
105490
+ this.#startLeaseRenewal(pubsub, key, runId, owner, workerFenced);
104268
105491
  }
104269
105492
  }
104270
105493
  /** @internal Renew only the captured execution's thread lease; never acquire or transfer it. */
@@ -104280,6 +105503,11 @@ var AgentThreadStreamRuntime = class {
104280
105503
  const { acquired } = await this.#getLeaseProvider(pubsub).acquireLease(this.#threadKey(resourceId, threadId), threadLeaseOwner(runId, generation, executionId), AGENT_THREAD_LEASE_TTL_MS);
104281
105504
  return acquired;
104282
105505
  }
105506
+ /** @internal Missing ownership is not evidence that another run took the thread. */
105507
+ async isDurableThreadLeaseHeldByAnotherRun(pubsub, runId, threadId, resourceId) {
105508
+ const owner = await this.#getLeaseProvider(pubsub).getLeaseOwner(this.#threadKey(resourceId, threadId));
105509
+ return owner !== void 0 && threadLeaseRunId(owner) !== runId;
105510
+ }
104283
105511
  /** @internal Whether `error` from the thread lease backend means it is refusing every client, not just this one. */
104284
105512
  isThreadLeaseBackendUnavailableToAll(pubsub, error) {
104285
105513
  return this.#getLeaseProvider(pubsub).isUnavailableToAll?.(error) === true;
@@ -104493,7 +105721,7 @@ var AgentThreadStreamRuntime = class {
104493
105721
  * that point, so once it passes a successor may own the thread and the
104494
105722
  * run is aborted, even if the backend never answers.
104495
105723
  */
104496
- #startLeaseRenewal(pubsub, key, runId, owner = this.#threadLeaseOwner(pubsub, runId)) {
105724
+ #startLeaseRenewal(pubsub, key, runId, owner = this.#threadLeaseOwner(pubsub, runId), workerFenced = false, confirmedSentAt = Date.now()) {
104497
105725
  const state = this.#getState(pubsub);
104498
105726
  if (state.leaseRenewalTimers.has(runId)) {
104499
105727
  if (state.leaseOwners.get(runId) === owner) return;
@@ -104501,10 +105729,12 @@ var AgentThreadStreamRuntime = class {
104501
105729
  }
104502
105730
  const leaseProvider = this.#getLeaseProvider(pubsub);
104503
105731
  const timer = setInterval(() => {
105732
+ if (workerFenced && state.pendingLeaseRenewals.has(runId)) return;
104504
105733
  const sentAt = Date.now();
104505
105734
  state.pendingLeaseRenewals.set(runId, (state.pendingLeaseRenewals.get(runId) ?? 0) + 1);
104506
105735
  leaseProvider.renewLease(key, owner, AGENT_THREAD_LEASE_TTL_MS).then((renewed) => {
104507
105736
  if (!renewed) {
105737
+ if (workerFenced) return;
104508
105738
  if (state.leaseRenewalTimers.get(runId) !== timer) return;
104509
105739
  const confirmed = state.leaseDeadlines.get(runId)?.confirmedSentAt;
104510
105740
  (confirmed === void 0 || Date.now() >= confirmed + AGENT_THREAD_LEASE_TTL_MS ? this.#retakeLease(pubsub, key, runId, timer) : Promise.resolve(false)).then((kept) => {
@@ -104513,7 +105743,7 @@ var AgentThreadStreamRuntime = class {
104513
105743
  this.#abortLeaseLostRun(state, runId);
104514
105744
  });
104515
105745
  } else {
104516
- if (state.leaseRenewalTimers.get(runId) === timer) this.#armLeaseDeadline(pubsub, key, runId, sentAt);
105746
+ if (!workerFenced && state.leaseRenewalTimers.get(runId) === timer) this.#armLeaseDeadline(pubsub, key, runId, sentAt);
104517
105747
  if (state.sweptLeasedRunIds.has(runId)) state.sweptLeasedRunIds.set(runId, Date.now());
104518
105748
  }
104519
105749
  }).catch(() => {}).finally(() => {
@@ -104525,7 +105755,8 @@ var AgentThreadStreamRuntime = class {
104525
105755
  if (typeof timer === "object" && timer && typeof timer.unref === "function") timer.unref();
104526
105756
  state.leaseRenewalTimers.set(runId, timer);
104527
105757
  state.leaseOwners.set(runId, owner);
104528
- this.#armLeaseDeadline(pubsub, key, runId, Date.now());
105758
+ if (workerFenced) return;
105759
+ this.#armLeaseDeadline(pubsub, key, runId, confirmedSentAt);
104529
105760
  if (!this.#resolveLeaseProvider(pubsub).isFallback) {
104530
105761
  const fence = this.#leaseFence(pubsub, key, runId, timer, owner);
104531
105762
  state.leaseFences.set(runId, fence);
@@ -107245,7 +108476,14 @@ var AgentThreadStreamRuntime = class {
107245
108476
  async #publishRunSuspended(pubsub, key, record) {
107246
108477
  record.lifecycle = "suspended";
107247
108478
  record.suspendedAt = Date.now();
107248
- if (this.#getState(pubsub).shutdownStreams.has(record.streamId)) return;
108479
+ const state = this.#getState(pubsub);
108480
+ const owner = state.leaseOwners.get(record.runId);
108481
+ if (owner && state.threadRunsById.get(record.runId) === record && !state.leaseDeadlines.has(record.runId)) {
108482
+ const resolvedPubSub = this.#getPubSub(pubsub);
108483
+ this.#stopLeaseRenewal(resolvedPubSub, record.runId);
108484
+ this.#startLeaseRenewal(resolvedPubSub, key, record.runId, owner, false, record.suspendedAt - AGENT_THREAD_LEASE_TTL_MS);
108485
+ }
108486
+ if (state.shutdownStreams.has(record.streamId)) return;
107249
108487
  await this.#publishAndWait(pubsub, key, {
107250
108488
  type: "run-suspended",
107251
108489
  runId: record.runId,
@@ -107272,6 +108510,11 @@ var AgentThreadStreamRuntime = class {
107272
108510
  record.lifecycle = "completed";
107273
108511
  this.#clearSuspendedRun(state, record.runId);
107274
108512
  state.threadRunsByStreamId.delete(record.streamId);
108513
+ if (state.threadRunsById.get(record.runId) === record) for (const [streamId, other] of state.threadRunsByStreamId) {
108514
+ if (other.runId !== record.runId || other.lifecycle !== "suspended") continue;
108515
+ state.threadRunsByStreamId.delete(streamId);
108516
+ state.watchedThreadStreamIds.delete(streamId);
108517
+ }
107275
108518
  if (state.threadRunsById.get(record.runId) === record) {
107276
108519
  state.threadRunsById.delete(record.runId);
107277
108520
  state.threadKeysByRunId.delete(record.runId);
@@ -109717,8 +110960,26 @@ function getRunRegistryEntry(runId, mastra) {
109717
110960
  }
109718
110961
  return require_observability.unwrapMastraTracingProxy(entry.mastra) === require_observability.unwrapMastraTracingProxy(mastra) ? entry : void 0;
109719
110962
  }
109720
- function getLiveRunRequestContext(entry) {
109721
- return entry?.requestContextRebuilt ? void 0 : entry?.requestContext;
110963
+ /**
110964
+ * Request-context key that identifies a run segment on engines whose steps carry no Core execution
110965
+ * claim (Inngest). The engine stores the same value on the registry entry it seeds for the segment.
110966
+ */
110967
+ const DURABLE_CONTEXT_SEGMENT_KEY = "__mastra_durableContextSegment";
110968
+ /**
110969
+ * The registry's live request context, when it belongs to the execution running this step. Once
110970
+ * another process claims the run (for example an approval from another host), the context cached
110971
+ * here still belongs to the previous caller and must not be reused for the new execution.
110972
+ */
110973
+ function getLiveRunRequestContext(entry, runId, stepContext, executionId) {
110974
+ const live = entry?.requestContext;
110975
+ if (!live || entry.requestContextRebuilt) return void 0;
110976
+ const expectedExecutionId = executionId ?? (runId ? getExecutionClaim(stepContext, runId)?.executionId : void 0);
110977
+ if (!expectedExecutionId) {
110978
+ const stepSegment = stepContext?.get(DURABLE_CONTEXT_SEGMENT_KEY);
110979
+ if (stepSegment === void 0) return live;
110980
+ return stepSegment === entry.requestContextSegment ? live : void 0;
110981
+ }
110982
+ return runId && getExecutionClaim(live, runId)?.executionId === expectedExecutionId ? live : void 0;
109722
110983
  }
109723
110984
  /**
109724
110985
  * Publish an entry for `runId`, owned by `mastra`, unless the slot holds
@@ -110150,12 +111411,24 @@ Object.defineProperty(exports, "CONTINUE_RUN_MESSAGE", {
110150
111411
  return CONTINUE_RUN_MESSAGE;
110151
111412
  }
110152
111413
  });
111414
+ Object.defineProperty(exports, "CONTROLLER_RUN_BINDING_KEY", {
111415
+ enumerable: true,
111416
+ get: function() {
111417
+ return CONTROLLER_RUN_BINDING_KEY;
111418
+ }
111419
+ });
110153
111420
  Object.defineProperty(exports, "ChannelSessionRejectedError", {
110154
111421
  enumerable: true,
110155
111422
  get: function() {
110156
111423
  return ChannelSessionRejectedError;
110157
111424
  }
110158
111425
  });
111426
+ Object.defineProperty(exports, "ChannelThreadLinkProcessor", {
111427
+ enumerable: true,
111428
+ get: function() {
111429
+ return ChannelThreadLinkProcessor;
111430
+ }
111431
+ });
110159
111432
  Object.defineProperty(exports, "ChannelsStorage", {
110160
111433
  enumerable: true,
110161
111434
  get: function() {
@@ -110210,6 +111483,12 @@ Object.defineProperty(exports, "DEFAULT_TOOL_DECLINE_REASON", {
110210
111483
  return DEFAULT_TOOL_DECLINE_REASON;
110211
111484
  }
110212
111485
  });
111486
+ Object.defineProperty(exports, "DURABLE_CONTEXT_SEGMENT_KEY", {
111487
+ enumerable: true,
111488
+ get: function() {
111489
+ return DURABLE_CONTEXT_SEGMENT_KEY;
111490
+ }
111491
+ });
110213
111492
  Object.defineProperty(exports, "DURABLE_STOP_WHEN_ERROR_ID", {
110214
111493
  enumerable: true,
110215
111494
  get: function() {
@@ -110504,6 +111783,12 @@ Object.defineProperty(exports, "KnowledgeRun", {
110504
111783
  return KnowledgeRun;
110505
111784
  }
110506
111785
  });
111786
+ Object.defineProperty(exports, "KnowledgeRunScopesError", {
111787
+ enumerable: true,
111788
+ get: function() {
111789
+ return KnowledgeRunScopesError;
111790
+ }
111791
+ });
110507
111792
  Object.defineProperty(exports, "KnowledgeSchemaResetRequiredError", {
110508
111793
  enumerable: true,
110509
111794
  get: function() {
@@ -110720,6 +112005,12 @@ Object.defineProperty(exports, "ModerationProcessor", {
110720
112005
  return ModerationProcessor;
110721
112006
  }
110722
112007
  });
112008
+ Object.defineProperty(exports, "NEW_CHANNEL_THREAD_KEY", {
112009
+ enumerable: true,
112010
+ get: function() {
112011
+ return NEW_CHANNEL_THREAD_KEY;
112012
+ }
112013
+ });
110723
112014
  Object.defineProperty(exports, "NotificationsStorage", {
110724
112015
  enumerable: true,
110725
112016
  get: function() {
@@ -110822,6 +112113,12 @@ Object.defineProperty(exports, "PromptInjectionDetector", {
110822
112113
  return PromptInjectionDetector;
110823
112114
  }
110824
112115
  });
112116
+ Object.defineProperty(exports, "REPLY_TOOL_NAME", {
112117
+ enumerable: true,
112118
+ get: function() {
112119
+ return REPLY_TOOL_NAME;
112120
+ }
112121
+ });
110825
112122
  Object.defineProperty(exports, "RESPONSE_CACHE_CONTEXT_KEY", {
110826
112123
  enumerable: true,
110827
112124
  get: function() {
@@ -112226,6 +113523,12 @@ Object.defineProperty(exports, "hasResumableStreams", {
112226
113523
  return hasResumableStreams;
112227
113524
  }
112228
113525
  });
113526
+ Object.defineProperty(exports, "heldScopes", {
113527
+ enumerable: true,
113528
+ get: function() {
113529
+ return heldScopes;
113530
+ }
113531
+ });
112229
113532
  Object.defineProperty(exports, "hydrateSerializedStepErrors", {
112230
113533
  enumerable: true,
112231
113534
  get: function() {
@@ -112346,6 +113649,12 @@ Object.defineProperty(exports, "knowledgeAccessGrants", {
112346
113649
  return knowledgeAccessGrants;
112347
113650
  }
112348
113651
  });
113652
+ Object.defineProperty(exports, "knowledgeAgentScopes", {
113653
+ enumerable: true,
113654
+ get: function() {
113655
+ return knowledgeAgentScopes;
113656
+ }
113657
+ });
112349
113658
  Object.defineProperty(exports, "knowledgeDeliveredPins", {
112350
113659
  enumerable: true,
112351
113660
  get: function() {
@@ -112370,6 +113679,12 @@ Object.defineProperty(exports, "knowledgePagePath", {
112370
113679
  return knowledgePagePath;
112371
113680
  }
112372
113681
  });
113682
+ Object.defineProperty(exports, "knowledgePersonaScopes", {
113683
+ enumerable: true,
113684
+ get: function() {
113685
+ return knowledgePersonaScopes;
113686
+ }
113687
+ });
112373
113688
  Object.defineProperty(exports, "knowledgePinDepth", {
112374
113689
  enumerable: true,
112375
113690
  get: function() {
@@ -112478,6 +113793,12 @@ Object.defineProperty(exports, "mapVariable", {
112478
113793
  return mapVariable;
112479
113794
  }
112480
113795
  });
113796
+ Object.defineProperty(exports, "markNewChannelThread", {
113797
+ enumerable: true,
113798
+ get: function() {
113799
+ return markNewChannelThread;
113800
+ }
113801
+ });
112481
113802
  Object.defineProperty(exports, "matchesRunFence", {
112482
113803
  enumerable: true,
112483
113804
  get: function() {
@@ -112490,6 +113811,12 @@ Object.defineProperty(exports, "memoryDefaultOptions", {
112490
113811
  return memoryDefaultOptions;
112491
113812
  }
112492
113813
  });
113814
+ Object.defineProperty(exports, "mergeAgentPersona", {
113815
+ enumerable: true,
113816
+ get: function() {
113817
+ return mergeAgentPersona;
113818
+ }
113819
+ });
112493
113820
  Object.defineProperty(exports, "mergeStepResult", {
112494
113821
  enumerable: true,
112495
113822
  get: function() {
@@ -112772,6 +114099,12 @@ Object.defineProperty(exports, "resolveAgentById", {
112772
114099
  return resolveAgentById;
112773
114100
  }
112774
114101
  });
114102
+ Object.defineProperty(exports, "resolveChannelRenderContext", {
114103
+ enumerable: true,
114104
+ get: function() {
114105
+ return resolveChannelRenderContext;
114106
+ }
114107
+ });
112775
114108
  Object.defineProperty(exports, "resolveChannelToolsSettings", {
112776
114109
  enumerable: true,
112777
114110
  get: function() {
@@ -112862,6 +114195,12 @@ Object.defineProperty(exports, "resolveWaitUntil", {
112862
114195
  return resolveWaitUntil;
112863
114196
  }
112864
114197
  });
114198
+ Object.defineProperty(exports, "restoredWorkerControllerContexts", {
114199
+ enumerable: true,
114200
+ get: function() {
114201
+ return restoredWorkerControllerContexts;
114202
+ }
114203
+ });
112865
114204
  Object.defineProperty(exports, "retentionCutoffMs", {
112866
114205
  enumerable: true,
112867
114206
  get: function() {