@mastra/core 1.87.0-alpha.1 → 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 (481) hide show
  1. package/dist/_types/@ai-sdk_openai@4.0.106/dist/index.d.ts +2034 -0
  2. package/dist/_types/@ai-sdk_openai@4.0.106/package.json +1 -0
  3. package/dist/a2a/index.cjs +1 -1
  4. package/dist/a2a/index.js +1 -1
  5. package/dist/agent/agent.d.ts +3 -1
  6. package/dist/agent/durable/index.cjs +1 -1
  7. package/dist/agent/durable/index.js +1 -1
  8. package/dist/agent/durable/run-message-refs.d.ts +3 -2
  9. package/dist/agent/index.cjs +5 -4
  10. package/dist/agent/index.d.ts +2 -0
  11. package/dist/agent/index.js +5 -5
  12. package/dist/agent/merge-persona.d.ts +15 -0
  13. package/dist/agent/message-list/adapters/AIV5Adapter.d.ts +15 -1
  14. package/dist/agent/message-list/index.cjs +2 -2
  15. package/dist/agent/message-list/index.js +2 -2
  16. package/dist/agent/message-list/state/types.d.ts +5 -1
  17. package/dist/agent/message-list/types.d.ts +1 -1
  18. package/dist/agent/message-list/utils/provider-compat.d.ts +9 -1
  19. package/dist/agent-builder/ee/index.cjs +1 -1
  20. package/dist/agent-builder/ee/index.js +1 -1
  21. package/dist/agent-controller/agent-controller.d.ts +6 -0
  22. package/dist/agent-controller/index.cjs +2 -2
  23. package/dist/agent-controller/index.js +2 -2
  24. package/dist/agent-controller/worker-run-binding.d.ts +15 -0
  25. package/dist/{agent-controller-C1bK0CXm.js → agent-controller--gKWI81G.js} +50 -8
  26. package/dist/{agent-controller-BTIxiD1u.cjs → agent-controller-BolLBwDm.cjs} +50 -8
  27. package/dist/background-tasks/index.cjs +2 -1
  28. package/dist/background-tasks/index.d.ts +1 -1
  29. package/dist/background-tasks/index.js +1 -1
  30. package/dist/background-tasks/resolve-config.d.ts +30 -1
  31. package/dist/background-tasks/system-prompt.d.ts +8 -2
  32. package/dist/background-tasks/types.d.ts +47 -1
  33. package/dist/{background-tasks-BbVsBghi.js → background-tasks-CgzXjBfE.js} +156 -33
  34. package/dist/{background-tasks-CVl6e0Jo.cjs → background-tasks-DYtlijQ1.cjs} +167 -32
  35. package/dist/browser/index.cjs +2 -2
  36. package/dist/browser/index.js +2 -2
  37. package/dist/{builder-BRJPSTig.cjs → builder-Dz-g-9CZ.cjs} +2 -2
  38. package/dist/{builder-C8XzrtBQ.js → builder-emNPaIaC.js} +2 -2
  39. package/dist/capabilities/302ai.json +202 -202
  40. package/dist/capabilities/abliteratedllm.json +39 -30
  41. package/dist/capabilities/abliteration-ai.json +9 -9
  42. package/dist/capabilities/above.json +20 -20
  43. package/dist/capabilities/adaption.json +16 -16
  44. package/dist/capabilities/adzuki.json +24 -24
  45. package/dist/capabilities/agentrouter.json +6 -6
  46. package/dist/capabilities/agnes.json +2 -2
  47. package/dist/capabilities/ai-router.json +9 -9
  48. package/dist/capabilities/aiand.json +25 -25
  49. package/dist/capabilities/aigrow.json +14 -14
  50. package/dist/capabilities/aimlapi.json +140 -143
  51. package/dist/capabilities/aixy.json +15 -15
  52. package/dist/capabilities/aki-io.json +16 -16
  53. package/dist/capabilities/alibaba-cn.json +98 -92
  54. package/dist/capabilities/alibaba-coding-plan-cn.json +4 -4
  55. package/dist/capabilities/alibaba-coding-plan.json +4 -4
  56. package/dist/capabilities/alibaba-token-plan-cn.json +54 -54
  57. package/dist/capabilities/alibaba-token-plan.json +54 -54
  58. package/dist/capabilities/alibaba.json +100 -66
  59. package/dist/capabilities/ambient.json +17 -10
  60. package/dist/capabilities/amd.json +9 -9
  61. package/dist/capabilities/anthropic.json +47 -47
  62. package/dist/capabilities/anyapi.json +13 -13
  63. package/dist/capabilities/apiko.json +5 -5
  64. package/dist/capabilities/arcee.json +6 -6
  65. package/dist/capabilities/augure.json +7 -7
  66. package/dist/capabilities/auriko.json +15 -15
  67. package/dist/capabilities/bailing.json +3 -3
  68. package/dist/capabilities/baseten.json +34 -34
  69. package/dist/capabilities/bee.json +4 -4
  70. package/dist/capabilities/berget.json +16 -3
  71. package/dist/capabilities/bothub.json +12 -12
  72. package/dist/capabilities/boundless.json +37 -37
  73. package/dist/capabilities/bumo.json +42 -42
  74. package/dist/capabilities/byteplus.json +27 -27
  75. package/dist/capabilities/cerebras.json +4 -4
  76. package/dist/capabilities/cheapaimodel.json +8 -8
  77. package/dist/capabilities/cheapest-token.json +31 -31
  78. package/dist/capabilities/chutes.json +10 -10
  79. package/dist/capabilities/claudinio.json +10 -1
  80. package/dist/capabilities/cline-pass.json +38 -38
  81. package/dist/capabilities/cloudcode.json +7 -14
  82. package/dist/capabilities/cloudflare-workers-ai.json +15 -15
  83. package/dist/capabilities/commandcode.json +124 -124
  84. package/dist/capabilities/concentrate.json +275 -292
  85. package/dist/capabilities/cortecs.json +107 -107
  86. package/dist/capabilities/crossmodel.json +180 -180
  87. package/dist/capabilities/crusoe.json +34 -5
  88. package/dist/capabilities/daoxe.json +8 -8
  89. package/dist/capabilities/databricks.json +127 -127
  90. package/dist/capabilities/deepinfra.json +102 -93
  91. package/dist/capabilities/deepseek.json +4 -4
  92. package/dist/capabilities/digitalocean.json +114 -114
  93. package/dist/capabilities/dothoosh.json +28 -28
  94. package/dist/capabilities/doubleword.json +25 -25
  95. package/dist/capabilities/edenai.json +283 -295
  96. package/dist/capabilities/empiriolabs.json +173 -173
  97. package/dist/capabilities/engy.json +18 -18
  98. package/dist/capabilities/entrim.json +2 -2
  99. package/dist/capabilities/evroc.json +14 -14
  100. package/dist/capabilities/ezkielyna.json +6 -6
  101. package/dist/capabilities/fastrouter.json +71 -71
  102. package/dist/capabilities/fireworks-ai.json +132 -71
  103. package/dist/capabilities/fortytwo.json +9 -3
  104. package/dist/capabilities/freemodel.json +12 -12
  105. package/dist/capabilities/friendli.json +8 -8
  106. package/dist/capabilities/frogbot.json +96 -96
  107. package/dist/capabilities/gisoo.json +18 -18
  108. package/dist/capabilities/gmicloud.json +22 -22
  109. package/dist/capabilities/google.json +54 -54
  110. package/dist/capabilities/graphn.json +16 -16
  111. package/dist/capabilities/greenpt.json +35 -35
  112. package/dist/capabilities/groq.json +2 -2
  113. package/dist/capabilities/helicone.json +78 -78
  114. package/dist/capabilities/hetzner.json +35 -3
  115. package/dist/capabilities/hopper.json +2 -2
  116. package/dist/capabilities/hostinger-router.json +14 -14
  117. package/dist/capabilities/hpc-ai.json +10 -10
  118. package/dist/capabilities/huawei-maas.json +15 -15
  119. package/dist/capabilities/hubris.json +29 -29
  120. package/dist/capabilities/huggingface.json +105 -155
  121. package/dist/capabilities/hyper.json +21 -29
  122. package/dist/capabilities/impossibl.json +144 -144
  123. package/dist/capabilities/inception.json +2 -2
  124. package/dist/capabilities/inceptron.json +6 -6
  125. package/dist/capabilities/inco.json +4 -4
  126. package/dist/capabilities/infer.json +20 -20
  127. package/dist/capabilities/inferall.json +11 -11
  128. package/dist/capabilities/inference-coop.json +12 -12
  129. package/dist/capabilities/inferenceapis.json +18 -18
  130. package/dist/capabilities/inferris.json +3 -3
  131. package/dist/capabilities/infersia.json +12 -12
  132. package/dist/capabilities/infomaniak.json +2 -2
  133. package/dist/capabilities/io-net.json +2 -2
  134. package/dist/capabilities/isoquant.json +4 -4
  135. package/dist/capabilities/iteracompute.json +57 -57
  136. package/dist/capabilities/jad-ai.json +3 -3
  137. package/dist/capabilities/jalapeno.json +12 -12
  138. package/dist/capabilities/jiekou.json +63 -63
  139. package/dist/capabilities/jzstoken.json +52 -53
  140. package/dist/capabilities/keln.json +21 -21
  141. package/dist/capabilities/kenari.json +120 -128
  142. package/dist/capabilities/kilo.json +597 -601
  143. package/dist/capabilities/kimi-code-plan-cn.json +9 -9
  144. package/dist/capabilities/kimi-code-plan-global.json +9 -9
  145. package/dist/capabilities/kitani.json +6 -6
  146. package/dist/capabilities/klavo.json +18 -18
  147. package/dist/capabilities/korouter.json +35 -35
  148. package/dist/capabilities/kunavo.json +9 -9
  149. package/dist/capabilities/liquid.json +10 -10
  150. package/dist/capabilities/lithosai.json +2 -2
  151. package/dist/capabilities/llmgateway-providers.json +959 -890
  152. package/dist/capabilities/llmgateway.json +344 -343
  153. package/dist/capabilities/llmtr.json +24 -24
  154. package/dist/capabilities/lowrouter.json +60 -60
  155. package/dist/capabilities/lyceum.json +18 -10
  156. package/dist/capabilities/melious.json +14 -14
  157. package/dist/capabilities/merge-gateway.json +266 -265
  158. package/dist/capabilities/meta.json +11 -11
  159. package/dist/capabilities/minimax-cn-coding-plan.json +2 -2
  160. package/dist/capabilities/minimax-cn.json +5 -5
  161. package/dist/capabilities/minimax-coding-plan.json +2 -2
  162. package/dist/capabilities/minimax.json +5 -5
  163. package/dist/capabilities/mistral.json +22 -22
  164. package/dist/capabilities/mixlayer.json +5 -5
  165. package/dist/capabilities/modal.json +7 -7
  166. package/dist/capabilities/model-oracle-ai.json +27 -27
  167. package/dist/capabilities/modelis.json +20 -20
  168. package/dist/capabilities/modular.json +25 -3
  169. package/dist/capabilities/moneo.json +6 -6
  170. package/dist/capabilities/moonshotai-cn.json +5 -5
  171. package/dist/capabilities/moonshotai.json +5 -5
  172. package/dist/capabilities/morph.json +16 -16
  173. package/dist/capabilities/munito-eu.json +8 -8
  174. package/dist/capabilities/munito.json +8 -8
  175. package/dist/capabilities/nan.json +25 -25
  176. package/dist/capabilities/nano-gpt.json +577 -564
  177. package/dist/capabilities/nearai.json +87 -87
  178. package/dist/capabilities/nebius.json +32 -32
  179. package/dist/capabilities/neon.json +123 -123
  180. package/dist/capabilities/neuralwatt.json +37 -37
  181. package/dist/capabilities/nokeep.json +5 -5
  182. package/dist/capabilities/novita-ai.json +144 -144
  183. package/dist/capabilities/nvidia.json +40 -23
  184. package/dist/capabilities/oathbreaker.json +24 -1
  185. package/dist/capabilities/obscurify.json +22 -22
  186. package/dist/capabilities/oci.json +8 -8
  187. package/dist/capabilities/ofox.json +306 -306
  188. package/dist/capabilities/ollama-cloud.json +61 -61
  189. package/dist/capabilities/openai.json +53 -53
  190. package/dist/capabilities/opencode-go.json +88 -88
  191. package/dist/capabilities/openreason.json +5 -5
  192. package/dist/capabilities/openrouter.json +507 -497
  193. package/dist/capabilities/opper.json +26 -26
  194. package/dist/capabilities/orcarouter.json +203 -203
  195. package/dist/capabilities/outerlabs.json +27 -27
  196. package/dist/capabilities/ovhcloud.json +21 -21
  197. package/dist/capabilities/pareto.json +5 -5
  198. package/dist/capabilities/perplexity-agent.json +61 -61
  199. package/dist/capabilities/perplexity.json +2 -2
  200. package/dist/capabilities/phala.json +27 -27
  201. package/dist/capabilities/pioneer.json +28 -28
  202. package/dist/capabilities/poe.json +123 -123
  203. package/dist/capabilities/poolside.json +3 -3
  204. package/dist/capabilities/powerspring.json +12 -12
  205. package/dist/capabilities/primalabs.json +7 -7
  206. package/dist/capabilities/prime.json +117 -107
  207. package/dist/capabilities/privatemode-ai.json +12 -12
  208. package/dist/capabilities/proxystacks.json +3 -3
  209. package/dist/capabilities/qiniu-ai.json +15 -15
  210. package/dist/capabilities/refuseless.json +8 -8
  211. package/dist/capabilities/regolo-ai.json +8 -8
  212. package/dist/capabilities/requesty.json +384 -169
  213. package/dist/capabilities/ruapi.json +36 -20
  214. package/dist/capabilities/runcrate.json +7 -7
  215. package/dist/capabilities/runinfra.json +10 -10
  216. package/dist/capabilities/sakana.json +5 -5
  217. package/dist/capabilities/sambanova.json +6 -6
  218. package/dist/capabilities/sandbase.json +24 -24
  219. package/dist/capabilities/sarvam.json +11 -11
  220. package/dist/capabilities/scaleway.json +19 -19
  221. package/dist/capabilities/scnet-token-plan.json +11 -11
  222. package/dist/capabilities/scx-ai.json +31 -31
  223. package/dist/capabilities/sensenova.json +14 -14
  224. package/dist/capabilities/siliconflow-cn.json +41 -41
  225. package/dist/capabilities/siliconflow.json +53 -53
  226. package/dist/capabilities/snowflake-cortex.json +18 -18
  227. package/dist/capabilities/sokkan.json +4 -4
  228. package/dist/capabilities/sparrowcodes.json +18 -18
  229. package/dist/capabilities/standardcompute.json +84 -84
  230. package/dist/capabilities/steadyrouter.json +41 -41
  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 +11 -11
  236. package/dist/capabilities/synthetic.json +14 -14
  237. package/dist/capabilities/synthorai.json +25 -25
  238. package/dist/capabilities/teamorouter.json +20 -20
  239. package/dist/capabilities/teapot-router.json +14 -14
  240. package/dist/capabilities/tencent-token-plan-intl.json +126 -0
  241. package/dist/capabilities/tencent-token-plan.json +36 -36
  242. package/dist/capabilities/tencent-tokenhub.json +54 -39
  243. package/dist/capabilities/tensorx.json +43 -43
  244. package/dist/capabilities/tenstorrent.json +6 -6
  245. package/dist/capabilities/the-grid-ai.json +28 -28
  246. package/dist/capabilities/thinkingmachines.json +73 -73
  247. package/dist/capabilities/tinfoil.json +10 -10
  248. package/dist/capabilities/toapis.json +3 -3
  249. package/dist/capabilities/togetherai.json +48 -48
  250. package/dist/capabilities/tokengo.json +17 -17
  251. package/dist/capabilities/tokenify.json +10 -10
  252. package/dist/capabilities/tokenwatt.json +10 -2
  253. package/dist/capabilities/trustedrouter.json +7 -7
  254. package/dist/capabilities/trustedtokens.json +13 -13
  255. package/dist/capabilities/umans-ai-coding-plan.json +14 -14
  256. package/dist/capabilities/umans-ai.json +12 -12
  257. package/dist/capabilities/uncensuredai.json +2 -2
  258. package/dist/capabilities/unrestricted.json +8 -8
  259. package/dist/capabilities/uplinkswitch.json +20 -20
  260. package/dist/capabilities/upstage.json +6 -6
  261. package/dist/capabilities/vancine.json +21 -21
  262. package/dist/capabilities/vercel.json +508 -505
  263. package/dist/capabilities/vivgrid.json +84 -75
  264. package/dist/capabilities/volcengine-coding-plan.json +28 -28
  265. package/dist/capabilities/volcengine.json +29 -28
  266. package/dist/capabilities/vultr.json +28 -28
  267. package/dist/capabilities/wafer.ai.json +17 -17
  268. package/dist/capabilities/wally.json +12 -12
  269. package/dist/capabilities/wandb.json +16 -16
  270. package/dist/capabilities/watt.json +21 -21
  271. package/dist/capabilities/xai.json +7 -7
  272. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -2
  273. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -2
  274. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -2
  275. package/dist/capabilities/xiaomi.json +2 -2
  276. package/dist/capabilities/xpersona.json +13 -13
  277. package/dist/capabilities/xxapi.json +26 -26
  278. package/dist/capabilities/zai-coding-plan.json +20 -20
  279. package/dist/capabilities/zai.json +34 -34
  280. package/dist/capabilities/zenifra.json +31 -31
  281. package/dist/capabilities/zenmux.json +178 -178
  282. package/dist/capabilities/zerogpu.json +12 -12
  283. package/dist/capabilities/zhipuai-coding-plan.json +8 -8
  284. package/dist/capabilities/zhipuai.json +30 -30
  285. package/dist/capabilities/zro.json +3 -3
  286. package/dist/channels/agent-channels.d.ts +22 -0
  287. package/dist/channels/index.cjs +2 -2
  288. package/dist/channels/index.js +2 -2
  289. package/dist/channels/output-processor.d.ts +12 -0
  290. package/dist/channels/state-adapter.d.ts +3 -1
  291. package/dist/channels/stream-helpers.d.ts +17 -0
  292. package/dist/{channels-Cl-pRrWB.cjs → channels-BVnDIsZS.cjs} +1 -1
  293. package/dist/{channels-DegTNzaq.js → channels-CndspFXP.js} +1 -1
  294. package/dist/coding-agent/index.cjs +2 -2
  295. package/dist/coding-agent/index.js +2 -2
  296. package/dist/{constants-B9ZDvXZ4.cjs → constants-Bou0hEgY.cjs} +4 -0
  297. package/dist/{constants-BmdTvEYN.js → constants-CFWgIaqA.js} +4 -0
  298. package/dist/datasets/experiment/scorer.d.ts +16 -5
  299. package/dist/datasets/index.cjs +2 -2
  300. package/dist/datasets/index.js +2 -2
  301. package/dist/docs/SKILL.md +2 -1
  302. package/dist/docs/assets/SOURCE_MAP.json +1070 -1055
  303. package/dist/docs/references/docs-agents-code-mode.md +36 -0
  304. package/dist/docs/references/docs-agents-networks.md +1 -1
  305. package/dist/docs/references/docs-agents-tools.md +6 -0
  306. package/dist/docs/references/docs-auth-simple-auth.md +8 -8
  307. package/dist/docs/references/docs-browser.md +3 -1
  308. package/dist/docs/references/docs-evals-custom-scorers.md +1 -1
  309. package/dist/docs/references/docs-harness-background-tasks.md +38 -0
  310. package/dist/docs/references/docs-knowledge-agents-and-tools.md +2 -0
  311. package/dist/docs/references/docs-mastra-platform-observability-overview.md +3 -189
  312. package/dist/docs/references/docs-memory-message-history.md +25 -0
  313. package/dist/docs/references/docs-sandbox-lsp.md +5 -6
  314. package/dist/docs/references/docs-sandbox-overview.md +20 -0
  315. package/dist/docs/references/docs-sandbox-skills.md +2 -0
  316. package/dist/docs/references/docs-signals-sending-signals.md +1 -1
  317. package/dist/docs/references/integrations.md +1 -0
  318. package/dist/docs/references/reference-agent-controller-session.md +1 -1
  319. package/dist/docs/references/reference-agents-generate.md +1 -1
  320. package/dist/docs/references/reference-agents-network.md +1 -1
  321. package/dist/docs/references/reference-configuration.md +8 -8
  322. package/dist/docs/references/reference-core-getWorkspaceById.md +37 -0
  323. package/dist/docs/references/reference-evals-create-scorer.md +5 -5
  324. package/dist/docs/references/reference-evals-run-evals.md +1 -1
  325. package/dist/docs/references/reference-knowledge-knowledge-tools.md +3 -3
  326. package/dist/docs/references/reference-manual-install.md +1 -1
  327. package/dist/docs/references/reference-memory-observational-memory.md +8 -0
  328. package/dist/docs/references/reference-observability-tracing-interfaces.md +10 -6
  329. package/dist/docs/references/reference-processors-processor-interface.md +3 -2
  330. package/dist/docs/references/reference-processors-system-prompt-scrubber.md +1 -1
  331. package/dist/docs/references/reference-processors-tool-search-processor.md +3 -3
  332. package/dist/docs/references/reference-pubsub-base.md +5 -3
  333. package/dist/docs/references/reference-pubsub-caching-pubsub.md +3 -1
  334. package/dist/docs/references/reference-storage-overview.md +1 -1
  335. package/dist/docs/references/reference-storage-retention.md +20 -20
  336. package/dist/docs/references/reference-tools-create-code-mode.md +22 -0
  337. package/dist/docs/references/reference-tools-vector-query-tool.md +8 -0
  338. package/dist/docs/references/reference-voice-overview.md +11 -26
  339. package/dist/docs/references/reference-voice-speech-to-speech.md +1 -1
  340. package/dist/docs/references/reference-voice-voice.listen.md +1 -0
  341. package/dist/docs/references/reference-voice-voice.speak.md +1 -3
  342. package/dist/docs/references/reference-workspace-factory-sandbox.md +6 -6
  343. package/dist/docs/references/reference-workspace-sandbox.md +14 -0
  344. package/dist/docs/references/reference.md +1 -0
  345. package/dist/evals/index.cjs +2 -2
  346. package/dist/evals/index.js +2 -2
  347. package/dist/evals/scoreTraces/index.cjs +2 -2
  348. package/dist/evals/scoreTraces/index.js +2 -2
  349. package/dist/events/index.cjs +1 -1
  350. package/dist/events/index.js +1 -1
  351. package/dist/harness/index.cjs +2 -2
  352. package/dist/harness/index.js +2 -2
  353. package/dist/index.cjs +1 -1
  354. package/dist/index.js +1 -1
  355. package/dist/knowledge/agent-scopes.d.ts +17 -0
  356. package/dist/knowledge/declarations.d.ts +2 -0
  357. package/dist/knowledge/held-scopes-state-processor.d.ts +50 -0
  358. package/dist/knowledge/importers/host.d.ts +7 -1
  359. package/dist/knowledge/importers/runner.d.ts +12 -0
  360. package/dist/knowledge/importers/types.d.ts +4 -0
  361. package/dist/knowledge/index.cjs +209 -38
  362. package/dist/knowledge/index.d.ts +12 -2
  363. package/dist/knowledge/index.js +208 -39
  364. package/dist/knowledge/page-tools.d.ts +23 -0
  365. package/dist/knowledge/pinned-state-processor.d.ts +2 -2
  366. package/dist/knowledge/run.d.ts +5 -0
  367. package/dist/knowledge/scope-runtime.d.ts +6 -0
  368. package/dist/llm/index.cjs +3 -3
  369. package/dist/llm/index.js +3 -3
  370. package/dist/llm/model/base.types.d.ts +3 -1
  371. package/dist/llm/model/mastra-gateway-provider-tools.d.ts +9 -6
  372. package/dist/llm/model/model.d.ts +1 -1
  373. package/dist/llm/model/model.loop.d.ts +1 -1
  374. package/dist/llm/model/model.loop.types.d.ts +3 -1
  375. package/dist/llm/model/provider-options.d.ts +4 -3
  376. package/dist/llm/model/provider-types.generated.d.ts +7657 -7592
  377. package/dist/{llm-BKxlS9Kk.cjs → llm-B1semiTO.cjs} +38 -78
  378. package/dist/{llm-CMkzIFAk.js → llm-CytL7cpw.js} +38 -78
  379. package/dist/loop/index.cjs +2 -2
  380. package/dist/loop/index.js +2 -2
  381. package/dist/{manager-CasaT35Q.cjs → manager-BwyfS4ha.cjs} +106 -35
  382. package/dist/{manager-C-eQXmRq.js → manager-DnTzA9GL.js} +106 -35
  383. package/dist/mastra/index.cjs +1 -1
  384. package/dist/mastra/index.js +1 -1
  385. package/dist/{mastra-5EEmN3Ok.js → mastra-DTkZPpch.js} +17 -17
  386. package/dist/{mastra-C7Tj4U8c.cjs → mastra-Dj35Lj_J.cjs} +17 -17
  387. package/dist/memory/index.cjs +3 -3
  388. package/dist/memory/index.js +3 -3
  389. package/dist/{message-list-wI71UGxk.js → message-list-BGm1DCiG.js} +230 -129
  390. package/dist/{message-list-DfN9mWeN.cjs → message-list-vR3uLAHL.cjs} +230 -129
  391. package/dist/{model-DCLUL-8a.js → model-DyQ07rPH.js} +4 -3
  392. package/dist/{model-9HA-W0tg.cjs → model-eDfetuno.cjs} +4 -3
  393. package/dist/{netlify-Cq3H-A9I.cjs → netlify-BC4v7Ufv.cjs} +41364 -30461
  394. package/dist/{netlify-DaWURNSU.js → netlify-BUvdxfHe.js} +41361 -30464
  395. package/dist/notifications/index.cjs +1 -1
  396. package/dist/notifications/index.js +1 -1
  397. package/dist/observability/types/tracing.d.ts +1 -1
  398. package/dist/processor-provider/index.cjs +1 -1
  399. package/dist/processor-provider/index.js +1 -1
  400. package/dist/processors/index.cjs +2 -2
  401. package/dist/processors/index.js +2 -2
  402. package/dist/processors/processors/tool-search.d.ts +2 -2
  403. package/dist/processors/runner.d.ts +12 -0
  404. package/dist/{provider-registry-a649fS5r.cjs → provider-registry-Bn01gq9y.cjs} +21872 -21660
  405. package/dist/{provider-registry-DWixjFX7.js → provider-registry-CP_5SNiw.js} +21873 -21661
  406. package/dist/provider-registry.json +22748 -22596
  407. package/dist/{registry-generator-BYJC7p8M.js → registry-generator-CDPyxbzt.js} +1 -1
  408. package/dist/{registry-generator-BuKC7UKd.cjs → registry-generator-CNFKGRFQ.cjs} +1 -1
  409. package/dist/{rehydrate-DPhmASM6.js → rehydrate-CnGNY2zq.js} +2 -2
  410. package/dist/{rehydrate-DR2_WAz2.cjs → rehydrate-DExpzlNS.cjs} +2 -2
  411. package/dist/relevance/index.cjs +2 -2
  412. package/dist/relevance/index.js +2 -2
  413. package/dist/{run-registry-D3X7XvUL.js → run-registry-BL_kKvFE.js} +724 -125
  414. package/dist/{run-registry-oUNF6szW.cjs → run-registry-CibQoN6K.cjs} +766 -125
  415. package/dist/storage/constants.cjs +1 -1
  416. package/dist/storage/constants.js +1 -1
  417. package/dist/storage/domains/knowledge/base.d.ts +16 -1
  418. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +1 -0
  419. package/dist/storage/domains/knowledge/importers.d.ts +8 -0
  420. package/dist/storage/domains/knowledge/inmemory.d.ts +1 -0
  421. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +5 -1
  422. package/dist/storage/index.cjs +3 -3
  423. package/dist/storage/index.js +3 -3
  424. package/dist/storage/types.d.ts +8 -0
  425. package/dist/stream/index.cjs +2 -2
  426. package/dist/stream/index.js +2 -2
  427. package/dist/{stream-DoZ6F41o.js → stream-1DGoEkG2.js} +37 -14
  428. package/dist/{stream-DQC1vpvl.cjs → stream-D_7tMaJe.cjs} +37 -14
  429. package/dist/test-utils/llm-mock.cjs +1 -1
  430. package/dist/test-utils/llm-mock.js +1 -1
  431. package/dist/{to-prompt-B9eZo2U5.cjs → to-prompt-CG-LyaBY.cjs} +9 -0
  432. package/dist/{to-prompt-BsDtVXrf.js → to-prompt-CMlVGYxC.js} +9 -0
  433. package/dist/tool-loop-agent/index.cjs +1 -1
  434. package/dist/tool-loop-agent/index.js +1 -1
  435. package/dist/{tool-loop-agent-C9YkvDRd.js → tool-loop-agent-BXya_RYj.js} +4 -4
  436. package/dist/{tool-loop-agent-Cy4NDOMS.cjs → tool-loop-agent-CLB1r3X3.cjs} +4 -4
  437. package/dist/tools/code-mode/index.d.ts +2 -0
  438. package/dist/tools/code-mode/log-collector.d.ts +49 -0
  439. package/dist/tools/code-mode/types.d.ts +71 -0
  440. package/dist/tools/index.cjs +3 -1
  441. package/dist/tools/index.js +2 -2
  442. package/dist/{tools-CGF5Ik6j.cjs → tools-BEYxowf0.cjs} +429 -61
  443. package/dist/{tools-CDfyMpzN.js → tools-tPy2FwMI.js} +418 -62
  444. package/dist/{utils-Bs2IYyOb.cjs → utils-B-KOMA_Q.cjs} +7 -6
  445. package/dist/{utils-9JyiKu5r.js → utils-C55ZdVaj.js} +7 -6
  446. package/dist/utils.cjs +1 -1
  447. package/dist/utils.js +1 -1
  448. package/dist/{validate-8j0phWFV.js → validate-BDfYr72F.js} +1 -1
  449. package/dist/{validate-BE3mVxVy.cjs → validate-CmZhnsmX.cjs} +1 -1
  450. package/dist/vector/index.cjs +2 -2
  451. package/dist/vector/index.js +2 -2
  452. package/dist/worker/index.cjs +1 -1
  453. package/dist/worker/index.js +1 -1
  454. package/dist/worker/workers/orchestration-worker.d.ts +1 -0
  455. package/dist/{worker-BfWFqSH2.js → worker-BG1rw_dg.js} +5 -5
  456. package/dist/{worker-BiK1kfMa.cjs → worker-BoybIUTI.cjs} +10 -4
  457. package/dist/{worker-DIRdEwih.js → worker-CuK2RaC0.js} +2 -2
  458. package/dist/{worker-DwdgU6E9.cjs → worker-D2B-x7Le.cjs} +2 -2
  459. package/dist/{workflow-ni-keg2i.js → workflow-Bt09PcH1.js} +3 -3
  460. package/dist/{workflow-CxQMcTbT.cjs → workflow-CTKqeRXU.cjs} +3 -3
  461. package/dist/workflows/builder/index.cjs +1 -1
  462. package/dist/workflows/builder/index.js +1 -1
  463. package/dist/workflows/evented/index.cjs +1 -1
  464. package/dist/workflows/evented/index.js +1 -1
  465. package/dist/workflows/index.cjs +4 -4
  466. package/dist/workflows/index.js +4 -4
  467. package/dist/workflows/step.d.ts +2 -0
  468. package/dist/workflows/workflow.d.ts +2 -0
  469. package/dist/workspace/index.cjs +3 -1
  470. package/dist/workspace/index.d.ts +1 -1
  471. package/dist/workspace/index.js +2 -2
  472. package/dist/workspace/lsp/manager.d.ts +19 -4
  473. package/dist/workspace/sandbox/mastra-sandbox.d.ts +17 -0
  474. package/dist/workspace/sandbox/teardown-context.d.ts +74 -0
  475. package/dist/workspace/tools/index.d.ts +1 -0
  476. package/dist/workspace/tools/media.d.ts +20 -1
  477. package/dist/workspace/tools/recreate-sandbox.d.ts +24 -0
  478. package/dist/{workspace-X2RHJZU9.cjs → workspace-C8Zo5_qK.cjs} +387 -109
  479. package/dist/{workspace-DY2Nxiyi.js → workspace-DOAil8mG.js} +376 -110
  480. package/package.json +8 -8
  481. package/src/llm/model/provider-types.generated.d.ts +7657 -7592
