@mastra/core 1.87.0-alpha.1 → 1.87.0-alpha.11

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 (494) 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/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +49 -0
  4. package/dist/a2a/index.cjs +1 -1
  5. package/dist/a2a/index.js +1 -1
  6. package/dist/agent/agent.d.ts +3 -1
  7. package/dist/agent/durable/index.cjs +1 -1
  8. package/dist/agent/durable/index.js +1 -1
  9. package/dist/agent/durable/run-message-refs.d.ts +3 -2
  10. package/dist/agent/index.cjs +5 -4
  11. package/dist/agent/index.d.ts +2 -0
  12. package/dist/agent/index.js +5 -5
  13. package/dist/agent/merge-persona.d.ts +15 -0
  14. package/dist/agent/message-list/adapters/AIV5Adapter.d.ts +15 -1
  15. package/dist/agent/message-list/index.cjs +2 -2
  16. package/dist/agent/message-list/index.js +2 -2
  17. package/dist/agent/message-list/state/types.d.ts +5 -1
  18. package/dist/agent/message-list/types.d.ts +1 -1
  19. package/dist/agent/message-list/utils/provider-compat.d.ts +9 -1
  20. package/dist/agent-builder/ee/index.cjs +1 -1
  21. package/dist/agent-builder/ee/index.js +1 -1
  22. package/dist/agent-controller/agent-controller.d.ts +6 -0
  23. package/dist/agent-controller/index.cjs +2 -2
  24. package/dist/agent-controller/index.js +2 -2
  25. package/dist/agent-controller/session.d.ts +11 -1
  26. package/dist/agent-controller/worker-run-binding.d.ts +15 -0
  27. package/dist/{agent-controller-C1bK0CXm.js → agent-controller-BrRzZy4-.js} +66 -15
  28. package/dist/{agent-controller-BTIxiD1u.cjs → agent-controller-DKI-d-np.cjs} +66 -15
  29. package/dist/background-tasks/index.cjs +2 -1
  30. package/dist/background-tasks/index.d.ts +1 -1
  31. package/dist/background-tasks/index.js +1 -1
  32. package/dist/background-tasks/resolve-config.d.ts +30 -1
  33. package/dist/background-tasks/system-prompt.d.ts +8 -2
  34. package/dist/background-tasks/types.d.ts +47 -1
  35. package/dist/{background-tasks-BbVsBghi.js → background-tasks-CDP3Pgeu.js} +156 -33
  36. package/dist/{background-tasks-CVl6e0Jo.cjs → background-tasks-CDgdfRmB.cjs} +167 -32
  37. package/dist/browser/index.cjs +2 -2
  38. package/dist/browser/index.js +2 -2
  39. package/dist/{builder-BRJPSTig.cjs → builder-Bs4CtyqT.cjs} +2 -2
  40. package/dist/{builder-C8XzrtBQ.js → builder-DuT0Iqb5.js} +2 -2
  41. package/dist/capabilities/302ai.json +199 -199
  42. package/dist/capabilities/abliteratedllm.json +43 -34
  43. package/dist/capabilities/abliteration-ai.json +7 -7
  44. package/dist/capabilities/above.json +19 -19
  45. package/dist/capabilities/adaption.json +15 -15
  46. package/dist/capabilities/adzuki.json +27 -27
  47. package/dist/capabilities/agentrouter.json +13 -13
  48. package/dist/capabilities/agnes.json +3 -3
  49. package/dist/capabilities/ai-router.json +6 -6
  50. package/dist/capabilities/aiand.json +21 -21
  51. package/dist/capabilities/aigrow.json +12 -12
  52. package/dist/capabilities/aimlapi.json +143 -146
  53. package/dist/capabilities/aipg.json +2 -2
  54. package/dist/capabilities/aixy.json +22 -22
  55. package/dist/capabilities/aki-io.json +16 -16
  56. package/dist/capabilities/alibaba-cn.json +108 -102
  57. package/dist/capabilities/alibaba-coding-plan-cn.json +5 -5
  58. package/dist/capabilities/alibaba-coding-plan.json +5 -5
  59. package/dist/capabilities/alibaba-token-plan-cn.json +52 -52
  60. package/dist/capabilities/alibaba-token-plan.json +53 -53
  61. package/dist/capabilities/alibaba.json +98 -64
  62. package/dist/capabilities/ambient.json +17 -10
  63. package/dist/capabilities/amd.json +9 -9
  64. package/dist/capabilities/anthropic.json +45 -45
  65. package/dist/capabilities/anyapi.json +47 -47
  66. package/dist/capabilities/apiko.json +2 -2
  67. package/dist/capabilities/arcee.json +11 -11
  68. package/dist/capabilities/augure.json +6 -6
  69. package/dist/capabilities/auriko.json +20 -20
  70. package/dist/capabilities/bailing.json +4 -4
  71. package/dist/capabilities/baseten.json +33 -33
  72. package/dist/capabilities/bee.json +5 -5
  73. package/dist/capabilities/berget.json +20 -7
  74. package/dist/capabilities/bothub.json +14 -14
  75. package/dist/capabilities/boundless.json +37 -37
  76. package/dist/capabilities/bumo.json +42 -42
  77. package/dist/capabilities/byteplus.json +28 -28
  78. package/dist/capabilities/cerebras.json +4 -4
  79. package/dist/capabilities/cheapaimodel.json +7 -7
  80. package/dist/capabilities/cheapest-token.json +30 -30
  81. package/dist/capabilities/chutes.json +4 -4
  82. package/dist/capabilities/clarifai.json +2 -2
  83. package/dist/capabilities/claudinio.json +10 -1
  84. package/dist/capabilities/cline-pass.json +42 -42
  85. package/dist/capabilities/cloudcode.json +9 -16
  86. package/dist/capabilities/cloudferro-sherlock.json +4 -4
  87. package/dist/capabilities/cloudflare-workers-ai.json +14 -14
  88. package/dist/capabilities/commandcode.json +140 -140
  89. package/dist/capabilities/concentrate.json +289 -298
  90. package/dist/capabilities/cortecs.json +105 -105
  91. package/dist/capabilities/crossmodel.json +197 -197
  92. package/dist/capabilities/crusoe.json +38 -9
  93. package/dist/capabilities/daoxe.json +8 -8
  94. package/dist/capabilities/databricks.json +125 -125
  95. package/dist/capabilities/deepinfra.json +109 -94
  96. package/dist/capabilities/deepseek.json +4 -4
  97. package/dist/capabilities/digitalocean.json +112 -112
  98. package/dist/capabilities/dothoosh.json +34 -34
  99. package/dist/capabilities/doubleword.json +24 -24
  100. package/dist/capabilities/edenai.json +280 -292
  101. package/dist/capabilities/empiriolabs.json +168 -168
  102. package/dist/capabilities/engy.json +21 -21
  103. package/dist/capabilities/entrim.json +8 -8
  104. package/dist/capabilities/evroc.json +12 -12
  105. package/dist/capabilities/ezkielyna.json +8 -8
  106. package/dist/capabilities/fastrouter.json +87 -87
  107. package/dist/capabilities/fireworks-ai.json +130 -69
  108. package/dist/capabilities/fortytwo.json +9 -3
  109. package/dist/capabilities/freemodel.json +14 -14
  110. package/dist/capabilities/friendli.json +2 -2
  111. package/dist/capabilities/frogbot.json +96 -96
  112. package/dist/capabilities/gisoo.json +17 -17
  113. package/dist/capabilities/gmicloud.json +24 -24
  114. package/dist/capabilities/google.json +54 -54
  115. package/dist/capabilities/graphn.json +16 -16
  116. package/dist/capabilities/greenpt.json +35 -35
  117. package/dist/capabilities/groq.json +2 -2
  118. package/dist/capabilities/helicone.json +94 -94
  119. package/dist/capabilities/hetzner.json +35 -3
  120. package/dist/capabilities/hostinger-router.json +14 -14
  121. package/dist/capabilities/hpc-ai.json +11 -11
  122. package/dist/capabilities/huawei-maas.json +14 -14
  123. package/dist/capabilities/hubris.json +30 -30
  124. package/dist/capabilities/huggingface.json +113 -155
  125. package/dist/capabilities/humain.json +2 -2
  126. package/dist/capabilities/hyper.json +25 -33
  127. package/dist/capabilities/impossibl.json +155 -155
  128. package/dist/capabilities/inception.json +2 -2
  129. package/dist/capabilities/inceptron.json +8 -8
  130. package/dist/capabilities/inco.json +5 -5
  131. package/dist/capabilities/infer.json +20 -20
  132. package/dist/capabilities/inferall.json +14 -14
  133. package/dist/capabilities/inference-coop.json +9 -9
  134. package/dist/capabilities/inferenceapis.json +20 -20
  135. package/dist/capabilities/inferris.json +4 -4
  136. package/dist/capabilities/infersia.json +11 -11
  137. package/dist/capabilities/infomaniak.json +4 -4
  138. package/dist/capabilities/io-net.json +4 -4
  139. package/dist/capabilities/isoquant.json +4 -4
  140. package/dist/capabilities/iteracompute.json +59 -59
  141. package/dist/capabilities/jad-ai.json +3 -3
  142. package/dist/capabilities/jalapeno.json +10 -10
  143. package/dist/capabilities/jiekou.json +60 -60
  144. package/dist/capabilities/joingonka.json +4 -4
  145. package/dist/capabilities/jzstoken.json +58 -59
  146. package/dist/capabilities/keln.json +18 -18
  147. package/dist/capabilities/kenari.json +119 -127
  148. package/dist/capabilities/kilo.json +609 -613
  149. package/dist/capabilities/kimi-code-plan-cn.json +5 -5
  150. package/dist/capabilities/kimi-code-plan-global.json +5 -5
  151. package/dist/capabilities/kitani.json +6 -6
  152. package/dist/capabilities/klavo.json +20 -20
  153. package/dist/capabilities/korouter.json +32 -32
  154. package/dist/capabilities/kunavo.json +8 -8
  155. package/dist/capabilities/liquid.json +12 -12
  156. package/dist/capabilities/lithosai.json +2 -2
  157. package/dist/capabilities/llmgateway-providers.json +947 -878
  158. package/dist/capabilities/llmgateway.json +336 -335
  159. package/dist/capabilities/llmtr.json +26 -26
  160. package/dist/capabilities/logits.json +2 -2
  161. package/dist/capabilities/longcat.json +2 -2
  162. package/dist/capabilities/lowrouter.json +65 -65
  163. package/dist/capabilities/lyceum.json +19 -11
  164. package/dist/capabilities/melious.json +14 -14
  165. package/dist/capabilities/merge-gateway.json +264 -263
  166. package/dist/capabilities/meta.json +13 -13
  167. package/dist/capabilities/minimax-cn-coding-plan.json +2 -2
  168. package/dist/capabilities/minimax-cn.json +5 -5
  169. package/dist/capabilities/minimax-coding-plan.json +2 -2
  170. package/dist/capabilities/minimax.json +5 -5
  171. package/dist/capabilities/mistral.json +21 -21
  172. package/dist/capabilities/mixlayer.json +3 -3
  173. package/dist/capabilities/modal.json +10 -10
  174. package/dist/capabilities/model-oracle-ai.json +26 -26
  175. package/dist/capabilities/modelis.json +17 -17
  176. package/dist/capabilities/modelscope.json +2 -2
  177. package/dist/capabilities/modular.json +30 -8
  178. package/dist/capabilities/moneo.json +12 -12
  179. package/dist/capabilities/moonshotai-cn.json +2 -2
  180. package/dist/capabilities/moonshotai.json +2 -2
  181. package/dist/capabilities/morph.json +17 -17
  182. package/dist/capabilities/munito-eu.json +6 -6
  183. package/dist/capabilities/munito.json +6 -6
  184. package/dist/capabilities/nan.json +29 -29
  185. package/dist/capabilities/nano-gpt.json +606 -593
  186. package/dist/capabilities/nearai.json +112 -112
  187. package/dist/capabilities/nebius.json +30 -30
  188. package/dist/capabilities/neon.json +136 -136
  189. package/dist/capabilities/neuralwatt.json +43 -43
  190. package/dist/capabilities/nokeep.json +4 -4
  191. package/dist/capabilities/novita-ai.json +136 -136
  192. package/dist/capabilities/nvidia.json +52 -35
  193. package/dist/capabilities/oathbreaker.json +24 -1
  194. package/dist/capabilities/obscurify.json +29 -29
  195. package/dist/capabilities/oci.json +7 -7
  196. package/dist/capabilities/ofox.json +315 -315
  197. package/dist/capabilities/ollama-cloud.json +53 -53
  198. package/dist/capabilities/openai.json +53 -53
  199. package/dist/capabilities/opencode-go.json +88 -88
  200. package/dist/capabilities/openreason.json +5 -5
  201. package/dist/capabilities/openrouter.json +528 -519
  202. package/dist/capabilities/opper.json +29 -29
  203. package/dist/capabilities/orcarouter.json +214 -214
  204. package/dist/capabilities/outerlabs.json +33 -33
  205. package/dist/capabilities/ovhcloud.json +20 -20
  206. package/dist/capabilities/pareto.json +6 -6
  207. package/dist/capabilities/pendra.json +4 -4
  208. package/dist/capabilities/perplexity-agent.json +55 -55
  209. package/dist/capabilities/perplexity.json +2 -2
  210. package/dist/capabilities/phala.json +26 -26
  211. package/dist/capabilities/pioneer.json +31 -31
  212. package/dist/capabilities/poe.json +136 -136
  213. package/dist/capabilities/poolside.json +2 -2
  214. package/dist/capabilities/powerspring.json +12 -12
  215. package/dist/capabilities/primalabs.json +9 -9
  216. package/dist/capabilities/prime.json +121 -111
  217. package/dist/capabilities/privatemode-ai.json +5 -5
  218. package/dist/capabilities/proxystacks.json +7 -7
  219. package/dist/capabilities/qiniu-ai.json +16 -16
  220. package/dist/capabilities/refuseless.json +9 -9
  221. package/dist/capabilities/regolo-ai.json +11 -11
  222. package/dist/capabilities/requesty.json +451 -177
  223. package/dist/capabilities/ruapi.json +35 -19
  224. package/dist/capabilities/runcrate.json +13 -13
  225. package/dist/capabilities/runinfra.json +18 -18
  226. package/dist/capabilities/sakana.json +7 -7
  227. package/dist/capabilities/sambanova.json +6 -6
  228. package/dist/capabilities/sandbase.json +25 -25
  229. package/dist/capabilities/sarvam.json +7 -7
  230. package/dist/capabilities/scaleway.json +19 -19
  231. package/dist/capabilities/scnet-token-plan.json +10 -10
  232. package/dist/capabilities/scx-ai.json +30 -30
  233. package/dist/capabilities/sensenova.json +12 -12
  234. package/dist/capabilities/siliconflow-cn.json +60 -60
  235. package/dist/capabilities/siliconflow.json +62 -62
  236. package/dist/capabilities/snowflake-cortex.json +21 -21
  237. package/dist/capabilities/sokkan.json +7 -7
  238. package/dist/capabilities/sparrowcodes.json +19 -19
  239. package/dist/capabilities/standardcompute.json +106 -106
  240. package/dist/capabilities/steadyrouter.json +37 -37
  241. package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
  242. package/dist/capabilities/stepfun-ai.json +6 -6
  243. package/dist/capabilities/stepfun-step-plan.json +6 -6
  244. package/dist/capabilities/stepfun.json +6 -6
  245. package/dist/capabilities/stepping-stone.json +17 -17
  246. package/dist/capabilities/superbot-gg.json +4 -4
  247. package/dist/capabilities/synthetic.json +13 -13
  248. package/dist/capabilities/synthorai.json +24 -24
  249. package/dist/capabilities/teamorouter.json +23 -23
  250. package/dist/capabilities/teapot-router.json +11 -11
  251. package/dist/capabilities/tencent-token-plan-intl.json +126 -0
  252. package/dist/capabilities/tencent-token-plan.json +44 -44
  253. package/dist/capabilities/tencent-tokenhub.json +58 -43
  254. package/dist/capabilities/tensorx.json +40 -40
  255. package/dist/capabilities/tenstorrent.json +8 -8
  256. package/dist/capabilities/the-grid-ai.json +35 -35
  257. package/dist/capabilities/thinkingmachines.json +76 -76
  258. package/dist/capabilities/tinfoil.json +13 -13
  259. package/dist/capabilities/toapis.json +3 -3
  260. package/dist/capabilities/togetherai.json +54 -54
  261. package/dist/capabilities/tokengo.json +25 -25
  262. package/dist/capabilities/tokenify.json +9 -9
  263. package/dist/capabilities/tokenwatt.json +10 -2
  264. package/dist/capabilities/trustedrouter.json +7 -7
  265. package/dist/capabilities/trustedtokens.json +18 -18
  266. package/dist/capabilities/umans-ai-coding-plan.json +13 -13
  267. package/dist/capabilities/umans-ai.json +14 -14
  268. package/dist/capabilities/uncensuredai.json +5 -5
  269. package/dist/capabilities/unrestricted.json +8 -8
  270. package/dist/capabilities/uplinkswitch.json +22 -22
  271. package/dist/capabilities/upstage.json +6 -6
  272. package/dist/capabilities/vancine.json +23 -23
  273. package/dist/capabilities/vercel.json +543 -540
  274. package/dist/capabilities/vivgrid.json +88 -79
  275. package/dist/capabilities/volcengine-coding-plan.json +26 -26
  276. package/dist/capabilities/volcengine.json +26 -25
  277. package/dist/capabilities/vultr.json +32 -32
  278. package/dist/capabilities/wafer.ai.json +16 -16
  279. package/dist/capabilities/wallaby.json +2 -2
  280. package/dist/capabilities/wally.json +11 -11
  281. package/dist/capabilities/wandb.json +17 -17
  282. package/dist/capabilities/watt.json +25 -25
  283. package/dist/capabilities/xai.json +6 -6
  284. package/dist/capabilities/xiaomi.json +2 -2
  285. package/dist/capabilities/xpersona.json +13 -13
  286. package/dist/capabilities/xxapi.json +26 -26
  287. package/dist/capabilities/zai-coding-plan.json +15 -15
  288. package/dist/capabilities/zai.json +32 -32
  289. package/dist/capabilities/zenifra.json +26 -26
  290. package/dist/capabilities/zenmux.json +208 -208
  291. package/dist/capabilities/zerogpu.json +13 -13
  292. package/dist/capabilities/zhipuai-coding-plan.json +4 -4
  293. package/dist/capabilities/zhipuai.json +31 -31
  294. package/dist/capabilities/zro.json +7 -7
  295. package/dist/channels/agent-channels.d.ts +22 -0
  296. package/dist/channels/index.cjs +2 -2
  297. package/dist/channels/index.js +2 -2
  298. package/dist/channels/output-processor.d.ts +12 -0
  299. package/dist/channels/state-adapter.d.ts +3 -1
  300. package/dist/channels/stream-helpers.d.ts +17 -0
  301. package/dist/{channels-Cl-pRrWB.cjs → channels-Bkd_v8M1.cjs} +1 -1
  302. package/dist/{channels-DegTNzaq.js → channels-CkRMEIQ6.js} +1 -1
  303. package/dist/coding-agent/index.cjs +2 -2
  304. package/dist/coding-agent/index.js +2 -2
  305. package/dist/{constants-B9ZDvXZ4.cjs → constants-Bou0hEgY.cjs} +4 -0
  306. package/dist/{constants-BmdTvEYN.js → constants-CFWgIaqA.js} +4 -0
  307. package/dist/datasets/experiment/scorer.d.ts +16 -5
  308. package/dist/datasets/index.cjs +2 -2
  309. package/dist/datasets/index.js +2 -2
  310. package/dist/docs/SKILL.md +2 -1
  311. package/dist/docs/assets/SOURCE_MAP.json +1070 -1055
  312. package/dist/docs/references/docs-agents-code-mode.md +36 -0
  313. package/dist/docs/references/docs-agents-networks.md +1 -1
  314. package/dist/docs/references/docs-agents-tools.md +6 -0
  315. package/dist/docs/references/docs-auth-simple-auth.md +8 -8
  316. package/dist/docs/references/docs-browser.md +3 -1
  317. package/dist/docs/references/docs-evals-custom-scorers.md +1 -1
  318. package/dist/docs/references/docs-harness-background-tasks.md +38 -0
  319. package/dist/docs/references/docs-knowledge-agents-and-tools.md +2 -0
  320. package/dist/docs/references/docs-mastra-platform-observability-overview.md +3 -189
  321. package/dist/docs/references/docs-memory-message-history.md +25 -0
  322. package/dist/docs/references/docs-sandbox-lsp.md +5 -6
  323. package/dist/docs/references/docs-sandbox-overview.md +20 -0
  324. package/dist/docs/references/docs-sandbox-skills.md +2 -0
  325. package/dist/docs/references/docs-signals-sending-signals.md +1 -1
  326. package/dist/docs/references/integrations.md +1 -0
  327. package/dist/docs/references/reference-agent-controller-session.md +30 -2
  328. package/dist/docs/references/reference-agents-generate.md +1 -1
  329. package/dist/docs/references/reference-agents-network.md +1 -1
  330. package/dist/docs/references/reference-configuration.md +8 -8
  331. package/dist/docs/references/reference-core-getWorkspaceById.md +37 -0
  332. package/dist/docs/references/reference-evals-create-scorer.md +5 -5
  333. package/dist/docs/references/reference-evals-run-evals.md +1 -1
  334. package/dist/docs/references/reference-knowledge-knowledge-tools.md +3 -3
  335. package/dist/docs/references/reference-manual-install.md +1 -1
  336. package/dist/docs/references/reference-memory-observational-memory.md +8 -0
  337. package/dist/docs/references/reference-observability-tracing-interfaces.md +10 -6
  338. package/dist/docs/references/reference-processors-processor-interface.md +3 -2
  339. package/dist/docs/references/reference-processors-system-prompt-scrubber.md +1 -1
  340. package/dist/docs/references/reference-processors-tool-search-processor.md +3 -3
  341. package/dist/docs/references/reference-pubsub-base.md +5 -3
  342. package/dist/docs/references/reference-pubsub-caching-pubsub.md +3 -1
  343. package/dist/docs/references/reference-storage-overview.md +1 -1
  344. package/dist/docs/references/reference-storage-retention.md +20 -20
  345. package/dist/docs/references/reference-tools-create-code-mode.md +22 -0
  346. package/dist/docs/references/reference-tools-vector-query-tool.md +8 -0
  347. package/dist/docs/references/reference-voice-overview.md +11 -26
  348. package/dist/docs/references/reference-voice-speech-to-speech.md +1 -1
  349. package/dist/docs/references/reference-voice-voice.listen.md +1 -0
  350. package/dist/docs/references/reference-voice-voice.speak.md +1 -3
  351. package/dist/docs/references/reference-workspace-factory-sandbox.md +6 -6
  352. package/dist/docs/references/reference-workspace-sandbox.md +14 -0
  353. package/dist/docs/references/reference.md +1 -0
  354. package/dist/evals/index.cjs +2 -2
  355. package/dist/evals/index.js +2 -2
  356. package/dist/evals/scoreTraces/index.cjs +2 -2
  357. package/dist/evals/scoreTraces/index.js +2 -2
  358. package/dist/events/index.cjs +1 -1
  359. package/dist/events/index.js +1 -1
  360. package/dist/harness/index.cjs +2 -2
  361. package/dist/harness/index.js +2 -2
  362. package/dist/index.cjs +1 -1
  363. package/dist/index.js +1 -1
  364. package/dist/knowledge/agent-scopes.d.ts +17 -0
  365. package/dist/knowledge/declarations.d.ts +2 -0
  366. package/dist/knowledge/held-scopes-state-processor.d.ts +50 -0
  367. package/dist/knowledge/importers/host.d.ts +7 -1
  368. package/dist/knowledge/importers/overlay.d.ts +138 -0
  369. package/dist/knowledge/importers/runner.d.ts +12 -0
  370. package/dist/knowledge/importers/sink.d.ts +6 -0
  371. package/dist/knowledge/importers/types.d.ts +9 -0
  372. package/dist/knowledge/index.cjs +1611 -167
  373. package/dist/knowledge/index.d.ts +12 -2
  374. package/dist/knowledge/index.js +1610 -168
  375. package/dist/knowledge/links.d.ts +27 -0
  376. package/dist/knowledge/page-tools.d.ts +23 -0
  377. package/dist/knowledge/pinned-state-processor.d.ts +2 -2
  378. package/dist/knowledge/run.d.ts +5 -0
  379. package/dist/knowledge/scope-runtime.d.ts +6 -0
  380. package/dist/llm/index.cjs +3 -3
  381. package/dist/llm/index.js +3 -3
  382. package/dist/llm/model/base.types.d.ts +3 -1
  383. package/dist/llm/model/mastra-gateway-provider-tools.d.ts +9 -6
  384. package/dist/llm/model/model.d.ts +1 -1
  385. package/dist/llm/model/model.loop.d.ts +1 -1
  386. package/dist/llm/model/model.loop.types.d.ts +3 -1
  387. package/dist/llm/model/provider-options.d.ts +4 -3
  388. package/dist/llm/model/provider-types.generated.d.ts +8161 -8082
  389. package/dist/{llm-BKxlS9Kk.cjs → llm-DAw2eouV.cjs} +38 -78
  390. package/dist/{llm-CMkzIFAk.js → llm-DFT5EKp4.js} +38 -78
  391. package/dist/loop/index.cjs +2 -2
  392. package/dist/loop/index.js +2 -2
  393. package/dist/{manager-C-eQXmRq.js → manager-DiDnvKLM.js} +106 -35
  394. package/dist/{manager-CasaT35Q.cjs → manager-hxzEe4U5.cjs} +106 -35
  395. package/dist/mastra/index.cjs +1 -1
  396. package/dist/mastra/index.js +1 -1
  397. package/dist/{mastra-C7Tj4U8c.cjs → mastra-1diaq68N.cjs} +17 -17
  398. package/dist/{mastra-5EEmN3Ok.js → mastra-BPaPxG5t.js} +17 -17
  399. package/dist/memory/index.cjs +3 -3
  400. package/dist/memory/index.js +3 -3
  401. package/dist/{message-list-wI71UGxk.js → message-list-BGm1DCiG.js} +230 -129
  402. package/dist/{message-list-DfN9mWeN.cjs → message-list-vR3uLAHL.cjs} +230 -129
  403. package/dist/{model-DCLUL-8a.js → model-CUBZjm0T.js} +4 -3
  404. package/dist/{model-9HA-W0tg.cjs → model-DSMHJM3c.cjs} +4 -3
  405. package/dist/{netlify-Cq3H-A9I.cjs → netlify-C21T9ozJ.cjs} +41364 -30461
  406. package/dist/{netlify-DaWURNSU.js → netlify-D1BKjns0.js} +41361 -30464
  407. package/dist/notifications/index.cjs +1 -1
  408. package/dist/notifications/index.js +1 -1
  409. package/dist/observability/types/tracing.d.ts +1 -1
  410. package/dist/processor-provider/index.cjs +1 -1
  411. package/dist/processor-provider/index.js +1 -1
  412. package/dist/processors/index.cjs +2 -2
  413. package/dist/processors/index.js +2 -2
  414. package/dist/processors/processors/tool-search.d.ts +2 -2
  415. package/dist/processors/runner.d.ts +12 -0
  416. package/dist/{provider-registry-DWixjFX7.js → provider-registry-BAlFFX5o.js} +21911 -21671
  417. package/dist/{provider-registry-a649fS5r.cjs → provider-registry-ChojUVJa.cjs} +21910 -21670
  418. package/dist/provider-registry.json +21947 -21767
  419. package/dist/{registry-generator-BYJC7p8M.js → registry-generator-BbWSH6W4.js} +1 -1
  420. package/dist/{registry-generator-BuKC7UKd.cjs → registry-generator-CAUL9Hek.cjs} +1 -1
  421. package/dist/{rehydrate-DR2_WAz2.cjs → rehydrate-0xSq47n9.cjs} +2 -2
  422. package/dist/{rehydrate-DPhmASM6.js → rehydrate-CzUnNFU6.js} +2 -2
  423. package/dist/relevance/index.cjs +2 -2
  424. package/dist/relevance/index.js +2 -2
  425. package/dist/{run-registry-oUNF6szW.cjs → run-registry-CrTsH9iL.cjs} +1158 -125
  426. package/dist/{run-registry-D3X7XvUL.js → run-registry-DJT02z_9.js} +1092 -125
  427. package/dist/storage/constants.cjs +1 -1
  428. package/dist/storage/constants.js +1 -1
  429. package/dist/storage/domains/knowledge/base.d.ts +101 -1
  430. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +10 -0
  431. package/dist/storage/domains/knowledge/importers.d.ts +39 -0
  432. package/dist/storage/domains/knowledge/inmemory.d.ts +8 -0
  433. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +35 -1
  434. package/dist/storage/domains/knowledge/pages.d.ts +74 -0
  435. package/dist/storage/index.cjs +3 -3
  436. package/dist/storage/index.js +3 -3
  437. package/dist/storage/types.d.ts +14 -0
  438. package/dist/stream/index.cjs +2 -2
  439. package/dist/stream/index.js +2 -2
  440. package/dist/{stream-DoZ6F41o.js → stream-CG9OooRx.js} +37 -14
  441. package/dist/{stream-DQC1vpvl.cjs → stream-CMKRczs4.cjs} +37 -14
  442. package/dist/test-utils/llm-mock.cjs +1 -1
  443. package/dist/test-utils/llm-mock.js +1 -1
  444. package/dist/{to-prompt-B9eZo2U5.cjs → to-prompt-CG-LyaBY.cjs} +9 -0
  445. package/dist/{to-prompt-BsDtVXrf.js → to-prompt-CMlVGYxC.js} +9 -0
  446. package/dist/tool-loop-agent/index.cjs +1 -1
  447. package/dist/tool-loop-agent/index.js +1 -1
  448. package/dist/{tool-loop-agent-Cy4NDOMS.cjs → tool-loop-agent-14o3Z1qo.cjs} +4 -4
  449. package/dist/{tool-loop-agent-C9YkvDRd.js → tool-loop-agent-Bi6z_q7o.js} +4 -4
  450. package/dist/tools/code-mode/index.d.ts +2 -0
  451. package/dist/tools/code-mode/log-collector.d.ts +49 -0
  452. package/dist/tools/code-mode/types.d.ts +71 -0
  453. package/dist/tools/index.cjs +3 -1
  454. package/dist/tools/index.js +2 -2
  455. package/dist/{tools-CGF5Ik6j.cjs → tools-BEYxowf0.cjs} +429 -61
  456. package/dist/{tools-CDfyMpzN.js → tools-tPy2FwMI.js} +418 -62
  457. package/dist/{utils-Bs2IYyOb.cjs → utils-DkvbP8EA.cjs} +7 -6
  458. package/dist/{utils-9JyiKu5r.js → utils-Fag7YDBU.js} +7 -6
  459. package/dist/utils.cjs +1 -1
  460. package/dist/utils.js +1 -1
  461. package/dist/{validate-BE3mVxVy.cjs → validate-Bhrlve2E.cjs} +1 -1
  462. package/dist/{validate-8j0phWFV.js → validate-DLER0nlQ.js} +1 -1
  463. package/dist/vector/index.cjs +2 -2
  464. package/dist/vector/index.js +2 -2
  465. package/dist/worker/index.cjs +1 -1
  466. package/dist/worker/index.js +1 -1
  467. package/dist/worker/workers/orchestration-worker.d.ts +1 -0
  468. package/dist/{worker-DwdgU6E9.cjs → worker-0gczpztM.cjs} +2 -2
  469. package/dist/{worker-BiK1kfMa.cjs → worker-BwJyrFQN.cjs} +10 -4
  470. package/dist/{worker-BfWFqSH2.js → worker-D-em3hyS.js} +5 -5
  471. package/dist/{worker-DIRdEwih.js → worker-leYV1Y91.js} +2 -2
  472. package/dist/{workflow-CxQMcTbT.cjs → workflow-DWdcEcxw.cjs} +3 -3
  473. package/dist/{workflow-ni-keg2i.js → workflow-FikHVwog.js} +3 -3
  474. package/dist/workflows/builder/index.cjs +1 -1
  475. package/dist/workflows/builder/index.js +1 -1
  476. package/dist/workflows/evented/index.cjs +1 -1
  477. package/dist/workflows/evented/index.js +1 -1
  478. package/dist/workflows/index.cjs +4 -4
  479. package/dist/workflows/index.js +4 -4
  480. package/dist/workflows/step.d.ts +2 -0
  481. package/dist/workflows/workflow.d.ts +2 -0
  482. package/dist/workspace/index.cjs +3 -1
  483. package/dist/workspace/index.d.ts +1 -1
  484. package/dist/workspace/index.js +2 -2
  485. package/dist/workspace/lsp/manager.d.ts +19 -4
  486. package/dist/workspace/sandbox/mastra-sandbox.d.ts +17 -0
  487. package/dist/workspace/sandbox/teardown-context.d.ts +74 -0
  488. package/dist/workspace/tools/index.d.ts +1 -0
  489. package/dist/workspace/tools/media.d.ts +20 -1
  490. package/dist/workspace/tools/recreate-sandbox.d.ts +24 -0
  491. package/dist/{workspace-X2RHJZU9.cjs → workspace-C8Zo5_qK.cjs} +387 -109
  492. package/dist/{workspace-DY2Nxiyi.js → workspace-DOAil8mG.js} +376 -110
  493. package/package.json +6 -6
  494. package/src/llm/model/provider-types.generated.d.ts +8161 -8082