@@ -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-DQC1vpvl.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-DfN9mWeN.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-BKxlS9Kk.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-a649fS5r.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-9HA-W0tg.cjs");
30
- const require_utils$1 = require("./utils-Bs2IYyOb.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-CVl6e0Jo.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
  }
@@ -15489,7 +15509,8 @@ var StepExecutor = class extends require_base.MastraBase {
15489
15509
  return require_stream.storageV2StepResultAccessors((step) => require_stream.getHydratedStepResult(stepResults, step, hydrate));
15490
15510
  }
15491
15511
  async execute(params) {
15492
- const { entry, stepResults, runId, requestContext, retryCount = 0, perStep } = params;
15512
+ const { entry, stepResults, runId, retryCount = 0, perStep } = params;
15513
+ let { requestContext } = params;
15493
15514
  const stepId = getEntryId(entry);
15494
15515
  const errorAttemptId = `${runId}:${stepId}:${params.foreachIdx ?? ""}:attempt:${retryCount}`;
15495
15516
  const schemas = getEntrySchemas(entry, this.mastra);
@@ -15545,6 +15566,18 @@ var StepExecutor = class extends require_base.MastraBase {
15545
15566
  const stepTracingContext = workflowStepSpan ? { currentSpan: workflowStepSpan } : params.tracingContext ?? {};
15546
15567
  try {
15547
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
+ }
15548
15581
  const callId = globalThis.crypto.randomUUID();
15549
15582
  const outputWriter = this.createOutputWriter(runId);
15550
15583
  const stepOutput = await require_utils.executeWithContext({
@@ -21341,7 +21374,8 @@ function cloneStep(step, opts) {
21341
21374
  retries: step.retries,
21342
21375
  scorers: step.scorers,
21343
21376
  metadata: step.metadata,
21344
- component: step.component
21377
+ component: step.component,
21378
+ processorId: step.processorId
21345
21379
  };
21346
21380
  }
21347
21381
  function isToolStep(input) {
@@ -21601,6 +21635,7 @@ function createStepFromProcessor(processor) {
21601
21635
  };
21602
21636
  return {
21603
21637
  id: `processor:${processor.id}`,
21638
+ processorId: processor.id,
21604
21639
  description: processor.name ?? `Processor ${processor.id}`,
21605
21640
  inputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepSchema),
21606
21641
  outputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepOutputSchema),
@@ -27750,12 +27785,14 @@ async function partitionMessages(messagesDescending, limits, tokenCounter, initi
27750
27785
  if (maxTokens !== void 0 && !tokenCounter) throw new Error("A token counter is required to load token-limited message history");
27751
27786
  let messageCount = 0;
27752
27787
  let tokenCount = initialTokens;
27788
+ let loadedTokens = initialTokens;
27753
27789
  let reachedLimit = false;
27754
27790
  let overflowReason;
27755
27791
  const retainedIds = /* @__PURE__ */ new Set();
27756
27792
  for (const group of groupLinkedToolMessages(messagesDescending)) {
27757
27793
  let groupTokens = 0;
27758
27794
  if (tokenCounter) for (const message of group) groupTokens += await tokenCounter.countMessage(message);
27795
+ loadedTokens += groupTokens;
27759
27796
  const exceedsMessageLimit = limits.maxMessages !== void 0 && messageCount + group.length > limits.maxMessages;
27760
27797
  const exceedsTokenLimit = maxTokens !== void 0 && tokenCount + groupTokens > maxTokens;
27761
27798
  if (reachedLimit || exceedsMessageLimit || exceedsTokenLimit) {
@@ -27770,7 +27807,8 @@ async function partitionMessages(messagesDescending, limits, tokenCounter, initi
27770
27807
  return {
27771
27808
  messages: messagesDescending.filter((message) => retainedIds.has(message.id)).reverse(),
27772
27809
  overflow: messagesDescending.filter((message) => !retainedIds.has(message.id)).reverse(),
27773
- overflowReason
27810
+ overflowReason,
27811
+ loadedTokens
27774
27812
  };
27775
27813
  }
27776
27814
  function laterDate(left, right) {
@@ -27832,15 +27870,15 @@ async function loadMessageHistory(args) {
27832
27870
  const newestOverflow = partitioned.overflow.at(-1);
27833
27871
  if (newestOverflow) cutoffTimestamp = newestOverflow.createdAt.getTime();
27834
27872
  const oldestTimestamp = result.messages.at(-1)?.createdAt.getTime();
27835
- 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));
27836
27874
  const reachedBoundary = args.boundary !== void 0 && oldestTimestamp !== void 0 && oldestTimestamp < new Date(args.boundary.createdAt).getTime();
27837
- 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 {
27838
27876
  messages: partitioned.messages,
27839
- overflow: []
27877
+ overflow: args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned.overflow : []
27840
27878
  };
27841
- if (oldestTimestamp === void 0) return args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned : {
27879
+ if (oldestTimestamp === void 0) return {
27842
27880
  messages: partitioned.messages,
27843
- overflow: []
27881
+ overflow: args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned.overflow : []
27844
27882
  };
27845
27883
  if (end?.getTime() === oldestTimestamp && added === 0) page++;
27846
27884
  else {
@@ -30335,19 +30373,24 @@ var ToolSearchProcessor = class {
30335
30373
  });
30336
30374
  }
30337
30375
  async processInputStep(args) {
30338
- const { tools, messageList } = args;
30376
+ const { tools, messageList, activeTools } = args;
30339
30377
  const catalog = this.catalogForStep(tools);
30340
30378
  const storeContext = this.makeStoreContext(args);
30341
30379
  const loadedToolNames = await this.store.getLoadedNames(storeContext);
30342
30380
  const autoLoad = this.searchConfig.autoLoad;
30343
- 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.");
30344
- 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)) {
30345
30388
  const catalogList = await this.formatCatalog(catalog, args.requestContext);
30346
- 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);
30347
30390
  }
30348
30391
  const searchTool = require_tool.createTool({
30349
30392
  id: "search_tools",
30350
- 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." : ""),
30351
30394
  inputSchema: zod_v4.z.object({ query: zod_v4.z.string().describe("Search keywords (e.g., \"weather\", \"github issue\", \"database query\")") }),
30352
30395
  outputSchema: zod_v4.z.object({
30353
30396
  results: zod_v4.z.array(zod_v4.z.object({
@@ -30377,13 +30420,13 @@ var ToolSearchProcessor = class {
30377
30420
  }
30378
30421
  return {
30379
30422
  results,
30380
- 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(", ")}.`
30381
30424
  };
30382
30425
  }
30383
30426
  });
30384
30427
  const loadTool = require_tool.createTool({
30385
30428
  id: "load_tool",
30386
- 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.",
30387
30430
  inputSchema: zod_v4.z.object({
30388
30431
  toolName: zod_v4.z.string().optional().describe("The exact name of a tool to load (from search results)"),
30389
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)")
@@ -30440,7 +30483,7 @@ var ToolSearchProcessor = class {
30440
30483
  const suggestions = await this.getSuggestedToolNames(catalog, name, args.requestContext);
30441
30484
  let message = `Tool "${name}" not found.`;
30442
30485
  if (suggestions.length > 0) message += ` Did you mean: ${suggestions.slice(0, 3).join(", ")}?`;
30443
- else message += " Use search_tools to find available tools.";
30486
+ else if (searchAvailable) message += " Use search_tools to find available tools.";
30444
30487
  return {
30445
30488
  success: false,
30446
30489
  message,
@@ -30474,8 +30517,8 @@ var ToolSearchProcessor = class {
30474
30517
  });
30475
30518
  const loadedTools = await this.getLoadedTools(catalog, loadedToolNames, args.requestContext);
30476
30519
  return { tools: {
30477
- search_tools: searchTool,
30478
- ...autoLoad ? {} : { load_tool: loadTool },
30520
+ ...searchAvailable ? { search_tools: searchTool } : {},
30521
+ ...loadAvailable ? { load_tool: loadTool } : {},
30479
30522
  ...this.includeResolvedTools ? unsearchableResolvedTools(tools) : tools ?? {},
30480
30523
  ...loadedTools
30481
30524
  } };
@@ -30837,7 +30880,7 @@ var SkillSearchProcessor = class {
30837
30880
  return this.cleanupStaleState();
30838
30881
  }
30839
30882
  async processInputStep(args) {
30840
- const { tools, messageList } = args;
30883
+ const { tools, messageList, activeTools } = args;
30841
30884
  const threadId = this.getThreadId(args);
30842
30885
  const threadState = this.getThreadState(threadId);
30843
30886
  const configuredSkills = this.skills;
@@ -30847,10 +30890,18 @@ var SkillSearchProcessor = class {
30847
30890
  if (this.blockingRefresh) await skills.maybeRefresh({ requestContext: args.requestContext })?.catch(this.warnRefreshFailed);
30848
30891
  else skills.maybeRefresh({ requestContext: args.requestContext })?.catch(this.warnRefreshFailed);
30849
30892
  }
30850
- 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
+ }
30851
30902
  const searchSkillTool = require_tool.createTool({
30852
30903
  id: "search_skills",
30853
- 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." : ""),
30854
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\")") }),
30855
30906
  outputSchema: zod_v4.z.object({
30856
30907
  results: zod_v4.z.array(zod_v4.z.object({
@@ -30887,13 +30938,13 @@ var SkillSearchProcessor = class {
30887
30938
  });
30888
30939
  return {
30889
30940
  results,
30890
- 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(", ")}.`
30891
30942
  };
30892
30943
  }
30893
30944
  });
30894
30945
  const loadSkillTool = require_tool.createTool({
30895
30946
  id: "load_skill",
30896
- 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.",
30897
30948
  inputSchema: zod_v4.z.object({ skillName: zod_v4.z.string().describe("The exact name of the skill to load (from search results)") }),
30898
30949
  outputSchema: zod_v4.z.object({
30899
30950
  success: zod_v4.z.boolean(),
@@ -30911,7 +30962,7 @@ var SkillSearchProcessor = class {
30911
30962
  const suggestions = (await skills.list()).filter((s) => s.name.toLowerCase().includes(skillName.toLowerCase()) || skillName.toLowerCase().includes(s.name.toLowerCase())).slice(0, 3);
30912
30963
  let message = `Skill "${skillName}" not found.`;
30913
30964
  if (suggestions.length > 0) message += ` Did you mean: ${suggestions.map((s) => s.name).join(", ")}?`;
30914
- else message += " Use search_skills to find available skills.";
30965
+ else if (searchAvailable) message += " Use search_skills to find available skills.";
30915
30966
  return {
30916
30967
  success: false,
30917
30968
  message
@@ -30927,8 +30978,8 @@ var SkillSearchProcessor = class {
30927
30978
  });
30928
30979
  for (const [skillName, instructions] of threadState.skills) messageList.addSystem(`[Skill: ${skillName}]\n\n${instructions}`);
30929
30980
  const metaTools = {
30930
- search_skills: searchSkillTool,
30931
- load_skill: loadSkillTool
30981
+ ...searchAvailable ? { search_skills: searchSkillTool } : {},
30982
+ ...loadAvailable ? { load_skill: loadSkillTool } : {}
30932
30983
  };
30933
30984
  if (tools) {
30934
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.`);
@@ -38729,6 +38780,7 @@ var ExperimentsInMemory = class extends ExperimentsStorage {
38729
38780
  targetType: input.targetType ?? null,
38730
38781
  targetId: input.targetId ?? null,
38731
38782
  scorerIds: input.scorerIds ?? null,
38783
+ scorerVersions: input.scorerVersions ?? null,
38732
38784
  name: input.name,
38733
38785
  description: input.description,
38734
38786
  metadata: input.metadata,
@@ -39635,6 +39687,31 @@ var KnowledgeStorage = class extends require_filesystem_versioned.StorageDomain
39635
39687
  getPages(_input) {
39636
39688
  return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPages"));
39637
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
+ }
39638
39715
  getPageByPath(_input) {
39639
39716
  return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPageByPath"));
39640
39717
  }
@@ -39952,6 +40029,12 @@ var InMemoryKnowledgeImportersStorage = class extends KnowledgeImportersStorage
39952
40029
  const node = this.#s.nodes.get(key(bindingId, sourceId));
39953
40030
  return node ? structuredClone(node) : null;
39954
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
+ }
39955
40038
  async getNodeByPage(pageId) {
39956
40039
  const node = [...this.#s.nodes.values()].find((n) => n.pageId === pageId);
39957
40040
  return node ? structuredClone(node) : null;
@@ -40342,6 +40425,15 @@ var InMemoryKnowledgePageStore = class {
40342
40425
  const page = this.#pages.get(input.id);
40343
40426
  return page && this.#pageReadable(page, input.read) ? clone$1(page) : null;
40344
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
+ }
40345
40437
  async getPages(input) {
40346
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);
40347
40439
  }
@@ -40849,6 +40941,9 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40849
40941
  getPage(input) {
40850
40942
  return this.#pageStore.getPage(input);
40851
40943
  }
40944
+ getPageParents(input) {
40945
+ return this.#pageStore.getPageParents(input);
40946
+ }
40852
40947
  listScopeDeclarations() {
40853
40948
  return this.#pageStore.listScopeDeclarations();
40854
40949
  }
@@ -47890,6 +47985,32 @@ function chunkToFallbackMessage(chunk) {
47890
47985
  if (chunk.type === "plan_update") return chunk.title && chunk.title.length > 0 ? chunk.title : null;
47891
47986
  return null;
47892
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
+ }
47893
48014
  // src/channels/chat-driver-static.ts
47894
48015
  /**
47895
48016
  * Static (non-streaming) driver: consumes `AgentChunkType<any>` chunks and
@@ -47934,7 +48055,7 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47934
48055
  let textBuffer = "";
47935
48056
  const toolMessageIds = /* @__PURE__ */ new Map();
47936
48057
  const flushText = async () => {
47937
- const cleaned = textBuffer.replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
48058
+ const cleaned = cleanBufferedText(textBuffer);
47938
48059
  if (cleaned) try {
47939
48060
  await chatThread.post(textFormat === "plain" ? cleaned : { markdown: cleaned });
47940
48061
  } catch (e) {
@@ -48269,7 +48390,7 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
48269
48390
  if (closed) break;
48270
48391
  await waitForNext();
48271
48392
  }
48272
- const cleaned = fallback.replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
48393
+ const cleaned = cleanBufferedText(fallback);
48273
48394
  if (cleaned) try {
48274
48395
  await chatThread.post(textFormat === "plain" ? cleaned : { markdown: cleaned });
48275
48396
  } catch (postErr) {
@@ -48752,6 +48873,20 @@ const TEXT_CHUNK_TYPES = /* @__PURE__ */ new Set([
48752
48873
  /** Key the processor reads off `requestContext` to locate its render deps. */
48753
48874
  const CHAT_CHANNEL_RENDER_CONTEXT_KEY = "__mastra_chat_channel_render";
48754
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
+ /**
48755
48890
  * Single-producer / single-consumer async queue. The processor pushes chunks
48756
48891
  * synchronously from `processOutputStream`; the driver consumes them via the
48757
48892
  * async iterable. `close()` ends the iteration after pending items are drained.
@@ -48885,7 +49020,7 @@ var ChatChannelOutputProcessor = class {
48885
49020
  async #resolveRenderContext(state, requestContext) {
48886
49021
  if (state.render !== void 0) return state.render;
48887
49022
  const fromRequest = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
48888
- if (fromRequest) {
49023
+ if (isUsableRenderContext(fromRequest)) {
48889
49024
  state.render = fromRequest;
48890
49025
  return fromRequest;
48891
49026
  }
@@ -49058,7 +49193,7 @@ var ChatChannelGenerativeUIProcessor = class {
49058
49193
  }
49059
49194
  async #resolve(requestContext, state) {
49060
49195
  const inbound = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
49061
- if (inbound) return inbound;
49196
+ if (isUsableRenderContext(inbound)) return inbound;
49062
49197
  if (state && "render" in state) return state.render ?? void 0;
49063
49198
  const threadId = require_stream.parseMemoryRequestContext(requestContext)?.thread?.id;
49064
49199
  const render = threadId && this.#channels ? await this.#channels.buildRenderContextForThread(threadId) : null;
@@ -49212,6 +49347,8 @@ async function headContentType(url, logger) {
49212
49347
  }
49213
49348
  }
49214
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";
49215
49352
  /**
49216
49353
  * Input processor that injects channel context (platform, bot identity, DM vs.
49217
49354
  * public-channel guidance) into the agent's system prompt on every step.
@@ -49245,19 +49382,37 @@ var ChatChannelProcessor = class {
49245
49382
  }
49246
49383
  async #resolve(requestContext, state) {
49247
49384
  const channel = requestContext?.get("channel");
49248
- if (channel) return {
49249
- channel,
49250
- textHidden: (requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY))?.textDisplay === "hidden"
49251
- };
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
+ }
49252
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) {
49253
49399
  const threadId = require_stream.parseMemoryRequestContext(requestContext)?.thread?.id;
49254
49400
  const found = threadId && this.#channels ? await this.#channels.buildChannelContextForThread(threadId) : null;
49255
- const resolved = found ? {
49401
+ return found ? {
49256
49402
  channel: found.channel,
49257
49403
  textHidden: found.render.textDisplay === "hidden"
49258
49404
  } : null;
49259
- if (state) state.thread = resolved;
49260
- 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;
49261
49416
  }
49262
49417
  };
49263
49418
  function channelLines(ctx, textHidden, tools) {
@@ -49780,15 +49935,17 @@ var ChannelReplyModeProcessor = class {
49780
49935
  var MastraStateAdapter = class {
49781
49936
  memoryStore;
49782
49937
  getOwnerId;
49938
+ logger;
49783
49939
  connected = false;
49784
49940
  connectPromise = null;
49785
49941
  cache = /* @__PURE__ */ new Map();
49786
49942
  locks = /* @__PURE__ */ new Map();
49787
49943
  lists = /* @__PURE__ */ new Map();
49788
49944
  queues = /* @__PURE__ */ new Map();
49789
- constructor(memoryStore, getOwnerId) {
49945
+ constructor(memoryStore, getOwnerId, logger) {
49790
49946
  this.memoryStore = memoryStore;
49791
49947
  this.getOwnerId = getOwnerId;
49948
+ this.logger = logger;
49792
49949
  }
49793
49950
  async connect() {
49794
49951
  if (this.connected) return;
@@ -49807,7 +49964,10 @@ var MastraStateAdapter = class {
49807
49964
  }
49808
49965
  async subscribe(threadId) {
49809
49966
  const thread = await this.findThreadByExternalId(threadId);
49810
- 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
+ }
49811
49971
  await this.memoryStore.patchThread({
49812
49972
  id: thread.id,
49813
49973
  metadata: {
@@ -50199,7 +50359,7 @@ function formatLegacyHistoryBlock(history, chatThread, platform) {
50199
50359
  async function resolveChannelRenderContext(requestContext, channels) {
50200
50360
  if (!requestContext) return void 0;
50201
50361
  const stashed = requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
50202
- if (stashed) return stashed;
50362
+ if (isUsableRenderContext(stashed)) return stashed;
50203
50363
  const threadId = requestContext.get("controller")?.threadId ?? require_stream.parseMemoryRequestContext(requestContext)?.thread?.id;
50204
50364
  if (!threadId) return void 0;
50205
50365
  return await channels?.()?.buildRenderContextForThread(threadId) ?? void 0;
@@ -50643,7 +50803,7 @@ var AgentChannels = class {
50643
50803
  const storage = mastra.getStorage();
50644
50804
  const memoryStore = storage ? await storage.getStore("memory") : void 0;
50645
50805
  if (!memoryStore) throw new Error("Channels require storage to be configured on the Mastra instance. Configure a storage provider like LibSQLStore.");
50646
- this.stateAdapter = new MastraStateAdapter(memoryStore, () => this.getOwnerId());
50806
+ this.stateAdapter = new MastraStateAdapter(memoryStore, () => this.getOwnerId(), this.logger);
50647
50807
  this.log("info", "Using MastraStateAdapter (subscriptions persist across restarts)");
50648
50808
  }
50649
50809
  const { Chat, Message: ChatMessage, ThreadImpl } = await getChatModule();
@@ -50871,25 +51031,30 @@ var AgentChannels = class {
50871
51031
  runId = stashed.runId;
50872
51032
  toolName = stashed.toolName;
50873
51033
  toolArgs = stashed.args;
50874
- } else {
51034
+ }
51035
+ if (!requesterId) {
50875
51036
  const { result: lookup } = await this.lookupPersistedApproval({
50876
51037
  mastra,
50877
51038
  card,
50878
51039
  platform
50879
51040
  });
50880
- if (lookup.status === "answered") {
50881
- this.log("info", "Tool approval already answered", actionEventContext);
50882
- 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
+ }
50883
51051
  }
50884
51052
  if (lookup.status === "pending") {
50885
- runId = lookup.runId;
50886
- toolName = lookup.toolName;
50887
- toolArgs = lookup.args;
50888
- if (adapterConfig?.toolApprovers !== "anyone" && !requesterId && lookup.authors.length > 1) {
51053
+ if (adapterConfig?.toolApprovers !== "anyone" && lookup.authors.length > 1) {
50889
51054
  this.log("info", "Ignoring tool approval action: requester is ambiguous", actionEventContext);
50890
51055
  return;
50891
51056
  }
50892
- requesterId ??= lookup.authors[0];
51057
+ requesterId = lookup.authors[0];
50893
51058
  }
50894
51059
  }
50895
51060
  if (!runId) {
@@ -51194,7 +51359,7 @@ var AgentChannels = class {
51194
51359
  */
51195
51360
  async resolveRunRender(requestContext, state) {
51196
51361
  const inbound = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
51197
- if (inbound) return inbound;
51362
+ if (isUsableRenderContext(inbound)) return inbound;
51198
51363
  if (state && "render" in state) return state.render ?? void 0;
51199
51364
  const render = await resolveChannelRenderContext(requestContext, () => this);
51200
51365
  if (state) state.render = render ?? null;
@@ -51223,8 +51388,8 @@ var AgentChannels = class {
51223
51388
  const has = (id) => configuredProcessors.some((p) => !require_stream.isProcessorWorkflow(p) && p.id === id);
51224
51389
  const processors = [];
51225
51390
  if (Object.values(this.adapterConfigs).some((cfg) => cfg.threadLink) && !has(THREAD_LINK_PROCESSOR_ID)) processors.push(new ChannelThreadLinkProcessor((requestContext) => {
51226
- const render = requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
51227
- return render && threadLinkOptions(this.adapterConfigs[render.platform]?.threadLink);
51391
+ const platform = requestContext.get("channel")?.platform ?? requestContext.get("__mastra_chat_channel_render")?.platform;
51392
+ return platform ? threadLinkOptions(this.adapterConfigs[platform]?.threadLink) : void 0;
51228
51393
  }));
51229
51394
  if (!has("chat-channel-render")) processors.push(new ChatChannelOutputProcessor(this));
51230
51395
  if (this.replyModeEnabled && !has(REPLY_STREAM_PROCESSOR_ID)) processors.push(new ChannelReplyStreamProcessor((requestContext) => this.resolveRunRender(requestContext)));
@@ -52406,6 +52571,36 @@ var AgentChannels = class {
52406
52571
  };
52407
52572
  }
52408
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
+ /**
52409
52604
  * Resolves an existing Mastra thread for the given external IDs, or creates one.
52410
52605
  */
52411
52606
  async getOrCreateThread({ externalThreadId, channelId, platform, resourceId, threadId, onCreate, mastra }) {
@@ -52633,6 +52828,132 @@ function withReplyModeDefaults(cfg) {
52633
52828
  ...set
52634
52829
  };
52635
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
+ };
52636
52957
  // src/knowledge/instructions.ts
52637
52958
  function readInstructions(canEdit) {
52638
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.`;
@@ -52923,6 +53244,16 @@ function compileKnowledgeScopes(declarations) {
52923
53244
  const concreteEntries = [];
52924
53245
  for (const [key, declaration] of Object.entries(declarations)) {
52925
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
+ }
52926
53257
  if (pattern.params.length === 0) {
52927
53258
  concreteEntries.push([key, declaration]);
52928
53259
  continue;
@@ -53391,17 +53722,19 @@ async function pageRefKeys(storage, page) {
53391
53722
  if (page.address) keys.push(knowledgeLinkRefKey(page.address));
53392
53723
  return keys;
53393
53724
  }
53725
+ if (!page.key || !page.parentId) return keys;
53394
53726
  const path = [];
53395
- let current = page;
53396
- 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
+ }
53397
53735
  if (!current.key || !current.parentId) return keys;
53398
53736
  path.unshift(current.key);
53399
- current = await storage.getPage({
53400
- id: current.parentId,
53401
- read: "all"
53402
- });
53403
53737
  }
53404
- if (current?.address) keys.push(knowledgeLinkRefKey(`${current.address}#${path.join("/")}`));
53405
53738
  return keys;
53406
53739
  }
53407
53740
  /** The page and its live ordinary descendants, at most {@link MAX_KNOWLEDGE_MOVE_PAGES} + 1. */
@@ -62894,6 +63227,94 @@ async function removeKnowledgeNote(host, input) {
62894
63227
  await embed$1(host, (index) => index.remove([`note:${note.id}`]), UNEMBED_FAILED$1);
62895
63228
  return removed;
62896
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
+ }
62897
63318
  // src/knowledge/run.ts
62898
63319
  /** A page reference the run can't resolve; identical for missing and unreadable pages. */
62899
63320
  var KnowledgeNotFoundError = class extends Error {
@@ -62902,6 +63323,13 @@ var KnowledgeNotFoundError = class extends Error {
62902
63323
  this.name = "KnowledgeNotFoundError";
62903
63324
  }
62904
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
+ };
62905
63333
  const NAME_CANDIDATES = 5;
62906
63334
  const CLOSE_MATCHES = 3;
62907
63335
  /**
@@ -63053,9 +63481,15 @@ function knowledgeRunPrincipals(runtime, context) {
63053
63481
  const memory = [];
63054
63482
  if (context?.agent?.resourceId) memory.push(knowledgeScopeAddress("resource:$resourceId", { resourceId: context.agent.resourceId }));
63055
63483
  if (context?.agent?.threadId) memory.push(knowledgeScopeAddress("thread:$threadId", { threadId: context.agent.threadId }));
63056
- 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();
63057
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()\`).`);
63058
- 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
+ ])];
63059
63493
  }
63060
63494
  /** Longest heading line a hit shows ahead of its excerpt; a longer one is cut with `…`. */
63061
63495
  const HEADING_CHARS = 120;
@@ -63429,6 +63863,30 @@ async function noteSummaries(run, notes, cache = /* @__PURE__ */ new Map()) {
63429
63863
  for (const note of notes) summaries.push(noteSummary(note, await noteMentions(run, note, cache)));
63430
63864
  return summaries;
63431
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
+ }
63432
63890
  /** Scope pages for addresses the run names; each must be readable. */
63433
63891
  async function readableScopes(run, addresses) {
63434
63892
  const page = addresses.find((address) => address.includes("#"));
@@ -63465,11 +63923,13 @@ async function visibleNote(run, id) {
63465
63923
  page
63466
63924
  };
63467
63925
  }
63468
- /** 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. */
63469
63927
  async function requireAudienceAuthority(run, audience) {
63470
63928
  for (const address of audience) {
63471
- if (run.principals.includes(address)) continue;
63472
- 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.`);
63473
63933
  const [scope] = await run.storage.getScopesByAddress([address]);
63474
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.`);
63475
63935
  }
@@ -63709,7 +64169,7 @@ function bodyView(body, input) {
63709
64169
  function readTool(host, canEdit) {
63710
64170
  return require_tool.createTool({
63711
64171
  id: "knowledge_read",
63712
- 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." : ""),
63713
64173
  inputSchema: {
63714
64174
  type: "object",
63715
64175
  properties: {
@@ -63791,10 +64251,13 @@ function readTool(host, canEdit) {
63791
64251
  if (outline && from) throw new Error("knowledge_read: an outline covers the whole body; pass it without from.");
63792
64252
  const run = await start(host, context);
63793
64253
  const limit = limitOf(requested);
63794
- if (!ref) return { scopes: (await run.storage.getScopesByAddress(run.principals)).filter((scope) => knowledgeScopeReadable(scope, run.read)).map((scope) => ({
63795
- address: scope.address,
63796
- name: scope.name,
63797
- ...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 }
63798
64261
  })) };
63799
64262
  const page = await run.pageOrCloseMatches(ref);
63800
64263
  if (outline || section || match || from) {
@@ -64008,12 +64471,13 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
64008
64471
  let scopes = [];
64009
64472
  if (!origin) {
64010
64473
  if (cursor?.startsWith("p")) throw new Error("knowledge_list: a page cursor needs the `from` it came from.");
64011
- const held = await run.storage.getScopesByAddress(run.principals);
64012
- const order = (scope) => run.principals.indexOf(scope.address ?? "");
64013
- 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
+ }));
64014
64478
  } else {
64015
64479
  originRef = (await pageRefs(run, [origin])).refs.get(origin.id) ?? origin.id;
64016
- 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 }));
64017
64481
  }
64018
64482
  const shownScopes = scopes.slice(scopeOffset, scopeOffset + limit);
64019
64483
  let roots = shownScopes;
@@ -64023,7 +64487,7 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
64023
64487
  const room = limit - shownScopes.length;
64024
64488
  if (room > 0) {
64025
64489
  const pages = await childPages(origin.id, room, pageCursor);
64026
- roots = [...shownScopes, ...pages.pages];
64490
+ roots = [...shownScopes, ...pages.pages.map((page) => ({ page }))];
64027
64491
  if (pages.nextCursor) nextCursor = `p${pages.nextCursor}`;
64028
64492
  } else if ((await run.storage.countChildPages({
64029
64493
  parentIds: [origin.id],
@@ -64037,10 +64501,19 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
64037
64501
  children: 0,
64038
64502
  below: []
64039
64503
  });
64040
- 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
+ });
64041
64514
  let budget = Math.max(limit - top.length, 0);
64042
64515
  let truncated = false;
64043
- let level = top;
64516
+ let level = top.filter((node) => node.page);
64044
64517
  for (let current = 1; current <= depth && level.length; current++) {
64045
64518
  const parentIds = level.map((node) => node.page.id);
64046
64519
  const scopeParents = level.filter((node) => node.page.isScope).map((node) => node.page.id);
@@ -64064,22 +64537,30 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
64064
64537
  budget -= scopes.length;
64065
64538
  const pages = budget > 0 ? (await childPages(node.page.id, budget)).pages : [];
64066
64539
  budget -= pages.length;
64067
- node.below = [...scopes, ...pages].map((child) => nodeOf(child, childRef(node.page, node.ref, child), current + 1));
64068
- if (node.below.length < node.children) truncated = true;
64069
- 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);
64070
64547
  }
64071
64548
  level = nextLevel;
64072
64549
  }
64073
64550
  const entries = [];
64074
64551
  const flatten = (nodes) => {
64075
64552
  for (const node of nodes) {
64553
+ const { page, held } = node;
64076
64554
  entries.push({
64077
64555
  ref: node.ref,
64078
- name: node.page.name,
64079
- ...descriptions && node.page.description ? { description: node.page.description } : {},
64556
+ name: page?.name ?? node.ref,
64557
+ ...descriptions && page?.description ? { description: page.description } : {},
64080
64558
  depth: node.depth,
64081
64559
  children: node.children,
64082
- ...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 }
64083
64564
  });
64084
64565
  flatten(node.below);
64085
64566
  }
@@ -64096,7 +64577,7 @@ function listTool(host) {
64096
64577
  const maxTokens = maxTokensOf(host);
64097
64578
  return require_tool.createTool({
64098
64579
  id: "knowledge_list",
64099
- 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\`).`,
64100
64581
  inputSchema: {
64101
64582
  type: "object",
64102
64583
  properties: {
@@ -65268,12 +65749,8 @@ var PinnedStateProcessor = class {
65268
65749
  threadId: args.threadId
65269
65750
  }
65270
65751
  };
65271
- let key;
65272
- try {
65273
- key = this.deps.principalsKey(context);
65274
- } catch {
65275
- return;
65276
- }
65752
+ const key = await this.deps.principalsKey(context);
65753
+ if (key === void 0) return void 0;
65277
65754
  if (memo && memo.key === key && stepNumber > memo.atStep) return memo.entries;
65278
65755
  const entries = await this.deps.readPins(context);
65279
65756
  args.requestContext?.set?.(MEMO_KEY, {
@@ -67193,7 +67670,7 @@ var MastraLLMVNext = class extends require_base.MastraBase {
67193
67670
  content: messages
67194
67671
  }];
67195
67672
  }
67196
- 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 }) {
67197
67674
  const observabilityContext = require_observability.resolveObservabilityContext(rest);
67198
67675
  let stopWhenToUse;
67199
67676
  if (maxSteps && typeof maxSteps === "number") {
@@ -67219,7 +67696,8 @@ var MastraLLMVNext = class extends require_base.MastraBase {
67219
67696
  provider: firstModel.provider,
67220
67697
  streaming: true,
67221
67698
  parameters: modelSettings,
67222
- ...toolDefinitions ? { tools: toolDefinitions } : {}
67699
+ ...toolDefinitions ? { tools: toolDefinitions } : {},
67700
+ ...resultType ? { resultType } : {}
67223
67701
  },
67224
67702
  metadata: {
67225
67703
  runId,
@@ -73571,8 +74049,9 @@ function releaseRunMessageRefs(runId) {
73571
74049
  /**
73572
74050
  * A `SaveQueueManager` `onSaved` callback that records the rows a run saved,
73573
74051
  * so its persisted transcript references them instead of repeating them. Only
73574
- * runs that store refs hold an entry (the transcript store creates it), so saves
73575
- * 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.
73576
74055
  */
73577
74056
  function recordRunSavedMessages(runId) {
73578
74057
  return (rows) => {
@@ -73594,6 +74073,15 @@ function recordRunSavedMessages(runId) {
73594
74073
  };
73595
74074
  }
73596
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
+ }
73597
74085
  /**
73598
74086
  * Build a SaveQueueManager for a run's memory, or `undefined` when no memory
73599
74087
  * is configured. Shared by `resolveRuntimeDependencies` and
@@ -73756,6 +74244,7 @@ async function resolveRuntimeDependencies(options) {
73756
74244
  backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
73757
74245
  tools = await agent.getToolsForExecution({
73758
74246
  runId,
74247
+ toolsets: await restoreWorkerToolsets(mastra, resolveRequestContext, input.options?.toolsetToolNames),
73759
74248
  threadId: input.state.threadId,
73760
74249
  resourceId: input.state.resourceId,
73761
74250
  requestContext: resolveRequestContext,
@@ -73877,6 +74366,7 @@ async function rebuildRunToolsFromMastra(options) {
73877
74366
  const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
73878
74367
  const tools = await agent.getToolsForExecution({
73879
74368
  runId,
74369
+ toolsets: await restoreWorkerToolsets(mastra, resolveRequestContext, execOptions?.toolsetToolNames),
73880
74370
  threadId: state.threadId,
73881
74371
  resourceId: state.resourceId,
73882
74372
  requestContext: resolveRequestContext,
@@ -74346,7 +74836,11 @@ function mergeRequestContextForFinalization(entries, fallback, liveRunContext) {
74346
74836
  if (liveRunContext) return liveRunContext;
74347
74837
  if (!entries) return fallback ?? new require_request_context.RequestContext();
74348
74838
  const restored = new require_request_context.RequestContext(fallback?.entries());
74349
- 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
+ }
74350
74844
  restoreRunAgentScopes(restored);
74351
74845
  return restored;
74352
74846
  }
@@ -74387,6 +74881,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
74387
74881
  ...initData,
74388
74882
  messageListState
74389
74883
  },
74884
+ requestContext,
74390
74885
  logger: effectiveLogger
74391
74886
  });
74392
74887
  rebuiltSaveQueueManager = resolved.saveQueueManager;
@@ -76391,6 +76886,15 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
76391
76886
  });
76392
76887
  break;
76393
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
+ }
76394
76898
  case "tool-call": {
76395
76899
  const p = chunk.payload;
76396
76900
  const toolDef = tools?.[p.toolName] || findProviderToolByName(tools, p.toolName);
@@ -79930,6 +80434,12 @@ function createDurableToolCallStep() {
79930
80434
  error
79931
80435
  };
79932
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
+ });
79933
80443
  const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;
79934
80444
  const memory = registryEntry?.memory ?? rebuiltMemory;
79935
80445
  const workspace = registryEntry?.workspace ?? rebuiltWorkspace;
@@ -83725,15 +84235,21 @@ async function persistDurableRunInput(runId, workflowInput, mastra, beforeSave)
83725
84235
  await beforeSave();
83726
84236
  }
83727
84237
  const inputCopy = entry.messageList.clone();
83728
- await entry.saveQueueManager.flushMessages(inputCopy, state.threadId, state.memoryConfig, {
83729
- throwOnError: true,
83730
- beforePersist: () => assertExecutionOwned({
83731
- runId,
83732
- agentId: workflowInput.agentId,
83733
- mastra,
83734
- requestContext
83735
- })
83736
- });
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
+ }
83737
84253
  const embedded = entry.messageList.getEmbeddedMessages();
83738
84254
  for (const [messageId, textHash] of inputCopy.getEmbeddedMessages()) embedded.set(messageId, textHash);
83739
84255
  }
@@ -84060,7 +84576,7 @@ async function prepareForDurableExecution(options) {
84060
84576
  });
84061
84577
  let tripwireData;
84062
84578
  if (inputProcessors.length > 0) try {
84063
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-DQC1vpvl.cjs")).then((n) => n.runner_exports);
84579
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-D_7tMaJe.cjs")).then((n) => n.runner_exports);
84064
84580
  await new ProcessorRunner({
84065
84581
  inputProcessors,
84066
84582
  outputProcessors,
@@ -86820,6 +87336,11 @@ var Agent = class Agent extends require_base.MastraBase {
86820
87336
  const processors = [];
86821
87337
  const instructions = knowledge.getInstructions();
86822
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
+ }));
86823
87344
  if (knowledge.pinnedContextEnabled && !configuredIds.has("knowledge")) {
86824
87345
  if (!hasMemory) {
86825
87346
  if (!this.#warnedPinsWithoutMemory) {
@@ -86828,9 +87349,26 @@ var Agent = class Agent extends require_base.MastraBase {
86828
87349
  }
86829
87350
  return processors;
86830
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
+ };
86831
87369
  processors.push(new PinnedStateProcessor({
86832
- principalsKey: (context) => knowledge.__principalsKey(context),
86833
- readPins: (context) => knowledge.__deliveredPins(context),
87370
+ principalsKey: async (context) => knowledge.__principalsKey(await pinContext(context)),
87371
+ readPins: async (context) => knowledge.__deliveredPins(await pinContext(context)),
86834
87372
  ...knowledge.__toolGroups
86835
87373
  }));
86836
87374
  }
@@ -87787,7 +88325,8 @@ var Agent = class Agent extends require_base.MastraBase {
87787
88325
  }
87788
88326
  /**
87789
88327
  * Gets the metadata for this agent, resolving function-based metadata if necessary.
87790
- * 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.
87791
88330
  *
87792
88331
  * @example
87793
88332
  * ```typescript
@@ -88525,11 +89064,13 @@ var Agent = class Agent extends require_base.MastraBase {
88525
89064
  ...observabilityContext,
88526
89065
  messageList,
88527
89066
  agentId: this.id,
88528
- agentName: this.name
89067
+ agentName: this.name,
89068
+ resultType: "title_generation"
88529
89069
  }).text;
88530
89070
  } else text = (await llm.__text({
88531
89071
  requestContext,
88532
89072
  ...observabilityContext,
89073
+ resultType: "title_generation",
88533
89074
  messages: [{
88534
89075
  role: "system",
88535
89076
  content: systemInstructions
@@ -88676,10 +89217,34 @@ var Agent = class Agent extends require_base.MastraBase {
88676
89217
  backgroundConfig: tool.background,
88677
89218
  agentBackgroundConfig: this.#backgroundTasks
88678
89219
  };
88679
- 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);
88680
89237
  }
88681
89238
  return converted;
88682
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
+ }
88683
89248
  /**
88684
89249
  * Lists workspace tools if a workspace is configured.
88685
89250
  * @internal
@@ -96420,6 +96985,29 @@ var Agent = class Agent extends require_base.MastraBase {
96420
96985
  };
96421
96986
  }
96422
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
+ }
96423
97011
  // ../_internal-core/dist/fs-routing/index.js
96424
97012
  /**
96425
97013
  * Maximum nesting depth for declared subagents. A top-level agent is depth 0;
@@ -103086,6 +103674,12 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
103086
103674
  args = argsFromInput;
103087
103675
  resumeDataFromArgs = resumeDataFromInput;
103088
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
+ });
103089
103683
  const resumeData = resumeDataFromArgs ?? workflowResumeData;
103090
103684
  const isResumeToolCall = resumeDataFromArgs != null;
103091
103685
  const approvalVerdicts = readScoped(scopeCtx, TOOL_APPROVAL_VERDICTS_KEY, "toolApprovalVerdicts");
@@ -107916,6 +108510,11 @@ var AgentThreadStreamRuntime = class {
107916
108510
  record.lifecycle = "completed";
107917
108511
  this.#clearSuspendedRun(state, record.runId);
107918
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
+ }
107919
108518
  if (state.threadRunsById.get(record.runId) === record) {
107920
108519
  state.threadRunsById.delete(record.runId);
107921
108520
  state.threadKeysByRunId.delete(record.runId);
@@ -110812,6 +111411,12 @@ Object.defineProperty(exports, "CONTINUE_RUN_MESSAGE", {
110812
111411
  return CONTINUE_RUN_MESSAGE;
110813
111412
  }
110814
111413
  });
111414
+ Object.defineProperty(exports, "CONTROLLER_RUN_BINDING_KEY", {
111415
+ enumerable: true,
111416
+ get: function() {
111417
+ return CONTROLLER_RUN_BINDING_KEY;
111418
+ }
111419
+ });
110815
111420
  Object.defineProperty(exports, "ChannelSessionRejectedError", {
110816
111421
  enumerable: true,
110817
111422
  get: function() {
@@ -111178,6 +111783,12 @@ Object.defineProperty(exports, "KnowledgeRun", {
111178
111783
  return KnowledgeRun;
111179
111784
  }
111180
111785
  });
111786
+ Object.defineProperty(exports, "KnowledgeRunScopesError", {
111787
+ enumerable: true,
111788
+ get: function() {
111789
+ return KnowledgeRunScopesError;
111790
+ }
111791
+ });
111181
111792
  Object.defineProperty(exports, "KnowledgeSchemaResetRequiredError", {
111182
111793
  enumerable: true,
111183
111794
  get: function() {
@@ -112912,6 +113523,12 @@ Object.defineProperty(exports, "hasResumableStreams", {
112912
113523
  return hasResumableStreams;
112913
113524
  }
112914
113525
  });
113526
+ Object.defineProperty(exports, "heldScopes", {
113527
+ enumerable: true,
113528
+ get: function() {
113529
+ return heldScopes;
113530
+ }
113531
+ });
112915
113532
  Object.defineProperty(exports, "hydrateSerializedStepErrors", {
112916
113533
  enumerable: true,
112917
113534
  get: function() {
@@ -113032,6 +113649,12 @@ Object.defineProperty(exports, "knowledgeAccessGrants", {
113032
113649
  return knowledgeAccessGrants;
113033
113650
  }
113034
113651
  });
113652
+ Object.defineProperty(exports, "knowledgeAgentScopes", {
113653
+ enumerable: true,
113654
+ get: function() {
113655
+ return knowledgeAgentScopes;
113656
+ }
113657
+ });
113035
113658
  Object.defineProperty(exports, "knowledgeDeliveredPins", {
113036
113659
  enumerable: true,
113037
113660
  get: function() {
@@ -113056,6 +113679,12 @@ Object.defineProperty(exports, "knowledgePagePath", {
113056
113679
  return knowledgePagePath;
113057
113680
  }
113058
113681
  });
113682
+ Object.defineProperty(exports, "knowledgePersonaScopes", {
113683
+ enumerable: true,
113684
+ get: function() {
113685
+ return knowledgePersonaScopes;
113686
+ }
113687
+ });
113059
113688
  Object.defineProperty(exports, "knowledgePinDepth", {
113060
113689
  enumerable: true,
113061
113690
  get: function() {
@@ -113182,6 +113811,12 @@ Object.defineProperty(exports, "memoryDefaultOptions", {
113182
113811
  return memoryDefaultOptions;
113183
113812
  }
113184
113813
  });
113814
+ Object.defineProperty(exports, "mergeAgentPersona", {
113815
+ enumerable: true,
113816
+ get: function() {
113817
+ return mergeAgentPersona;
113818
+ }
113819
+ });
113185
113820
  Object.defineProperty(exports, "mergeStepResult", {
113186
113821
  enumerable: true,
113187
113822
  get: function() {
@@ -113560,6 +114195,12 @@ Object.defineProperty(exports, "resolveWaitUntil", {
113560
114195
  return resolveWaitUntil;
113561
114196
  }
113562
114197
  });
114198
+ Object.defineProperty(exports, "restoredWorkerControllerContexts", {
114199
+ enumerable: true,
114200
+ get: function() {
114201
+ return restoredWorkerControllerContexts;
114202
+ }
114203
+ });
113563
114204
  Object.defineProperty(exports, "retentionCutoffMs", {
113564
114205
  enumerable: true,
113565
114206
  get: function() {