@@ -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-CMKRczs4.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-DAw2eouV.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-ChojUVJa.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-DSMHJM3c.cjs");
30
+ const require_utils$1 = require("./utils-DkvbP8EA.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-CDgdfRmB.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,
@@ -39150,6 +39202,29 @@ function knowledgePageKeyProblem(key) {
39150
39202
  if (!key) return "Knowledge page key must not be empty";
39151
39203
  if (/[/#%]/.test(key)) return `Knowledge page key "${key}" must not contain "/", "#" or "%"`;
39152
39204
  }
39205
+ const isRowWrite = (write) => write.op === "create" || write.op === "update" || write.op === "move" || write.op === "delete";
39206
+ /**
39207
+ * Throws unless the batch holds `applyPageWrites`' first rule: at most one create, one move and one
39208
+ * delete per page, no create, update or move of a page the batch deletes, and at most one write
39209
+ * per note (stores apply note removals before additions, so two writes of one note can't keep
39210
+ * input order).
39211
+ */
39212
+ function assertKnowledgePageWritesBatchable(writes) {
39213
+ const rows = /* @__PURE__ */ new Map();
39214
+ const notes = /* @__PURE__ */ new Map();
39215
+ for (const write of writes) {
39216
+ if (isRowWrite(write)) rows.set(write.id, [...rows.get(write.id) ?? [], write.op]);
39217
+ if ((write.op === "add-note" || write.op === "remove-note") && write.id !== void 0) {
39218
+ const seen = notes.get(write.id);
39219
+ if (seen !== void 0) throw new Error(`Knowledge page writes can't apply ${seen}, ${write.op} to note ${write.id} in one batch`);
39220
+ notes.set(write.id, write.op);
39221
+ }
39222
+ }
39223
+ for (const [id, ops] of rows) {
39224
+ const count = (op) => ops.filter((o) => o === op).length;
39225
+ if (count("create") > 1 || count("move") > 1 || count("delete") > 1 || count("delete") === 1 && ops.length > 1) throw new Error(`Knowledge page writes can't apply ${ops.join(", ")} to page ${id} in one batch`);
39226
+ }
39227
+ }
39153
39228
  // src/storage/domains/knowledge/pages.ts
39154
39229
  /**
39155
39230
  * Knowledge storage contract, schema 4: pages, notes, stamps, mentions, body links and pins.
@@ -39635,6 +39710,31 @@ var KnowledgeStorage = class extends require_filesystem_versioned.StorageDomain
39635
39710
  getPages(_input) {
39636
39711
  return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPages"));
39637
39712
  }
39713
+ /**
39714
+ * The page `parentId` and its ancestors, nearest first: for each row what {@link getPage} would
39715
+ * return with the same `read`, deleted rows included. Stops after the first scope page, before
39716
+ * the first row `getPage` would return null for, or after {@link MAX_KNOWLEDGE_PAGE_DEPTH} + 1
39717
+ * rows. Lets a caller holding a page walk its parents in one call instead of one per level.
39718
+ *
39719
+ * The base class reads one {@link getPage} per level; adapters that can read the chain in one
39720
+ * query override it.
39721
+ *
39722
+ * @experimental
39723
+ */
39724
+ async getPageParents(input) {
39725
+ const parents = [];
39726
+ let id = input.parentId;
39727
+ while (id && parents.length <= 10) {
39728
+ const page = await this.getPage({
39729
+ id,
39730
+ read: input.read
39731
+ });
39732
+ if (!page) break;
39733
+ parents.push(page);
39734
+ id = page.isScope ? null : page.parentId;
39735
+ }
39736
+ return parents;
39737
+ }
39638
39738
  getPageByPath(_input) {
39639
39739
  return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPageByPath"));
39640
39740
  }
@@ -39952,10 +40052,20 @@ var InMemoryKnowledgeImportersStorage = class extends KnowledgeImportersStorage
39952
40052
  const node = this.#s.nodes.get(key(bindingId, sourceId));
39953
40053
  return node ? structuredClone(node) : null;
39954
40054
  }
40055
+ async getNodes(bindingId, sourceIds) {
40056
+ return [...new Set(sourceIds)].flatMap((sourceId) => {
40057
+ const node = this.#s.nodes.get(key(bindingId, sourceId));
40058
+ return node ? [structuredClone(node)] : [];
40059
+ });
40060
+ }
39955
40061
  async getNodeByPage(pageId) {
39956
40062
  const node = [...this.#s.nodes.values()].find((n) => n.pageId === pageId);
39957
40063
  return node ? structuredClone(node) : null;
39958
40064
  }
40065
+ async getNodesByPages(pageIds) {
40066
+ const pages = new Set(pageIds);
40067
+ return [...this.#s.nodes.values()].filter((n) => pages.has(n.pageId)).map((n) => structuredClone(n));
40068
+ }
39959
40069
  async saveNode(node) {
39960
40070
  const owner = [...this.#s.nodes.values()].find((n) => n.pageId === node.pageId);
39961
40071
  if (owner && (owner.bindingId !== node.bindingId || owner.sourceId !== node.sourceId)) throw new Error(`Knowledge page ${node.pageId} is already mapped to another imported node`);
@@ -39967,6 +40077,22 @@ var InMemoryKnowledgeImportersStorage = class extends KnowledgeImportersStorage
39967
40077
  async deleteNode(bindingId, sourceId) {
39968
40078
  this.#s.nodes.delete(key(bindingId, sourceId));
39969
40079
  }
40080
+ async writeNodes(input) {
40081
+ const next = new Map(this.#s.nodes);
40082
+ for (const d of input.deletes) next.delete(key(d.bindingId, d.sourceId));
40083
+ const updatedAt = /* @__PURE__ */ new Date();
40084
+ for (const node of input.saves) next.set(key(node.bindingId, node.sourceId), structuredClone({
40085
+ ...node,
40086
+ updatedAt
40087
+ }));
40088
+ const byPage = /* @__PURE__ */ new Map();
40089
+ for (const [k, node] of next) {
40090
+ const other = byPage.get(node.pageId);
40091
+ if (other !== void 0 && other !== k) throw new Error(`Knowledge page ${node.pageId} is already mapped to another imported node`);
40092
+ byPage.set(node.pageId, k);
40093
+ }
40094
+ this.#s.nodes = next;
40095
+ }
39970
40096
  async listNodes(bindingId, options = {}) {
39971
40097
  const limit = options.limit ?? 500;
39972
40098
  const nodes = [...this.#s.nodes.values()].filter((n) => n.bindingId === bindingId && (options.after === void 0 || byteOrder(n.sourceId, options.after) > 0) && (!options.unsettled || n.unsettled)).sort((a, b) => byteOrder(a.sourceId, b.sourceId));
@@ -40019,6 +40145,9 @@ var InMemoryKnowledgeImportersStorage = class extends KnowledgeImportersStorage
40019
40145
  change: structuredClone(change)
40020
40146
  });
40021
40147
  }
40148
+ async recordRunChanges(changes) {
40149
+ for (const change of changes) await this.recordRunChange(change);
40150
+ }
40022
40151
  async listRunChanges(runId, options = {}) {
40023
40152
  const limit = options.limit ?? 500;
40024
40153
  const after = options.after === void 0 ? 0 : Number(options.after);
@@ -40342,6 +40471,15 @@ var InMemoryKnowledgePageStore = class {
40342
40471
  const page = this.#pages.get(input.id);
40343
40472
  return page && this.#pageReadable(page, input.read) ? clone$1(page) : null;
40344
40473
  }
40474
+ async getPageParents(input) {
40475
+ const parents = [];
40476
+ let page = this.#pages.get(input.parentId);
40477
+ while (page && this.#pageReadable(page, input.read) && parents.length <= 10) {
40478
+ parents.push(clone$1(page));
40479
+ page = page.isScope || !page.parentId ? void 0 : this.#pages.get(page.parentId);
40480
+ }
40481
+ return parents;
40482
+ }
40345
40483
  async getPages(input) {
40346
40484
  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
40485
  }
@@ -40355,10 +40493,53 @@ var InMemoryKnowledgePageStore = class {
40355
40493
  }
40356
40494
  return page && this.#pageReadable(page, input.read) ? clone$1(page) : null;
40357
40495
  }
40496
+ async getPageChains(input) {
40497
+ const ids = [...new Set(input.ids)];
40498
+ const chains = await Promise.all(ids.map((id) => this.getPageParents({
40499
+ parentId: id,
40500
+ read: input.read
40501
+ })));
40502
+ return Object.fromEntries(ids.map((id, i) => [id, chains[i]]));
40503
+ }
40504
+ async getPagesByPaths(input) {
40505
+ return Promise.all(input.paths.map((path) => this.getPageByPath({
40506
+ scopeId: input.scopeId,
40507
+ path,
40508
+ read: input.read
40509
+ })));
40510
+ }
40511
+ async getLastChildPositions(input) {
40512
+ return Object.fromEntries([...new Set(input.parentIds)].map((id) => [id, this.#children(id).sort(byPosition).at(-1)?.position ?? null]));
40513
+ }
40514
+ async getPageSubtrees(input) {
40515
+ const out = Object.fromEntries(input.rootIds.map((id) => [id, null]));
40516
+ for (const rootId of new Set(input.rootIds)) {
40517
+ const pages = [];
40518
+ for (let i = -1; i < pages.length && pages.length <= input.limit; i++) {
40519
+ const parentId = i < 0 ? rootId : pages[i].id;
40520
+ pages.push(...this.#children(parentId).filter((page) => !page.isScope));
40521
+ }
40522
+ out[rootId] = pages.length > input.limit ? null : pages.map(clone$1);
40523
+ }
40524
+ return out;
40525
+ }
40526
+ async listNotesByPages(input) {
40527
+ const notes = Object.fromEntries([...new Set(input.pageIds)].map((id) => [id, []]));
40528
+ for (const note of [...this.#notes.values()].sort(oldestFirst)) if (Object.hasOwn(notes, note.pageId) && !note.deletedAt && this.#noteVisible(note, input.read)) notes[note.pageId].push(clone$1(note));
40529
+ return notes;
40530
+ }
40358
40531
  async findPagesByName(input) {
40359
40532
  const name = canonicalKnowledgeName(input.name);
40360
40533
  return [...this.#pages.values()].filter((page) => !page.deletedAt && canonicalKnowledgeName(page.name) === name && (input.scopeId === void 0 || page.scopeId === input.scopeId) && this.#pageReadable(page, input.read)).sort(newestFirst).slice(0, pageSize(input.limit)).map(clone$1);
40361
40534
  }
40535
+ async findPagesByNames(input) {
40536
+ const names = [...new Set(input.names)];
40537
+ const found = await Promise.all(names.map((name) => this.findPagesByName({
40538
+ ...input,
40539
+ name
40540
+ })));
40541
+ return Object.fromEntries(names.map((name, i) => [name, found[i]]));
40542
+ }
40362
40543
  async listChildPages(input) {
40363
40544
  const { items, nextCursor } = paginate(this.#children(input.parentId).filter((page) => !page.isScope && this.#pageReadable(page, input.read)).sort(byPosition), input.cursor, input.limit);
40364
40545
  return {
@@ -40454,6 +40635,63 @@ var InMemoryKnowledgePageStore = class {
40454
40635
  ...nextCursor ? { nextCursor } : {}
40455
40636
  };
40456
40637
  }
40638
+ /** The single writes, one by one in input order; all undone if one fails. */
40639
+ async applyPageWrites(input) {
40640
+ assertKnowledgePageWritesBatchable(input.writes);
40641
+ const before = this.snapshot();
40642
+ try {
40643
+ for (const write of input.writes) switch (write.op) {
40644
+ case "create": {
40645
+ const { op: _op, scopeId: _scope, depth: _depth, ...create } = write;
40646
+ await this.createPage(create);
40647
+ break;
40648
+ }
40649
+ case "update": {
40650
+ const { op: _op, scopeId: _scope, ...update } = write;
40651
+ await this.updatePage(update);
40652
+ break;
40653
+ }
40654
+ case "move": {
40655
+ const { op: _op, scopeId: _scope, fromScopeId: _from, depth: _depth, ...move } = write;
40656
+ await this.movePage(move);
40657
+ break;
40658
+ }
40659
+ case "delete":
40660
+ await this.deletePage({
40661
+ id: write.id,
40662
+ expectedVersion: write.expectedVersion,
40663
+ deletedBy: write.deletedBy
40664
+ });
40665
+ break;
40666
+ case "add-note": {
40667
+ const { op: _op, scopeId: _scope, ...note } = write;
40668
+ await this.addNote(note);
40669
+ break;
40670
+ }
40671
+ case "remove-note": {
40672
+ const note = await this.getNote({
40673
+ id: write.id,
40674
+ read: "all",
40675
+ includeDeleted: true
40676
+ });
40677
+ if (note && note.pageId !== write.pageId) throw new KnowledgeConflictError(write.id);
40678
+ await this.removeNote({
40679
+ id: write.id,
40680
+ deletedBy: write.deletedBy,
40681
+ provenance: write.provenance
40682
+ });
40683
+ break;
40684
+ }
40685
+ case "replace-links": await this.replacePageBodyLinks({
40686
+ pageId: write.pageId,
40687
+ links: write.links
40688
+ });
40689
+ }
40690
+ } catch (error) {
40691
+ this.restore(before);
40692
+ throw error;
40693
+ }
40694
+ }
40457
40695
  async createPage(input) {
40458
40696
  const parent = this.#livePage(input.parentId);
40459
40697
  const scopeId = parent.isScope ? parent.id : parent.scopeId;
@@ -40849,6 +41087,27 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40849
41087
  getPage(input) {
40850
41088
  return this.#pageStore.getPage(input);
40851
41089
  }
41090
+ getPageParents(input) {
41091
+ return this.#pageStore.getPageParents(input);
41092
+ }
41093
+ getPageChains(input) {
41094
+ return this.#pageStore.getPageChains(input);
41095
+ }
41096
+ getPagesByPaths(input) {
41097
+ return this.#pageStore.getPagesByPaths(input);
41098
+ }
41099
+ getLastChildPositions(input) {
41100
+ return this.#pageStore.getLastChildPositions(input);
41101
+ }
41102
+ getPageSubtrees(input) {
41103
+ return this.#pageStore.getPageSubtrees(input);
41104
+ }
41105
+ listNotesByPages(input) {
41106
+ return this.#pageStore.listNotesByPages(input);
41107
+ }
41108
+ applyPageWrites(input) {
41109
+ return this.#pageStore.applyPageWrites(input);
41110
+ }
40852
41111
  listScopeDeclarations() {
40853
41112
  return this.#pageStore.listScopeDeclarations();
40854
41113
  }
@@ -40861,6 +41120,9 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40861
41120
  getPageByPath(input) {
40862
41121
  return this.#pageStore.getPageByPath(input);
40863
41122
  }
41123
+ findPagesByNames(input) {
41124
+ return this.#pageStore.findPagesByNames(input);
41125
+ }
40864
41126
  findPagesByName(input) {
40865
41127
  return this.#pageStore.findPagesByName(input);
40866
41128
  }
@@ -47890,6 +48152,32 @@ function chunkToFallbackMessage(chunk) {
47890
48152
  if (chunk.type === "plan_update") return chunk.title && chunk.title.length > 0 ? chunk.title : null;
47891
48153
  return null;
47892
48154
  }
48155
+ /** Whitespace plus the meaningful joiners ZWNJ (U+200C) and ZWJ (U+200D). */
48156
+ const EDGE_PADDING = /[\s\u200C\u200D]/;
48157
+ /**
48158
+ * Sanitize a buffered channel reply before posting.
48159
+ *
48160
+ * Zero-width space (U+200B) and the byte-order mark (U+FEFF) are invisible
48161
+ * padding and are removed everywhere. Whitespace and the joiners ZWNJ
48162
+ * (U+200C) / ZWJ (U+200D) are trimmed only at the edges, so internal joiners
48163
+ * in compound emoji (🏄🏼‍♂️, 👨‍👩‍👧) and scripts such as Persian (می‌خواهم)
48164
+ * survive — the bug behind #31205. Invisible-only input collapses to '' so
48165
+ * callers skip posting it entirely.
48166
+ *
48167
+ * The edge trim is a single-pass scan rather than
48168
+ * `.replace(/^[\s\u200C\u200D]+|[\s\u200C\u200D]+$/g, '')`: that anchored
48169
+ * alternation backtracks quadratically over a long interior run of the class
48170
+ * (a 300k-character run of model-controlled output took ~80s), while this
48171
+ * scan is O(n).
48172
+ */
48173
+ function cleanBufferedText(input) {
48174
+ const stripped = input.replace(/[\u200B\uFEFF]/g, "");
48175
+ let start = 0;
48176
+ let end = stripped.length;
48177
+ while (start < end && EDGE_PADDING.test(stripped.charAt(start))) start++;
48178
+ while (end > start && EDGE_PADDING.test(stripped.charAt(end - 1))) end--;
48179
+ return start === 0 && end === stripped.length ? stripped : stripped.slice(start, end);
48180
+ }
47893
48181
  // src/channels/chat-driver-static.ts
47894
48182
  /**
47895
48183
  * Static (non-streaming) driver: consumes `AgentChunkType<any>` chunks and
@@ -47934,7 +48222,7 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47934
48222
  let textBuffer = "";
47935
48223
  const toolMessageIds = /* @__PURE__ */ new Map();
47936
48224
  const flushText = async () => {
47937
- const cleaned = textBuffer.replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
48225
+ const cleaned = cleanBufferedText(textBuffer);
47938
48226
  if (cleaned) try {
47939
48227
  await chatThread.post(textFormat === "plain" ? cleaned : { markdown: cleaned });
47940
48228
  } catch (e) {
@@ -48269,7 +48557,7 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
48269
48557
  if (closed) break;
48270
48558
  await waitForNext();
48271
48559
  }
48272
- const cleaned = fallback.replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
48560
+ const cleaned = cleanBufferedText(fallback);
48273
48561
  if (cleaned) try {
48274
48562
  await chatThread.post(textFormat === "plain" ? cleaned : { markdown: cleaned });
48275
48563
  } catch (postErr) {
@@ -48752,6 +49040,20 @@ const TEXT_CHUNK_TYPES = /* @__PURE__ */ new Set([
48752
49040
  /** Key the processor reads off `requestContext` to locate its render deps. */
48753
49041
  const CHAT_CHANNEL_RENDER_CONTEXT_KEY = "__mastra_chat_channel_render";
48754
49042
  /**
49043
+ * Whether a `requestContext` entry is a live render context rather than the
49044
+ * method-less husk a JSON snapshot round-trip leaves behind (issue #31310).
49045
+ * `wrapStream` is the first method the session calls, so its presence is the
49046
+ * signal that the object is usable.
49047
+ *
49048
+ * Every reader that treats a stashed render context as a live object (the
49049
+ * output processor, `resolveChannelRenderContext`, `AgentChannels.resolveRunRender`
49050
+ * and the generative-UI processor) guards with this, so a husk on a replica's
49051
+ * restored `requestContext` always falls through to a rebuild from the thread.
49052
+ */
49053
+ function isUsableRenderContext(value) {
49054
+ return typeof value === "object" && value !== null && typeof value.wrapStream === "function";
49055
+ }
49056
+ /**
48755
49057
  * Single-producer / single-consumer async queue. The processor pushes chunks
48756
49058
  * synchronously from `processOutputStream`; the driver consumes them via the
48757
49059
  * async iterable. `close()` ends the iteration after pending items are drained.
@@ -48885,7 +49187,7 @@ var ChatChannelOutputProcessor = class {
48885
49187
  async #resolveRenderContext(state, requestContext) {
48886
49188
  if (state.render !== void 0) return state.render;
48887
49189
  const fromRequest = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
48888
- if (fromRequest) {
49190
+ if (isUsableRenderContext(fromRequest)) {
48889
49191
  state.render = fromRequest;
48890
49192
  return fromRequest;
48891
49193
  }
@@ -49058,7 +49360,7 @@ var ChatChannelGenerativeUIProcessor = class {
49058
49360
  }
49059
49361
  async #resolve(requestContext, state) {
49060
49362
  const inbound = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
49061
- if (inbound) return inbound;
49363
+ if (isUsableRenderContext(inbound)) return inbound;
49062
49364
  if (state && "render" in state) return state.render ?? void 0;
49063
49365
  const threadId = require_stream.parseMemoryRequestContext(requestContext)?.thread?.id;
49064
49366
  const render = threadId && this.#channels ? await this.#channels.buildRenderContextForThread(threadId) : null;
@@ -49212,6 +49514,8 @@ async function headContentType(url, logger) {
49212
49514
  }
49213
49515
  }
49214
49516
  // src/channels/processor.ts
49517
+ /** Per-run `state` key caching a thread's display mode recovered without a render context. */
49518
+ const RECOVERED_DISPLAY_KEY = "threadTextHidden";
49215
49519
  /**
49216
49520
  * Input processor that injects channel context (platform, bot identity, DM vs.
49217
49521
  * public-channel guidance) into the agent's system prompt on every step.
@@ -49245,19 +49549,37 @@ var ChatChannelProcessor = class {
49245
49549
  }
49246
49550
  async #resolve(requestContext, state) {
49247
49551
  const channel = requestContext?.get("channel");
49248
- if (channel) return {
49249
- channel,
49250
- textHidden: (requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY))?.textDisplay === "hidden"
49251
- };
49552
+ if (channel) {
49553
+ const render = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
49554
+ return {
49555
+ channel,
49556
+ textHidden: isUsableRenderContext(render) ? render.textDisplay === "hidden" : await this.#recoverTextHidden(requestContext, state)
49557
+ };
49558
+ }
49252
49559
  if (state && "thread" in state) return state.thread ?? void 0;
49560
+ const resolved = await this.#resolveThread(requestContext);
49561
+ if (state) state.thread = resolved;
49562
+ return resolved ?? void 0;
49563
+ }
49564
+ /** The channel-backed context of the run's memory thread, or `null` when it has none. */
49565
+ async #resolveThread(requestContext) {
49253
49566
  const threadId = require_stream.parseMemoryRequestContext(requestContext)?.thread?.id;
49254
49567
  const found = threadId && this.#channels ? await this.#channels.buildChannelContextForThread(threadId) : null;
49255
- const resolved = found ? {
49568
+ return found ? {
49256
49569
  channel: found.channel,
49257
49570
  textHidden: found.render.textDisplay === "hidden"
49258
49571
  } : null;
49259
- if (state) state.thread = resolved;
49260
- return resolved ?? void 0;
49572
+ }
49573
+ /**
49574
+ * Display mode of a channel-backed thread whose render context is no longer on the
49575
+ * restored request context. Cached per run like the thread lookup above, so later
49576
+ * steps of the same run read the thread once.
49577
+ */
49578
+ async #recoverTextHidden(requestContext, state) {
49579
+ if (state && RECOVERED_DISPLAY_KEY in state) return state[RECOVERED_DISPLAY_KEY] === true;
49580
+ const textHidden = (await this.#resolveThread(requestContext))?.textHidden ?? false;
49581
+ if (state) state[RECOVERED_DISPLAY_KEY] = textHidden;
49582
+ return textHidden;
49261
49583
  }
49262
49584
  };
49263
49585
  function channelLines(ctx, textHidden, tools) {
@@ -49780,15 +50102,17 @@ var ChannelReplyModeProcessor = class {
49780
50102
  var MastraStateAdapter = class {
49781
50103
  memoryStore;
49782
50104
  getOwnerId;
50105
+ logger;
49783
50106
  connected = false;
49784
50107
  connectPromise = null;
49785
50108
  cache = /* @__PURE__ */ new Map();
49786
50109
  locks = /* @__PURE__ */ new Map();
49787
50110
  lists = /* @__PURE__ */ new Map();
49788
50111
  queues = /* @__PURE__ */ new Map();
49789
- constructor(memoryStore, getOwnerId) {
50112
+ constructor(memoryStore, getOwnerId, logger) {
49790
50113
  this.memoryStore = memoryStore;
49791
50114
  this.getOwnerId = getOwnerId;
50115
+ this.logger = logger;
49792
50116
  }
49793
50117
  async connect() {
49794
50118
  if (this.connected) return;
@@ -49807,7 +50131,10 @@ var MastraStateAdapter = class {
49807
50131
  }
49808
50132
  async subscribe(threadId) {
49809
50133
  const thread = await this.findThreadByExternalId(threadId);
49810
- if (!thread) return;
50134
+ if (!thread) {
50135
+ this.logger?.warn(`subscribe(${threadId}) ignored: no Mastra thread is mapped to this chat thread. Use AgentChannels.subscribeThread() for threads the bot started itself.`);
50136
+ return;
50137
+ }
49811
50138
  await this.memoryStore.patchThread({
49812
50139
  id: thread.id,
49813
50140
  metadata: {
@@ -50199,7 +50526,7 @@ function formatLegacyHistoryBlock(history, chatThread, platform) {
50199
50526
  async function resolveChannelRenderContext(requestContext, channels) {
50200
50527
  if (!requestContext) return void 0;
50201
50528
  const stashed = requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
50202
- if (stashed) return stashed;
50529
+ if (isUsableRenderContext(stashed)) return stashed;
50203
50530
  const threadId = requestContext.get("controller")?.threadId ?? require_stream.parseMemoryRequestContext(requestContext)?.thread?.id;
50204
50531
  if (!threadId) return void 0;
50205
50532
  return await channels?.()?.buildRenderContextForThread(threadId) ?? void 0;
@@ -50643,7 +50970,7 @@ var AgentChannels = class {
50643
50970
  const storage = mastra.getStorage();
50644
50971
  const memoryStore = storage ? await storage.getStore("memory") : void 0;
50645
50972
  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());
50973
+ this.stateAdapter = new MastraStateAdapter(memoryStore, () => this.getOwnerId(), this.logger);
50647
50974
  this.log("info", "Using MastraStateAdapter (subscriptions persist across restarts)");
50648
50975
  }
50649
50976
  const { Chat, Message: ChatMessage, ThreadImpl } = await getChatModule();
@@ -50871,25 +51198,30 @@ var AgentChannels = class {
50871
51198
  runId = stashed.runId;
50872
51199
  toolName = stashed.toolName;
50873
51200
  toolArgs = stashed.args;
50874
- } else {
51201
+ }
51202
+ if (!requesterId) {
50875
51203
  const { result: lookup } = await this.lookupPersistedApproval({
50876
51204
  mastra,
50877
51205
  card,
50878
51206
  platform
50879
51207
  });
50880
- if (lookup.status === "answered") {
50881
- this.log("info", "Tool approval already answered", actionEventContext);
50882
- return;
51208
+ if (!stashed?.runId) {
51209
+ if (lookup.status === "answered") {
51210
+ this.log("info", "Tool approval already answered", actionEventContext);
51211
+ return;
51212
+ }
51213
+ if (lookup.status === "pending") {
51214
+ runId = lookup.runId;
51215
+ toolName = lookup.toolName;
51216
+ toolArgs = lookup.args;
51217
+ }
50883
51218
  }
50884
51219
  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) {
51220
+ if (adapterConfig?.toolApprovers !== "anyone" && lookup.authors.length > 1) {
50889
51221
  this.log("info", "Ignoring tool approval action: requester is ambiguous", actionEventContext);
50890
51222
  return;
50891
51223
  }
50892
- requesterId ??= lookup.authors[0];
51224
+ requesterId = lookup.authors[0];
50893
51225
  }
50894
51226
  }
50895
51227
  if (!runId) {
@@ -51194,7 +51526,7 @@ var AgentChannels = class {
51194
51526
  */
51195
51527
  async resolveRunRender(requestContext, state) {
51196
51528
  const inbound = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
51197
- if (inbound) return inbound;
51529
+ if (isUsableRenderContext(inbound)) return inbound;
51198
51530
  if (state && "render" in state) return state.render ?? void 0;
51199
51531
  const render = await resolveChannelRenderContext(requestContext, () => this);
51200
51532
  if (state) state.render = render ?? null;
@@ -51223,8 +51555,8 @@ var AgentChannels = class {
51223
51555
  const has = (id) => configuredProcessors.some((p) => !require_stream.isProcessorWorkflow(p) && p.id === id);
51224
51556
  const processors = [];
51225
51557
  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);
51558
+ const platform = requestContext.get("channel")?.platform ?? requestContext.get("__mastra_chat_channel_render")?.platform;
51559
+ return platform ? threadLinkOptions(this.adapterConfigs[platform]?.threadLink) : void 0;
51228
51560
  }));
51229
51561
  if (!has("chat-channel-render")) processors.push(new ChatChannelOutputProcessor(this));
51230
51562
  if (this.replyModeEnabled && !has(REPLY_STREAM_PROCESSOR_ID)) processors.push(new ChannelReplyStreamProcessor((requestContext) => this.resolveRunRender(requestContext)));
@@ -52406,6 +52738,36 @@ var AgentChannels = class {
52406
52738
  };
52407
52739
  }
52408
52740
  /**
52741
+ * Map a chat thread to a Mastra thread (creating the mapping if needed) and
52742
+ * subscribe to it, so follow-up replies reach the agent without a mention.
52743
+ *
52744
+ * Use this for threads the bot started itself, e.g. a scheduled digest posted
52745
+ * to Slack. Inbound messages create the mapping automatically, but a thread
52746
+ * the bot opened has none until someone mentions it. An existing mapping is
52747
+ * reused and keeps its original owner.
52748
+ *
52749
+ * @example
52750
+ * ```ts
52751
+ * const sent = await channel.post('Daily digest');
52752
+ * await agent.getChannels()!.subscribeThread({ thread: sent.thread, resourceId: 'digest-bot' });
52753
+ * ```
52754
+ */
52755
+ async subscribeThread({ thread, resourceId, threadId }) {
52756
+ const mastra = this.getMastra();
52757
+ if (!mastra) throw new Error("subscribeThread requires the agent to be registered with a Mastra instance.");
52758
+ await this.initialize(mastra);
52759
+ const mastraThread = await this.getOrCreateThread({
52760
+ externalThreadId: thread.id,
52761
+ channelId: thread.channelId,
52762
+ platform: thread.adapter.name,
52763
+ resourceId,
52764
+ threadId: threadId ? () => threadId : void 0,
52765
+ mastra
52766
+ });
52767
+ await this.stateAdapter.subscribe(thread.id);
52768
+ return mastraThread;
52769
+ }
52770
+ /**
52409
52771
  * Resolves an existing Mastra thread for the given external IDs, or creates one.
52410
52772
  */
52411
52773
  async getOrCreateThread({ externalThreadId, channelId, platform, resourceId, threadId, onCreate, mastra }) {
@@ -52633,6 +52995,132 @@ function withReplyModeDefaults(cfg) {
52633
52995
  ...set
52634
52996
  };
52635
52997
  }
52998
+ // src/knowledge/held-scopes-state-processor.ts
52999
+ const HELD_SCOPES_STATE_ID = "knowledge-scopes";
53000
+ const HELD_SCOPES_SNAPSHOT_TAG = "knowledge-scopes";
53001
+ const HELD_SCOPES_DELTA_TAG = "knowledge-scopes-update";
53002
+ function lp$1(value) {
53003
+ return `${value.length}:${value}`;
53004
+ }
53005
+ function fingerprint$1(scope) {
53006
+ return `${lp$1(scope.address)}${lp$1(scope.role)}`;
53007
+ }
53008
+ function cacheKey(scopes) {
53009
+ return `scopes:${scopes.map(fingerprint$1).join("|")}`;
53010
+ }
53011
+ function scopesFromSnapshot(snapshot) {
53012
+ const value = (snapshot?.metadata)?.value?.scopes;
53013
+ return Array.isArray(value) ? value : [];
53014
+ }
53015
+ function opsFromDelta(delta) {
53016
+ const ops = delta.metadata?.delta?.ops;
53017
+ return Array.isArray(ops) ? ops : [];
53018
+ }
53019
+ function applyOps(scopes, ops) {
53020
+ const next = scopes.slice();
53021
+ for (const op of ops) {
53022
+ const address = op.op === "remove" ? op.address : op.scope.address;
53023
+ const idx = next.findIndex((scope) => scope.address === address);
53024
+ if (op.op === "remove") {
53025
+ if (idx >= 0) next.splice(idx, 1);
53026
+ } else if (idx >= 0) next[idx] = op.scope;
53027
+ else next.push(op.scope);
53028
+ }
53029
+ return next;
53030
+ }
53031
+ function diffScopes(prior, current) {
53032
+ const ops = [];
53033
+ const before = new Map(prior.map((scope) => [scope.address, fingerprint$1(scope)]));
53034
+ const currentAddresses = new Set(current.map((scope) => scope.address));
53035
+ for (const scope of prior) if (!currentAddresses.has(scope.address)) ops.push({
53036
+ op: "remove",
53037
+ address: scope.address
53038
+ });
53039
+ for (const scope of current) {
53040
+ const was = before.get(scope.address);
53041
+ if (was === void 0) ops.push({
53042
+ op: "add",
53043
+ scope
53044
+ });
53045
+ else if (was !== fingerprint$1(scope)) ops.push({
53046
+ op: "change",
53047
+ scope
53048
+ });
53049
+ }
53050
+ return ops;
53051
+ }
53052
+ function line(scope) {
53053
+ return `${scope.address} (${scope.role})`;
53054
+ }
53055
+ function renderSnapshot(scopes) {
53056
+ if (scopes.length === 0) return "\n Your session holds no Knowledge scopes.\n";
53057
+ return `\n Your session has access to:\n${scopes.map((scope) => ` - ${line(scope)}`).join("\n")}\n`;
53058
+ }
53059
+ function renderDelta$1(ops) {
53060
+ return `\n${ops.map((op) => {
53061
+ if (op.op === "remove") return ` - ${op.address} was removed from your scopes`;
53062
+ if (op.op === "change") return ` ~ ${op.scope.address} role changed to ${op.scope.role}`;
53063
+ return ` + ${line(op.scope)}`;
53064
+ }).join("\n")}\n`;
53065
+ }
53066
+ var HeldScopesStateProcessor = class {
53067
+ deps;
53068
+ id = HELD_SCOPES_STATE_ID;
53069
+ stateId = HELD_SCOPES_STATE_ID;
53070
+ constructor(deps) {
53071
+ this.deps = deps;
53072
+ }
53073
+ processInput(args) {
53074
+ return {
53075
+ messages: args.messages,
53076
+ systemMessages: [...args.systemMessages, {
53077
+ role: "system",
53078
+ 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.`
53079
+ }]
53080
+ };
53081
+ }
53082
+ async computeStateSignal(args) {
53083
+ const context = {
53084
+ requestContext: args.requestContext,
53085
+ agent: {
53086
+ resourceId: args.resourceId,
53087
+ threadId: args.threadId
53088
+ }
53089
+ };
53090
+ if (await this.deps.principalsKey(context) === void 0) return;
53091
+ const current = await this.deps.readHeldScopes(context);
53092
+ let prior = scopesFromSnapshot(args.lastSnapshot);
53093
+ for (const delta of args.deltasSinceSnapshot ?? []) prior = applyOps(prior, opsFromDelta(delta));
53094
+ const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;
53095
+ const ops = diffScopes(prior, current);
53096
+ if (ops.length === 0 && hasBase) return;
53097
+ if (!hasBase || current.length === 0) {
53098
+ if (!hasBase && current.length === 0) return;
53099
+ return {
53100
+ id: HELD_SCOPES_STATE_ID,
53101
+ mode: "snapshot",
53102
+ cacheKey: cacheKey(current),
53103
+ tagName: HELD_SCOPES_SNAPSHOT_TAG,
53104
+ contents: renderSnapshot(current),
53105
+ value: { scopes: current },
53106
+ metadata: { value: { scopes: current } }
53107
+ };
53108
+ }
53109
+ return {
53110
+ id: HELD_SCOPES_STATE_ID,
53111
+ mode: "delta",
53112
+ cacheKey: cacheKey(current),
53113
+ tagName: HELD_SCOPES_DELTA_TAG,
53114
+ contents: renderDelta$1(ops),
53115
+ value: { scopes: current },
53116
+ delta: { ops },
53117
+ metadata: {
53118
+ value: { scopes: current },
53119
+ delta: { ops }
53120
+ }
53121
+ };
53122
+ }
53123
+ };
52636
53124
  // src/knowledge/instructions.ts
52637
53125
  function readInstructions(canEdit) {
52638
53126
  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 +53411,16 @@ function compileKnowledgeScopes(declarations) {
52923
53411
  const concreteEntries = [];
52924
53412
  for (const [key, declaration] of Object.entries(declarations)) {
52925
53413
  const pattern = parsePattern(key, "Knowledge scope key");
53414
+ if (declaration.mint !== void 0) {
53415
+ 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'.`);
53416
+ for (const param of pattern.params) if (![
53417
+ "agentId",
53418
+ "orgId",
53419
+ "resourceId",
53420
+ "role",
53421
+ "teamId"
53422
+ ].includes(param)) throw new KnowledgeDeclarationError(`Knowledge scope "${key}" cannot mint unknown parameter $${param}.`);
53423
+ }
52926
53424
  if (pattern.params.length === 0) {
52927
53425
  concreteEntries.push([key, declaration]);
52928
53426
  continue;
@@ -53386,22 +53884,28 @@ async function syncKnowledgePageBodyLinks(storage, page, resolver = new BodyLink
53386
53884
  }
53387
53885
  /** The ref keys a page answers to now: its id, name, scope address and `scope#key/key` path. */
53388
53886
  async function pageRefKeys(storage, page) {
53887
+ return refKeysOf(page, !page.isScope && page.key && page.parentId ? await storage.getPageParents({
53888
+ parentId: page.parentId,
53889
+ read: "all"
53890
+ }) : []);
53891
+ }
53892
+ /** {@link pageRefKeys} from the page's parents as `getPageParents` gives them. */
53893
+ function refKeysOf(page, parents) {
53389
53894
  const keys = [knowledgeLinkRefKey(page.id), knowledgeLinkRefKey(page.name)];
53390
53895
  if (page.isScope) {
53391
53896
  if (page.address) keys.push(knowledgeLinkRefKey(page.address));
53392
53897
  return keys;
53393
53898
  }
53899
+ if (!page.key || !page.parentId) return keys;
53394
53900
  const path = [];
53395
- let current = page;
53396
- while (current && !current.isScope) {
53901
+ for (const current of [page, ...parents]) {
53902
+ if (current.isScope) {
53903
+ if (current.address) keys.push(knowledgeLinkRefKey(`${current.address}#${path.join("/")}`));
53904
+ return keys;
53905
+ }
53397
53906
  if (!current.key || !current.parentId) return keys;
53398
53907
  path.unshift(current.key);
53399
- current = await storage.getPage({
53400
- id: current.parentId,
53401
- read: "all"
53402
- });
53403
53908
  }
53404
- if (current?.address) keys.push(knowledgeLinkRefKey(`${current.address}#${path.join("/")}`));
53405
53909
  return keys;
53406
53910
  }
53407
53911
  /** The page and its live ordinary descendants, at most {@link MAX_KNOWLEDGE_MOVE_PAGES} + 1. */
@@ -53543,6 +54047,203 @@ async function reindexKnowledgeLinks(storage) {
53543
54047
  } while (cursor);
53544
54048
  return count;
53545
54049
  }
54050
+ /**
54051
+ * A batched link repair that would stop at a cap the op-by-op refreshes enforce one write at a time
54052
+ * (linking pages, namesakes, refs looked up, subtree size): the caller saves op by op instead, so the
54053
+ * caps apply exactly as they do there.
54054
+ */
54055
+ var KnowledgeLinkRepairUnsupportedError = class extends Error {
54056
+ reason;
54057
+ constructor(reason) {
54058
+ super(`batched link repair: ${reason}`);
54059
+ this.reason = reason;
54060
+ this.name = "KnowledgeLinkRepairUnsupportedError";
54061
+ }
54062
+ };
54063
+ /** True when the store has every set-based read and write {@link repairKnowledgeLinks} uses. */
54064
+ function canRepairKnowledgeLinksInBatch(storage) {
54065
+ return !!(storage.getPageChains && storage.getPagesByPaths && storage.getPageSubtrees && storage.findPagesByNames && storage.applyPageWrites);
54066
+ }
54067
+ /**
54068
+ * Every {@link syncKnowledgePageBodyLinks} and {@link refreshKnowledgeLinksTo} of a flush, run once
54069
+ * over the store as the flush left it, in a fixed number of statements: each page's links come out
54070
+ * as they do when the calls run one after another after the writes. Throws
54071
+ * {@link KnowledgeLinkRepairUnsupportedError}, having written nothing, when a cap could bite.
54072
+ */
54073
+ async function repairKnowledgeLinks(storage, repair) {
54074
+ const synced = new Map(repair.synced.map((page) => [page.id, page]));
54075
+ if (!synced.size && !repair.refreshed.length) return;
54076
+ const roots = repair.refreshed.filter((item) => item.withDescendants).map((item) => item.page.id);
54077
+ const subtrees = roots.length ? await storage.getPageSubtrees({
54078
+ rootIds: [...new Set(roots)],
54079
+ limit: 500
54080
+ }) : {};
54081
+ const affected = [];
54082
+ for (const { page, withDescendants } of repair.refreshed) {
54083
+ affected.push(page);
54084
+ if (!withDescendants) continue;
54085
+ const under = subtrees[page.id];
54086
+ if (!under) throw new KnowledgeLinkRepairUnsupportedError("a moved subtree past the move limit");
54087
+ affected.push(...under);
54088
+ }
54089
+ const parentIds = affected.flatMap((page) => !page.isScope && page.key && page.parentId ? [page.parentId] : []);
54090
+ const chains = parentIds.length ? await storage.getPageChains({
54091
+ ids: [...new Set(parentIds)],
54092
+ read: "all"
54093
+ }) : {};
54094
+ const refs = /* @__PURE__ */ new Set();
54095
+ const targets = new Set(affected.map((page) => page.id));
54096
+ const names = /* @__PURE__ */ new Set();
54097
+ for (const page of affected) {
54098
+ const parents = !page.isScope && page.key && page.parentId ? chains[page.parentId] ?? [] : [];
54099
+ for (const key of refKeysOf(page, parents)) refs.add(key);
54100
+ if (!page.deletedAt) names.add(page.name);
54101
+ }
54102
+ if (names.size) {
54103
+ const namesakes = await storage.findPagesByNames({
54104
+ names: [...names],
54105
+ read: "all",
54106
+ limit: 100
54107
+ });
54108
+ for (const found of Object.values(namesakes)) {
54109
+ if (found.length > MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES) throw new KnowledgeLinkRepairUnsupportedError("a name past the namesake limit");
54110
+ for (const namesake of found) targets.add(namesake.id);
54111
+ }
54112
+ }
54113
+ const sources = affected.length ? await storage.listPageBodyLinkSources({
54114
+ refs: [...refs],
54115
+ toPageIds: [...targets]
54116
+ }) : [];
54117
+ if (sources.length > 100) throw new KnowledgeLinkRepairUnsupportedError("linking pages past the refresh limit");
54118
+ const unread = sources.filter((id) => !synced.has(id));
54119
+ const live = new Map((unread.length ? await storage.getPages({
54120
+ ids: unread,
54121
+ read: "all"
54122
+ }) : []).map((page) => [page.id, page]));
54123
+ const rewrite = /* @__PURE__ */ new Map();
54124
+ for (const id of unread) rewrite.set(id, live.get(id) ?? null);
54125
+ for (const [id, page] of synced) rewrite.set(id, page);
54126
+ const wanted = /* @__PURE__ */ new Map();
54127
+ const lookups = [];
54128
+ const refreshing = new Set(sources);
54129
+ let looked = 0;
54130
+ for (const [id, page] of rewrite) {
54131
+ const byKey = /* @__PURE__ */ new Map();
54132
+ if (page && !page.deletedAt) for (const [ref, count] of knowledgeBodyLinkRefs(page.body)) {
54133
+ const key = knowledgeLinkRefKey(ref);
54134
+ if (key.length > 512) continue;
54135
+ const entry = byKey.get(key);
54136
+ if (entry) entry.count += count;
54137
+ else byKey.set(key, {
54138
+ ref,
54139
+ count
54140
+ });
54141
+ }
54142
+ const entries = [...byKey];
54143
+ wanted.set(id, entries);
54144
+ if (page) for (const [, { ref }] of entries) lookups.push({
54145
+ ref,
54146
+ home: page.scopeId
54147
+ });
54148
+ if (refreshing.has(id)) looked += new Set(entries.map(([, { ref }]) => ref)).size;
54149
+ }
54150
+ if (looked >= 1e3) throw new KnowledgeLinkRepairUnsupportedError("refs looked up past the refresh limit");
54151
+ const resolved = await resolveKnowledgeBodyLinks(storage, lookups);
54152
+ await storage.applyPageWrites({ writes: [...wanted].map(([pageId, entries]) => {
54153
+ const home = rewrite.get(pageId)?.scopeId;
54154
+ return {
54155
+ op: "replace-links",
54156
+ pageId,
54157
+ links: entries.map(([key, { ref, count }]) => ({
54158
+ ref: key,
54159
+ toPageId: home === void 0 ? null : resolved.get(`${home}\u0000${ref}`) ?? null,
54160
+ count
54161
+ }))
54162
+ };
54163
+ }) });
54164
+ }
54165
+ /** What {@link BodyLinkResolver} answers for each `(home, ref)`, keyed `home\0ref`, in a fixed number of reads. */
54166
+ async function resolveKnowledgeBodyLinks(storage, lookups) {
54167
+ const answers = /* @__PURE__ */ new Map();
54168
+ if (!lookups.length) return answers;
54169
+ const keyOf = (home, ref) => `${home}\u0000${ref}`;
54170
+ const byId = new Set((await storage.getPages({
54171
+ ids: [...new Set(lookups.map((item) => item.ref))],
54172
+ read: "all"
54173
+ })).map((page) => page.id));
54174
+ const remaining = lookups.filter(({ ref, home }) => {
54175
+ if (!byId.has(ref)) return true;
54176
+ answers.set(keyOf(home, ref), ref);
54177
+ return false;
54178
+ });
54179
+ const paths = /* @__PURE__ */ new Map();
54180
+ const addresses = /* @__PURE__ */ new Set();
54181
+ for (const { ref } of remaining) if (ref.indexOf("#") > 0) {
54182
+ const parsed = parseKnowledgePageRef(ref);
54183
+ paths.set(ref, parsed);
54184
+ if (parsed) addresses.add(parsed.scope);
54185
+ } else addresses.add(ref);
54186
+ const scopes = /* @__PURE__ */ new Map();
54187
+ if (addresses.size) {
54188
+ for (const scope of await storage.getScopesByAddress([...addresses])) if (!scope.deletedAt && scope.address) scopes.set(scope.address, scope.id);
54189
+ }
54190
+ const pathsByScope = /* @__PURE__ */ new Map();
54191
+ for (const [ref, parsed] of paths) {
54192
+ const scopeId = parsed && scopes.get(parsed.scope);
54193
+ if (!scopeId) continue;
54194
+ if (!pathsByScope.has(scopeId)) pathsByScope.set(scopeId, /* @__PURE__ */ new Map());
54195
+ pathsByScope.get(scopeId).set(ref, parsed.path);
54196
+ }
54197
+ const pathAnswers = /* @__PURE__ */ new Map();
54198
+ for (const [scopeId, refs] of pathsByScope) {
54199
+ const found = await storage.getPagesByPaths({
54200
+ scopeId,
54201
+ paths: [...refs.values()],
54202
+ read: "all"
54203
+ });
54204
+ [...refs.keys()].forEach((ref, i) => pathAnswers.set(ref, found[i]?.id ?? null));
54205
+ }
54206
+ const namesByHome = /* @__PURE__ */ new Map();
54207
+ for (const { ref, home } of remaining) {
54208
+ if (paths.has(ref)) {
54209
+ answers.set(keyOf(home, ref), pathAnswers.get(ref) ?? null);
54210
+ continue;
54211
+ }
54212
+ const scopeId = scopes.get(ref);
54213
+ if (scopeId) {
54214
+ answers.set(keyOf(home, ref), scopeId);
54215
+ continue;
54216
+ }
54217
+ if (!namesByHome.has(home)) namesByHome.set(home, /* @__PURE__ */ new Set());
54218
+ namesByHome.get(home).add(ref);
54219
+ }
54220
+ const anywhere = /* @__PURE__ */ new Map();
54221
+ for (const [home, names] of namesByHome) {
54222
+ const found = await storage.findPagesByNames({
54223
+ names: [...names],
54224
+ read: "all",
54225
+ scopeId: home,
54226
+ limit: 2
54227
+ });
54228
+ for (const name of names) {
54229
+ const inHome = found[name] ?? [];
54230
+ if (inHome.length) answers.set(keyOf(home, name), inHome.length === 1 ? inHome[0].id : null);
54231
+ else anywhere.set(name, [...anywhere.get(name) ?? [], home]);
54232
+ }
54233
+ }
54234
+ if (anywhere.size) {
54235
+ const found = await storage.findPagesByNames({
54236
+ names: [...anywhere.keys()],
54237
+ read: "all",
54238
+ limit: 2
54239
+ });
54240
+ for (const [name, homes] of anywhere) {
54241
+ const pages = found[name] ?? [];
54242
+ for (const home of homes) answers.set(keyOf(home, name), pages.length === 1 ? pages[0].id : null);
54243
+ }
54244
+ }
54245
+ return answers;
54246
+ }
53546
54247
  // ../_vendored/ai_v7/dist/dist-C-C3A1Ts.js
53547
54248
  /**
53548
54249
  * Symbol used for identifying AI SDK Error instances.
@@ -62894,6 +63595,94 @@ async function removeKnowledgeNote(host, input) {
62894
63595
  await embed$1(host, (index) => index.remove([`note:${note.id}`]), UNEMBED_FAILED$1);
62895
63596
  return removed;
62896
63597
  }
63598
+ // src/knowledge/agent-scopes.ts
63599
+ /** Agent identity declarations. Identities grant nothing until an access rule names them. @experimental */
63600
+ function knowledgeAgentScopes() {
63601
+ return Object.fromEntries([
63602
+ "agent:$agentId",
63603
+ "agent:$agentId:org:$orgId",
63604
+ "agent:$agentId:user:$resourceId",
63605
+ "agent:persona:role:$role",
63606
+ "agent:persona:role:$role:org:$orgId",
63607
+ "agent:persona:role:$role:user:$resourceId",
63608
+ "agent:persona:team:$teamId"
63609
+ ].map((key) => [key, {
63610
+ mint: "run-identity",
63611
+ access: []
63612
+ }]));
63613
+ }
63614
+ /**
63615
+ * {@link knowledgeAgentScopes} plus a read-only persona convention: each agent reads and pins its own
63616
+ * `#persona` page, and every agent of a role or team reads and pins that scope's `#rules` page. The
63617
+ * `:edit` forms give editor on one role or team scope and are never minted; host code passes them.
63618
+ * @experimental
63619
+ */
63620
+ function knowledgePersonaScopes() {
63621
+ const scopes = knowledgeAgentScopes();
63622
+ for (const [key, page, name, edit] of [
63623
+ [
63624
+ "agent:$agentId",
63625
+ "persona",
63626
+ "Persona",
63627
+ false
63628
+ ],
63629
+ [
63630
+ "agent:persona:role:$role",
63631
+ "rules",
63632
+ "Role rules",
63633
+ true
63634
+ ],
63635
+ [
63636
+ "agent:persona:team:$teamId",
63637
+ "rules",
63638
+ "Team rules",
63639
+ true
63640
+ ]
63641
+ ]) {
63642
+ scopes[key] = {
63643
+ ...scopes[key],
63644
+ access: [{
63645
+ principal: "self",
63646
+ role: "viewer"
63647
+ }, ...edit ? [{
63648
+ principal: `${key}:edit`,
63649
+ role: "editor"
63650
+ }] : []],
63651
+ pages: [{
63652
+ key: page,
63653
+ name
63654
+ }],
63655
+ pinnedContext: [`${key}#${page}`]
63656
+ };
63657
+ if (edit) scopes[`${key}:edit`] = { access: [] };
63658
+ }
63659
+ return scopes;
63660
+ }
63661
+ /** @internal */
63662
+ function mintKnowledgeAgentScopes(compiled, scopes, agent) {
63663
+ const params = {};
63664
+ if (agent?.agentId) params.agentId = agent.agentId;
63665
+ if (agent?.resourceId) params.resourceId = agent.resourceId;
63666
+ const persona = agent?.persona;
63667
+ if (persona && typeof persona === "object") for (const [field, param] of [["role", "role"], ["teamId", "teamId"]]) {
63668
+ const value = persona[field];
63669
+ if (typeof value === "string" && value.length > 0) params[param] = value;
63670
+ }
63671
+ const orgs = scopes.filter((scope) => /^org:[^:]+$/.test(scope)).map((scope) => decodeKnowledgeScopeValue(scope.slice(4))).filter((value) => value !== null);
63672
+ const minted = [];
63673
+ for (const declaration of compiled.declarations.values()) {
63674
+ if (declaration.declaration.mint !== "run-identity") continue;
63675
+ const bindings = declaration.pattern.params.includes("orgId") ? orgs.map((orgId) => ({
63676
+ ...params,
63677
+ orgId
63678
+ })) : [params];
63679
+ for (const binding of bindings) {
63680
+ const address = bindKnowledgePattern(declaration.pattern, binding);
63681
+ if (address) minted.push(address);
63682
+ }
63683
+ }
63684
+ return minted;
63685
+ }
62897
63686
  // src/knowledge/run.ts
62898
63687
  /** A page reference the run can't resolve; identical for missing and unreadable pages. */
62899
63688
  var KnowledgeNotFoundError = class extends Error {
@@ -62902,6 +63691,13 @@ var KnowledgeNotFoundError = class extends Error {
62902
63691
  this.name = "KnowledgeNotFoundError";
62903
63692
  }
62904
63693
  };
63694
+ /** A run with no scopes and no Memory identity: it has no Knowledge view. @internal */
63695
+ var KnowledgeRunScopesError = class extends Error {
63696
+ constructor() {
63697
+ super("Knowledge tools need run scopes: give the agent or the call `scopes`, or run it with Memory.");
63698
+ this.name = "KnowledgeRunScopesError";
63699
+ }
63700
+ };
62905
63701
  const NAME_CANDIDATES = 5;
62906
63702
  const CLOSE_MATCHES = 3;
62907
63703
  /**
@@ -63053,9 +63849,15 @@ function knowledgeRunPrincipals(runtime, context) {
63053
63849
  const memory = [];
63054
63850
  if (context?.agent?.resourceId) memory.push(knowledgeScopeAddress("resource:$resourceId", { resourceId: context.agent.resourceId }));
63055
63851
  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.");
63852
+ if (raw.length === 0 && memory.length === 0) throw new KnowledgeRunScopesError();
63057
63853
  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])];
63854
+ const scopes = knowledgeRunScopes(runtime.compiled, raw);
63855
+ const minted = mintKnowledgeAgentScopes(runtime.compiled, scopes, context?.agent);
63856
+ return [.../* @__PURE__ */ new Set([
63857
+ ...scopes,
63858
+ ...memory,
63859
+ ...minted
63860
+ ])];
63059
63861
  }
63060
63862
  /** Longest heading line a hit shows ahead of its excerpt; a longer one is cut with `…`. */
63061
63863
  const HEADING_CHARS = 120;
@@ -63429,6 +64231,30 @@ async function noteSummaries(run, notes, cache = /* @__PURE__ */ new Map()) {
63429
64231
  for (const note of notes) summaries.push(noteSummary(note, await noteMentions(run, note, cache)));
63430
64232
  return summaries;
63431
64233
  }
64234
+ /**
64235
+ * Every scope the run holds, in principal order, with its role and what it can do there. A held scope
64236
+ * gets its page on the first write, so before that its role comes from the declarations and the parent
64237
+ * that write would link it under: without it a model sees no scopes on its first turn and concludes it
64238
+ * has nowhere to write. A stored scope it can't read keeps only its address.
64239
+ */
64240
+ async function heldScopes(run) {
64241
+ const stored = await run.storage.getScopesByAddress(run.principals);
64242
+ return Promise.all(run.principals.map(async (address) => {
64243
+ const found = stored.find((scope) => scope.address === address);
64244
+ const page = found && knowledgeScopeReadable(found, run.read) ? found : void 0;
64245
+ const role = found ? await run.roleOn(found) : knowledgeRoleOn(run.runtime.compiled, run.principals, {
64246
+ address,
64247
+ parentAddress: run.runtime.firstWriteParentAddress(address, run.principals)
64248
+ });
64249
+ const can = !role ? "none" : knowledgeRoleAtLeast(role, "contributor") ? "write" : "read";
64250
+ return {
64251
+ address,
64252
+ ...page ? { page } : {},
64253
+ role,
64254
+ can
64255
+ };
64256
+ }));
64257
+ }
63432
64258
  /** Scope pages for addresses the run names; each must be readable. */
63433
64259
  async function readableScopes(run, addresses) {
63434
64260
  const page = addresses.find((address) => address.includes("#"));
@@ -63465,11 +64291,13 @@ async function visibleNote(run, id) {
63465
64291
  page
63466
64292
  };
63467
64293
  }
63468
- /** Pin authority over an audience entry: the run holds it, or rules give it editor+ there. */
64294
+ /** Shared persona audiences need editor authority even when the run holds them. */
63469
64295
  async function requireAudienceAuthority(run, audience) {
63470
64296
  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.`);
64297
+ const match = run.runtime.compiled.match(address);
64298
+ const sharedPersona = match?.compiled.declaration.mint === "run-identity" && match.compiled.pattern.params.some((param) => param === "role" || param === "teamId");
64299
+ if (run.principals.includes(address) && !sharedPersona) continue;
64300
+ if (!match) throw new Error(`Pin audience "${address}" does not match a declared scope type.`);
63473
64301
  const [scope] = await run.storage.getScopesByAddress([address]);
63474
64302
  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
64303
  }
@@ -63709,7 +64537,7 @@ function bodyView(body, input) {
63709
64537
  function readTool(host, canEdit) {
63710
64538
  return require_tool.createTool({
63711
64539
  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." : ""),
64540
+ 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
64541
  inputSchema: {
63714
64542
  type: "object",
63715
64543
  properties: {
@@ -63791,10 +64619,13 @@ function readTool(host, canEdit) {
63791
64619
  if (outline && from) throw new Error("knowledge_read: an outline covers the whole body; pass it without from.");
63792
64620
  const run = await start(host, context);
63793
64621
  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 } : {}
64622
+ if (!ref) return { scopes: (await heldScopes(run)).map(({ address, page, role, can }) => ({
64623
+ address,
64624
+ name: page?.name ?? address,
64625
+ ...page?.description ? { description: page.description } : {},
64626
+ ...role ? { role } : {},
64627
+ can,
64628
+ ...page ? {} : { empty: true }
63798
64629
  })) };
63799
64630
  const page = await run.pageOrCloseMatches(ref);
63800
64631
  if (outline || section || match || from) {
@@ -64008,12 +64839,13 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
64008
64839
  let scopes = [];
64009
64840
  if (!origin) {
64010
64841
  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));
64842
+ scopes = (await heldScopes(run)).map((held) => ({
64843
+ ...held.page ? { page: held.page } : {},
64844
+ held
64845
+ }));
64014
64846
  } else {
64015
64847
  originRef = (await pageRefs(run, [origin])).refs.get(origin.id) ?? origin.id;
64016
- if (origin.isScope && !cursor?.startsWith("p")) scopes = await childScopes(origin.id);
64848
+ if (origin.isScope && !cursor?.startsWith("p")) scopes = (await childScopes(origin.id)).map((page) => ({ page }));
64017
64849
  }
64018
64850
  const shownScopes = scopes.slice(scopeOffset, scopeOffset + limit);
64019
64851
  let roots = shownScopes;
@@ -64023,7 +64855,7 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
64023
64855
  const room = limit - shownScopes.length;
64024
64856
  if (room > 0) {
64025
64857
  const pages = await childPages(origin.id, room, pageCursor);
64026
- roots = [...shownScopes, ...pages.pages];
64858
+ roots = [...shownScopes, ...pages.pages.map((page) => ({ page }))];
64027
64859
  if (pages.nextCursor) nextCursor = `p${pages.nextCursor}`;
64028
64860
  } else if ((await run.storage.countChildPages({
64029
64861
  parentIds: [origin.id],
@@ -64037,10 +64869,19 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
64037
64869
  children: 0,
64038
64870
  below: []
64039
64871
  });
64040
- const top = roots.map((page) => nodeOf(page, origin && originRef ? childRef(origin, originRef, page) : page.address ?? page.id, 1));
64872
+ const top = roots.map(({ page, held }) => page ? {
64873
+ ...nodeOf(page, origin && originRef ? childRef(origin, originRef, page) : page.address ?? page.id, 1),
64874
+ ...held ? { held } : {}
64875
+ } : {
64876
+ held,
64877
+ ref: held.address,
64878
+ depth: 1,
64879
+ children: 0,
64880
+ below: []
64881
+ });
64041
64882
  let budget = Math.max(limit - top.length, 0);
64042
64883
  let truncated = false;
64043
- let level = top;
64884
+ let level = top.filter((node) => node.page);
64044
64885
  for (let current = 1; current <= depth && level.length; current++) {
64045
64886
  const parentIds = level.map((node) => node.page.id);
64046
64887
  const scopeParents = level.filter((node) => node.page.isScope).map((node) => node.page.id);
@@ -64064,22 +64905,30 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
64064
64905
  budget -= scopes.length;
64065
64906
  const pages = budget > 0 ? (await childPages(node.page.id, budget)).pages : [];
64066
64907
  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);
64908
+ const below = [...scopes, ...pages].map((child) => ({
64909
+ ...nodeOf(child, childRef(node.page, node.ref, child), current + 1),
64910
+ page: child
64911
+ }));
64912
+ node.below = below;
64913
+ if (below.length < node.children) truncated = true;
64914
+ nextLevel.push(...below);
64070
64915
  }
64071
64916
  level = nextLevel;
64072
64917
  }
64073
64918
  const entries = [];
64074
64919
  const flatten = (nodes) => {
64075
64920
  for (const node of nodes) {
64921
+ const { page, held } = node;
64076
64922
  entries.push({
64077
64923
  ref: node.ref,
64078
- name: node.page.name,
64079
- ...descriptions && node.page.description ? { description: node.page.description } : {},
64924
+ name: page?.name ?? node.ref,
64925
+ ...descriptions && page?.description ? { description: page.description } : {},
64080
64926
  depth: node.depth,
64081
64927
  children: node.children,
64082
- ...node.page.isScope ? { scope: true } : {}
64928
+ ...!page || page.isScope ? { scope: true } : {},
64929
+ ...held?.role ? { role: held.role } : {},
64930
+ ...held ? { can: held.can } : {},
64931
+ ...page ? {} : { empty: true }
64083
64932
  });
64084
64933
  flatten(node.below);
64085
64934
  }
@@ -64096,7 +64945,7 @@ function listTool(host) {
64096
64945
  const maxTokens = maxTokensOf(host);
64097
64946
  return require_tool.createTool({
64098
64947
  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\`).`,
64948
+ 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
64949
  inputSchema: {
64101
64950
  type: "object",
64102
64951
  properties: {
@@ -65268,12 +66117,8 @@ var PinnedStateProcessor = class {
65268
66117
  threadId: args.threadId
65269
66118
  }
65270
66119
  };
65271
- let key;
65272
- try {
65273
- key = this.deps.principalsKey(context);
65274
- } catch {
65275
- return;
65276
- }
66120
+ const key = await this.deps.principalsKey(context);
66121
+ if (key === void 0) return void 0;
65277
66122
  if (memo && memo.key === key && stepNumber > memo.atStep) return memo.entries;
65278
66123
  const entries = await this.deps.readPins(context);
65279
66124
  args.requestContext?.set?.(MEMO_KEY, {
@@ -67193,7 +68038,7 @@ var MastraLLMVNext = class extends require_base.MastraBase {
67193
68038
  content: messages
67194
68039
  }];
67195
68040
  }
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 }) {
68041
+ 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
68042
  const observabilityContext = require_observability.resolveObservabilityContext(rest);
67198
68043
  let stopWhenToUse;
67199
68044
  if (maxSteps && typeof maxSteps === "number") {
@@ -67219,7 +68064,8 @@ var MastraLLMVNext = class extends require_base.MastraBase {
67219
68064
  provider: firstModel.provider,
67220
68065
  streaming: true,
67221
68066
  parameters: modelSettings,
67222
- ...toolDefinitions ? { tools: toolDefinitions } : {}
68067
+ ...toolDefinitions ? { tools: toolDefinitions } : {},
68068
+ ...resultType ? { resultType } : {}
67223
68069
  },
67224
68070
  metadata: {
67225
68071
  runId,
@@ -73571,8 +74417,9 @@ function releaseRunMessageRefs(runId) {
73571
74417
  /**
73572
74418
  * A `SaveQueueManager` `onSaved` callback that records the rows a run saved,
73573
74419
  * 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.
74420
+ * runs that store refs hold an entry (created before the run saves its input,
74421
+ * else by the transcript store), so saves for other runs, or landing after the
74422
+ * run released its entry, are not kept.
73576
74423
  */
73577
74424
  function recordRunSavedMessages(runId) {
73578
74425
  return (rows) => {
@@ -73594,6 +74441,15 @@ function recordRunSavedMessages(runId) {
73594
74441
  };
73595
74442
  }
73596
74443
  // src/agent/durable/utils/resolve-runtime.ts
74444
+ async function restoreWorkerToolsets(mastra, context, names) {
74445
+ const controller = context.get("controller");
74446
+ if (!isRestoredWorkerControllerContext(controller) || !names?.length) return;
74447
+ const toolsets = await mastra.getAgentControllerById(controller.controllerId)?.__restoreWorkerToolsets(context);
74448
+ if (!toolsets) return;
74449
+ const allowed = new Set(names);
74450
+ for (const [key, tools] of Object.entries(toolsets)) if (tools) toolsets[key] = Object.fromEntries(Object.entries(tools).filter(([name]) => allowed.has(name)));
74451
+ return toolsets;
74452
+ }
73597
74453
  /**
73598
74454
  * Build a SaveQueueManager for a run's memory, or `undefined` when no memory
73599
74455
  * is configured. Shared by `resolveRuntimeDependencies` and
@@ -73756,6 +74612,7 @@ async function resolveRuntimeDependencies(options) {
73756
74612
  backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
73757
74613
  tools = await agent.getToolsForExecution({
73758
74614
  runId,
74615
+ toolsets: await restoreWorkerToolsets(mastra, resolveRequestContext, input.options?.toolsetToolNames),
73759
74616
  threadId: input.state.threadId,
73760
74617
  resourceId: input.state.resourceId,
73761
74618
  requestContext: resolveRequestContext,
@@ -73877,6 +74734,7 @@ async function rebuildRunToolsFromMastra(options) {
73877
74734
  const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
73878
74735
  const tools = await agent.getToolsForExecution({
73879
74736
  runId,
74737
+ toolsets: await restoreWorkerToolsets(mastra, resolveRequestContext, execOptions?.toolsetToolNames),
73880
74738
  threadId: state.threadId,
73881
74739
  resourceId: state.resourceId,
73882
74740
  requestContext: resolveRequestContext,
@@ -74346,7 +75204,11 @@ function mergeRequestContextForFinalization(entries, fallback, liveRunContext) {
74346
75204
  if (liveRunContext) return liveRunContext;
74347
75205
  if (!entries) return fallback ?? new require_request_context.RequestContext();
74348
75206
  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);
75207
+ const controller = fallback?.get("controller");
75208
+ for (const [key, value] of Object.entries(require_request_context.withoutLiveRequestKeys(entries))) {
75209
+ if (key === "controller" && isRestoredWorkerControllerContext(controller)) continue;
75210
+ restored.set(key, value);
75211
+ }
74350
75212
  restoreRunAgentScopes(restored);
74351
75213
  return restored;
74352
75214
  }
@@ -74387,6 +75249,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
74387
75249
  ...initData,
74388
75250
  messageListState
74389
75251
  },
75252
+ requestContext,
74390
75253
  logger: effectiveLogger
74391
75254
  });
74392
75255
  rebuiltSaveQueueManager = resolved.saveQueueManager;
@@ -76391,6 +77254,15 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
76391
77254
  });
76392
77255
  break;
76393
77256
  }
77257
+ case "custom": {
77258
+ const p = chunk.payload;
77259
+ parts.push({
77260
+ type: "custom",
77261
+ kind: p.kind,
77262
+ ...p.providerMetadata ? { providerMetadata: p.providerMetadata } : {}
77263
+ });
77264
+ break;
77265
+ }
76394
77266
  case "tool-call": {
76395
77267
  const p = chunk.payload;
76396
77268
  const toolDef = tools?.[p.toolName] || findProviderToolByName(tools, p.toolName);
@@ -79930,6 +80802,12 @@ function createDurableToolCallStep() {
79930
80802
  error
79931
80803
  };
79932
80804
  }
80805
+ if (typeof args === "object" && args !== null) args = require_background_tasks.sanitizeToolArguments({
80806
+ args,
80807
+ toolName,
80808
+ toolConfig: tool?.backgroundConfig,
80809
+ agentConfig: registryEntry?.backgroundTasksConfig
80810
+ });
79933
80811
  const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;
79934
80812
  const memory = registryEntry?.memory ?? rebuiltMemory;
79935
80813
  const workspace = registryEntry?.workspace ?? rebuiltWorkspace;
@@ -83725,15 +84603,21 @@ async function persistDurableRunInput(runId, workflowInput, mastra, beforeSave)
83725
84603
  await beforeSave();
83726
84604
  }
83727
84605
  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
- });
84606
+ if (state.fixedMemory) getRunMessageRefs(runId);
84607
+ try {
84608
+ await entry.saveQueueManager.flushMessages(inputCopy, state.threadId, state.memoryConfig, {
84609
+ throwOnError: true,
84610
+ beforePersist: () => assertExecutionOwned({
84611
+ runId,
84612
+ agentId: workflowInput.agentId,
84613
+ mastra,
84614
+ requestContext
84615
+ })
84616
+ });
84617
+ } catch (error) {
84618
+ if (state.fixedMemory) releaseRunMessageRefs(runId);
84619
+ throw error;
84620
+ }
83737
84621
  const embedded = entry.messageList.getEmbeddedMessages();
83738
84622
  for (const [messageId, textHash] of inputCopy.getEmbeddedMessages()) embedded.set(messageId, textHash);
83739
84623
  }
@@ -84060,7 +84944,7 @@ async function prepareForDurableExecution(options) {
84060
84944
  });
84061
84945
  let tripwireData;
84062
84946
  if (inputProcessors.length > 0) try {
84063
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-DQC1vpvl.cjs")).then((n) => n.runner_exports);
84947
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-CMKRczs4.cjs")).then((n) => n.runner_exports);
84064
84948
  await new ProcessorRunner({
84065
84949
  inputProcessors,
84066
84950
  outputProcessors,
@@ -86820,6 +87704,11 @@ var Agent = class Agent extends require_base.MastraBase {
86820
87704
  const processors = [];
86821
87705
  const instructions = knowledge.getInstructions();
86822
87706
  if (instructions && !configuredIds.has("knowledge-instructions-processor")) processors.push(new KnowledgeInstructionsProcessor(instructions));
87707
+ const toolGroups = knowledge.__toolGroups;
87708
+ if (hasMemory && (toolGroups.read || toolGroups.write) && !hasConfiguredProcessor(configuredProcessors, (processor) => processor.id === "knowledge-scopes")) processors.push(new HeldScopesStateProcessor({
87709
+ principalsKey: (context) => knowledge.__principalsKey(context),
87710
+ readHeldScopes: (context) => knowledge.__heldScopes(context)
87711
+ }));
86823
87712
  if (knowledge.pinnedContextEnabled && !configuredIds.has("knowledge")) {
86824
87713
  if (!hasMemory) {
86825
87714
  if (!this.#warnedPinsWithoutMemory) {
@@ -86828,9 +87717,26 @@ var Agent = class Agent extends require_base.MastraBase {
86828
87717
  }
86829
87718
  return processors;
86830
87719
  }
87720
+ const contexts = /* @__PURE__ */ new WeakMap();
87721
+ const pinContext = (context) => {
87722
+ let resolved = contexts.get(context);
87723
+ if (!resolved) {
87724
+ const requestContext = context.requestContext instanceof require_request_context.RequestContext ? context.requestContext : void 0;
87725
+ resolved = this.resolveKnowledgePersona(knowledge, requestContext).then((persona) => ({
87726
+ ...context,
87727
+ agent: {
87728
+ ...context.agent,
87729
+ agentId: this.id,
87730
+ persona
87731
+ }
87732
+ }));
87733
+ contexts.set(context, resolved);
87734
+ }
87735
+ return resolved;
87736
+ };
86831
87737
  processors.push(new PinnedStateProcessor({
86832
- principalsKey: (context) => knowledge.__principalsKey(context),
86833
- readPins: (context) => knowledge.__deliveredPins(context),
87738
+ principalsKey: async (context) => knowledge.__principalsKey(await pinContext(context)),
87739
+ readPins: async (context) => knowledge.__deliveredPins(await pinContext(context)),
86834
87740
  ...knowledge.__toolGroups
86835
87741
  }));
86836
87742
  }
@@ -87787,7 +88693,8 @@ var Agent = class Agent extends require_base.MastraBase {
87787
88693
  }
87788
88694
  /**
87789
88695
  * 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.
88696
+ * Metadata is a classification bag for clients. The agent runtime reads only `metadata.persona`, to mint
88697
+ * Knowledge persona scopes; it reads nothing else in metadata.
87791
88698
  *
87792
88699
  * @example
87793
88700
  * ```typescript
@@ -88525,11 +89432,13 @@ var Agent = class Agent extends require_base.MastraBase {
88525
89432
  ...observabilityContext,
88526
89433
  messageList,
88527
89434
  agentId: this.id,
88528
- agentName: this.name
89435
+ agentName: this.name,
89436
+ resultType: "title_generation"
88529
89437
  }).text;
88530
89438
  } else text = (await llm.__text({
88531
89439
  requestContext,
88532
89440
  ...observabilityContext,
89441
+ resultType: "title_generation",
88533
89442
  messages: [{
88534
89443
  role: "system",
88535
89444
  content: systemInstructions
@@ -88676,10 +89585,34 @@ var Agent = class Agent extends require_base.MastraBase {
88676
89585
  backgroundConfig: tool.background,
88677
89586
  agentBackgroundConfig: this.#backgroundTasks
88678
89587
  };
88679
- converted[toolName] = require_utils$1.makeCoreTool(tool, options, void 0, autoResumeSuspendedTools, backgroundTaskEnabled);
89588
+ const execute = tool.execute;
89589
+ const agentTool = execute ? {
89590
+ ...tool,
89591
+ execute: async (input, context) => {
89592
+ const persona = await this.resolveKnowledgePersona(knowledge, requestContext);
89593
+ const runContext = {
89594
+ ...context,
89595
+ agent: context?.agent ? {
89596
+ ...context.agent,
89597
+ agentId: this.id,
89598
+ persona
89599
+ } : void 0
89600
+ };
89601
+ return execute(input, runContext);
89602
+ }
89603
+ } : tool;
89604
+ converted[toolName] = require_utils$1.makeCoreTool(agentTool, options, void 0, autoResumeSuspendedTools, backgroundTaskEnabled);
88680
89605
  }
88681
89606
  return converted;
88682
89607
  }
89608
+ async resolveKnowledgePersona(knowledge, requestContext) {
89609
+ if (!await knowledge.__needsAgentPersona()) return void 0;
89610
+ try {
89611
+ return (await this.getMetadata({ requestContext }))?.persona;
89612
+ } catch {
89613
+ return;
89614
+ }
89615
+ }
88683
89616
  /**
88684
89617
  * Lists workspace tools if a workspace is configured.
88685
89618
  * @internal
@@ -96420,6 +97353,29 @@ var Agent = class Agent extends require_base.MastraBase {
96420
97353
  };
96421
97354
  }
96422
97355
  };
97356
+ // src/agent/merge-persona.ts
97357
+ function merge(metadata, persona) {
97358
+ const code = metadata?.persona;
97359
+ const base = code && typeof code === "object" && !Array.isArray(code) ? code : {};
97360
+ const set = Object.fromEntries(Object.entries(persona).filter(([, value]) => value !== void 0));
97361
+ return {
97362
+ ...metadata,
97363
+ persona: {
97364
+ ...base,
97365
+ ...set
97366
+ }
97367
+ };
97368
+ }
97369
+ /**
97370
+ * Overrides an Agent's `metadata.persona` field by field: a field `persona` sets wins, a field it leaves
97371
+ * unset keeps the code's value, and keys outside `persona` stay as they are. Function-form metadata is
97372
+ * wrapped so the override applies to whatever it resolves to.
97373
+ * @experimental
97374
+ */
97375
+ function mergeAgentPersona(metadata, persona) {
97376
+ if (typeof metadata !== "function") return merge(metadata, persona);
97377
+ return async (context) => merge(await metadata(context), persona);
97378
+ }
96423
97379
  // ../_internal-core/dist/fs-routing/index.js
96424
97380
  /**
96425
97381
  * Maximum nesting depth for declared subagents. A top-level agent is depth 0;
@@ -103086,6 +104042,12 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
103086
104042
  args = argsFromInput;
103087
104043
  resumeDataFromArgs = resumeDataFromInput;
103088
104044
  }
104045
+ if (typeof args === "object" && args !== null) args = require_background_tasks.sanitizeToolArguments({
104046
+ args,
104047
+ toolName: inputData.toolName,
104048
+ toolConfig: tool?.backgroundConfig,
104049
+ agentConfig: readScoped(scopeCtx, AGENT_BACKGROUND_CONFIG_KEY, "agentBackgroundConfig")
104050
+ });
103089
104051
  const resumeData = resumeDataFromArgs ?? workflowResumeData;
103090
104052
  const isResumeToolCall = resumeDataFromArgs != null;
103091
104053
  const approvalVerdicts = readScoped(scopeCtx, TOOL_APPROVAL_VERDICTS_KEY, "toolApprovalVerdicts");
@@ -107916,6 +108878,11 @@ var AgentThreadStreamRuntime = class {
107916
108878
  record.lifecycle = "completed";
107917
108879
  this.#clearSuspendedRun(state, record.runId);
107918
108880
  state.threadRunsByStreamId.delete(record.streamId);
108881
+ if (state.threadRunsById.get(record.runId) === record) for (const [streamId, other] of state.threadRunsByStreamId) {
108882
+ if (other.runId !== record.runId || other.lifecycle !== "suspended") continue;
108883
+ state.threadRunsByStreamId.delete(streamId);
108884
+ state.watchedThreadStreamIds.delete(streamId);
108885
+ }
107919
108886
  if (state.threadRunsById.get(record.runId) === record) {
107920
108887
  state.threadRunsById.delete(record.runId);
107921
108888
  state.threadKeysByRunId.delete(record.runId);
@@ -110812,6 +111779,12 @@ Object.defineProperty(exports, "CONTINUE_RUN_MESSAGE", {
110812
111779
  return CONTINUE_RUN_MESSAGE;
110813
111780
  }
110814
111781
  });
111782
+ Object.defineProperty(exports, "CONTROLLER_RUN_BINDING_KEY", {
111783
+ enumerable: true,
111784
+ get: function() {
111785
+ return CONTROLLER_RUN_BINDING_KEY;
111786
+ }
111787
+ });
110815
111788
  Object.defineProperty(exports, "ChannelSessionRejectedError", {
110816
111789
  enumerable: true,
110817
111790
  get: function() {
@@ -111142,6 +112115,12 @@ Object.defineProperty(exports, "KnowledgeLinkRefreshIncompleteError", {
111142
112115
  return KnowledgeLinkRefreshIncompleteError;
111143
112116
  }
111144
112117
  });
112118
+ Object.defineProperty(exports, "KnowledgeLinkRepairUnsupportedError", {
112119
+ enumerable: true,
112120
+ get: function() {
112121
+ return KnowledgeLinkRepairUnsupportedError;
112122
+ }
112123
+ });
111145
112124
  Object.defineProperty(exports, "KnowledgeMoveTooLargeError", {
111146
112125
  enumerable: true,
111147
112126
  get: function() {
@@ -111178,6 +112157,12 @@ Object.defineProperty(exports, "KnowledgeRun", {
111178
112157
  return KnowledgeRun;
111179
112158
  }
111180
112159
  });
112160
+ Object.defineProperty(exports, "KnowledgeRunScopesError", {
112161
+ enumerable: true,
112162
+ get: function() {
112163
+ return KnowledgeRunScopesError;
112164
+ }
112165
+ });
111181
112166
  Object.defineProperty(exports, "KnowledgeSchemaResetRequiredError", {
111182
112167
  enumerable: true,
111183
112168
  get: function() {
@@ -112108,6 +113093,12 @@ Object.defineProperty(exports, "calculateAccumulatedUsage", {
112108
113093
  return calculateAccumulatedUsage;
112109
113094
  }
112110
113095
  });
113096
+ Object.defineProperty(exports, "canRepairKnowledgeLinksInBatch", {
113097
+ enumerable: true,
113098
+ get: function() {
113099
+ return canRepairKnowledgeLinksInBatch;
113100
+ }
113101
+ });
112111
113102
  Object.defineProperty(exports, "cancelNestedRun", {
112112
113103
  enumerable: true,
112113
113104
  get: function() {
@@ -112912,6 +113903,12 @@ Object.defineProperty(exports, "hasResumableStreams", {
112912
113903
  return hasResumableStreams;
112913
113904
  }
112914
113905
  });
113906
+ Object.defineProperty(exports, "heldScopes", {
113907
+ enumerable: true,
113908
+ get: function() {
113909
+ return heldScopes;
113910
+ }
113911
+ });
112915
113912
  Object.defineProperty(exports, "hydrateSerializedStepErrors", {
112916
113913
  enumerable: true,
112917
113914
  get: function() {
@@ -113032,6 +114029,12 @@ Object.defineProperty(exports, "knowledgeAccessGrants", {
113032
114029
  return knowledgeAccessGrants;
113033
114030
  }
113034
114031
  });
114032
+ Object.defineProperty(exports, "knowledgeAgentScopes", {
114033
+ enumerable: true,
114034
+ get: function() {
114035
+ return knowledgeAgentScopes;
114036
+ }
114037
+ });
113035
114038
  Object.defineProperty(exports, "knowledgeDeliveredPins", {
113036
114039
  enumerable: true,
113037
114040
  get: function() {
@@ -113050,12 +114053,24 @@ Object.defineProperty(exports, "knowledgeMemoryScopes", {
113050
114053
  return knowledgeMemoryScopes;
113051
114054
  }
113052
114055
  });
114056
+ Object.defineProperty(exports, "knowledgePageKeyProblem", {
114057
+ enumerable: true,
114058
+ get: function() {
114059
+ return knowledgePageKeyProblem;
114060
+ }
114061
+ });
113053
114062
  Object.defineProperty(exports, "knowledgePagePath", {
113054
114063
  enumerable: true,
113055
114064
  get: function() {
113056
114065
  return knowledgePagePath;
113057
114066
  }
113058
114067
  });
114068
+ Object.defineProperty(exports, "knowledgePersonaScopes", {
114069
+ enumerable: true,
114070
+ get: function() {
114071
+ return knowledgePersonaScopes;
114072
+ }
114073
+ });
113059
114074
  Object.defineProperty(exports, "knowledgePinDepth", {
113060
114075
  enumerable: true,
113061
114076
  get: function() {
@@ -113182,6 +114197,12 @@ Object.defineProperty(exports, "memoryDefaultOptions", {
113182
114197
  return memoryDefaultOptions;
113183
114198
  }
113184
114199
  });
114200
+ Object.defineProperty(exports, "mergeAgentPersona", {
114201
+ enumerable: true,
114202
+ get: function() {
114203
+ return mergeAgentPersona;
114204
+ }
114205
+ });
113185
114206
  Object.defineProperty(exports, "mergeStepResult", {
113186
114207
  enumerable: true,
113187
114208
  get: function() {
@@ -113446,6 +114467,12 @@ Object.defineProperty(exports, "renewWorkflowLease", {
113446
114467
  return renewWorkflowLease;
113447
114468
  }
113448
114469
  });
114470
+ Object.defineProperty(exports, "repairKnowledgeLinks", {
114471
+ enumerable: true,
114472
+ get: function() {
114473
+ return repairKnowledgeLinks;
114474
+ }
114475
+ });
113449
114476
  Object.defineProperty(exports, "repeatAfterSettled", {
113450
114477
  enumerable: true,
113451
114478
  get: function() {
@@ -113560,6 +114587,12 @@ Object.defineProperty(exports, "resolveWaitUntil", {
113560
114587
  return resolveWaitUntil;
113561
114588
  }
113562
114589
  });
114590
+ Object.defineProperty(exports, "restoredWorkerControllerContexts", {
114591
+ enumerable: true,
114592
+ get: function() {
114593
+ return restoredWorkerControllerContexts;
114594
+ }
114595
+ });
113563
114596
  Object.defineProperty(exports, "retentionCutoffMs", {
113564
114597
  enumerable: true,
113565
114598
  get: function() {