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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (503) hide show
  1. package/dist/_types/@ai-sdk_anthropic@3.0.137/dist/index.d.ts +2 -2
  2. package/dist/_types/@ai-sdk_google@3.0.140/dist/index.d.ts +2 -2
  3. package/dist/_types/@ai-sdk_openai@3.0.135/dist/index.d.ts +2 -2
  4. package/dist/_types/@ai-sdk_openai@4.0.106/dist/index.d.ts +2034 -0
  5. package/dist/_types/@ai-sdk_openai@4.0.106/package.json +1 -0
  6. package/dist/a2a/index.cjs +1 -1
  7. package/dist/a2a/index.js +1 -1
  8. package/dist/agent/agent.d.ts +3 -1
  9. package/dist/agent/durable/index.cjs +2 -1
  10. package/dist/agent/durable/index.d.ts +1 -0
  11. package/dist/agent/durable/index.js +2 -2
  12. package/dist/agent/durable/run-message-refs.d.ts +3 -2
  13. package/dist/agent/durable/run-registry.d.ts +12 -1
  14. package/dist/agent/durable/types.d.ts +2 -0
  15. package/dist/agent/durable/workflows/finalize-run.d.ts +2 -1
  16. package/dist/agent/index.cjs +5 -4
  17. package/dist/agent/index.d.ts +2 -0
  18. package/dist/agent/index.js +5 -5
  19. package/dist/agent/merge-persona.d.ts +15 -0
  20. package/dist/agent/message-list/adapters/AIV5Adapter.d.ts +15 -1
  21. package/dist/agent/message-list/index.cjs +2 -2
  22. package/dist/agent/message-list/index.js +2 -2
  23. package/dist/agent/message-list/state/types.d.ts +5 -1
  24. package/dist/agent/message-list/types.d.ts +1 -1
  25. package/dist/agent/message-list/utils/provider-compat.d.ts +9 -1
  26. package/dist/agent/thread-stream-runtime.d.ts +3 -1
  27. package/dist/agent-builder/ee/index.cjs +1 -1
  28. package/dist/agent-builder/ee/index.js +1 -1
  29. package/dist/agent-controller/agent-controller.d.ts +6 -0
  30. package/dist/agent-controller/index.cjs +2 -2
  31. package/dist/agent-controller/index.js +2 -2
  32. package/dist/agent-controller/worker-run-binding.d.ts +15 -0
  33. package/dist/{agent-controller-B8LoFdtu.js → agent-controller--gKWI81G.js} +50 -8
  34. package/dist/{agent-controller-DSnFynpa.cjs → agent-controller-BolLBwDm.cjs} +50 -8
  35. package/dist/background-tasks/index.cjs +2 -1
  36. package/dist/background-tasks/index.d.ts +1 -1
  37. package/dist/background-tasks/index.js +1 -1
  38. package/dist/background-tasks/resolve-config.d.ts +30 -1
  39. package/dist/background-tasks/system-prompt.d.ts +8 -2
  40. package/dist/background-tasks/types.d.ts +47 -1
  41. package/dist/{background-tasks-IW7M4iD2.js → background-tasks-CgzXjBfE.js} +156 -33
  42. package/dist/{background-tasks-Ci5h0dhj.cjs → background-tasks-DYtlijQ1.cjs} +167 -32
  43. package/dist/browser/index.cjs +2 -2
  44. package/dist/browser/index.js +2 -2
  45. package/dist/{builder-14Uptu8y.cjs → builder-Dz-g-9CZ.cjs} +2 -2
  46. package/dist/{builder-DI2c2xjy.js → builder-emNPaIaC.js} +2 -2
  47. package/dist/capabilities/302ai.json +202 -202
  48. package/dist/capabilities/abliteratedllm.json +36 -27
  49. package/dist/capabilities/abliteration-ai.json +12 -12
  50. package/dist/capabilities/above.json +14 -14
  51. package/dist/capabilities/adaption.json +9 -9
  52. package/dist/capabilities/adzuki.json +26 -26
  53. package/dist/capabilities/agentrouter.json +4 -4
  54. package/dist/capabilities/agnes.json +2 -2
  55. package/dist/capabilities/ai-router.json +5 -5
  56. package/dist/capabilities/aiand.json +11 -11
  57. package/dist/capabilities/aigrow.json +14 -14
  58. package/dist/capabilities/aimlapi.json +154 -158
  59. package/dist/capabilities/aixy.json +21 -21
  60. package/dist/capabilities/aki-io.json +14 -14
  61. package/dist/capabilities/alibaba-cn.json +107 -101
  62. package/dist/capabilities/alibaba-coding-plan-cn.json +3 -3
  63. package/dist/capabilities/alibaba-coding-plan.json +3 -3
  64. package/dist/capabilities/alibaba-token-plan-cn.json +53 -53
  65. package/dist/capabilities/alibaba-token-plan.json +53 -53
  66. package/dist/capabilities/alibaba.json +99 -65
  67. package/dist/capabilities/ambient.json +14 -7
  68. package/dist/capabilities/amd.json +8 -8
  69. package/dist/capabilities/anthropic.json +47 -47
  70. package/dist/capabilities/anyapi.json +19 -19
  71. package/dist/capabilities/apiko.json +2 -2
  72. package/dist/capabilities/arcee.json +4 -4
  73. package/dist/capabilities/augure.json +5 -5
  74. package/dist/capabilities/auriko.json +22 -22
  75. package/dist/capabilities/bailing.json +3 -3
  76. package/dist/capabilities/baseten.json +25 -25
  77. package/dist/capabilities/bee.json +5 -5
  78. package/dist/capabilities/berget.json +14 -1
  79. package/dist/capabilities/bothub.json +17 -17
  80. package/dist/capabilities/boundless.json +31 -31
  81. package/dist/capabilities/bumo.json +40 -40
  82. package/dist/capabilities/byteplus.json +29 -29
  83. package/dist/capabilities/cheapaimodel.json +9 -9
  84. package/dist/capabilities/cheapest-token.json +30 -30
  85. package/dist/capabilities/chutes.json +9 -9
  86. package/dist/capabilities/claudinio.json +10 -1
  87. package/dist/capabilities/cline-pass.json +40 -40
  88. package/dist/capabilities/cloudcode.json +8 -15
  89. package/dist/capabilities/cloudflare-workers-ai.json +8 -8
  90. package/dist/capabilities/commandcode.json +145 -145
  91. package/dist/capabilities/concentrate.json +272 -289
  92. package/dist/capabilities/cortecs.json +110 -110
  93. package/dist/capabilities/crossmodel.json +182 -182
  94. package/dist/capabilities/crusoe.json +37 -8
  95. package/dist/capabilities/daoxe.json +8 -8
  96. package/dist/capabilities/databricks.json +130 -130
  97. package/dist/capabilities/deepinfra.json +92 -83
  98. package/dist/capabilities/digitalocean.json +112 -112
  99. package/dist/capabilities/dothoosh.json +31 -31
  100. package/dist/capabilities/doubleword.json +22 -22
  101. package/dist/capabilities/edenai.json +898 -1743
  102. package/dist/capabilities/empiriolabs.json +168 -168
  103. package/dist/capabilities/engy.json +19 -19
  104. package/dist/capabilities/entrim.json +2 -2
  105. package/dist/capabilities/evroc.json +12 -12
  106. package/dist/capabilities/ezkielyna.json +11 -11
  107. package/dist/capabilities/fastrouter.json +82 -82
  108. package/dist/capabilities/fireworks-ai.json +125 -64
  109. package/dist/capabilities/fortytwo.json +9 -3
  110. package/dist/capabilities/freemodel.json +19 -19
  111. package/dist/capabilities/friendli.json +8 -8
  112. package/dist/capabilities/frogbot.json +100 -100
  113. package/dist/capabilities/gisoo.json +20 -20
  114. package/dist/capabilities/gmicloud.json +23 -23
  115. package/dist/capabilities/google.json +50 -50
  116. package/dist/capabilities/graphn.json +13 -13
  117. package/dist/capabilities/greenpt.json +35 -35
  118. package/dist/capabilities/groq.json +3 -3
  119. package/dist/capabilities/helicone.json +84 -84
  120. package/dist/capabilities/hetzner.json +35 -3
  121. package/dist/capabilities/hostinger-router.json +15 -15
  122. package/dist/capabilities/hpc-ai.json +12 -12
  123. package/dist/capabilities/huawei-maas.json +14 -14
  124. package/dist/capabilities/hubris.json +33 -33
  125. package/dist/capabilities/huggingface.json +108 -158
  126. package/dist/capabilities/humain.json +2 -2
  127. package/dist/capabilities/hyper.json +20 -28
  128. package/dist/capabilities/impossibl.json +152 -152
  129. package/dist/capabilities/inception.json +2 -2
  130. package/dist/capabilities/inceptron.json +6 -6
  131. package/dist/capabilities/inco.json +5 -5
  132. package/dist/capabilities/infer.json +20 -20
  133. package/dist/capabilities/inferall.json +10 -10
  134. package/dist/capabilities/inference-coop.json +15 -15
  135. package/dist/capabilities/inferenceapis.json +11 -11
  136. package/dist/capabilities/inferris.json +3 -3
  137. package/dist/capabilities/infersia.json +11 -11
  138. package/dist/capabilities/infomaniak.json +2 -2
  139. package/dist/capabilities/iteracompute.json +48 -48
  140. package/dist/capabilities/jad-ai.json +2 -2
  141. package/dist/capabilities/jalapeno.json +12 -12
  142. package/dist/capabilities/jiekou.json +58 -58
  143. package/dist/capabilities/jzstoken.json +53 -54
  144. package/dist/capabilities/keln.json +13 -13
  145. package/dist/capabilities/kenari.json +119 -127
  146. package/dist/capabilities/kilo.json +643 -647
  147. package/dist/capabilities/kimi-code-plan-cn.json +6 -6
  148. package/dist/capabilities/kimi-code-plan-global.json +6 -6
  149. package/dist/capabilities/kitani.json +6 -6
  150. package/dist/capabilities/klavo.json +14 -14
  151. package/dist/capabilities/korouter.json +34 -34
  152. package/dist/capabilities/kunavo.json +7 -7
  153. package/dist/capabilities/liquid.json +11 -11
  154. package/dist/capabilities/lithosai.json +3 -3
  155. package/dist/capabilities/llmgateway-providers.json +949 -880
  156. package/dist/capabilities/llmgateway.json +344 -343
  157. package/dist/capabilities/llmtr.json +29 -29
  158. package/dist/capabilities/longcat.json +2 -2
  159. package/dist/capabilities/lowrouter.json +53 -53
  160. package/dist/capabilities/lyceum.json +17 -9
  161. package/dist/capabilities/melious.json +14 -14
  162. package/dist/capabilities/merge-gateway.json +303 -301
  163. package/dist/capabilities/meta.json +9 -9
  164. package/dist/capabilities/mistral.json +20 -20
  165. package/dist/capabilities/mixlayer.json +2 -2
  166. package/dist/capabilities/modal.json +10 -10
  167. package/dist/capabilities/model-oracle-ai.json +23 -23
  168. package/dist/capabilities/modelis.json +22 -22
  169. package/dist/capabilities/modular.json +31 -9
  170. package/dist/capabilities/moneo.json +13 -13
  171. package/dist/capabilities/moonshotai-cn.json +6 -6
  172. package/dist/capabilities/moonshotai.json +6 -6
  173. package/dist/capabilities/morph.json +15 -15
  174. package/dist/capabilities/munito.json +2 -2
  175. package/dist/capabilities/nan.json +24 -24
  176. package/dist/capabilities/nano-gpt.json +595 -580
  177. package/dist/capabilities/nearai.json +101 -101
  178. package/dist/capabilities/nebius.json +26 -26
  179. package/dist/capabilities/neon.json +125 -125
  180. package/dist/capabilities/neuralwatt.json +43 -43
  181. package/dist/capabilities/nokeep.json +4 -4
  182. package/dist/capabilities/novita-ai.json +123 -123
  183. package/dist/capabilities/nvidia.json +39 -22
  184. package/dist/capabilities/oathbreaker.json +26 -3
  185. package/dist/capabilities/obscurify.json +22 -22
  186. package/dist/capabilities/oci.json +5 -5
  187. package/dist/capabilities/ofox.json +327 -327
  188. package/dist/capabilities/ollama-cloud.json +58 -58
  189. package/dist/capabilities/openai.json +57 -57
  190. package/dist/capabilities/opencode-go.json +90 -90
  191. package/dist/capabilities/openreason.json +5 -5
  192. package/dist/capabilities/openrouter.json +561 -557
  193. package/dist/capabilities/opper.json +30 -30
  194. package/dist/capabilities/orcarouter.json +238 -238
  195. package/dist/capabilities/outerlabs.json +29 -29
  196. package/dist/capabilities/ovhcloud.json +20 -20
  197. package/dist/capabilities/pareto.json +4 -4
  198. package/dist/capabilities/pendra.json +4 -4
  199. package/dist/capabilities/perplexity-agent.json +63 -63
  200. package/dist/capabilities/phala.json +22 -22
  201. package/dist/capabilities/pioneer.json +26 -26
  202. package/dist/capabilities/poe.json +134 -134
  203. package/dist/capabilities/poolside.json +3 -3
  204. package/dist/capabilities/powerspring.json +8 -8
  205. package/dist/capabilities/primalabs.json +8 -8
  206. package/dist/capabilities/prime.json +133 -123
  207. package/dist/capabilities/privatemode-ai.json +13 -13
  208. package/dist/capabilities/proxystacks.json +6 -6
  209. package/dist/capabilities/qiniu-ai.json +15 -15
  210. package/dist/capabilities/refuseless.json +6 -6
  211. package/dist/capabilities/regolo-ai.json +9 -9
  212. package/dist/capabilities/requesty.json +386 -171
  213. package/dist/capabilities/ruapi.json +29 -13
  214. package/dist/capabilities/runcrate.json +8 -8
  215. package/dist/capabilities/runinfra.json +9 -9
  216. package/dist/capabilities/sakana.json +3 -3
  217. package/dist/capabilities/sambanova.json +5 -5
  218. package/dist/capabilities/sandbase.json +17 -17
  219. package/dist/capabilities/sarvam.json +14 -14
  220. package/dist/capabilities/scaleway.json +13 -13
  221. package/dist/capabilities/scnet-token-plan.json +12 -12
  222. package/dist/capabilities/scx-ai.json +22 -22
  223. package/dist/capabilities/sensenova.json +10 -10
  224. package/dist/capabilities/siliconflow-cn.json +49 -49
  225. package/dist/capabilities/siliconflow.json +54 -54
  226. package/dist/capabilities/snowflake-cortex.json +17 -17
  227. package/dist/capabilities/sokkan.json +5 -5
  228. package/dist/capabilities/sparrowcodes.json +23 -23
  229. package/dist/capabilities/standardcompute.json +94 -94
  230. package/dist/capabilities/steadyrouter.json +40 -40
  231. package/dist/capabilities/stepfun-ai-step-plan.json +5 -5
  232. package/dist/capabilities/stepfun-ai.json +5 -5
  233. package/dist/capabilities/stepfun-step-plan.json +5 -5
  234. package/dist/capabilities/stepfun.json +5 -5
  235. package/dist/capabilities/stepping-stone.json +9 -9
  236. package/dist/capabilities/subconscious.json +2 -2
  237. package/dist/capabilities/synthetic.json +10 -10
  238. package/dist/capabilities/synthorai.json +22 -22
  239. package/dist/capabilities/teamorouter.json +23 -23
  240. package/dist/capabilities/teapot-router.json +12 -12
  241. package/dist/capabilities/tencent-token-plan-intl.json +126 -0
  242. package/dist/capabilities/tencent-token-plan.json +35 -35
  243. package/dist/capabilities/tencent-tokenhub.json +51 -36
  244. package/dist/capabilities/tensorx.json +44 -44
  245. package/dist/capabilities/tenstorrent.json +6 -6
  246. package/dist/capabilities/the-grid-ai.json +32 -32
  247. package/dist/capabilities/thinkingmachines.json +48 -48
  248. package/dist/capabilities/tinfoil.json +11 -11
  249. package/dist/capabilities/toapis.json +2 -2
  250. package/dist/capabilities/togetherai.json +40 -40
  251. package/dist/capabilities/tokengo.json +25 -25
  252. package/dist/capabilities/tokenify.json +9 -9
  253. package/dist/capabilities/tokenwatt.json +10 -2
  254. package/dist/capabilities/trustedrouter.json +6 -6
  255. package/dist/capabilities/trustedtokens.json +13 -13
  256. package/dist/capabilities/umans-ai-coding-plan.json +14 -14
  257. package/dist/capabilities/umans-ai.json +12 -12
  258. package/dist/capabilities/uncensuredai.json +2 -2
  259. package/dist/capabilities/unrestricted.json +8 -8
  260. package/dist/capabilities/uplinkswitch.json +18 -18
  261. package/dist/capabilities/upstage.json +6 -6
  262. package/dist/capabilities/vancine.json +18 -18
  263. package/dist/capabilities/vercel.json +590 -587
  264. package/dist/capabilities/vivgrid.json +87 -78
  265. package/dist/capabilities/volcengine-coding-plan.json +32 -23
  266. package/dist/capabilities/volcengine.json +31 -30
  267. package/dist/capabilities/vultr.json +26 -26
  268. package/dist/capabilities/wafer.ai.json +18 -18
  269. package/dist/capabilities/wallaby.json +5 -5
  270. package/dist/capabilities/wally.json +10 -10
  271. package/dist/capabilities/wandb.json +10 -10
  272. package/dist/capabilities/watt.json +26 -26
  273. package/dist/capabilities/xai.json +4 -4
  274. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -2
  275. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -2
  276. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -2
  277. package/dist/capabilities/xiaomi.json +2 -2
  278. package/dist/capabilities/xpersona.json +13 -13
  279. package/dist/capabilities/xxapi.json +28 -28
  280. package/dist/capabilities/zai-coding-plan.json +18 -18
  281. package/dist/capabilities/zai.json +30 -30
  282. package/dist/capabilities/zenifra.json +30 -30
  283. package/dist/capabilities/zenmux.json +205 -205
  284. package/dist/capabilities/zerogpu.json +11 -11
  285. package/dist/capabilities/zhipuai-coding-plan.json +2 -2
  286. package/dist/capabilities/zhipuai.json +30 -30
  287. package/dist/capabilities/zro.json +4 -4
  288. package/dist/channels/agent-channels.d.ts +29 -0
  289. package/dist/channels/attach-file-tool.d.ts +22 -0
  290. package/dist/channels/index.cjs +11 -2
  291. package/dist/channels/index.d.ts +10 -0
  292. package/dist/channels/index.js +3 -3
  293. package/dist/channels/output-processor.d.ts +12 -0
  294. package/dist/channels/reply-guidance-processor.d.ts +26 -0
  295. package/dist/channels/reply-mode.d.ts +66 -0
  296. package/dist/channels/reply-reminder-processor.d.ts +23 -0
  297. package/dist/channels/reply-tool.d.ts +43 -0
  298. package/dist/channels/state-adapter.d.ts +3 -1
  299. package/dist/channels/stream-helpers.d.ts +17 -0
  300. package/dist/channels/thread-link-processor.d.ts +48 -0
  301. package/dist/channels/thread-lookup.d.ts +16 -0
  302. package/dist/channels/tool-announcement-processor.d.ts +29 -0
  303. package/dist/channels/types.d.ts +25 -0
  304. package/dist/{channels-tVV_de9Q.cjs → channels-BVnDIsZS.cjs} +122 -1
  305. package/dist/{channels-Wh32drgu.js → channels-CndspFXP.js} +99 -2
  306. package/dist/coding-agent/index.cjs +2 -2
  307. package/dist/coding-agent/index.js +2 -2
  308. package/dist/{constants-B9ZDvXZ4.cjs → constants-Bou0hEgY.cjs} +4 -0
  309. package/dist/{constants-BmdTvEYN.js → constants-CFWgIaqA.js} +4 -0
  310. package/dist/datasets/experiment/index.d.ts +1 -1
  311. package/dist/datasets/experiment/item.d.ts +4 -3
  312. package/dist/datasets/experiment/scorer.d.ts +45 -11
  313. package/dist/datasets/index.cjs +3 -2
  314. package/dist/datasets/index.js +3 -3
  315. package/dist/{dist-ByO0vuJJ-BjMue5_p.cjs → dist-CufwpBZM-CwERFaas.cjs} +4 -4
  316. package/dist/{dist-ByO0vuJJ-CCXLBnvJ.js → dist-CufwpBZM-DK14Qe0Z.js} +4 -4
  317. package/dist/docs/SKILL.md +3 -1
  318. package/dist/docs/assets/SOURCE_MAP.json +1070 -1055
  319. package/dist/docs/references/docs-agents-code-mode.md +36 -0
  320. package/dist/docs/references/docs-agents-networks.md +1 -1
  321. package/dist/docs/references/docs-agents-tools.md +6 -0
  322. package/dist/docs/references/docs-auth-simple-auth.md +8 -8
  323. package/dist/docs/references/docs-browser.md +3 -1
  324. package/dist/docs/references/docs-channels.md +43 -0
  325. package/dist/docs/references/docs-evals-custom-scorers.md +1 -1
  326. package/dist/docs/references/docs-evals-experiments.md +13 -3
  327. package/dist/docs/references/docs-harness-background-tasks.md +38 -0
  328. package/dist/docs/references/docs-knowledge-agents-and-tools.md +2 -0
  329. package/dist/docs/references/docs-mastra-platform-observability-overview.md +3 -189
  330. package/dist/docs/references/docs-memory-message-history.md +25 -0
  331. package/dist/docs/references/docs-sandbox-lsp.md +5 -6
  332. package/dist/docs/references/docs-sandbox-overview.md +20 -0
  333. package/dist/docs/references/docs-sandbox-skills.md +2 -0
  334. package/dist/docs/references/docs-signals-sending-signals.md +1 -1
  335. package/dist/docs/references/integrations.md +1 -0
  336. package/dist/docs/references/reference-agent-controller-session.md +1 -1
  337. package/dist/docs/references/reference-agents-durable-agent.md +2 -0
  338. package/dist/docs/references/reference-agents-generate.md +1 -1
  339. package/dist/docs/references/reference-agents-network.md +1 -1
  340. package/dist/docs/references/reference-channels-thread-link.md +67 -0
  341. package/dist/docs/references/reference-configuration.md +8 -8
  342. package/dist/docs/references/reference-core-getWorkspaceById.md +37 -0
  343. package/dist/docs/references/reference-evals-create-scorer.md +5 -5
  344. package/dist/docs/references/reference-evals-run-evals.md +1 -1
  345. package/dist/docs/references/reference-knowledge-knowledge-tools.md +3 -3
  346. package/dist/docs/references/reference-manual-install.md +1 -1
  347. package/dist/docs/references/reference-memory-observational-memory.md +8 -0
  348. package/dist/docs/references/reference-observability-tracing-interfaces.md +10 -6
  349. package/dist/docs/references/reference-processors-processor-interface.md +3 -2
  350. package/dist/docs/references/reference-processors-system-prompt-scrubber.md +1 -1
  351. package/dist/docs/references/reference-processors-tool-search-processor.md +3 -3
  352. package/dist/docs/references/reference-pubsub-base.md +5 -3
  353. package/dist/docs/references/reference-pubsub-caching-pubsub.md +3 -1
  354. package/dist/docs/references/reference-storage-overview.md +1 -1
  355. package/dist/docs/references/reference-storage-retention.md +20 -20
  356. package/dist/docs/references/reference-tools-create-code-mode.md +22 -0
  357. package/dist/docs/references/reference-tools-vector-query-tool.md +8 -0
  358. package/dist/docs/references/reference-voice-overview.md +11 -26
  359. package/dist/docs/references/reference-voice-speech-to-speech.md +1 -1
  360. package/dist/docs/references/reference-voice-voice.listen.md +1 -0
  361. package/dist/docs/references/reference-voice-voice.speak.md +1 -3
  362. package/dist/docs/references/reference-workspace-factory-sandbox.md +8 -7
  363. package/dist/docs/references/reference-workspace-sandbox.md +14 -0
  364. package/dist/docs/references/reference.md +2 -0
  365. package/dist/evals/index.cjs +2 -2
  366. package/dist/evals/index.js +2 -2
  367. package/dist/evals/scoreTraces/index.cjs +2 -2
  368. package/dist/evals/scoreTraces/index.js +2 -2
  369. package/dist/events/index.cjs +1 -1
  370. package/dist/events/index.js +1 -1
  371. package/dist/harness/index.cjs +2 -2
  372. package/dist/harness/index.js +2 -2
  373. package/dist/index.cjs +1 -1
  374. package/dist/index.js +1 -1
  375. package/dist/knowledge/agent-scopes.d.ts +17 -0
  376. package/dist/knowledge/declarations.d.ts +2 -0
  377. package/dist/knowledge/held-scopes-state-processor.d.ts +50 -0
  378. package/dist/knowledge/importers/host.d.ts +7 -1
  379. package/dist/knowledge/importers/runner.d.ts +12 -0
  380. package/dist/knowledge/importers/types.d.ts +4 -0
  381. package/dist/knowledge/index.cjs +209 -38
  382. package/dist/knowledge/index.d.ts +12 -2
  383. package/dist/knowledge/index.js +208 -39
  384. package/dist/knowledge/page-tools.d.ts +23 -0
  385. package/dist/knowledge/pinned-state-processor.d.ts +2 -2
  386. package/dist/knowledge/run.d.ts +5 -0
  387. package/dist/knowledge/scope-runtime.d.ts +6 -0
  388. package/dist/llm/index.cjs +3 -3
  389. package/dist/llm/index.js +3 -3
  390. package/dist/llm/model/base.types.d.ts +3 -1
  391. package/dist/llm/model/mastra-gateway-provider-tools.d.ts +9 -6
  392. package/dist/llm/model/model.d.ts +1 -1
  393. package/dist/llm/model/model.loop.d.ts +1 -1
  394. package/dist/llm/model/model.loop.types.d.ts +3 -1
  395. package/dist/llm/model/provider-options.d.ts +4 -3
  396. package/dist/llm/model/provider-types.generated.d.ts +7091 -7163
  397. package/dist/{llm-BAiOsNAP.cjs → llm-B1semiTO.cjs} +38 -78
  398. package/dist/{llm-B1zaFLYZ.js → llm-CytL7cpw.js} +38 -78
  399. package/dist/loop/index.cjs +2 -2
  400. package/dist/loop/index.js +2 -2
  401. package/dist/{manager-BVX9nVrM.cjs → manager-BwyfS4ha.cjs} +220 -93
  402. package/dist/{manager-ChK9GdGz.js → manager-DnTzA9GL.js} +215 -94
  403. package/dist/mastra/index.cjs +1 -1
  404. package/dist/mastra/index.js +1 -1
  405. package/dist/{mastra-CUGfgEpZ.js → mastra-DTkZPpch.js} +17 -17
  406. package/dist/{mastra-HSmofHEJ.cjs → mastra-Dj35Lj_J.cjs} +17 -17
  407. package/dist/memory/index.cjs +3 -3
  408. package/dist/memory/index.js +3 -3
  409. package/dist/{message-list-KRbg-TnI.js → message-list-BGm1DCiG.js} +231 -130
  410. package/dist/{message-list-Cj0Sq_JP.cjs → message-list-vR3uLAHL.cjs} +351 -250
  411. package/dist/{model-C47BJRtR.js → model-DyQ07rPH.js} +4 -3
  412. package/dist/{model-WahorgzJ.cjs → model-eDfetuno.cjs} +4 -3
  413. package/dist/{netlify-D99AnEhW.cjs → netlify-BC4v7Ufv.cjs} +41377 -30474
  414. package/dist/{netlify-CfDXkuLf.js → netlify-BUvdxfHe.js} +41373 -30476
  415. package/dist/notifications/index.cjs +1 -1
  416. package/dist/notifications/index.js +1 -1
  417. package/dist/observability/types/tracing.d.ts +1 -1
  418. package/dist/processor-provider/index.cjs +1 -1
  419. package/dist/processor-provider/index.js +1 -1
  420. package/dist/processors/index.cjs +2 -2
  421. package/dist/processors/index.js +2 -2
  422. package/dist/processors/processors/tool-search.d.ts +2 -2
  423. package/dist/processors/runner.d.ts +12 -0
  424. package/dist/{provider-registry-CO1NVbO5.cjs → provider-registry-Bn01gq9y.cjs} +22180 -22242
  425. package/dist/{provider-registry-CR385GJ4.js → provider-registry-CP_5SNiw.js} +22181 -22243
  426. package/dist/provider-registry.json +22417 -22539
  427. package/dist/{registry-generator-B3erRqYS.js → registry-generator-CDPyxbzt.js} +1 -1
  428. package/dist/{registry-generator-Cvp34qcB.cjs → registry-generator-CNFKGRFQ.cjs} +1 -1
  429. package/dist/{rehydrate-CJBLrZxs.js → rehydrate-CnGNY2zq.js} +2 -2
  430. package/dist/{rehydrate-Da4hNuaK.cjs → rehydrate-DExpzlNS.cjs} +2 -2
  431. package/dist/relevance/index.cjs +2 -2
  432. package/dist/relevance/index.js +2 -2
  433. package/dist/{run-registry-DdeEBsVW.js → run-registry-BL_kKvFE.js} +1559 -298
  434. package/dist/{run-registry-TOOfO3hT.cjs → run-registry-CibQoN6K.cjs} +1637 -298
  435. package/dist/storage/constants.cjs +1 -1
  436. package/dist/storage/constants.js +1 -1
  437. package/dist/storage/domains/knowledge/base.d.ts +16 -1
  438. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +1 -0
  439. package/dist/storage/domains/knowledge/importers.d.ts +8 -0
  440. package/dist/storage/domains/knowledge/inmemory.d.ts +1 -0
  441. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +5 -1
  442. package/dist/storage/index.cjs +3 -3
  443. package/dist/storage/index.js +3 -3
  444. package/dist/storage/types.d.ts +8 -0
  445. package/dist/stream/index.cjs +2 -2
  446. package/dist/stream/index.js +2 -2
  447. package/dist/{stream-C5PagEDs.js → stream-1DGoEkG2.js} +37 -14
  448. package/dist/{stream-DH7Qgz8l.cjs → stream-D_7tMaJe.cjs} +37 -14
  449. package/dist/test-utils/llm-mock.cjs +1 -1
  450. package/dist/test-utils/llm-mock.js +1 -1
  451. package/dist/{to-prompt-B9eZo2U5.cjs → to-prompt-CG-LyaBY.cjs} +9 -0
  452. package/dist/{to-prompt-BsDtVXrf.js → to-prompt-CMlVGYxC.js} +9 -0
  453. package/dist/tool-loop-agent/index.cjs +1 -1
  454. package/dist/tool-loop-agent/index.js +1 -1
  455. package/dist/{tool-loop-agent-DVYJXlQJ.js → tool-loop-agent-BXya_RYj.js} +4 -4
  456. package/dist/{tool-loop-agent-CJTs4T8b.cjs → tool-loop-agent-CLB1r3X3.cjs} +4 -4
  457. package/dist/tools/code-mode/index.d.ts +2 -0
  458. package/dist/tools/code-mode/log-collector.d.ts +49 -0
  459. package/dist/tools/code-mode/types.d.ts +71 -0
  460. package/dist/tools/index.cjs +3 -1
  461. package/dist/tools/index.js +2 -2
  462. package/dist/{tools-CGF5Ik6j.cjs → tools-BEYxowf0.cjs} +429 -61
  463. package/dist/{tools-CDfyMpzN.js → tools-tPy2FwMI.js} +418 -62
  464. package/dist/{utils-xJi_N6Tx.cjs → utils-B-KOMA_Q.cjs} +7 -6
  465. package/dist/{utils-D8upuTwy.js → utils-C55ZdVaj.js} +7 -6
  466. package/dist/utils.cjs +1 -1
  467. package/dist/utils.js +1 -1
  468. package/dist/{validate-DTkW3Vlp.js → validate-BDfYr72F.js} +1 -1
  469. package/dist/{validate-6eZ8Wssn.cjs → validate-CmZhnsmX.cjs} +1 -1
  470. package/dist/vector/index.cjs +2 -2
  471. package/dist/vector/index.js +2 -2
  472. package/dist/worker/index.cjs +1 -1
  473. package/dist/worker/index.js +1 -1
  474. package/dist/worker/workers/orchestration-worker.d.ts +1 -0
  475. package/dist/{worker-DbcFkKJO.js → worker-BG1rw_dg.js} +5 -5
  476. package/dist/{worker-24ORi-wV.cjs → worker-BoybIUTI.cjs} +10 -4
  477. package/dist/{worker-Dqubrnf8.js → worker-CuK2RaC0.js} +2 -2
  478. package/dist/{worker-BO3u_WjZ.cjs → worker-D2B-x7Le.cjs} +2 -2
  479. package/dist/{workflow-wXOf72fO.js → workflow-Bt09PcH1.js} +3 -3
  480. package/dist/{workflow-D5Fc5ieC.cjs → workflow-CTKqeRXU.cjs} +3 -3
  481. package/dist/workflows/builder/index.cjs +1 -1
  482. package/dist/workflows/builder/index.js +1 -1
  483. package/dist/workflows/evented/index.cjs +1 -1
  484. package/dist/workflows/evented/index.js +1 -1
  485. package/dist/workflows/index.cjs +4 -4
  486. package/dist/workflows/index.js +4 -4
  487. package/dist/workflows/step.d.ts +2 -0
  488. package/dist/workflows/workflow.d.ts +2 -0
  489. package/dist/workspace/index.cjs +3 -1
  490. package/dist/workspace/index.d.ts +1 -1
  491. package/dist/workspace/index.js +2 -2
  492. package/dist/workspace/lsp/manager.d.ts +19 -4
  493. package/dist/workspace/sandbox/mastra-sandbox.d.ts +17 -0
  494. package/dist/workspace/sandbox/teardown-context.d.ts +74 -0
  495. package/dist/workspace/tools/index.d.ts +1 -0
  496. package/dist/workspace/tools/media.d.ts +20 -1
  497. package/dist/workspace/tools/recreate-sandbox.d.ts +24 -0
  498. package/dist/{workspace-X2RHJZU9.cjs → workspace-C8Zo5_qK.cjs} +387 -109
  499. package/dist/{workspace-DY2Nxiyi.js → workspace-DOAil8mG.js} +376 -110
  500. package/package.json +8 -8
  501. package/src/llm/model/provider-types.generated.d.ts +7091 -7163
  502. /package/dist/_types/{@ai-sdk_provider-utils@4.0.66 → @ai-sdk_provider-utils@4.0.67}/dist/index.d.ts +0 -0
  503. /package/dist/_types/{@ai-sdk_provider-utils@4.0.66 → @ai-sdk_provider-utils@4.0.67}/package.json +0 -0
@@ -4,18 +4,18 @@ import { t as MastraBase } from "./base-CKLWBhDo.js";
4
4
  import { A as compactStopReasonContext, D as agentLoopTermination, O as executionFailureTermination, S as resolveObservabilityContext, b as wrapMastra, i as subtractReportedUsage, k as tripwireTermination, n as extractUsageMetrics, r as isUsageIncomplete, t as calculateObservedUsage, x as createObservabilityContext, y as unwrapMastraTracingProxy } from "./observability-D7RNOAPx.js";
5
5
  import { a as MastraNonRetryableError, i as MastraError, n as ErrorDomain, o as getErrorFromUnknown, t as ErrorCategory } from "./error-oh2DLsP2.js";
6
6
  import { a as classifyProviderError, l as describeProviderError, t as recordTerminalErrorMessage, u as readProviderErrorDetails } from "./error-BC9Au-22.js";
7
- import { $ as resolveProcessorSpanAttributes, $t as computeModelOutputProviderMetadata, A as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, An as safeError, B as ProviderHistoryCompat, Bt as summarizeStepResult, C as markChunkOutputProcessed, Cn as isMastraTimeoutError, Ct as resolveTemplate, D as asJsonSchema, Dn as MastraModelInput, Dt as getStepResult, E as isStructuredOutputError, Et as validateTemplate, F as findOwnModelStepSpan, Ft as materializeState, G as REPROCESS_PART_KEY, Gt as patchState, Ht as applyStatePatch, It as materializeWorkflowRun, J as summarizeActiveToolsForSpan, Jt as isObservationalMemoryEnabled$1, K as takeHeldParts, L as isTrailingAssistantGuardContinuation, Lt as pickStateKeys, M as ProcessorState, Mn as createRunScopeKey, Mt as applyStateColumnsWrite, N as endOutputStreamSpanAtStepEnd, Nt as isStateCheckpointDue, O as getResponseFormat, On as safeClose, Ot as getStepResultAsync, P as endOutputStreamSpanOutsideStep, Pt as latestStepResults, Q as summarizeToolChoiceForSpan, Qt as commitToolResult, R as needsTrailingAssistantGuard, Rt as stateBaseOf, S as stampChunkProducedAt, Sn as guardStreamWithAbort, T as escapeUnescapedControlCharsInJsonStrings, Tn as settledOrElapsed, Tt as traverseMappingPath, Vt as unusedStateEntries, W as FLUSH_HELD_PARTS_KEY, Wt as diffStateAsJson, X as summarizeProcessorResultForSpan, Xt as parseMemoryRequestContext, Y as summarizeProcessorModelForSpan, Z as summarizeProcessorToolsForSpan, _ as reconcileBufferedStepTexts, _n as DEADLINE_SAVE_WAIT_MS, _t as collectMappingStepRefs, a as convertFullStreamChunkToMastra, an as withAgentWorkflowToolMarker, at as RunJournal, b as resolveProcessorWriterMessageId, bn as getAbortReason, bt as resolveStepOutputs, c as WorkflowRunOutput, cn as isProcessorWorkflow, ct as hydrateStepResults, d as MastraModelOutput, dn as resolveThreadIdFromArgs, dt as loadStepResults, en as hasToolResultProcessor, et as resolveProcessorSpanName, f as clearStepPartIndexes, fn as supportedLanguageModelSpecifications, ft as loadedStepResults, g as persistProcessorDataChunk, gn as DEADLINE_SAVE_CLAIM_HOLD_MS, gt as stubStepResult, h as findStepPartBoundaries, hn as applyStateSignal, ht as storageV2StepResultAccessors, in as snapshotToolResult, it as PROCESSOR_ABORT_SIGNAL, j as ProcessorRunner, jn as createRunScope, k as isSignalChunkExcluded, kn as safeEnqueue, kt as getSnapshotMemoryInfo, l as TripWire, ln as isSupportedLanguageModel, lt as isStepResultStub, m as findIterationOffsetInParts, mn as tryStreamWithJsonFallback, mt as residentStepResultsLoader, nn as readModelOutput, nt as PROCESSOR_LATE_SIGNAL_SINK, on as normalizeModelOutput, ot as buildStepResultAccessors, p as createDestructurableOutput, pn as tryGenerateWithJsonFallback, pt as residentStepResults, q as withoutHeldContent, rn as resolveModelOutputAfterToolResultProcessors, rt as createProcessorSendSignal, s as MastraAgentNetworkStream, sn as validationErrorModelOutput, st as getHydratedStepResult, tn as latestProcessedModelOutput, tt as toProcessorSpanPhase, u as getModelOutputForTripwire, un as resolveSuspendedToolRunId, ut as lazyStepResults, v as resolveMessageText, vn as MastraTimeoutError, vt as collectPredicateStepRefs, w as createOutputHandler, wn as raceAgainstAbort, wt as templateReadsState, x as getChunkProducedAt, xn as guardStreamUntilMatch, xt as stepRefId, y as resolveOutputMessageSkippingCompletionChecks, yn as createTimeoutAbortSignal, yt as predicateReadsState, z as removeTrailingAssistantGuardContinuations, zt as stateColumnsWrite } from "./stream-C5PagEDs.js";
7
+ import { $ as resolveProcessorSpanAttributes, $t as computeModelOutputProviderMetadata, A as OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX, An as safeError, B as ProviderHistoryCompat, Bt as summarizeStepResult, C as markChunkOutputProcessed, Cn as isMastraTimeoutError, Ct as resolveTemplate, D as asJsonSchema, Dn as MastraModelInput, Dt as getStepResult, E as isStructuredOutputError, Et as validateTemplate, F as findOwnModelStepSpan, Ft as materializeState, G as REPROCESS_PART_KEY, Gt as patchState, Ht as applyStatePatch, It as materializeWorkflowRun, J as summarizeActiveToolsForSpan, Jt as isObservationalMemoryEnabled$1, K as takeHeldParts, L as isTrailingAssistantGuardContinuation, Lt as pickStateKeys, M as ProcessorState, Mn as createRunScopeKey, Mt as applyStateColumnsWrite, N as endOutputStreamSpanAtStepEnd, Nt as isStateCheckpointDue, O as getResponseFormat, On as safeClose, Ot as getStepResultAsync, P as endOutputStreamSpanOutsideStep, Pt as latestStepResults, Q as summarizeToolChoiceForSpan, Qt as commitToolResult, R as needsTrailingAssistantGuard, Rt as stateBaseOf, S as stampChunkProducedAt, Sn as guardStreamWithAbort, T as escapeUnescapedControlCharsInJsonStrings, Tn as settledOrElapsed, Tt as traverseMappingPath, Vt as unusedStateEntries, W as FLUSH_HELD_PARTS_KEY, Wt as diffStateAsJson, X as summarizeProcessorResultForSpan, Xt as parseMemoryRequestContext, Y as summarizeProcessorModelForSpan, Z as summarizeProcessorToolsForSpan, _ as reconcileBufferedStepTexts, _n as DEADLINE_SAVE_WAIT_MS, _t as collectMappingStepRefs, a as convertFullStreamChunkToMastra, an as withAgentWorkflowToolMarker, at as RunJournal, b as resolveProcessorWriterMessageId, bn as getAbortReason, bt as resolveStepOutputs, c as WorkflowRunOutput, cn as isProcessorWorkflow, ct as hydrateStepResults, d as MastraModelOutput, dn as resolveThreadIdFromArgs, dt as loadStepResults, en as hasToolResultProcessor, et as resolveProcessorSpanName, f as clearStepPartIndexes, fn as supportedLanguageModelSpecifications, ft as loadedStepResults, g as persistProcessorDataChunk, gn as DEADLINE_SAVE_CLAIM_HOLD_MS, gt as stubStepResult, h as findStepPartBoundaries, hn as applyStateSignal, ht as storageV2StepResultAccessors, in as snapshotToolResult, it as PROCESSOR_ABORT_SIGNAL, j as ProcessorRunner, jn as createRunScope, k as isSignalChunkExcluded, kn as safeEnqueue, kt as getSnapshotMemoryInfo, l as TripWire, ln as isSupportedLanguageModel, lt as isStepResultStub, m as findIterationOffsetInParts, mn as tryStreamWithJsonFallback, mt as residentStepResultsLoader, nn as readModelOutput, nt as PROCESSOR_LATE_SIGNAL_SINK, on as normalizeModelOutput, ot as buildStepResultAccessors, p as createDestructurableOutput, pn as tryGenerateWithJsonFallback, pt as residentStepResults, q as withoutHeldContent, rn as resolveModelOutputAfterToolResultProcessors, rt as createProcessorSendSignal, s as MastraAgentNetworkStream, sn as validationErrorModelOutput, st as getHydratedStepResult, tn as latestProcessedModelOutput, tt as toProcessorSpanPhase, u as getModelOutputForTripwire, un as resolveSuspendedToolRunId, ut as lazyStepResults, v as resolveMessageText, vn as MastraTimeoutError, vt as collectPredicateStepRefs, w as createOutputHandler, wn as raceAgainstAbort, wt as templateReadsState, x as getChunkProducedAt, xn as guardStreamUntilMatch, xt as stepRefId, y as resolveOutputMessageSkippingCompletionChecks, yn as createTimeoutAbortSignal, yt as predicateReadsState, z as removeTrailingAssistantGuardContinuations, zt as stateColumnsWrite } from "./stream-1DGoEkG2.js";
8
8
  import { c as MASTRA_THREAD_ID_KEY, d as isReservedRequestContextKey, f as mergeVersionOverrides$1, l as MASTRA_VERSIONS_KEY, n as MASTRA_AUTH_TOKEN_KEY, o as MASTRA_RESOURCE_ID_KEY, p as withoutLiveRequestKeys, r as MASTRA_INHERITED_MEMORY_KEY, s as MASTRA_SCOPES_KEY, t as MASTRA_CONTINUATION_TOOL_CALL_IDS_KEY, u as RequestContext } from "./request-context-COnZHt2-.js";
9
9
  import { S as withAck, _ as serializeError$1, h as stripModelSnapshots, n as PublisherQueueLimitError, p as slimNestedAgentChunks, r as CachingPubSub, t as DefaultStepResult, u as isRunLocalTopic, v as EventEmitterPubSub, x as isLeaseProvider, y as NoopLeaseProvider } from "./output-helpers-CVzhy1Y0.js";
10
- import { A as stableStringify$1, E as removeWorkingMemoryTags, P as embed$3, Z as preserveResponseItemIdsOnMerge, a as isTerminalToolInvocationState, c as withUnavailableAttachmentUrls, d as aiV5UIMessagesToAIV5ModelMessages, f as coreContentToString, i as isClientToolInvocationUpdate, l as isDownloadAssetsError, m as filterMessagesForPersistence, n as MessageList, ot as normalizeToolOutput, p as messagesAreEqual, r as advancesToolInvocationState, s as unavailableAttachmentPlaceholder, t as convertMessages, u as MessageMerger } from "./message-list-KRbg-TnI.js";
10
+ import { A as stableStringify$1, E as removeWorkingMemoryTags, P as embed$3, Z as preserveResponseItemIdsOnMerge, a as isTerminalToolInvocationState, c as withUnavailableAttachmentUrls, d as aiV5UIMessagesToAIV5ModelMessages, f as coreContentToString, i as isClientToolInvocationUpdate, l as isDownloadAssetsError, m as filterMessagesForPersistence, n as MessageList, ot as normalizeToolOutput, p as messagesAreEqual, r as advancesToolInvocationState, s as unavailableAttachmentPlaceholder, t as convertMessages, u as MessageMerger } from "./message-list-BGm1DCiG.js";
11
11
  import { Bt as listScoresArgsSchema, Ft as listLogsArgsSchema, Lt as listMetricsArgsSchema, Nt as listFeedbackArgsSchema, t as EntityType } from "./storage-Cc50aQAp.js";
12
12
  import { a as getOrCreateSpan, f as resolveCurrentSpan, l as getTimeToFirstChunkMs, n as executeWithContextSync, o as getResumeTracingContext, p as resolveExportedSpanId, s as getRootExportSpan, t as executeWithContext, u as getWorkflowResumeTracingContext } from "./utils-DU_pU5SK.js";
13
13
  import { i as setSpanErrorOrigin, n as getSpanErrorOrigin } from "./error-count-BH-rJW7q.js";
14
- import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-B1zaFLYZ.js";
14
+ import { a as ModelRouterLanguageModel, d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, n as ModelRouterEmbeddingModel, o as resolveApiProviderId, p as readModelStreamTransport } from "./llm-CytL7cpw.js";
15
15
  import { a as withToolPayloadTransformMetadata, i as transformToolPayloadForTargets, n as hasTransformedToolPayload, o as withToolPayloadTransformProviderMetadata, r as normalizeToolPayloadTransformPolicy, t as getTransformedToolPayload } from "./payload-transform-Dj3HUeD4.js";
16
16
  import { boundedStringify, ensureSerializable, safeStringify } from "./utils/safe-stringify.js";
17
17
  import { d as signalSpanAttributes, h as signalToXmlMarkup, l as mastraDBMessageToSignal, n as createSignal, o as isMastraSignalMessage, s as isTransientSignalMessage, u as resolveDeliveryAttributes } from "./signals-CqR_iWkg.js";
18
- import { h as resolveFilePartMediaTypeAndData, m as parseDataUri, o as categorizeFileData } from "./to-prompt-BsDtVXrf.js";
18
+ import { h as resolveFilePartMediaTypeAndData, m as parseDataUri, o as categorizeFileData } from "./to-prompt-CMlVGYxC.js";
19
19
  import { c as parsePartialJson, h as tool$1, m as generateId$1, p as asSchema$1, r as embed$4, u as APICallError$1 } from "./dist-TPVqg8oV.js";
20
20
  import { n as embed$5 } from "./dist-D3cKCUe-.js";
21
21
  import { t as deepEqual$3 } from "./deep-equal-d1xU02ag.js";
@@ -24,13 +24,13 @@ import { _ as getRequestContextInputValues, a as getModelFacingValidationError,
24
24
  import { a as isApprovalExempt, c as isProviderDefinedTool, d as markAgentWorkflowTool, f as markApprovalExempt, l as isProviderTool, n as getNeedsApprovalFn, o as isBuiltBeforeApproval, r as getProviderToolName, s as isMastraTool, t as getBeforeApprovalFn } from "./toolchecks-DrsZdc3S.js";
25
25
  import { a as waitDelay, i as getRetryAfterMs, n as DEFAULT_MAX_RETRY_AFTER_MS, r as clampDelayMs } from "./fetchWithRetry-DFSvpYDT.js";
26
26
  import { i as hasFreeFormObject } from "./model-DS-b2R-R.js";
27
- import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-CR385GJ4.js";
27
+ import { c as modelSupportsStructuredOutput, l as modelSupportsTemperature } from "./provider-registry-CP_5SNiw.js";
28
28
  import { t as InMemoryServerCache } from "./inmemory-BK3zLwvM.js";
29
29
  import { n as resolveDynamicArgument, t as getRequestUser } from "./dynamic-argument-BzPK3qPN.js";
30
- import { t as MastraLLMV1 } from "./model-C47BJRtR.js";
31
- import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-D8upuTwy.js";
30
+ import { t as MastraLLMV1 } from "./model-DyQ07rPH.js";
31
+ import { A as eagerToolCallDidNotExecute, D as EagerToolExecutionCoordinator, E as EAGER_TOOL_EXECUTION_MARKER, F as hasRunningRunStep, I as isRunStepActive, L as setRunLeaseFence, M as isEagerlyExecutableToolCall, N as TOOL_ABORT_NOTICE, O as EagerToolExecutionNotRun, P as clearRunLeaseFence, R as startRunStep, S as selectFields, T as EAGER_TOOL_BAILOUT, a as ensureToolProperties, b as removeUndefinedValues, d as makeCoreTool, i as delay$1, j as eagerToolCallSuspensionIntent, k as eagerToolCallAlreadyAnnouncedInput, n as createMastraProxy, o as generateEmptyFromSchema, p as makeProcessorCoreTool, r as deepMerge$1, v as readPositiveIntEnv, w as EAGER_TOOL_ABORT_SIGNAL, y as rebindProcessorTools, z as whenRunStepsSettle } from "./utils-C55ZdVaj.js";
32
32
  import { h as getWorkflowFGAResourceId, i as MastraFGAPermissions, y as requireFGA } from "./ee-iTj2bRDt-By_B9ngH.js";
33
- import { a as resolveBackgroundConfig, o as createBackgroundTask, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-IW7M4iD2.js";
33
+ import { c as createBackgroundTask, o as resolveBackgroundConfig, s as sanitizeToolArguments, t as generateBackgroundTaskSystemPrompt } from "./background-tasks-CgzXjBfE.js";
34
34
  import { t as ToolStream } from "./stream-D9JOykz7.js";
35
35
  import { MISSING, collectInvalidPredicatePaths, createPredicateEvaluator, derivePredicateLabel, normalizePredicatePath, walk } from "./predicate/index.js";
36
36
  import { Classifier } from "./classifier/index.js";
@@ -39,11 +39,11 @@ import { HAND_BACK_STATE_SYMBOL, PARENT_STATE_SYMBOL, PUBSUB_SYMBOL, STREAM_FORM
39
39
  import { i as executeHook } from "./hooks-Bth8Cjpj.js";
40
40
  import { o as assertValidScheduleDefinition, v as validateScheduleTiming } from "./schedules-DZfSx-7P.js";
41
41
  import { A as writeObjective, D as readObjective, O as resolveEffectiveGoalSettings, T as formatGoalBudgetPausedReason, _ as clearCachedGoalObjective, b as GOAL_SCORER_ID, g as cacheGoalObjective, k as resolveGoalStore, w as clearObjective, x as GOAL_SCORE_WAITING } from "./state-processor-B9kxpM53.js";
42
- import { An as computeTraceStatus, Cr as extractTrajectory, Dr as saveScorePayloadSchema, It as TABLE_SCHEMAS, Lt as TABLE_SCORERS, Nn as extractBranchSpans, Pn as getBranchArgsSchema, Qn as listTracesArgsSchema, Sr as withBufferedReflectionVerified, Tr as extractWorkflowTrajectory, Yn as listBranchesArgsSchema, _r as isAppendOnlySince, ar as spanRecordSchema, br as maxObservationCursor, cr as toTraceSpans, gn as BRANCH_SPAN_TYPE_SET, gr as compareObservationalMemoryHeadOrder, hr as assertActiveObservationsApplied, or as toLightSpanRecord, pn as matchesExpectedWorkflowStatus, qn as isPreviewTruncated, sr as toTraceSpan, vn as TraceStatus, vr as isBufferedChunkCoveredByCursor, wr as extractTrajectoryFromTrace, xr as planReflectionGenerationText, yr as isBufferedReflectionUnchangedSince } from "./constants-BmdTvEYN.js";
42
+ import { An as computeTraceStatus, Cr as extractTrajectory, Dr as saveScorePayloadSchema, It as TABLE_SCHEMAS, Lt as TABLE_SCORERS, Nn as extractBranchSpans, Pn as getBranchArgsSchema, Qn as listTracesArgsSchema, Sr as withBufferedReflectionVerified, Tr as extractWorkflowTrajectory, Yn as listBranchesArgsSchema, _r as isAppendOnlySince, ar as spanRecordSchema, br as maxObservationCursor, cr as toTraceSpans, gn as BRANCH_SPAN_TYPE_SET, gr as compareObservationalMemoryHeadOrder, hr as assertActiveObservationsApplied, or as toLightSpanRecord, pn as matchesExpectedWorkflowStatus, qn as isPreviewTruncated, sr as toTraceSpan, vn as TraceStatus, vr as isBufferedChunkCoveredByCursor, wr as extractTrajectoryFromTrace, xr as planReflectionGenerationText, yr as isBufferedReflectionUnchangedSince } from "./constants-CFWgIaqA.js";
43
43
  import { t as GoalSignalProvider } from "./signal-provider-BslnAjWG.js";
44
44
  import { t as slugify } from "./slugify-BUNmb-Ga.js";
45
- import { N as LocalSandbox, at as LocalFilesystem, dt as sliceByTokensSafe, ft as estimateTokenCount, it as normalizeReadTrackerPath, lt as WORKSPACE_TOOLS, m as resolveToolConfig, mt as shellQuote, o as Workspace, p as createWorkspaceTools, pt as sliceByTokens, rt as evaluateReadRecord, s as createSkillTools, st as CompositeFilesystem } from "./workspace-DY2Nxiyi.js";
46
- import { i as normalizeWebSearchProvider, n as createWebSearchProviderTool, r as isWebSearchTool } from "./tools-CDfyMpzN.js";
45
+ import { F as LocalSandbox, at as evaluateReadRecord, c as Workspace, dt as WORKSPACE_TOOLS, g as resolveToolConfig, gt as shellQuote, h as createWorkspaceTools, ht as sliceByTokens, l as createSkillTools, lt as CompositeFilesystem, mt as estimateTokenCount, ot as normalizeReadTrackerPath, pt as sliceByTokensSafe, st as LocalFilesystem } from "./workspace-DOAil8mG.js";
46
+ import { i as normalizeWebSearchProvider, n as createWebSearchProviderTool, r as isWebSearchTool } from "./tools-tPy2FwMI.js";
47
47
  import { D as BM25Index, O as tokenize } from "./workspace-skills-38OY32_b.js";
48
48
  import { f as calculatePagination, g as InMemoryThreadStateStorage, h as resolveListOrderBy, m as normalizePerPage, p as compareByField, s as StorageDomain, u as MastraCompositeStore } from "./filesystem-versioned-BL1ojJLo.js";
49
49
  import { coreFeatures } from "./features/index.js";
@@ -65,11 +65,11 @@ import { ReadableStream as ReadableStream$1, TransformStream as TransformStream$
65
65
  import { injectJsonInstructionIntoMessages, isAbortError } from "@ai-sdk/provider-utils-v6";
66
66
  import { z as z$1 } from "zod";
67
67
  import { createHash, randomUUID } from "crypto";
68
+ import { config, toJSONSchema } from "zod/v4/core";
69
+ import en from "zod/v4/locales/en.js";
68
70
  import { prepareJsonSchemaForOpenAIStrictMode, wrapSchemaWithNullTransform } from "@mastra/schema-compat";
69
71
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
70
72
  import { dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep, win32 } from "path";
71
- import { config, toJSONSchema } from "zod/v4/core";
72
- import en from "zod/v4/locales/en.js";
73
73
  import { jsonSchemaToZod } from "@mastra/schema-compat/json-to-zod";
74
74
  import { AsyncLocalStorage } from "async_hooks";
75
75
  import fastq from "fastq";
@@ -7613,6 +7613,7 @@ function createStepFromProcessor$1(processor) {
7613
7613
  };
7614
7614
  const step = {
7615
7615
  id: `processor:${processor.id}`,
7616
+ processorId: processor.id,
7616
7617
  description: processor.name ?? `Processor ${processor.id}`,
7617
7618
  inputSchema: toStandardSchema(ProcessorStepInputSchema),
7618
7619
  outputSchema: toStandardSchema(ProcessorStepOutputSchema),
@@ -8258,7 +8259,8 @@ function cloneStep$1(step, opts) {
8258
8259
  retries: step.retries,
8259
8260
  scorers: step.scorers,
8260
8261
  component: step.component,
8261
- metadata: step.metadata
8262
+ metadata: step.metadata,
8263
+ processorId: step.processorId
8262
8264
  };
8263
8265
  }
8264
8266
  /**
@@ -11708,6 +11710,21 @@ function warnUnsupportedEventedSetup(mastra, workflowsStore) {
11708
11710
  warnedHosts.add(mastra);
11709
11711
  mastra.getLogger()?.warn(`Evented workflows and agents aren't supported on several processes with this setup: ${missing}. See ${DOCS_URL}`);
11710
11712
  }
11713
+ // src/agent-controller/worker-run-binding.ts
11714
+ const CONTROLLER_RUN_BINDING_KEY = "mastra__controllerRunBinding";
11715
+ const controllerRunBindingSchema = z.object({
11716
+ controllerId: z.string().min(1),
11717
+ agentId: z.string().min(1),
11718
+ sessionId: z.string().min(1),
11719
+ ownerId: z.string(),
11720
+ resourceId: z.string().min(1),
11721
+ threadId: z.string().min(1),
11722
+ modeId: z.string().min(1)
11723
+ });
11724
+ const restoredWorkerControllerContexts = /* @__PURE__ */ new WeakSet();
11725
+ function isRestoredWorkerControllerContext(value) {
11726
+ return typeof value === "object" && value !== null && restoredWorkerControllerContexts.has(value);
11727
+ }
11711
11728
  // src/agent/scopes.ts
11712
11729
  /**
11713
11730
  * Scope types Memory reads as the run's identity. Every other scope type is
@@ -11996,6 +12013,7 @@ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
11996
12013
  if (key === "mastra__versions") continue;
11997
12014
  if (key === "mastra__durableExecutions") continue;
11998
12015
  if (key === "mastra__durableSegments") continue;
12016
+ if (key === "__mastra_chat_channel_render") continue;
11999
12017
  const json = boundedStringify(value);
12000
12018
  if (json === void 0) {
12001
12019
  onEntryOmitted?.();
@@ -12022,6 +12040,8 @@ function restoreRequestContext(entries, runLevel, liveRunContext) {
12022
12040
  if (liveRunContext) return liveRunContext;
12023
12041
  if (entries) {
12024
12042
  const restored = new RequestContext([...Object.entries(withoutLiveRequestKeys(entries)), ...liveRequestEntries(runLevel)]);
12043
+ const controller = runLevel?.get("controller");
12044
+ if (isRestoredWorkerControllerContext(controller)) restored.set("controller", controller);
12025
12045
  restoreRunAgentScopes(restored);
12026
12046
  return restored;
12027
12047
  }
@@ -12034,6 +12054,118 @@ function liveRequestEntries(runLevel) {
12034
12054
  const kept = withoutLiveRequestKeys(live);
12035
12055
  return Object.entries(live).filter(([key]) => !(key in kept));
12036
12056
  }
12057
+ // src/agent/streams/constants.ts
12058
+ /**
12059
+ * Topics and event types of an agent's resumable run stream.
12060
+ */
12061
+ /**
12062
+ * Generate the pubsub topic name for agent streaming events
12063
+ * @param runId - The unique run identifier
12064
+ * @returns The topic name for subscribing/publishing agent stream events
12065
+ */
12066
+ const AGENT_STREAM_TOPIC = (runId) => `agent.stream.${runId}`;
12067
+ /**
12068
+ * Generate the pubsub topic name for agent control messages.
12069
+ *
12070
+ * Separate from {@link AGENT_STREAM_TOPIC} because control messages travel the
12071
+ * opposite direction: stream events flow worker -> consumer, control messages
12072
+ * flow caller -> worker. Keeping them apart means stream consumers never see
12073
+ * control traffic and vice versa.
12074
+ *
12075
+ * @param runId - The unique run identifier
12076
+ * @returns The topic name for publishing/subscribing agent control events
12077
+ */
12078
+ const AGENT_CONTROL_TOPIC = (runId) => `agent.control.${runId}`;
12079
+ /**
12080
+ * Event type constants for agent control events
12081
+ */
12082
+ const AgentControlEventTypes = {
12083
+ /**
12084
+ * Request that a run abort itself. Published by `abort()` in whichever
12085
+ * process the caller lives in; handled by whichever process is actually
12086
+ * executing the run's steps.
12087
+ */
12088
+ ABORT_REQUEST: "abort-request" };
12089
+ /**
12090
+ * Event type constants for agent stream events
12091
+ */
12092
+ const AgentStreamEventTypes = {
12093
+ /** Chunk of streaming data (text, tool call, etc.) */
12094
+ CHUNK: "chunk",
12095
+ /** Internal boundary preceding all output from an LLM execution step. */
12096
+ ITERATION_START: "iteration-start",
12097
+ /** Start of a new step in the agentic loop */
12098
+ STEP_START: "step-start",
12099
+ /** End of a step in the agentic loop */
12100
+ STEP_FINISH: "step-finish",
12101
+ /** Agent execution completed successfully */
12102
+ FINISH: "finish",
12103
+ /** Error occurred during execution */
12104
+ ERROR: "error",
12105
+ /** Workflow suspended (e.g., for tool approval) */
12106
+ SUSPENDED: "suspended",
12107
+ /** Execution aborted by abortSignal */
12108
+ ABORT: "abort",
12109
+ /** Single agentic-loop iteration completed (observability hook) */
12110
+ ITERATION_COMPLETE: "iteration-complete",
12111
+ /**
12112
+ * A new execution claimed the run. Carries no chunk: consumers only raise
12113
+ * their generation so events the superseded execution still publishes are
12114
+ * dropped.
12115
+ */
12116
+ OWNERSHIP_CLAIMED: "ownership-claimed"
12117
+ };
12118
+ // src/agent/durable/constants.ts
12119
+ const DURABLE_STOP_WHEN_ERROR_ID = "DURABLE_AGENT_STOP_WHEN_FAILED";
12120
+ const REJECT_STREAM_ERROR = Symbol("mastra.durable.rejectStreamError");
12121
+ function markErrorForStreamRejection(error) {
12122
+ error[REJECT_STREAM_ERROR] = true;
12123
+ return error;
12124
+ }
12125
+ function shouldRejectStream(error) {
12126
+ return error[REJECT_STREAM_ERROR] === true;
12127
+ }
12128
+ /**
12129
+ * Default values for durable agent execution
12130
+ */
12131
+ const DurableAgentDefaults = {
12132
+ /** Default maximum number of agentic loop iterations */
12133
+ MAX_STEPS: 5,
12134
+ /**
12135
+ * Default tool call concurrency.
12136
+ * Applied by `resolveDurableToolCallConcurrency` when a run doesn't
12137
+ * configure `toolCallConcurrency`. Approval / suspend-capable tool sets
12138
+ * always run sequentially (concurrency: 1) regardless of this value.
12139
+ */
12140
+ TOOL_CALL_CONCURRENCY: 10
12141
+ };
12142
+ /**
12143
+ * Step IDs used in the durable agentic workflow
12144
+ */
12145
+ const DurableStepIds = {
12146
+ /** LLM execution step */
12147
+ LLM_EXECUTION: "durable-llm-execution",
12148
+ /** Tool call step */
12149
+ TOOL_CALL: "durable-tool-call",
12150
+ /** LLM mapping step (combines results) */
12151
+ LLM_MAPPING: "durable-llm-mapping",
12152
+ /** Agentic execution workflow (one iteration) */
12153
+ AGENTIC_EXECUTION: "durable-agentic-execution",
12154
+ /** Full agentic loop workflow */
12155
+ AGENTIC_LOOP: "durable-agentic-loop",
12156
+ /** Scorer execution step */
12157
+ SCORER_EXECUTION: "durable-scorer-execution",
12158
+ /** isTaskComplete evaluation step */
12159
+ IS_TASK_COMPLETE: "durable-is-task-complete"
12160
+ };
12161
+ /** The loop's last step, which ends the run's spans when it succeeds. */
12162
+ const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
12163
+ const RECOVER_ALREADY_IN_PROGRESS_ERROR_ID = "DURABLE_AGENT_RECOVER_ALREADY_IN_PROGRESS";
12164
+ const RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID = "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND";
12165
+ const RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID = "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE";
12166
+ const RECOVER_RUN_SUSPENDED_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_SUSPENDED";
12167
+ const RECOVER_RUN_NOT_ACTIVE_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_NOT_ACTIVE";
12168
+ const RECOVER_SHUTDOWN_ERROR_ID = "DURABLE_AGENT_RECOVER_SHUTDOWN";
12037
12169
  // src/agent/durable/execution-ownership-guard.ts
12038
12170
  /** One step's observation of its immutable driver's claim. Never renews it. */
12039
12171
  var ExecutionOwnershipGuard = class {
@@ -12151,67 +12283,6 @@ var ExecutionOwnershipGuard = class {
12151
12283
  this.#unsubscribe?.();
12152
12284
  }
12153
12285
  };
12154
- // src/agent/streams/constants.ts
12155
- /**
12156
- * Topics and event types of an agent's resumable run stream.
12157
- */
12158
- /**
12159
- * Generate the pubsub topic name for agent streaming events
12160
- * @param runId - The unique run identifier
12161
- * @returns The topic name for subscribing/publishing agent stream events
12162
- */
12163
- const AGENT_STREAM_TOPIC = (runId) => `agent.stream.${runId}`;
12164
- /**
12165
- * Generate the pubsub topic name for agent control messages.
12166
- *
12167
- * Separate from {@link AGENT_STREAM_TOPIC} because control messages travel the
12168
- * opposite direction: stream events flow worker -> consumer, control messages
12169
- * flow caller -> worker. Keeping them apart means stream consumers never see
12170
- * control traffic and vice versa.
12171
- *
12172
- * @param runId - The unique run identifier
12173
- * @returns The topic name for publishing/subscribing agent control events
12174
- */
12175
- const AGENT_CONTROL_TOPIC = (runId) => `agent.control.${runId}`;
12176
- /**
12177
- * Event type constants for agent control events
12178
- */
12179
- const AgentControlEventTypes = {
12180
- /**
12181
- * Request that a run abort itself. Published by `abort()` in whichever
12182
- * process the caller lives in; handled by whichever process is actually
12183
- * executing the run's steps.
12184
- */
12185
- ABORT_REQUEST: "abort-request" };
12186
- /**
12187
- * Event type constants for agent stream events
12188
- */
12189
- const AgentStreamEventTypes = {
12190
- /** Chunk of streaming data (text, tool call, etc.) */
12191
- CHUNK: "chunk",
12192
- /** Internal boundary preceding all output from an LLM execution step. */
12193
- ITERATION_START: "iteration-start",
12194
- /** Start of a new step in the agentic loop */
12195
- STEP_START: "step-start",
12196
- /** End of a step in the agentic loop */
12197
- STEP_FINISH: "step-finish",
12198
- /** Agent execution completed successfully */
12199
- FINISH: "finish",
12200
- /** Error occurred during execution */
12201
- ERROR: "error",
12202
- /** Workflow suspended (e.g., for tool approval) */
12203
- SUSPENDED: "suspended",
12204
- /** Execution aborted by abortSignal */
12205
- ABORT: "abort",
12206
- /** Single agentic-loop iteration completed (observability hook) */
12207
- ITERATION_COMPLETE: "iteration-complete",
12208
- /**
12209
- * A new execution claimed the run. Carries no chunk: consumers only raise
12210
- * their generation so events the superseded execution still publishes are
12211
- * dropped.
12212
- */
12213
- OWNERSHIP_CLAIMED: "ownership-claimed"
12214
- };
12215
12286
  // src/agent/streams/run-records.ts
12216
12287
  /**
12217
12288
  * Lifetime of a running or suspended run's record. Deliberately much longer
@@ -14223,26 +14294,97 @@ var ExecutionFence = class ExecutionFence {
14223
14294
  if (!claim.agentId) return void 0;
14224
14295
  const executionBackend = await resolveRemoteBackend(mastra, claim.agentId, runId, claim);
14225
14296
  if (!executionBackend) return void 0;
14226
- const holdsThreadLease = async (threadId) => {
14227
- const lease = [
14228
- mastra.pubsub,
14229
- runId,
14230
- threadId,
14231
- claim.resourceId,
14232
- claim.generation,
14233
- claim.executionId
14234
- ];
14235
- if (claim.generation === void 0) return agentThreadStreamRuntime.renewDurableThreadLease(...lease);
14297
+ const details = {
14298
+ agentId: claim.agentId,
14299
+ runId,
14300
+ executionId: claim.executionId
14301
+ };
14302
+ const threadId = claim.threadId;
14303
+ const lease = threadId ? [
14304
+ mastra.pubsub,
14305
+ runId,
14306
+ threadId,
14307
+ claim.resourceId,
14308
+ claim.generation,
14309
+ claim.executionId
14310
+ ] : void 0;
14311
+ let heartbeatRenewal;
14312
+ let participant;
14313
+ const verifyCurrent = async () => {
14314
+ await executionBackend.verify(claim, details);
14315
+ if (participant?.isLost()) throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details);
14316
+ };
14317
+ const checkThread = async (threadLease, heartbeatWorker) => {
14318
+ const stopped = () => heartbeatWorker && (!heartbeatWorker.#heartbeat || heartbeatWorker.isLost());
14319
+ let timedOut = false;
14320
+ let timer;
14321
+ const check = async () => {
14322
+ let renewed;
14323
+ try {
14324
+ renewed = await agentThreadStreamRuntime.renewDurableThreadLease(...threadLease);
14325
+ } catch (error) {
14326
+ if (agentThreadStreamRuntime.isThreadLeaseBackendUnavailableToAll(mastra.pubsub, error)) return true;
14327
+ throw error;
14328
+ }
14329
+ if (renewed) return true;
14330
+ if (timedOut || stopped()) return void 0;
14331
+ await verifyCurrent();
14332
+ if (timedOut || stopped()) return void 0;
14333
+ let acquired;
14334
+ try {
14335
+ acquired = await agentThreadStreamRuntime.reclaimDurableThreadLease(...threadLease);
14336
+ } catch (error) {
14337
+ if (agentThreadStreamRuntime.isThreadLeaseBackendUnavailableToAll(mastra.pubsub, error)) return true;
14338
+ throw error;
14339
+ }
14340
+ if (acquired) try {
14341
+ await verifyCurrent();
14342
+ } catch (error) {
14343
+ if (error instanceof DurableExecutionFenceError && error.id === "DURABLE_AGENT_EXECUTION_SUPERSEDED") (async () => {
14344
+ const snapshot = await (await mastra.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
14345
+ workflowName: DurableStepIds.AGENTIC_LOOP,
14346
+ runId
14347
+ });
14348
+ if (!(snapshot?.status === "suspended" || snapshot?.status === "waiting") || await executionBackend.isSuperseded(claim)) await agentThreadStreamRuntime.releaseDurableThreadLease(...threadLease);
14349
+ })().catch(() => {});
14350
+ throw error;
14351
+ }
14352
+ else if (heartbeatWorker) {
14353
+ if (timedOut || stopped()) return void 0;
14354
+ const [pubsub, , threadId, resourceId] = threadLease;
14355
+ if (!await agentThreadStreamRuntime.isDurableThreadLeaseHeldByAnotherRun(pubsub, runId, threadId, resourceId)) return;
14356
+ }
14357
+ return acquired;
14358
+ };
14236
14359
  try {
14237
- return await agentThreadStreamRuntime.renewDurableThreadLease(...lease) || await agentThreadStreamRuntime.reclaimDurableThreadLease(...lease);
14238
- } catch (error) {
14239
- if (!agentThreadStreamRuntime.isThreadLeaseBackendUnavailableToAll(mastra.pubsub, error)) throw error;
14240
- mastra.getLogger()?.warn(`[DurableAgent] run ${runId}: thread lease backend unavailable, relying on run ownership`, { error });
14241
- return true;
14360
+ return await Promise.race([check(), new Promise((resolve) => {
14361
+ timer = setTimeout(() => {
14362
+ timedOut = true;
14363
+ resolve(void 0);
14364
+ }, EXECUTION_LEASE_RENEW_INTERVAL_MS);
14365
+ timer.unref?.();
14366
+ })]);
14367
+ } finally {
14368
+ clearTimeout(timer);
14242
14369
  }
14243
14370
  };
14244
14371
  const backend = {
14245
14372
  ...executionBackend,
14373
+ verify: async () => {
14374
+ await verifyCurrent();
14375
+ if (!lease || claim.generation === void 0) return;
14376
+ for (;;) {
14377
+ const held = await checkThread(lease);
14378
+ await verifyCurrent();
14379
+ if (held === true) return;
14380
+ if (held === false) {
14381
+ ExecutionFence.releaseSharedClaim(mastra, runId, claim, "abandoned").catch(() => {});
14382
+ throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details);
14383
+ }
14384
+ await sleep(VERIFY_RETRY_DELAY_MS);
14385
+ await verifyCurrent();
14386
+ }
14387
+ },
14246
14388
  renew: async (current) => {
14247
14389
  const result = await executionBackend.renew(current);
14248
14390
  if (!result.renewed) {
@@ -14253,20 +14395,22 @@ var ExecutionFence = class ExecutionFence {
14253
14395
  });
14254
14396
  return result;
14255
14397
  }
14256
- if (claim.threadId && !await holdsThreadLease(claim.threadId)) throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, {
14257
- agentId: claim.agentId,
14258
- runId,
14259
- executionId: claim.executionId
14260
- });
14398
+ if (lease) {
14399
+ if (claim.generation === void 0) {
14400
+ if (!await agentThreadStreamRuntime.renewDurableThreadLease(...lease)) throw new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details);
14401
+ } else if (participant && !heartbeatRenewal) {
14402
+ const worker = participant;
14403
+ heartbeatRenewal = checkThread(lease, worker).then(async (held) => {
14404
+ if (held !== false || !worker.#heartbeat || worker.isLost()) return;
14405
+ worker.#markLost(new DurableExecutionFenceError(EXECUTION_UNVERIFIED_ERROR_ID, details));
14406
+ await ExecutionFence.releaseSharedClaim(mastra, runId, claim, "abandoned");
14407
+ }).catch(() => {}).finally(() => heartbeatRenewal = void 0);
14408
+ }
14409
+ }
14261
14410
  return result;
14262
14411
  }
14263
14412
  };
14264
14413
  const startedAt = Date.now();
14265
- const details = {
14266
- agentId: claim.agentId,
14267
- runId,
14268
- executionId: claim.executionId
14269
- };
14270
14414
  let deadline;
14271
14415
  try {
14272
14416
  await Promise.race([(async () => {
@@ -14284,7 +14428,7 @@ var ExecutionFence = class ExecutionFence {
14284
14428
  } finally {
14285
14429
  if (deadline) clearTimeout(deadline);
14286
14430
  }
14287
- const fence = new ExecutionFence({
14431
+ const fence = participant = new ExecutionFence({
14288
14432
  ...details,
14289
14433
  backend,
14290
14434
  generation: claim.generation,
@@ -15361,7 +15505,8 @@ var StepExecutor = class extends MastraBase {
15361
15505
  return storageV2StepResultAccessors((step) => getHydratedStepResult(stepResults, step, hydrate));
15362
15506
  }
15363
15507
  async execute(params) {
15364
- const { entry, stepResults, runId, requestContext, retryCount = 0, perStep } = params;
15508
+ const { entry, stepResults, runId, retryCount = 0, perStep } = params;
15509
+ let { requestContext } = params;
15365
15510
  const stepId = getEntryId(entry);
15366
15511
  const errorAttemptId = `${runId}:${stepId}:${params.foreachIdx ?? ""}:attempt:${retryCount}`;
15367
15512
  const schemas = getEntrySchemas(entry, this.mastra);
@@ -15417,6 +15562,18 @@ var StepExecutor = class extends MastraBase {
15417
15562
  const stepTracingContext = workflowStepSpan ? { currentSpan: workflowStepSpan } : params.tracingContext ?? {};
15418
15563
  try {
15419
15564
  if (validationError) throw validationError;
15565
+ if (params.workflowId === DurableStepIds.AGENTIC_LOOP || params.workflowId === DurableStepIds.AGENTIC_EXECUTION) {
15566
+ const live = requestContext.get("controller");
15567
+ const initial = stepResults.input;
15568
+ const binding = initial?.requestContextEntries?.[CONTROLLER_RUN_BINDING_KEY];
15569
+ if (initial && binding !== void 0 && typeof live?.getState !== "function") {
15570
+ const parsed = controllerRunBindingSchema.parse(binding);
15571
+ 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");
15572
+ const controller = this.mastra?.getAgentControllerById(parsed.controllerId);
15573
+ if (!controller) throw new Error("Controller is not registered on this worker");
15574
+ requestContext = await controller.__restoreWorkerRequestContext(requestContext, parsed, abortController.signal, initial.runId);
15575
+ }
15576
+ }
15420
15577
  const callId = globalThis.crypto.randomUUID();
15421
15578
  const outputWriter = this.createOutputWriter(runId);
15422
15579
  const stepOutput = await executeWithContext({
@@ -21213,7 +21370,8 @@ function cloneStep(step, opts) {
21213
21370
  retries: step.retries,
21214
21371
  scorers: step.scorers,
21215
21372
  metadata: step.metadata,
21216
- component: step.component
21373
+ component: step.component,
21374
+ processorId: step.processorId
21217
21375
  };
21218
21376
  }
21219
21377
  function isToolStep(input) {
@@ -21473,6 +21631,7 @@ function createStepFromProcessor(processor) {
21473
21631
  };
21474
21632
  return {
21475
21633
  id: `processor:${processor.id}`,
21634
+ processorId: processor.id,
21476
21635
  description: processor.name ?? `Processor ${processor.id}`,
21477
21636
  inputSchema: toStandardSchema(ProcessorStepSchema),
21478
21637
  outputSchema: toStandardSchema(ProcessorStepOutputSchema),
@@ -27622,12 +27781,14 @@ async function partitionMessages(messagesDescending, limits, tokenCounter, initi
27622
27781
  if (maxTokens !== void 0 && !tokenCounter) throw new Error("A token counter is required to load token-limited message history");
27623
27782
  let messageCount = 0;
27624
27783
  let tokenCount = initialTokens;
27784
+ let loadedTokens = initialTokens;
27625
27785
  let reachedLimit = false;
27626
27786
  let overflowReason;
27627
27787
  const retainedIds = /* @__PURE__ */ new Set();
27628
27788
  for (const group of groupLinkedToolMessages(messagesDescending)) {
27629
27789
  let groupTokens = 0;
27630
27790
  if (tokenCounter) for (const message of group) groupTokens += await tokenCounter.countMessage(message);
27791
+ loadedTokens += groupTokens;
27631
27792
  const exceedsMessageLimit = limits.maxMessages !== void 0 && messageCount + group.length > limits.maxMessages;
27632
27793
  const exceedsTokenLimit = maxTokens !== void 0 && tokenCount + groupTokens > maxTokens;
27633
27794
  if (reachedLimit || exceedsMessageLimit || exceedsTokenLimit) {
@@ -27642,7 +27803,8 @@ async function partitionMessages(messagesDescending, limits, tokenCounter, initi
27642
27803
  return {
27643
27804
  messages: messagesDescending.filter((message) => retainedIds.has(message.id)).reverse(),
27644
27805
  overflow: messagesDescending.filter((message) => !retainedIds.has(message.id)).reverse(),
27645
- overflowReason
27806
+ overflowReason,
27807
+ loadedTokens
27646
27808
  };
27647
27809
  }
27648
27810
  function laterDate(left, right) {
@@ -27704,15 +27866,15 @@ async function loadMessageHistory(args) {
27704
27866
  const newestOverflow = partitioned.overflow.at(-1);
27705
27867
  if (newestOverflow) cutoffTimestamp = newestOverflow.createdAt.getTime();
27706
27868
  const oldestTimestamp = result.messages.at(-1)?.createdAt.getTime();
27707
- const crossedCutoff = cutoffTimestamp !== void 0 && oldestTimestamp !== void 0 && oldestTimestamp < cutoffTimestamp;
27869
+ const crossedCutoff = cutoffTimestamp !== void 0 && oldestTimestamp !== void 0 && oldestTimestamp < cutoffTimestamp && (!args.includeOverflow || partitioned.overflowReason !== "tokens" || partitioned.loadedTokens > (args.maxTokens ?? 0));
27708
27870
  const reachedBoundary = args.boundary !== void 0 && oldestTimestamp !== void 0 && oldestTimestamp < new Date(args.boundary.createdAt).getTime();
27709
- if (!result.hasMore || crossedCutoff || reachedBoundary || result.messages.length === 0) return args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned : {
27871
+ if (!result.hasMore || crossedCutoff || reachedBoundary || result.messages.length === 0) return {
27710
27872
  messages: partitioned.messages,
27711
- overflow: []
27873
+ overflow: args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned.overflow : []
27712
27874
  };
27713
- if (oldestTimestamp === void 0) return args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned : {
27875
+ if (oldestTimestamp === void 0) return {
27714
27876
  messages: partitioned.messages,
27715
- overflow: []
27877
+ overflow: args.includeOverflow && partitioned.overflowReason === "tokens" ? partitioned.overflow : []
27716
27878
  };
27717
27879
  if (end?.getTime() === oldestTimestamp && added === 0) page++;
27718
27880
  else {
@@ -30207,19 +30369,24 @@ var ToolSearchProcessor = class {
30207
30369
  });
30208
30370
  }
30209
30371
  async processInputStep(args) {
30210
- const { tools, messageList } = args;
30372
+ const { tools, messageList, activeTools } = args;
30211
30373
  const catalog = this.catalogForStep(tools);
30212
30374
  const storeContext = this.makeStoreContext(args);
30213
30375
  const loadedToolNames = await this.store.getLoadedNames(storeContext);
30214
30376
  const autoLoad = this.searchConfig.autoLoad;
30215
- 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.");
30216
- if (this.injectCatalog) {
30377
+ const searchAvailable = !activeTools || activeTools.includes("search_tools");
30378
+ const loadAvailable = !autoLoad && (!activeTools || activeTools.includes("load_tool"));
30379
+ const instructionParts = [];
30380
+ 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.");
30381
+ 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.");
30382
+ if (instructionParts.length > 0) messageList.addSystem(instructionParts.join(" "));
30383
+ if (this.injectCatalog && (autoLoad ? searchAvailable : loadAvailable)) {
30217
30384
  const catalogList = await this.formatCatalog(catalog, args.requestContext);
30218
- 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);
30385
+ 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);
30219
30386
  }
30220
30387
  const searchTool = createTool({
30221
30388
  id: "search_tools",
30222
- 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.",
30389
+ 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." : ""),
30223
30390
  inputSchema: z.object({ query: z.string().describe("Search keywords (e.g., \"weather\", \"github issue\", \"database query\")") }),
30224
30391
  outputSchema: z.object({
30225
30392
  results: z.array(z.object({
@@ -30249,13 +30416,13 @@ var ToolSearchProcessor = class {
30249
30416
  }
30250
30417
  return {
30251
30418
  results,
30252
- message: `Found ${results.length} tool(s). Use load_tool with an exact toolName or a toolNames array to make them available.`
30419
+ 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(", ")}.`
30253
30420
  };
30254
30421
  }
30255
30422
  });
30256
30423
  const loadTool = createTool({
30257
30424
  id: "load_tool",
30258
- 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.",
30425
+ 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.",
30259
30426
  inputSchema: z.object({
30260
30427
  toolName: z.string().optional().describe("The exact name of a tool to load (from search results)"),
30261
30428
  toolNames: z.array(z.string()).optional().describe("Array of exact tool names to load in one call (from search results)")
@@ -30312,7 +30479,7 @@ var ToolSearchProcessor = class {
30312
30479
  const suggestions = await this.getSuggestedToolNames(catalog, name, args.requestContext);
30313
30480
  let message = `Tool "${name}" not found.`;
30314
30481
  if (suggestions.length > 0) message += ` Did you mean: ${suggestions.slice(0, 3).join(", ")}?`;
30315
- else message += " Use search_tools to find available tools.";
30482
+ else if (searchAvailable) message += " Use search_tools to find available tools.";
30316
30483
  return {
30317
30484
  success: false,
30318
30485
  message,
@@ -30346,8 +30513,8 @@ var ToolSearchProcessor = class {
30346
30513
  });
30347
30514
  const loadedTools = await this.getLoadedTools(catalog, loadedToolNames, args.requestContext);
30348
30515
  return { tools: {
30349
- search_tools: searchTool,
30350
- ...autoLoad ? {} : { load_tool: loadTool },
30516
+ ...searchAvailable ? { search_tools: searchTool } : {},
30517
+ ...loadAvailable ? { load_tool: loadTool } : {},
30351
30518
  ...this.includeResolvedTools ? unsearchableResolvedTools(tools) : tools ?? {},
30352
30519
  ...loadedTools
30353
30520
  } };
@@ -30709,7 +30876,7 @@ var SkillSearchProcessor = class {
30709
30876
  return this.cleanupStaleState();
30710
30877
  }
30711
30878
  async processInputStep(args) {
30712
- const { tools, messageList } = args;
30879
+ const { tools, messageList, activeTools } = args;
30713
30880
  const threadId = this.getThreadId(args);
30714
30881
  const threadState = this.getThreadState(threadId);
30715
30882
  const configuredSkills = this.skills;
@@ -30719,10 +30886,18 @@ var SkillSearchProcessor = class {
30719
30886
  if (this.blockingRefresh) await skills.maybeRefresh({ requestContext: args.requestContext })?.catch(this.warnRefreshFailed);
30720
30887
  else skills.maybeRefresh({ requestContext: args.requestContext })?.catch(this.warnRefreshFailed);
30721
30888
  }
30722
- 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.");
30889
+ const searchAvailable = !activeTools || activeTools.includes("search_skills");
30890
+ const loadAvailable = !activeTools || activeTools.includes("load_skill");
30891
+ const instructionParts = [];
30892
+ if (searchAvailable) instructionParts.push("To discover available skills, call search_skills with a keyword query.");
30893
+ if (loadAvailable) instructionParts.push("To load a skill's instructions, call load_skill with the skill name.");
30894
+ if (instructionParts.length > 0) {
30895
+ instructionParts.push("Loaded skills provide context and instructions for the conversation.");
30896
+ messageList.addSystem(instructionParts.join(" "));
30897
+ }
30723
30898
  const searchSkillTool = createTool({
30724
30899
  id: "search_skills",
30725
- 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.",
30900
+ 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." : ""),
30726
30901
  inputSchema: z.object({ query: z.string().trim().min(1, "Query is required").describe("Search keywords (e.g., \"api design\", \"testing\", \"deployment\")") }),
30727
30902
  outputSchema: z.object({
30728
30903
  results: z.array(z.object({
@@ -30759,13 +30934,13 @@ var SkillSearchProcessor = class {
30759
30934
  });
30760
30935
  return {
30761
30936
  results,
30762
- message: `Found ${results.length} skill(s). Use load_skill with the exact skill name to load its instructions.`
30937
+ 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(", ")}.`
30763
30938
  };
30764
30939
  }
30765
30940
  });
30766
30941
  const loadSkillTool = createTool({
30767
30942
  id: "load_skill",
30768
- 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.",
30943
+ 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.",
30769
30944
  inputSchema: z.object({ skillName: z.string().describe("The exact name of the skill to load (from search results)") }),
30770
30945
  outputSchema: z.object({
30771
30946
  success: z.boolean(),
@@ -30783,7 +30958,7 @@ var SkillSearchProcessor = class {
30783
30958
  const suggestions = (await skills.list()).filter((s) => s.name.toLowerCase().includes(skillName.toLowerCase()) || skillName.toLowerCase().includes(s.name.toLowerCase())).slice(0, 3);
30784
30959
  let message = `Skill "${skillName}" not found.`;
30785
30960
  if (suggestions.length > 0) message += ` Did you mean: ${suggestions.map((s) => s.name).join(", ")}?`;
30786
- else message += " Use search_skills to find available skills.";
30961
+ else if (searchAvailable) message += " Use search_skills to find available skills.";
30787
30962
  return {
30788
30963
  success: false,
30789
30964
  message
@@ -30799,8 +30974,8 @@ var SkillSearchProcessor = class {
30799
30974
  });
30800
30975
  for (const [skillName, instructions] of threadState.skills) messageList.addSystem(`[Skill: ${skillName}]\n\n${instructions}`);
30801
30976
  const metaTools = {
30802
- search_skills: searchSkillTool,
30803
- load_skill: loadSkillTool
30977
+ ...searchAvailable ? { search_skills: searchSkillTool } : {},
30978
+ ...loadAvailable ? { load_skill: loadSkillTool } : {}
30804
30979
  };
30805
30980
  if (tools) {
30806
30981
  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.`);
@@ -38599,6 +38774,7 @@ var ExperimentsInMemory = class extends ExperimentsStorage {
38599
38774
  targetType: input.targetType ?? null,
38600
38775
  targetId: input.targetId ?? null,
38601
38776
  scorerIds: input.scorerIds ?? null,
38777
+ scorerVersions: input.scorerVersions ?? null,
38602
38778
  name: input.name,
38603
38779
  description: input.description,
38604
38780
  metadata: input.metadata,
@@ -39505,6 +39681,31 @@ var KnowledgeStorage = class extends StorageDomain {
39505
39681
  getPages(_input) {
39506
39682
  return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPages"));
39507
39683
  }
39684
+ /**
39685
+ * The page `parentId` and its ancestors, nearest first: for each row what {@link getPage} would
39686
+ * return with the same `read`, deleted rows included. Stops after the first scope page, before
39687
+ * the first row `getPage` would return null for, or after {@link MAX_KNOWLEDGE_PAGE_DEPTH} + 1
39688
+ * rows. Lets a caller holding a page walk its parents in one call instead of one per level.
39689
+ *
39690
+ * The base class reads one {@link getPage} per level; adapters that can read the chain in one
39691
+ * query override it.
39692
+ *
39693
+ * @experimental
39694
+ */
39695
+ async getPageParents(input) {
39696
+ const parents = [];
39697
+ let id = input.parentId;
39698
+ while (id && parents.length <= 10) {
39699
+ const page = await this.getPage({
39700
+ id,
39701
+ read: input.read
39702
+ });
39703
+ if (!page) break;
39704
+ parents.push(page);
39705
+ id = page.isScope ? null : page.parentId;
39706
+ }
39707
+ return parents;
39708
+ }
39508
39709
  getPageByPath(_input) {
39509
39710
  return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPageByPath"));
39510
39711
  }
@@ -39822,6 +40023,12 @@ var InMemoryKnowledgeImportersStorage = class extends KnowledgeImportersStorage
39822
40023
  const node = this.#s.nodes.get(key(bindingId, sourceId));
39823
40024
  return node ? structuredClone(node) : null;
39824
40025
  }
40026
+ async getNodes(bindingId, sourceIds) {
40027
+ return [...new Set(sourceIds)].flatMap((sourceId) => {
40028
+ const node = this.#s.nodes.get(key(bindingId, sourceId));
40029
+ return node ? [structuredClone(node)] : [];
40030
+ });
40031
+ }
39825
40032
  async getNodeByPage(pageId) {
39826
40033
  const node = [...this.#s.nodes.values()].find((n) => n.pageId === pageId);
39827
40034
  return node ? structuredClone(node) : null;
@@ -40212,6 +40419,15 @@ var InMemoryKnowledgePageStore = class {
40212
40419
  const page = this.#pages.get(input.id);
40213
40420
  return page && this.#pageReadable(page, input.read) ? clone$1(page) : null;
40214
40421
  }
40422
+ async getPageParents(input) {
40423
+ const parents = [];
40424
+ let page = this.#pages.get(input.parentId);
40425
+ while (page && this.#pageReadable(page, input.read) && parents.length <= 10) {
40426
+ parents.push(clone$1(page));
40427
+ page = page.isScope || !page.parentId ? void 0 : this.#pages.get(page.parentId);
40428
+ }
40429
+ return parents;
40430
+ }
40215
40431
  async getPages(input) {
40216
40432
  return [...new Set(input.ids)].map((id) => this.#pages.get(id)).filter((page) => !!page && !page.deletedAt && this.#pageReadable(page, input.read)).map(clone$1);
40217
40433
  }
@@ -40719,6 +40935,9 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40719
40935
  getPage(input) {
40720
40936
  return this.#pageStore.getPage(input);
40721
40937
  }
40938
+ getPageParents(input) {
40939
+ return this.#pageStore.getPageParents(input);
40940
+ }
40722
40941
  listScopeDeclarations() {
40723
40942
  return this.#pageStore.listScopeDeclarations();
40724
40943
  }
@@ -47760,6 +47979,32 @@ function chunkToFallbackMessage(chunk) {
47760
47979
  if (chunk.type === "plan_update") return chunk.title && chunk.title.length > 0 ? chunk.title : null;
47761
47980
  return null;
47762
47981
  }
47982
+ /** Whitespace plus the meaningful joiners ZWNJ (U+200C) and ZWJ (U+200D). */
47983
+ const EDGE_PADDING = /[\s\u200C\u200D]/;
47984
+ /**
47985
+ * Sanitize a buffered channel reply before posting.
47986
+ *
47987
+ * Zero-width space (U+200B) and the byte-order mark (U+FEFF) are invisible
47988
+ * padding and are removed everywhere. Whitespace and the joiners ZWNJ
47989
+ * (U+200C) / ZWJ (U+200D) are trimmed only at the edges, so internal joiners
47990
+ * in compound emoji (🏄🏼‍♂️, 👨‍👩‍👧) and scripts such as Persian (می‌خواهم)
47991
+ * survive — the bug behind #31205. Invisible-only input collapses to '' so
47992
+ * callers skip posting it entirely.
47993
+ *
47994
+ * The edge trim is a single-pass scan rather than
47995
+ * `.replace(/^[\s\u200C\u200D]+|[\s\u200C\u200D]+$/g, '')`: that anchored
47996
+ * alternation backtracks quadratically over a long interior run of the class
47997
+ * (a 300k-character run of model-controlled output took ~80s), while this
47998
+ * scan is O(n).
47999
+ */
48000
+ function cleanBufferedText(input) {
48001
+ const stripped = input.replace(/[\u200B\uFEFF]/g, "");
48002
+ let start = 0;
48003
+ let end = stripped.length;
48004
+ while (start < end && EDGE_PADDING.test(stripped.charAt(start))) start++;
48005
+ while (end > start && EDGE_PADDING.test(stripped.charAt(end - 1))) end--;
48006
+ return start === 0 && end === stripped.length ? stripped : stripped.slice(start, end);
48007
+ }
47763
48008
  // src/channels/chat-driver-static.ts
47764
48009
  /**
47765
48010
  * Static (non-streaming) driver: consumes `AgentChunkType<any>` chunks and
@@ -47804,7 +48049,7 @@ async function runStaticDriver({ stream, chatThread, adapter, toolDisplay, toolD
47804
48049
  let textBuffer = "";
47805
48050
  const toolMessageIds = /* @__PURE__ */ new Map();
47806
48051
  const flushText = async () => {
47807
- const cleaned = textBuffer.replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
48052
+ const cleaned = cleanBufferedText(textBuffer);
47808
48053
  if (cleaned) try {
47809
48054
  await chatThread.post(textFormat === "plain" ? cleaned : { markdown: cleaned });
47810
48055
  } catch (e) {
@@ -48139,7 +48384,7 @@ async function runStreamingDriver({ stream, chatThread, adapter, toolDisplay, to
48139
48384
  if (closed) break;
48140
48385
  await waitForNext();
48141
48386
  }
48142
- const cleaned = fallback.replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
48387
+ const cleaned = cleanBufferedText(fallback);
48143
48388
  if (cleaned) try {
48144
48389
  await chatThread.post(textFormat === "plain" ? cleaned : { markdown: cleaned });
48145
48390
  } catch (postErr) {
@@ -48622,6 +48867,20 @@ const TEXT_CHUNK_TYPES = /* @__PURE__ */ new Set([
48622
48867
  /** Key the processor reads off `requestContext` to locate its render deps. */
48623
48868
  const CHAT_CHANNEL_RENDER_CONTEXT_KEY = "__mastra_chat_channel_render";
48624
48869
  /**
48870
+ * Whether a `requestContext` entry is a live render context rather than the
48871
+ * method-less husk a JSON snapshot round-trip leaves behind (issue #31310).
48872
+ * `wrapStream` is the first method the session calls, so its presence is the
48873
+ * signal that the object is usable.
48874
+ *
48875
+ * Every reader that treats a stashed render context as a live object (the
48876
+ * output processor, `resolveChannelRenderContext`, `AgentChannels.resolveRunRender`
48877
+ * and the generative-UI processor) guards with this, so a husk on a replica's
48878
+ * restored `requestContext` always falls through to a rebuild from the thread.
48879
+ */
48880
+ function isUsableRenderContext(value) {
48881
+ return typeof value === "object" && value !== null && typeof value.wrapStream === "function";
48882
+ }
48883
+ /**
48625
48884
  * Single-producer / single-consumer async queue. The processor pushes chunks
48626
48885
  * synchronously from `processOutputStream`; the driver consumes them via the
48627
48886
  * async iterable. `close()` ends the iteration after pending items are drained.
@@ -48755,7 +49014,7 @@ var ChatChannelOutputProcessor = class {
48755
49014
  async #resolveRenderContext(state, requestContext) {
48756
49015
  if (state.render !== void 0) return state.render;
48757
49016
  const fromRequest = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
48758
- if (fromRequest) {
49017
+ if (isUsableRenderContext(fromRequest)) {
48759
49018
  state.render = fromRequest;
48760
49019
  return fromRequest;
48761
49020
  }
@@ -48928,7 +49187,7 @@ var ChatChannelGenerativeUIProcessor = class {
48928
49187
  }
48929
49188
  async #resolve(requestContext, state) {
48930
49189
  const inbound = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
48931
- if (inbound) return inbound;
49190
+ if (isUsableRenderContext(inbound)) return inbound;
48932
49191
  if (state && "render" in state) return state.render ?? void 0;
48933
49192
  const threadId = parseMemoryRequestContext(requestContext)?.thread?.id;
48934
49193
  const render = threadId && this.#channels ? await this.#channels.buildRenderContextForThread(threadId) : null;
@@ -49082,6 +49341,8 @@ async function headContentType(url, logger) {
49082
49341
  }
49083
49342
  }
49084
49343
  // src/channels/processor.ts
49344
+ /** Per-run `state` key caching a thread's display mode recovered without a render context. */
49345
+ const RECOVERED_DISPLAY_KEY = "threadTextHidden";
49085
49346
  /**
49086
49347
  * Input processor that injects channel context (platform, bot identity, DM vs.
49087
49348
  * public-channel guidance) into the agent's system prompt on every step.
@@ -49115,19 +49376,37 @@ var ChatChannelProcessor = class {
49115
49376
  }
49116
49377
  async #resolve(requestContext, state) {
49117
49378
  const channel = requestContext?.get("channel");
49118
- if (channel) return {
49119
- channel,
49120
- textHidden: (requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY))?.textDisplay === "hidden"
49121
- };
49379
+ if (channel) {
49380
+ const render = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
49381
+ return {
49382
+ channel,
49383
+ textHidden: isUsableRenderContext(render) ? render.textDisplay === "hidden" : await this.#recoverTextHidden(requestContext, state)
49384
+ };
49385
+ }
49122
49386
  if (state && "thread" in state) return state.thread ?? void 0;
49387
+ const resolved = await this.#resolveThread(requestContext);
49388
+ if (state) state.thread = resolved;
49389
+ return resolved ?? void 0;
49390
+ }
49391
+ /** The channel-backed context of the run's memory thread, or `null` when it has none. */
49392
+ async #resolveThread(requestContext) {
49123
49393
  const threadId = parseMemoryRequestContext(requestContext)?.thread?.id;
49124
49394
  const found = threadId && this.#channels ? await this.#channels.buildChannelContextForThread(threadId) : null;
49125
- const resolved = found ? {
49395
+ return found ? {
49126
49396
  channel: found.channel,
49127
49397
  textHidden: found.render.textDisplay === "hidden"
49128
49398
  } : null;
49129
- if (state) state.thread = resolved;
49130
- return resolved ?? void 0;
49399
+ }
49400
+ /**
49401
+ * Display mode of a channel-backed thread whose render context is no longer on the
49402
+ * restored request context. Cached per run like the thread lookup above, so later
49403
+ * steps of the same run read the thread once.
49404
+ */
49405
+ async #recoverTextHidden(requestContext, state) {
49406
+ if (state && RECOVERED_DISPLAY_KEY in state) return state[RECOVERED_DISPLAY_KEY] === true;
49407
+ const textHidden = (await this.#resolveThread(requestContext))?.textHidden ?? false;
49408
+ if (state) state[RECOVERED_DISPLAY_KEY] = textHidden;
49409
+ return textHidden;
49131
49410
  }
49132
49411
  };
49133
49412
  function channelLines(ctx, textHidden, tools) {
@@ -49155,6 +49434,488 @@ function channelLines(ctx, textHidden, tools) {
49155
49434
  if (tools && "add_reaction" in tools) lines.push(`If you want to acknowledge a message without ${textHidden ? "posting" : "speaking"}, use the \`add_reaction\` tool to react with an emoji instead of replying with text.`);
49156
49435
  return lines;
49157
49436
  }
49437
+ // src/channels/thread-link-processor.ts
49438
+ /**
49439
+ * Request-context marker for a run that opened a new channel thread. `AgentChannels` sets it when
49440
+ * it creates the thread; a host that decides "new" itself can call {@link markNewChannelThread}.
49441
+ */
49442
+ const NEW_CHANNEL_THREAD_KEY = "__mastra_new_channel_thread";
49443
+ function markNewChannelThread(requestContext) {
49444
+ requestContext.set(NEW_CHANNEL_THREAD_KEY, true);
49445
+ }
49446
+ /** Text-part id of the link delta; never collides with a model block id. */
49447
+ const LINK_PART_ID = "mastra-channel-thread-link";
49448
+ const EMITTED_SUFFIX_KEY = "mastra__channelThreadLinkSuffix";
49449
+ /**
49450
+ * Posts a link to the thread in the host's web UI right after the first reply of a new channel
49451
+ * thread, so the link closes the reply rather than leading it. The channel driver ends a post at
49452
+ * `text-end`, so the link shows as its own short message after the reply.
49453
+ *
49454
+ * "End of the reply" is not `text-end`: a reply with citations is several text blocks, each with
49455
+ * its own `text-end`. The reply ends at the first `tool-call` (an opener before tools run) or at
49456
+ * `step-finish` (a reply with no tools), whichever comes first after some text. A processor
49457
+ * returns one part, so on that chunk this returns a `text-delta` carrying the link and stashes the
49458
+ * chunk under `REPROCESS_PART_KEY`, which the runner re-drives through the chain right after.
49459
+ *
49460
+ * The link is a channel display detail. Saved to memory it would show the model its own link on
49461
+ * later turns (inviting it to fabricate links) and render a self-link in the web transcript, so
49462
+ * `processOutputStep` drops the link's text part before the message is saved.
49463
+ *
49464
+ * No-op unless the run opened a new thread, the reply text is shown, and `link` returns a URL.
49465
+ */
49466
+ var ChannelThreadLinkProcessor = class {
49467
+ id = "channel-thread-link";
49468
+ #options;
49469
+ /** Pass options, or a function picking them per run (e.g. by the run's platform). */
49470
+ constructor(options) {
49471
+ this.#options = typeof options === "function" ? options : () => options;
49472
+ }
49473
+ async processOutputStream({ part, state, requestContext }) {
49474
+ if (state.linked || !linksThisRun(requestContext)) return part;
49475
+ if (part.type === "text-delta") {
49476
+ if (part.payload.text.trim()) state.textStarted = true;
49477
+ return part;
49478
+ }
49479
+ if (part.type !== "tool-call" && part.type !== "step-finish" || !state.textStarted) return part;
49480
+ state.linked = true;
49481
+ const suffix = this.#suffix(requestContext);
49482
+ if (!suffix) return part;
49483
+ requestContext.set(EMITTED_SUFFIX_KEY, suffix);
49484
+ state[REPROCESS_PART_KEY] = part;
49485
+ return {
49486
+ type: "text-delta",
49487
+ runId: part.runId,
49488
+ from: part.from,
49489
+ payload: {
49490
+ id: LINK_PART_ID,
49491
+ text: suffix
49492
+ }
49493
+ };
49494
+ }
49495
+ processOutputStep({ messageList, requestContext }) {
49496
+ const suffix = requestContext?.get(EMITTED_SUFFIX_KEY);
49497
+ if (!suffix) return messageList;
49498
+ for (const message of messageList.get.response.db()) {
49499
+ if (message.role !== "assistant") continue;
49500
+ const index = message.content.parts.findIndex((part) => part.type === "text" && part.text === suffix);
49501
+ if (index === -1) continue;
49502
+ message.content.parts.splice(index, 1);
49503
+ if (typeof message.content.content === "string" && message.content.content.endsWith(suffix)) message.content.content = message.content.content.slice(0, -suffix.length);
49504
+ return messageList;
49505
+ }
49506
+ return messageList;
49507
+ }
49508
+ #suffix(requestContext) {
49509
+ const options = this.#options(requestContext);
49510
+ if (!options) return void 0;
49511
+ const memory = parseMemoryRequestContext(requestContext);
49512
+ const link = options.link({
49513
+ requestContext,
49514
+ threadId: memory?.thread?.id,
49515
+ resourceId: memory?.resourceId
49516
+ });
49517
+ return link && `\n\n[${options.label ?? "Open thread \u2197"}](${link})`;
49518
+ }
49519
+ };
49520
+ function linksThisRun(requestContext) {
49521
+ if (!requestContext?.get("__mastra_new_channel_thread")) return false;
49522
+ return requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY)?.textDisplay !== "hidden";
49523
+ }
49524
+ // src/channels/reply-tool.ts
49525
+ const REPLY_TOOL_NAME = "reply_in_thread";
49526
+ /**
49527
+ * Which reply carries the session link: `claimed` while that reply is posting,
49528
+ * `posted` once it landed. Claimed before any await, so overlapping replies
49529
+ * can't both take it; a failed post hands it back to the next reply.
49530
+ */
49531
+ const LINKED_KEY = "mastra__channelReplyLinked";
49532
+ const replyInput = z$1.object({ text: z$1.string().trim().min(1).max(12e3).describe("The message to post, in markdown.") }).strict();
49533
+ /** @internal */
49534
+ function createChannelReplyTool(requestContext, options) {
49535
+ const { resolveRender } = options;
49536
+ return { [REPLY_TOOL_NAME]: createTool({
49537
+ id: REPLY_TOOL_NAME,
49538
+ description: "Post a message in this chat thread. Nothing you write outside this tool reaches the thread, so use it for anything the people there should see: a short note that you are starting a longer job, a question you need answered, and the outcome when you finish. Post when you have something new; do not repeat yourself or post that nothing changed. To stay quiet, do not call it.",
49539
+ inputSchema: replyInput,
49540
+ execute: async (input, context) => {
49541
+ const link = claimFirstReplyLink(requestContext, options.link);
49542
+ const suffix = link ? `\n\n[${options.link?.label ?? "Open thread \u2197"}](${link})` : "";
49543
+ const toolCallId = context?.agent?.toolCallId;
49544
+ const streamed = toolCallId ? replyStreams(requestContext).get(toolCallId) : void 0;
49545
+ if (toolCallId) replyStreams(requestContext).delete(toolCallId);
49546
+ try {
49547
+ if (!streamed || !await streamed.finish(input.text, suffix)) {
49548
+ const render = await resolveRender(requestContext);
49549
+ if (!render) throw new Error("This session is no longer linked to a chat thread.");
49550
+ await render.chatThread.post({ markdown: `${input.text}${suffix}` });
49551
+ }
49552
+ } catch (error) {
49553
+ if (link) requestContext.set(LINKED_KEY, void 0);
49554
+ throw error;
49555
+ }
49556
+ if (link) requestContext.set(LINKED_KEY, "posted");
49557
+ return { posted: true };
49558
+ }
49559
+ }) };
49560
+ }
49561
+ /**
49562
+ * The session link the first reply of a new session ends with, claimed for
49563
+ * this reply. With reply text hidden, the session-link processor's text delta
49564
+ * never reaches the thread, so the tool carries the link instead.
49565
+ */
49566
+ function claimFirstReplyLink(requestContext, link) {
49567
+ if (!link || !requestContext.get("__mastra_new_channel_thread") || requestContext.get(LINKED_KEY)) return;
49568
+ const memory = parseMemoryRequestContext(requestContext);
49569
+ const url = link.link({
49570
+ requestContext,
49571
+ threadId: memory?.thread?.id,
49572
+ resourceId: memory?.resourceId
49573
+ });
49574
+ if (url) requestContext.set(LINKED_KEY, "claimed");
49575
+ return url;
49576
+ }
49577
+ /** Live posts of `reply_in_thread` calls whose text is still streaming in, by tool call id. */
49578
+ const STREAMS_KEY = "mastra__channelReplyStreams";
49579
+ function replyStreams(requestContext) {
49580
+ let streams = requestContext.get(STREAMS_KEY);
49581
+ if (!streams) {
49582
+ streams = /* @__PURE__ */ new Map();
49583
+ requestContext.set(STREAMS_KEY, streams);
49584
+ }
49585
+ return streams;
49586
+ }
49587
+ /**
49588
+ * One streamed post, opened on the first visible text so an abandoned
49589
+ * call never leaves an empty message behind.
49590
+ */
49591
+ function openReplyStream({ chatThread, logger }) {
49592
+ const queue = [];
49593
+ let sent = "";
49594
+ let closed = false;
49595
+ let wake;
49596
+ let done;
49597
+ async function* chunks() {
49598
+ while (true) {
49599
+ while (queue.length > 0) yield queue.shift();
49600
+ if (closed) return;
49601
+ await new Promise((resolve) => wake = resolve);
49602
+ }
49603
+ }
49604
+ const push = (text) => {
49605
+ if (!text) return;
49606
+ queue.push(text);
49607
+ done ??= chatThread.post(chunks()).then(() => true, (error) => {
49608
+ logger?.warn("[channels] streamed reply failed; posting it whole", { error });
49609
+ return false;
49610
+ });
49611
+ wake?.();
49612
+ };
49613
+ return {
49614
+ update(text) {
49615
+ const visible = text.trimStart();
49616
+ if (!visible.startsWith(sent)) return;
49617
+ push(visible.slice(sent.length));
49618
+ sent = visible;
49619
+ },
49620
+ async finish(text, suffix) {
49621
+ if (text.startsWith(sent)) push(text.slice(sent.length));
49622
+ if (!done) return false;
49623
+ push(suffix);
49624
+ closed = true;
49625
+ wake?.();
49626
+ return done;
49627
+ },
49628
+ async close() {
49629
+ closed = true;
49630
+ wake?.();
49631
+ return done ?? false;
49632
+ }
49633
+ };
49634
+ }
49635
+ /**
49636
+ * Streams a `reply_in_thread` call's `text` into the thread while the model is
49637
+ * still writing it, so a long reply appears as it is written instead of all at
49638
+ * once when the call completes. The tool finishes the post with the validated
49639
+ * text. Runs whose adapter doesn't stream, or that show reply text, are left
49640
+ * alone.
49641
+ */
49642
+ var ChannelReplyStreamProcessor = class {
49643
+ id = "channel-reply-stream";
49644
+ #resolveRender;
49645
+ constructor(resolveRender) {
49646
+ this.#resolveRender = resolveRender;
49647
+ }
49648
+ async processOutputStream({ part, state, requestContext }) {
49649
+ if (!requestContext) return part;
49650
+ const args = state.args ??= {};
49651
+ if (part.type === "tool-call-input-streaming-start" && part.payload.toolName === "reply_in_thread") {
49652
+ const render = await this.#resolveRender(requestContext);
49653
+ if (render?.textDisplay !== "hidden" || !render.streaming?.enabled) return part;
49654
+ args[part.payload.toolCallId] = "";
49655
+ replyStreams(requestContext).set(part.payload.toolCallId, openReplyStream(render));
49656
+ } else if (part.type === "tool-call-delta" && part.payload.toolCallId in args) {
49657
+ const text = partialStringField(args[part.payload.toolCallId] += part.payload.argsTextDelta, "text");
49658
+ if (text !== void 0) replyStreams(requestContext).get(part.payload.toolCallId)?.update(text);
49659
+ } else if ((part.type === "tool-error" || part.type === "tool-result") && part.payload.toolCallId in args) {
49660
+ delete args[part.payload.toolCallId];
49661
+ await closeStream(requestContext, part.payload.toolCallId);
49662
+ } else if (RUN_END.has(part.type)) {
49663
+ for (const toolCallId of Object.keys(args)) await closeStream(requestContext, toolCallId);
49664
+ state.args = {};
49665
+ }
49666
+ return part;
49667
+ }
49668
+ };
49669
+ /** Chunks after which no `reply_in_thread` call of this run will still execute. */
49670
+ const RUN_END = /* @__PURE__ */ new Set([
49671
+ "finish",
49672
+ "abort",
49673
+ "error",
49674
+ "tripwire"
49675
+ ]);
49676
+ /**
49677
+ * Ends a streamed post whose call will never reach `execute`, keeping the text
49678
+ * shown so far, so the platform isn't left with a message that never finishes.
49679
+ */
49680
+ async function closeStream(requestContext, toolCallId) {
49681
+ const streams = replyStreams(requestContext);
49682
+ const stream = streams.get(toolCallId);
49683
+ if (!stream) return;
49684
+ streams.delete(toolCallId);
49685
+ await stream.close();
49686
+ }
49687
+ const ESCAPES = {
49688
+ "\"": "\"",
49689
+ "\\": "\\",
49690
+ "/": "/",
49691
+ b: "\b",
49692
+ f: "\f",
49693
+ n: "\n",
49694
+ r: "\r",
49695
+ t: " "
49696
+ };
49697
+ /** The decoded value of a top-level string field in JSON that may still be cut off mid-string. */
49698
+ function partialStringField(json, field) {
49699
+ const start = new RegExp(`"${field}"\\s*:\\s*"`).exec(json);
49700
+ if (!start) return void 0;
49701
+ let out = "";
49702
+ for (let i = start.index + start[0].length; i < json.length; i++) {
49703
+ const ch = json[i];
49704
+ if (ch === "\"") return out;
49705
+ if (ch !== "\\") {
49706
+ out += ch;
49707
+ continue;
49708
+ }
49709
+ const next = json[i + 1];
49710
+ if (next === void 0) return out;
49711
+ if (next === "u") {
49712
+ const hex = json.slice(i + 2, i + 6);
49713
+ if (hex.length < 4) return out;
49714
+ out += String.fromCharCode(parseInt(hex, 16));
49715
+ i += 5;
49716
+ } else {
49717
+ out += ESCAPES[next] ?? next;
49718
+ i += 1;
49719
+ }
49720
+ }
49721
+ return out;
49722
+ }
49723
+ // src/channels/reply-guidance-processor.ts
49724
+ const ID$1 = "channel-reply-guidance";
49725
+ /** Chat surfaces show what the agent writes as-is, so a bare id is a dead end for the reader. */
49726
+ const LINK_REFERENCES = "Write every pull request, issue, commit, ticket or other reference you mention in the thread as a markdown link to its page, with the id as plain link text, e.g. [#28467](https://github.com/<owner>/<repo>/pull/28467). Never leave one as a bare id or wrap it in code formatting. Build links from URLs your tools returned; don't guess a URL, and leave a reference unlinked only when you can't work out its URL.";
49727
+ /** Agents tend to write the way they report to other agents: names, ids and shorthand only they follow. */
49728
+ const WRITE_FOR_PEOPLE = [
49729
+ "Write for the people in the thread, not for another agent. A teammate who knows the product and programming, but has not read this code or this conversation, should follow your message on first read.",
49730
+ "Lead with the answer or the outcome and anything you need from them, in plain sentences. Keep it short: a few sentences answer most questions, and when there is more, offer it rather than writing it all out. Say what code does rather than naming the function, file, field, error class or tool that does it; name one only when they need it to find the code. Use the project\u2019s real terms, not invented analogies.",
49731
+ "Leave out tool names and run ids unless someone asks for them, and always leave out agent shorthand. When you pass on what another agent reported, say what it means for the people here in your own words; never paste its report."
49732
+ ].join(" ");
49733
+ /**
49734
+ * Tells the agent how to speak in a chat channel: open a long job with one line that names it,
49735
+ * finish with the outcome, write for people, and link references. With `reply_in_thread` on the
49736
+ * run, that advice becomes advice on when to call it. A run outside the channel that can still
49737
+ * post there (a web prompt on a linked thread) gets a short note on when to. Runs with neither
49738
+ * get nothing.
49739
+ */
49740
+ var ChannelReplyGuidanceProcessor = class {
49741
+ id = ID$1;
49742
+ #instructions;
49743
+ constructor(options = {}) {
49744
+ this.#instructions = options.instructions;
49745
+ }
49746
+ processInputStep({ messageList, requestContext, tools }) {
49747
+ const canReply = !!tools && "reply_in_thread" in tools;
49748
+ let content;
49749
+ if (!requestContext?.get("channel")) {
49750
+ if (!canReply) return void 0;
49751
+ content = [`Post to that thread with \`${REPLY_TOOL_NAME}\`. This request came from outside it, so don't post an opener or progress there; post the outcome when the people in the thread asked for this work or are waiting on it, or when you're asked to. Don't write a note about what you posted.`];
49752
+ } else if (canReply) content = [
49753
+ `Only messages you send with \`${REPLY_TOOL_NAME}\` reach this thread; your other text stays out of it. Don't write a note about what you posted. After a reply, either keep working or end your turn with an empty message; any text you write after posting is wasted.`,
49754
+ "When a request will take tools or more than a moment, post one short line first that says what you are about to do, then do the work and post the outcome when you finish \u2014 not a replay of the steps.",
49755
+ "Post again in between only when you need an answer or have news the people in the thread would want. When a message that doesn't mention you needs nothing from you, don't call it."
49756
+ ];
49757
+ else content = ["When a request will take tools or more than a moment to answer, reply first with one short line that says what you are about to do \u2014 \"On it \u2014 <the task in a few words>.\" \u2014 then do the work; the opener posts as its own message before any progress is shown. Give direct answers and trivial replies without an opener.", "Finish with the outcome, not a replay of the steps."];
49758
+ const extra = typeof this.#instructions === "function" ? this.#instructions({ canReply }) : this.#instructions ?? [];
49759
+ messageList.addSystem({
49760
+ role: "system",
49761
+ content: [
49762
+ ...content,
49763
+ ...extra,
49764
+ LINK_REFERENCES,
49765
+ WRITE_FOR_PEOPLE
49766
+ ].join("\n")
49767
+ }, ID$1);
49768
+ return { messageList };
49769
+ }
49770
+ };
49771
+ // src/channels/reply-reminder-processor.ts
49772
+ const ID = "channel-reply-reminder";
49773
+ /** How long a run may work without posting before it is nudged. */
49774
+ const REPLY_REMINDER_AFTER_MS = 3e5;
49775
+ /**
49776
+ * With reply text hidden, a long job can run silently for an hour while the
49777
+ * person who asked has no idea whether anything is happening. Once a run has
49778
+ * gone `afterMs` without calling `reply_in_thread`, this sends the agent one
49779
+ * signal suggesting a status update, then restarts the clock. Ignoring it is
49780
+ * how the agent stays quiet. A signal joins the end of the transcript, so the
49781
+ * cached prompt prefix is untouched. Only runs that have the reply tool are
49782
+ * touched.
49783
+ */
49784
+ var ChannelReplyReminderProcessor = class {
49785
+ id = ID;
49786
+ #afterMs;
49787
+ #now;
49788
+ constructor({ afterMs = REPLY_REMINDER_AFTER_MS, now = Date.now } = {}) {
49789
+ this.#afterMs = afterMs;
49790
+ this.#now = now;
49791
+ }
49792
+ async processInputStep({ messageList, tools, state, sendSignal }) {
49793
+ if (!tools || !("reply_in_thread" in tools) || !sendSignal) return void 0;
49794
+ const reminder = state;
49795
+ const now = this.#now();
49796
+ reminder.quietSince ??= now;
49797
+ const seen = new Set(reminder.seenCalls ?? []);
49798
+ const calls = replyCalls(messageList.get.response.db());
49799
+ if (calls.some((id) => !seen.has(id))) reminder.quietSince = now;
49800
+ reminder.seenCalls = calls;
49801
+ const silentFor = now - reminder.quietSince;
49802
+ if (silentFor < this.#afterMs) return void 0;
49803
+ const minutes = Math.floor(silentFor / 6e4);
49804
+ await sendSignal({
49805
+ type: "reactive",
49806
+ contents: `It has been ${minutes} minute${minutes === 1 ? "" : "s"} since you last posted in this thread. If the people there would want to know where things stand, post a short status with \`${REPLY_TOOL_NAME}\`. Otherwise keep working.`
49807
+ });
49808
+ reminder.quietSince = now;
49809
+ }
49810
+ };
49811
+ /** Ids of the `reply_in_thread` calls this run has finished. */
49812
+ function replyCalls(messages) {
49813
+ const ids = [];
49814
+ for (const message of messages) {
49815
+ if (message.role !== "assistant") continue;
49816
+ for (const part of message.content.parts ?? []) {
49817
+ if (part.type !== "tool-invocation") continue;
49818
+ const { toolName, toolCallId, state } = part.toolInvocation;
49819
+ if (toolName === "reply_in_thread" && state === "result") ids.push(toolCallId);
49820
+ }
49821
+ }
49822
+ return ids;
49823
+ }
49824
+ // src/channels/reply-mode.ts
49825
+ /**
49826
+ * Slack renders the status inline next to the app name, and rejects a status
49827
+ * (sent as its loading message) of 51 characters or more. Other platforms get
49828
+ * the same cap; reply mode has only been tested on Slack.
49829
+ */
49830
+ const MAX_STATUS_LENGTH = 50;
49831
+ /**
49832
+ * Turns a tool's `description` arg ("Listing the repo root") into a status
49833
+ * line that reads after the app name ("<App> is listing the repo root…").
49834
+ * Only the first line counts: issue/PR creators carry whole bodies there.
49835
+ */
49836
+ function describeToolCall(args) {
49837
+ if (!args || typeof args !== "object") return void 0;
49838
+ const { description } = args;
49839
+ if (typeof description !== "string") return void 0;
49840
+ const line = description.split("\n").map((part) => part.replace(/\s+/g, " ").trim()).find(Boolean);
49841
+ if (!line) return void 0;
49842
+ const status = `is ${/^[A-Z][a-z]/.test(line) ? line.charAt(0).toLowerCase() + line.slice(1) : line}`;
49843
+ return status.length > MAX_STATUS_LENGTH ? `${status.slice(0, 49)}\u2026` : status;
49844
+ }
49845
+ /**
49846
+ * Progress as a status line rather than posts: "is thinking...", the current
49847
+ * tool's `description`, "is typing..." while a reply is written. With reply
49848
+ * text hidden, streamed text never reaches the thread, so it gets no status:
49849
+ * an "is typing..." set after the reply tool's post would sit on the thread
49850
+ * with nothing coming, and race the clear at the end of the run.
49851
+ *
49852
+ * @internal
49853
+ */
49854
+ function channelReplyTypingStatus(textDisplay = "hidden") {
49855
+ return (chunk) => {
49856
+ switch (chunk.type) {
49857
+ case "reasoning-delta": return "is thinking...";
49858
+ case "text-delta": return textDisplay === "show" ? "is typing..." : void 0;
49859
+ case "tool-call-input-streaming-start": return chunk.payload.toolName === "reply_in_thread" ? "is typing..." : void 0;
49860
+ case "tool-call":
49861
+ if (chunk.payload.toolName === "reply_in_thread") return "is typing...";
49862
+ return describeToolCall(chunk.payload.args) ?? "is working...";
49863
+ default: return;
49864
+ }
49865
+ };
49866
+ }
49867
+ function threadLinkOptions(link) {
49868
+ if (!link) return void 0;
49869
+ return typeof link === "function" ? { link } : link;
49870
+ }
49871
+ /**
49872
+ * Installed by `AgentChannels` when an adapter sets `replyMode`. On runs whose chat
49873
+ * thread is on that adapter (including runs started elsewhere whose thread is linked
49874
+ * to it) it adds the `reply_in_thread` tool, the reply guidance prompt, and the
49875
+ * nudge after a quiet stretch. Other runs are untouched.
49876
+ *
49877
+ * @internal
49878
+ */
49879
+ var ChannelReplyModeProcessor = class {
49880
+ id = "channel-reply-mode";
49881
+ #deps;
49882
+ constructor(deps) {
49883
+ this.#deps = deps;
49884
+ }
49885
+ async processInputStep(args) {
49886
+ const { requestContext, state } = args;
49887
+ const render = await this.#deps.resolveRender(requestContext, state);
49888
+ const adapter = render && this.#deps.adapter(render.platform);
49889
+ if (!requestContext || !render || !adapter?.replyMode) return void 0;
49890
+ const config = adapter.replyMode === "tool" ? {} : adapter.replyMode;
49891
+ if (render.textDisplay !== "hidden") {
49892
+ new ChannelReplyGuidanceProcessor({ instructions: config.instructions }).processInputStep(args);
49893
+ return { messageList: args.messageList };
49894
+ }
49895
+ const tools = {
49896
+ ...args.tools,
49897
+ ...createChannelReplyTool(requestContext, {
49898
+ resolveRender: async () => render,
49899
+ link: threadLinkOptions(adapter.threadLink)
49900
+ })
49901
+ };
49902
+ const withTools = {
49903
+ ...args,
49904
+ tools
49905
+ };
49906
+ new ChannelReplyGuidanceProcessor({ instructions: config.instructions }).processInputStep(withTools);
49907
+ await new ChannelReplyReminderProcessor({
49908
+ afterMs: config.reminderAfterMs,
49909
+ now: this.#deps.now
49910
+ }).processInputStep(withTools);
49911
+ const activeTools = args.activeTools && !args.activeTools.includes("reply_in_thread") ? [...args.activeTools, REPLY_TOOL_NAME] : void 0;
49912
+ return {
49913
+ tools,
49914
+ messageList: args.messageList,
49915
+ ...activeTools ? { activeTools } : {}
49916
+ };
49917
+ }
49918
+ };
49158
49919
  // src/channels/state-adapter.ts
49159
49920
  /**
49160
49921
  * Chat SDK StateAdapter backed by Mastra storage.
@@ -49168,15 +49929,17 @@ function channelLines(ctx, textHidden, tools) {
49168
49929
  var MastraStateAdapter = class {
49169
49930
  memoryStore;
49170
49931
  getOwnerId;
49932
+ logger;
49171
49933
  connected = false;
49172
49934
  connectPromise = null;
49173
49935
  cache = /* @__PURE__ */ new Map();
49174
49936
  locks = /* @__PURE__ */ new Map();
49175
49937
  lists = /* @__PURE__ */ new Map();
49176
49938
  queues = /* @__PURE__ */ new Map();
49177
- constructor(memoryStore, getOwnerId) {
49939
+ constructor(memoryStore, getOwnerId, logger) {
49178
49940
  this.memoryStore = memoryStore;
49179
49941
  this.getOwnerId = getOwnerId;
49942
+ this.logger = logger;
49180
49943
  }
49181
49944
  async connect() {
49182
49945
  if (this.connected) return;
@@ -49195,7 +49958,10 @@ var MastraStateAdapter = class {
49195
49958
  }
49196
49959
  async subscribe(threadId) {
49197
49960
  const thread = await this.findThreadByExternalId(threadId);
49198
- if (!thread) return;
49961
+ if (!thread) {
49962
+ this.logger?.warn(`subscribe(${threadId}) ignored: no Mastra thread is mapped to this chat thread. Use AgentChannels.subscribeThread() for threads the bot started itself.`);
49963
+ return;
49964
+ }
49199
49965
  await this.memoryStore.patchThread({
49200
49966
  id: thread.id,
49201
49967
  metadata: {
@@ -49574,6 +50340,24 @@ function formatLegacyHistoryBlock(history, chatThread, platform) {
49574
50340
  for (const msg of history.recent) lines.push(line(msg));
49575
50341
  return lines.join("\n");
49576
50342
  }
50343
+ // src/channels/thread-lookup.ts
50344
+ /**
50345
+ * The chat thread this run posts into, if any.
50346
+ *
50347
+ * A run started by a platform message has the render context on `requestContext`. A run
50348
+ * started elsewhere (web UI, schedule, signal wake) on a thread linked to a chat thread does
50349
+ * not, so rebuild it from the thread's persisted channel coordinates. The thread id comes from
50350
+ * the agent controller when there is one, else from the run's memory context. A forked
50351
+ * subagent's thread carries no channel metadata, so forks resolve nothing.
50352
+ */
50353
+ async function resolveChannelRenderContext(requestContext, channels) {
50354
+ if (!requestContext) return void 0;
50355
+ const stashed = requestContext.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
50356
+ if (isUsableRenderContext(stashed)) return stashed;
50357
+ const threadId = requestContext.get("controller")?.threadId ?? parseMemoryRequestContext(requestContext)?.thread?.id;
50358
+ if (!threadId) return void 0;
50359
+ return await channels?.()?.buildRenderContextForThread(threadId) ?? void 0;
50360
+ }
49577
50361
  // src/channels/typing-status.ts
49578
50362
  /**
49579
50363
  * Built-in typing-status resolver. Used when `typingStatus: true` (the default)
@@ -49819,7 +50603,7 @@ var AgentChannels = class {
49819
50603
  for (const [name, value] of Object.entries(config.adapters)) if (value && typeof value === "object" && "adapter" in value) {
49820
50604
  const cfg = value;
49821
50605
  adapters[name] = cfg.adapter;
49822
- adapterConfigs[name] = cfg;
50606
+ adapterConfigs[name] = cfg.replyMode ? withReplyModeDefaults(cfg) : cfg;
49823
50607
  } else {
49824
50608
  adapters[name] = value;
49825
50609
  adapterConfigs[name] = { adapter: value };
@@ -49840,6 +50624,7 @@ var AgentChannels = class {
49840
50624
  this.channelConfig = config;
49841
50625
  this.channelToolNames = new Set(Object.keys(this.getTools()));
49842
50626
  if (this.generativeUIEnabled) this.channelToolNames.add(RENDER_CARD_TOOL_NAME);
50627
+ if (this.replyModeEnabled) this.channelToolNames.add(REPLY_TOOL_NAME);
49843
50628
  }
49844
50629
  /**
49845
50630
  * Bind the owning agent used for webhook paths and stored-thread ownership.
@@ -50012,7 +50797,7 @@ var AgentChannels = class {
50012
50797
  const storage = mastra.getStorage();
50013
50798
  const memoryStore = storage ? await storage.getStore("memory") : void 0;
50014
50799
  if (!memoryStore) throw new Error("Channels require storage to be configured on the Mastra instance. Configure a storage provider like LibSQLStore.");
50015
- this.stateAdapter = new MastraStateAdapter(memoryStore, () => this.getOwnerId());
50800
+ this.stateAdapter = new MastraStateAdapter(memoryStore, () => this.getOwnerId(), this.logger);
50016
50801
  this.log("info", "Using MastraStateAdapter (subscriptions persist across restarts)");
50017
50802
  }
50018
50803
  const { Chat, Message: ChatMessage, ThreadImpl } = await getChatModule();
@@ -50240,25 +51025,30 @@ var AgentChannels = class {
50240
51025
  runId = stashed.runId;
50241
51026
  toolName = stashed.toolName;
50242
51027
  toolArgs = stashed.args;
50243
- } else {
51028
+ }
51029
+ if (!requesterId) {
50244
51030
  const { result: lookup } = await this.lookupPersistedApproval({
50245
51031
  mastra,
50246
51032
  card,
50247
51033
  platform
50248
51034
  });
50249
- if (lookup.status === "answered") {
50250
- this.log("info", "Tool approval already answered", actionEventContext);
50251
- return;
51035
+ if (!stashed?.runId) {
51036
+ if (lookup.status === "answered") {
51037
+ this.log("info", "Tool approval already answered", actionEventContext);
51038
+ return;
51039
+ }
51040
+ if (lookup.status === "pending") {
51041
+ runId = lookup.runId;
51042
+ toolName = lookup.toolName;
51043
+ toolArgs = lookup.args;
51044
+ }
50252
51045
  }
50253
51046
  if (lookup.status === "pending") {
50254
- runId = lookup.runId;
50255
- toolName = lookup.toolName;
50256
- toolArgs = lookup.args;
50257
- if (adapterConfig?.toolApprovers !== "anyone" && !requesterId && lookup.authors.length > 1) {
51047
+ if (adapterConfig?.toolApprovers !== "anyone" && lookup.authors.length > 1) {
50258
51048
  this.log("info", "Ignoring tool approval action: requester is ambiguous", actionEventContext);
50259
51049
  return;
50260
51050
  }
50261
- requesterId ??= lookup.authors[0];
51051
+ requesterId = lookup.authors[0];
50262
51052
  }
50263
51053
  }
50264
51054
  if (!runId) {
@@ -50547,8 +51337,28 @@ var AgentChannels = class {
50547
51337
  const processors = [];
50548
51338
  if (this.channelConfig.threadContext?.addSystemMessage !== false && !has("chat-channel-context")) processors.push(new ChatChannelProcessor(this));
50549
51339
  if (this.generativeUIEnabled && !has("chat-channel-generative-ui")) processors.push(new ChatChannelGenerativeUIProcessor(this));
51340
+ if (this.replyModeEnabled && !has(REPLY_MODE_PROCESSOR_ID)) processors.push(new ChannelReplyModeProcessor({
51341
+ resolveRender: (requestContext, state) => this.resolveRunRender(requestContext, state),
51342
+ adapter: (platform) => this.adapterConfigs[platform]
51343
+ }));
50550
51344
  return processors;
50551
51345
  }
51346
+ get replyModeEnabled() {
51347
+ return Object.values(this.adapterConfigs).some((cfg) => cfg.replyMode);
51348
+ }
51349
+ /**
51350
+ * The chat thread a run posts to: the one it came in on, else the one its
51351
+ * thread (the controller's, or memory's) is linked to. Cached on `state`
51352
+ * when given; `null` remembers a thread that isn't channel-backed.
51353
+ */
51354
+ async resolveRunRender(requestContext, state) {
51355
+ const inbound = requestContext?.get(CHAT_CHANNEL_RENDER_CONTEXT_KEY);
51356
+ if (isUsableRenderContext(inbound)) return inbound;
51357
+ if (state && "render" in state) return state.render ?? void 0;
51358
+ const render = await resolveChannelRenderContext(requestContext, () => this);
51359
+ if (state) state.render = render ?? null;
51360
+ return render;
51361
+ }
50552
51362
  /** Whether the Slack adapter opted into `generativeUI` (the only platform it supports). */
50553
51363
  get generativeUIEnabled() {
50554
51364
  return this.adapterConfigs.slack?.generativeUI === true;
@@ -50569,8 +51379,15 @@ var AgentChannels = class {
50569
51379
  */
50570
51380
  close() {}
50571
51381
  getOutputProcessors(configuredProcessors = []) {
50572
- if (configuredProcessors.some((p) => !isProcessorWorkflow(p) && p.id === "chat-channel-render")) return [];
50573
- return [new ChatChannelOutputProcessor(this)];
51382
+ const has = (id) => configuredProcessors.some((p) => !isProcessorWorkflow(p) && p.id === id);
51383
+ const processors = [];
51384
+ if (Object.values(this.adapterConfigs).some((cfg) => cfg.threadLink) && !has(THREAD_LINK_PROCESSOR_ID)) processors.push(new ChannelThreadLinkProcessor((requestContext) => {
51385
+ const platform = requestContext.get("channel")?.platform ?? requestContext.get("__mastra_chat_channel_render")?.platform;
51386
+ return platform ? threadLinkOptions(this.adapterConfigs[platform]?.threadLink) : void 0;
51387
+ }));
51388
+ if (!has("chat-channel-render")) processors.push(new ChatChannelOutputProcessor(this));
51389
+ if (this.replyModeEnabled && !has(REPLY_STREAM_PROCESSOR_ID)) processors.push(new ChannelReplyStreamProcessor((requestContext) => this.resolveRunRender(requestContext)));
51390
+ return processors;
50574
51391
  }
50575
51392
  /**
50576
51393
  * Returns generic channel tools (add_reaction, remove_reaction) that resolve
@@ -50845,6 +51662,7 @@ var AgentChannels = class {
50845
51662
  defaultThreadId,
50846
51663
  requestContext
50847
51664
  }) : void 0,
51665
+ onCreate: () => markNewChannelThread(requestContext),
50848
51666
  mastra
50849
51667
  });
50850
51668
  const threadResourceId = mastraThread.resourceId;
@@ -51747,9 +52565,39 @@ var AgentChannels = class {
51747
52565
  };
51748
52566
  }
51749
52567
  /**
52568
+ * Map a chat thread to a Mastra thread (creating the mapping if needed) and
52569
+ * subscribe to it, so follow-up replies reach the agent without a mention.
52570
+ *
52571
+ * Use this for threads the bot started itself, e.g. a scheduled digest posted
52572
+ * to Slack. Inbound messages create the mapping automatically, but a thread
52573
+ * the bot opened has none until someone mentions it. An existing mapping is
52574
+ * reused and keeps its original owner.
52575
+ *
52576
+ * @example
52577
+ * ```ts
52578
+ * const sent = await channel.post('Daily digest');
52579
+ * await agent.getChannels()!.subscribeThread({ thread: sent.thread, resourceId: 'digest-bot' });
52580
+ * ```
52581
+ */
52582
+ async subscribeThread({ thread, resourceId, threadId }) {
52583
+ const mastra = this.getMastra();
52584
+ if (!mastra) throw new Error("subscribeThread requires the agent to be registered with a Mastra instance.");
52585
+ await this.initialize(mastra);
52586
+ const mastraThread = await this.getOrCreateThread({
52587
+ externalThreadId: thread.id,
52588
+ channelId: thread.channelId,
52589
+ platform: thread.adapter.name,
52590
+ resourceId,
52591
+ threadId: threadId ? () => threadId : void 0,
52592
+ mastra
52593
+ });
52594
+ await this.stateAdapter.subscribe(thread.id);
52595
+ return mastraThread;
52596
+ }
52597
+ /**
51750
52598
  * Resolves an existing Mastra thread for the given external IDs, or creates one.
51751
52599
  */
51752
- async getOrCreateThread({ externalThreadId, channelId, platform, resourceId, threadId, mastra }) {
52600
+ async getOrCreateThread({ externalThreadId, channelId, platform, resourceId, threadId, onCreate, mastra }) {
51753
52601
  const { thread: existingThread, memoryStore, metadata } = await this.findThreadMapping({
51754
52602
  externalThreadId,
51755
52603
  channelId,
@@ -51757,6 +52605,7 @@ var AgentChannels = class {
51757
52605
  mastra
51758
52606
  });
51759
52607
  if (existingThread) return existingThread;
52608
+ onCreate?.();
51760
52609
  const resolvedResourceId = typeof resourceId === "function" ? await resourceId() : resourceId;
51761
52610
  const defaultThreadId = crypto.randomUUID();
51762
52611
  let resolvedThreadId = threadId ? await threadId(resolvedResourceId, defaultThreadId) : defaultThreadId;
@@ -51958,6 +52807,147 @@ async function storedAttachmentBytes(fs, dir, root = true) {
51958
52807
  }
51959
52808
  return total;
51960
52809
  }
52810
+ const REPLY_MODE_PROCESSOR_ID = "channel-reply-mode";
52811
+ const REPLY_STREAM_PROCESSOR_ID = "channel-reply-stream";
52812
+ const THREAD_LINK_PROCESSOR_ID = "channel-thread-link";
52813
+ /** Reply mode keeps reply text and tool calls out of the thread and shows progress in the status, unless set. */
52814
+ function withReplyModeDefaults(cfg) {
52815
+ const legacyCards = "cards" in cfg && cfg.cards !== void 0;
52816
+ const set = Object.fromEntries(Object.entries(cfg).filter(([, value]) => value !== void 0));
52817
+ const textDisplay = cfg.textDisplay ?? "hidden";
52818
+ return {
52819
+ textDisplay,
52820
+ ...legacyCards ? {} : { toolDisplay: "hidden" },
52821
+ typingStatus: channelReplyTypingStatus(textDisplay),
52822
+ ...set
52823
+ };
52824
+ }
52825
+ // src/knowledge/held-scopes-state-processor.ts
52826
+ const HELD_SCOPES_STATE_ID = "knowledge-scopes";
52827
+ const HELD_SCOPES_SNAPSHOT_TAG = "knowledge-scopes";
52828
+ const HELD_SCOPES_DELTA_TAG = "knowledge-scopes-update";
52829
+ function lp$1(value) {
52830
+ return `${value.length}:${value}`;
52831
+ }
52832
+ function fingerprint$1(scope) {
52833
+ return `${lp$1(scope.address)}${lp$1(scope.role)}`;
52834
+ }
52835
+ function cacheKey(scopes) {
52836
+ return `scopes:${scopes.map(fingerprint$1).join("|")}`;
52837
+ }
52838
+ function scopesFromSnapshot(snapshot) {
52839
+ const value = (snapshot?.metadata)?.value?.scopes;
52840
+ return Array.isArray(value) ? value : [];
52841
+ }
52842
+ function opsFromDelta(delta) {
52843
+ const ops = delta.metadata?.delta?.ops;
52844
+ return Array.isArray(ops) ? ops : [];
52845
+ }
52846
+ function applyOps(scopes, ops) {
52847
+ const next = scopes.slice();
52848
+ for (const op of ops) {
52849
+ const address = op.op === "remove" ? op.address : op.scope.address;
52850
+ const idx = next.findIndex((scope) => scope.address === address);
52851
+ if (op.op === "remove") {
52852
+ if (idx >= 0) next.splice(idx, 1);
52853
+ } else if (idx >= 0) next[idx] = op.scope;
52854
+ else next.push(op.scope);
52855
+ }
52856
+ return next;
52857
+ }
52858
+ function diffScopes(prior, current) {
52859
+ const ops = [];
52860
+ const before = new Map(prior.map((scope) => [scope.address, fingerprint$1(scope)]));
52861
+ const currentAddresses = new Set(current.map((scope) => scope.address));
52862
+ for (const scope of prior) if (!currentAddresses.has(scope.address)) ops.push({
52863
+ op: "remove",
52864
+ address: scope.address
52865
+ });
52866
+ for (const scope of current) {
52867
+ const was = before.get(scope.address);
52868
+ if (was === void 0) ops.push({
52869
+ op: "add",
52870
+ scope
52871
+ });
52872
+ else if (was !== fingerprint$1(scope)) ops.push({
52873
+ op: "change",
52874
+ scope
52875
+ });
52876
+ }
52877
+ return ops;
52878
+ }
52879
+ function line(scope) {
52880
+ return `${scope.address} (${scope.role})`;
52881
+ }
52882
+ function renderSnapshot(scopes) {
52883
+ if (scopes.length === 0) return "\n Your session holds no Knowledge scopes.\n";
52884
+ return `\n Your session has access to:\n${scopes.map((scope) => ` - ${line(scope)}`).join("\n")}\n`;
52885
+ }
52886
+ function renderDelta$1(ops) {
52887
+ return `\n${ops.map((op) => {
52888
+ if (op.op === "remove") return ` - ${op.address} was removed from your scopes`;
52889
+ if (op.op === "change") return ` ~ ${op.scope.address} role changed to ${op.scope.role}`;
52890
+ return ` + ${line(op.scope)}`;
52891
+ }).join("\n")}\n`;
52892
+ }
52893
+ var HeldScopesStateProcessor = class {
52894
+ deps;
52895
+ id = HELD_SCOPES_STATE_ID;
52896
+ stateId = HELD_SCOPES_STATE_ID;
52897
+ constructor(deps) {
52898
+ this.deps = deps;
52899
+ }
52900
+ processInput(args) {
52901
+ return {
52902
+ messages: args.messages,
52903
+ systemMessages: [...args.systemMessages, {
52904
+ role: "system",
52905
+ 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.`
52906
+ }]
52907
+ };
52908
+ }
52909
+ async computeStateSignal(args) {
52910
+ const context = {
52911
+ requestContext: args.requestContext,
52912
+ agent: {
52913
+ resourceId: args.resourceId,
52914
+ threadId: args.threadId
52915
+ }
52916
+ };
52917
+ if (await this.deps.principalsKey(context) === void 0) return;
52918
+ const current = await this.deps.readHeldScopes(context);
52919
+ let prior = scopesFromSnapshot(args.lastSnapshot);
52920
+ for (const delta of args.deltasSinceSnapshot ?? []) prior = applyOps(prior, opsFromDelta(delta));
52921
+ const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;
52922
+ const ops = diffScopes(prior, current);
52923
+ if (ops.length === 0 && hasBase) return;
52924
+ if (!hasBase || current.length === 0) {
52925
+ if (!hasBase && current.length === 0) return;
52926
+ return {
52927
+ id: HELD_SCOPES_STATE_ID,
52928
+ mode: "snapshot",
52929
+ cacheKey: cacheKey(current),
52930
+ tagName: HELD_SCOPES_SNAPSHOT_TAG,
52931
+ contents: renderSnapshot(current),
52932
+ value: { scopes: current },
52933
+ metadata: { value: { scopes: current } }
52934
+ };
52935
+ }
52936
+ return {
52937
+ id: HELD_SCOPES_STATE_ID,
52938
+ mode: "delta",
52939
+ cacheKey: cacheKey(current),
52940
+ tagName: HELD_SCOPES_DELTA_TAG,
52941
+ contents: renderDelta$1(ops),
52942
+ value: { scopes: current },
52943
+ delta: { ops },
52944
+ metadata: {
52945
+ value: { scopes: current },
52946
+ delta: { ops }
52947
+ }
52948
+ };
52949
+ }
52950
+ };
51961
52951
  // src/knowledge/instructions.ts
51962
52952
  function readInstructions(canEdit) {
51963
52953
  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.`;
@@ -52248,6 +53238,16 @@ function compileKnowledgeScopes(declarations) {
52248
53238
  const concreteEntries = [];
52249
53239
  for (const [key, declaration] of Object.entries(declarations)) {
52250
53240
  const pattern = parsePattern(key, "Knowledge scope key");
53241
+ if (declaration.mint !== void 0) {
53242
+ 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'.`);
53243
+ for (const param of pattern.params) if (![
53244
+ "agentId",
53245
+ "orgId",
53246
+ "resourceId",
53247
+ "role",
53248
+ "teamId"
53249
+ ].includes(param)) throw new KnowledgeDeclarationError(`Knowledge scope "${key}" cannot mint unknown parameter $${param}.`);
53250
+ }
52251
53251
  if (pattern.params.length === 0) {
52252
53252
  concreteEntries.push([key, declaration]);
52253
53253
  continue;
@@ -52716,17 +53716,19 @@ async function pageRefKeys(storage, page) {
52716
53716
  if (page.address) keys.push(knowledgeLinkRefKey(page.address));
52717
53717
  return keys;
52718
53718
  }
53719
+ if (!page.key || !page.parentId) return keys;
52719
53720
  const path = [];
52720
- let current = page;
52721
- while (current && !current.isScope) {
53721
+ for (const current of [page, ...await storage.getPageParents({
53722
+ parentId: page.parentId,
53723
+ read: "all"
53724
+ })]) {
53725
+ if (current.isScope) {
53726
+ if (current.address) keys.push(knowledgeLinkRefKey(`${current.address}#${path.join("/")}`));
53727
+ return keys;
53728
+ }
52722
53729
  if (!current.key || !current.parentId) return keys;
52723
53730
  path.unshift(current.key);
52724
- current = await storage.getPage({
52725
- id: current.parentId,
52726
- read: "all"
52727
- });
52728
53731
  }
52729
- if (current?.address) keys.push(knowledgeLinkRefKey(`${current.address}#${path.join("/")}`));
52730
53732
  return keys;
52731
53733
  }
52732
53734
  /** The page and its live ordinary descendants, at most {@link MAX_KNOWLEDGE_MOVE_PAGES} + 1. */
@@ -62219,6 +63221,94 @@ async function removeKnowledgeNote(host, input) {
62219
63221
  await embed$1(host, (index) => index.remove([`note:${note.id}`]), UNEMBED_FAILED$1);
62220
63222
  return removed;
62221
63223
  }
63224
+ // src/knowledge/agent-scopes.ts
63225
+ /** Agent identity declarations. Identities grant nothing until an access rule names them. @experimental */
63226
+ function knowledgeAgentScopes() {
63227
+ return Object.fromEntries([
63228
+ "agent:$agentId",
63229
+ "agent:$agentId:org:$orgId",
63230
+ "agent:$agentId:user:$resourceId",
63231
+ "agent:persona:role:$role",
63232
+ "agent:persona:role:$role:org:$orgId",
63233
+ "agent:persona:role:$role:user:$resourceId",
63234
+ "agent:persona:team:$teamId"
63235
+ ].map((key) => [key, {
63236
+ mint: "run-identity",
63237
+ access: []
63238
+ }]));
63239
+ }
63240
+ /**
63241
+ * {@link knowledgeAgentScopes} plus a read-only persona convention: each agent reads and pins its own
63242
+ * `#persona` page, and every agent of a role or team reads and pins that scope's `#rules` page. The
63243
+ * `:edit` forms give editor on one role or team scope and are never minted; host code passes them.
63244
+ * @experimental
63245
+ */
63246
+ function knowledgePersonaScopes() {
63247
+ const scopes = knowledgeAgentScopes();
63248
+ for (const [key, page, name, edit] of [
63249
+ [
63250
+ "agent:$agentId",
63251
+ "persona",
63252
+ "Persona",
63253
+ false
63254
+ ],
63255
+ [
63256
+ "agent:persona:role:$role",
63257
+ "rules",
63258
+ "Role rules",
63259
+ true
63260
+ ],
63261
+ [
63262
+ "agent:persona:team:$teamId",
63263
+ "rules",
63264
+ "Team rules",
63265
+ true
63266
+ ]
63267
+ ]) {
63268
+ scopes[key] = {
63269
+ ...scopes[key],
63270
+ access: [{
63271
+ principal: "self",
63272
+ role: "viewer"
63273
+ }, ...edit ? [{
63274
+ principal: `${key}:edit`,
63275
+ role: "editor"
63276
+ }] : []],
63277
+ pages: [{
63278
+ key: page,
63279
+ name
63280
+ }],
63281
+ pinnedContext: [`${key}#${page}`]
63282
+ };
63283
+ if (edit) scopes[`${key}:edit`] = { access: [] };
63284
+ }
63285
+ return scopes;
63286
+ }
63287
+ /** @internal */
63288
+ function mintKnowledgeAgentScopes(compiled, scopes, agent) {
63289
+ const params = {};
63290
+ if (agent?.agentId) params.agentId = agent.agentId;
63291
+ if (agent?.resourceId) params.resourceId = agent.resourceId;
63292
+ const persona = agent?.persona;
63293
+ if (persona && typeof persona === "object") for (const [field, param] of [["role", "role"], ["teamId", "teamId"]]) {
63294
+ const value = persona[field];
63295
+ if (typeof value === "string" && value.length > 0) params[param] = value;
63296
+ }
63297
+ const orgs = scopes.filter((scope) => /^org:[^:]+$/.test(scope)).map((scope) => decodeKnowledgeScopeValue(scope.slice(4))).filter((value) => value !== null);
63298
+ const minted = [];
63299
+ for (const declaration of compiled.declarations.values()) {
63300
+ if (declaration.declaration.mint !== "run-identity") continue;
63301
+ const bindings = declaration.pattern.params.includes("orgId") ? orgs.map((orgId) => ({
63302
+ ...params,
63303
+ orgId
63304
+ })) : [params];
63305
+ for (const binding of bindings) {
63306
+ const address = bindKnowledgePattern(declaration.pattern, binding);
63307
+ if (address) minted.push(address);
63308
+ }
63309
+ }
63310
+ return minted;
63311
+ }
62222
63312
  // src/knowledge/run.ts
62223
63313
  /** A page reference the run can't resolve; identical for missing and unreadable pages. */
62224
63314
  var KnowledgeNotFoundError = class extends Error {
@@ -62227,6 +63317,13 @@ var KnowledgeNotFoundError = class extends Error {
62227
63317
  this.name = "KnowledgeNotFoundError";
62228
63318
  }
62229
63319
  };
63320
+ /** A run with no scopes and no Memory identity: it has no Knowledge view. @internal */
63321
+ var KnowledgeRunScopesError = class extends Error {
63322
+ constructor() {
63323
+ super("Knowledge tools need run scopes: give the agent or the call `scopes`, or run it with Memory.");
63324
+ this.name = "KnowledgeRunScopesError";
63325
+ }
63326
+ };
62230
63327
  const NAME_CANDIDATES = 5;
62231
63328
  const CLOSE_MATCHES = 3;
62232
63329
  /**
@@ -62378,9 +63475,15 @@ function knowledgeRunPrincipals(runtime, context) {
62378
63475
  const memory = [];
62379
63476
  if (context?.agent?.resourceId) memory.push(knowledgeScopeAddress("resource:$resourceId", { resourceId: context.agent.resourceId }));
62380
63477
  if (context?.agent?.threadId) memory.push(knowledgeScopeAddress("thread:$threadId", { threadId: context.agent.threadId }));
62381
- 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.");
63478
+ if (raw.length === 0 && memory.length === 0) throw new KnowledgeRunScopesError();
62382
63479
  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()\`).`);
62383
- return [.../* @__PURE__ */ new Set([...knowledgeRunScopes(runtime.compiled, raw), ...memory])];
63480
+ const scopes = knowledgeRunScopes(runtime.compiled, raw);
63481
+ const minted = mintKnowledgeAgentScopes(runtime.compiled, scopes, context?.agent);
63482
+ return [.../* @__PURE__ */ new Set([
63483
+ ...scopes,
63484
+ ...memory,
63485
+ ...minted
63486
+ ])];
62384
63487
  }
62385
63488
  /** Longest heading line a hit shows ahead of its excerpt; a longer one is cut with `…`. */
62386
63489
  const HEADING_CHARS = 120;
@@ -62754,6 +63857,30 @@ async function noteSummaries(run, notes, cache = /* @__PURE__ */ new Map()) {
62754
63857
  for (const note of notes) summaries.push(noteSummary(note, await noteMentions(run, note, cache)));
62755
63858
  return summaries;
62756
63859
  }
63860
+ /**
63861
+ * Every scope the run holds, in principal order, with its role and what it can do there. A held scope
63862
+ * gets its page on the first write, so before that its role comes from the declarations and the parent
63863
+ * that write would link it under: without it a model sees no scopes on its first turn and concludes it
63864
+ * has nowhere to write. A stored scope it can't read keeps only its address.
63865
+ */
63866
+ async function heldScopes(run) {
63867
+ const stored = await run.storage.getScopesByAddress(run.principals);
63868
+ return Promise.all(run.principals.map(async (address) => {
63869
+ const found = stored.find((scope) => scope.address === address);
63870
+ const page = found && knowledgeScopeReadable(found, run.read) ? found : void 0;
63871
+ const role = found ? await run.roleOn(found) : knowledgeRoleOn(run.runtime.compiled, run.principals, {
63872
+ address,
63873
+ parentAddress: run.runtime.firstWriteParentAddress(address, run.principals)
63874
+ });
63875
+ const can = !role ? "none" : knowledgeRoleAtLeast(role, "contributor") ? "write" : "read";
63876
+ return {
63877
+ address,
63878
+ ...page ? { page } : {},
63879
+ role,
63880
+ can
63881
+ };
63882
+ }));
63883
+ }
62757
63884
  /** Scope pages for addresses the run names; each must be readable. */
62758
63885
  async function readableScopes(run, addresses) {
62759
63886
  const page = addresses.find((address) => address.includes("#"));
@@ -62790,11 +63917,13 @@ async function visibleNote(run, id) {
62790
63917
  page
62791
63918
  };
62792
63919
  }
62793
- /** Pin authority over an audience entry: the run holds it, or rules give it editor+ there. */
63920
+ /** Shared persona audiences need editor authority even when the run holds them. */
62794
63921
  async function requireAudienceAuthority(run, audience) {
62795
63922
  for (const address of audience) {
62796
- if (run.principals.includes(address)) continue;
62797
- if (!run.runtime.compiled.match(address)) throw new Error(`Pin audience "${address}" does not match a declared scope type.`);
63923
+ const match = run.runtime.compiled.match(address);
63924
+ const sharedPersona = match?.compiled.declaration.mint === "run-identity" && match.compiled.pattern.params.some((param) => param === "role" || param === "teamId");
63925
+ if (run.principals.includes(address) && !sharedPersona) continue;
63926
+ if (!match) throw new Error(`Pin audience "${address}" does not match a declared scope type.`);
62798
63927
  const [scope] = await run.storage.getScopesByAddress([address]);
62799
63928
  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.`);
62800
63929
  }
@@ -63034,7 +64163,7 @@ function bodyView(body, input) {
63034
64163
  function readTool(host, canEdit) {
63035
64164
  return createTool({
63036
64165
  id: "knowledge_read",
63037
- 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." : ""),
64166
+ 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." : ""),
63038
64167
  inputSchema: {
63039
64168
  type: "object",
63040
64169
  properties: {
@@ -63116,10 +64245,13 @@ function readTool(host, canEdit) {
63116
64245
  if (outline && from) throw new Error("knowledge_read: an outline covers the whole body; pass it without from.");
63117
64246
  const run = await start(host, context);
63118
64247
  const limit = limitOf(requested);
63119
- if (!ref) return { scopes: (await run.storage.getScopesByAddress(run.principals)).filter((scope) => knowledgeScopeReadable(scope, run.read)).map((scope) => ({
63120
- address: scope.address,
63121
- name: scope.name,
63122
- ...scope.description ? { description: scope.description } : {}
64248
+ if (!ref) return { scopes: (await heldScopes(run)).map(({ address, page, role, can }) => ({
64249
+ address,
64250
+ name: page?.name ?? address,
64251
+ ...page?.description ? { description: page.description } : {},
64252
+ ...role ? { role } : {},
64253
+ can,
64254
+ ...page ? {} : { empty: true }
63123
64255
  })) };
63124
64256
  const page = await run.pageOrCloseMatches(ref);
63125
64257
  if (outline || section || match || from) {
@@ -63333,12 +64465,13 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
63333
64465
  let scopes = [];
63334
64466
  if (!origin) {
63335
64467
  if (cursor?.startsWith("p")) throw new Error("knowledge_list: a page cursor needs the `from` it came from.");
63336
- const held = await run.storage.getScopesByAddress(run.principals);
63337
- const order = (scope) => run.principals.indexOf(scope.address ?? "");
63338
- scopes = held.filter((scope) => knowledgeScopeReadable(scope, run.read)).sort((a, b) => order(a) - order(b));
64468
+ scopes = (await heldScopes(run)).map((held) => ({
64469
+ ...held.page ? { page: held.page } : {},
64470
+ held
64471
+ }));
63339
64472
  } else {
63340
64473
  originRef = (await pageRefs(run, [origin])).refs.get(origin.id) ?? origin.id;
63341
- if (origin.isScope && !cursor?.startsWith("p")) scopes = await childScopes(origin.id);
64474
+ if (origin.isScope && !cursor?.startsWith("p")) scopes = (await childScopes(origin.id)).map((page) => ({ page }));
63342
64475
  }
63343
64476
  const shownScopes = scopes.slice(scopeOffset, scopeOffset + limit);
63344
64477
  let roots = shownScopes;
@@ -63348,7 +64481,7 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
63348
64481
  const room = limit - shownScopes.length;
63349
64482
  if (room > 0) {
63350
64483
  const pages = await childPages(origin.id, room, pageCursor);
63351
- roots = [...shownScopes, ...pages.pages];
64484
+ roots = [...shownScopes, ...pages.pages.map((page) => ({ page }))];
63352
64485
  if (pages.nextCursor) nextCursor = `p${pages.nextCursor}`;
63353
64486
  } else if ((await run.storage.countChildPages({
63354
64487
  parentIds: [origin.id],
@@ -63362,10 +64495,19 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
63362
64495
  children: 0,
63363
64496
  below: []
63364
64497
  });
63365
- const top = roots.map((page) => nodeOf(page, origin && originRef ? childRef(origin, originRef, page) : page.address ?? page.id, 1));
64498
+ const top = roots.map(({ page, held }) => page ? {
64499
+ ...nodeOf(page, origin && originRef ? childRef(origin, originRef, page) : page.address ?? page.id, 1),
64500
+ ...held ? { held } : {}
64501
+ } : {
64502
+ held,
64503
+ ref: held.address,
64504
+ depth: 1,
64505
+ children: 0,
64506
+ below: []
64507
+ });
63366
64508
  let budget = Math.max(limit - top.length, 0);
63367
64509
  let truncated = false;
63368
- let level = top;
64510
+ let level = top.filter((node) => node.page);
63369
64511
  for (let current = 1; current <= depth && level.length; current++) {
63370
64512
  const parentIds = level.map((node) => node.page.id);
63371
64513
  const scopeParents = level.filter((node) => node.page.isScope).map((node) => node.page.id);
@@ -63389,22 +64531,30 @@ async function listKnowledgeTree(run, { origin, depth, limit, cursor, descriptio
63389
64531
  budget -= scopes.length;
63390
64532
  const pages = budget > 0 ? (await childPages(node.page.id, budget)).pages : [];
63391
64533
  budget -= pages.length;
63392
- node.below = [...scopes, ...pages].map((child) => nodeOf(child, childRef(node.page, node.ref, child), current + 1));
63393
- if (node.below.length < node.children) truncated = true;
63394
- nextLevel.push(...node.below);
64534
+ const below = [...scopes, ...pages].map((child) => ({
64535
+ ...nodeOf(child, childRef(node.page, node.ref, child), current + 1),
64536
+ page: child
64537
+ }));
64538
+ node.below = below;
64539
+ if (below.length < node.children) truncated = true;
64540
+ nextLevel.push(...below);
63395
64541
  }
63396
64542
  level = nextLevel;
63397
64543
  }
63398
64544
  const entries = [];
63399
64545
  const flatten = (nodes) => {
63400
64546
  for (const node of nodes) {
64547
+ const { page, held } = node;
63401
64548
  entries.push({
63402
64549
  ref: node.ref,
63403
- name: node.page.name,
63404
- ...descriptions && node.page.description ? { description: node.page.description } : {},
64550
+ name: page?.name ?? node.ref,
64551
+ ...descriptions && page?.description ? { description: page.description } : {},
63405
64552
  depth: node.depth,
63406
64553
  children: node.children,
63407
- ...node.page.isScope ? { scope: true } : {}
64554
+ ...!page || page.isScope ? { scope: true } : {},
64555
+ ...held?.role ? { role: held.role } : {},
64556
+ ...held ? { can: held.can } : {},
64557
+ ...page ? {} : { empty: true }
63408
64558
  });
63409
64559
  flatten(node.below);
63410
64560
  }
@@ -63421,7 +64571,7 @@ function listTool(host) {
63421
64571
  const maxTokens = maxTokensOf(host);
63422
64572
  return createTool({
63423
64573
  id: "knowledge_list",
63424
- 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\`).`,
64574
+ 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\`).`,
63425
64575
  inputSchema: {
63426
64576
  type: "object",
63427
64577
  properties: {
@@ -64593,12 +65743,8 @@ var PinnedStateProcessor = class {
64593
65743
  threadId: args.threadId
64594
65744
  }
64595
65745
  };
64596
- let key;
64597
- try {
64598
- key = this.deps.principalsKey(context);
64599
- } catch {
64600
- return;
64601
- }
65746
+ const key = await this.deps.principalsKey(context);
65747
+ if (key === void 0) return void 0;
64602
65748
  if (memo && memo.key === key && stepNumber > memo.atStep) return memo.entries;
64603
65749
  const entries = await this.deps.readPins(context);
64604
65750
  args.requestContext?.set?.(MEMO_KEY, {
@@ -66518,7 +67664,7 @@ var MastraLLMVNext = class extends MastraBase {
66518
67664
  content: messages
66519
67665
  }];
66520
67666
  }
66521
- 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 = createRunScope(), agentId, agentVersionId, resolvedScopes, agentName, toolCallId, requestContext, actor, mcp, methodType, includeRawChunks, experimentalTransform, hideSignals, autoResumeSuspendedTools, maxProcessorRetries, processorStates, activeTools, isTaskComplete, goal, onIterationComplete, workspace, agentRunSpan, agent, ...rest }) {
67667
+ 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 = 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 }) {
66522
67668
  const observabilityContext = resolveObservabilityContext(rest);
66523
67669
  let stopWhenToUse;
66524
67670
  if (maxSteps && typeof maxSteps === "number") {
@@ -66544,7 +67690,8 @@ var MastraLLMVNext = class extends MastraBase {
66544
67690
  provider: firstModel.provider,
66545
67691
  streaming: true,
66546
67692
  parameters: modelSettings,
66547
- ...toolDefinitions ? { tools: toolDefinitions } : {}
67693
+ ...toolDefinitions ? { tools: toolDefinitions } : {},
67694
+ ...resultType ? { resultType } : {}
66548
67695
  },
66549
67696
  metadata: {
66550
67697
  runId,
@@ -71353,57 +72500,6 @@ function armRunDeadline(controller, deadline) {
71353
72500
  timer.unref?.();
71354
72501
  return timer;
71355
72502
  }
71356
- // src/agent/durable/constants.ts
71357
- const DURABLE_STOP_WHEN_ERROR_ID = "DURABLE_AGENT_STOP_WHEN_FAILED";
71358
- const REJECT_STREAM_ERROR = Symbol("mastra.durable.rejectStreamError");
71359
- function markErrorForStreamRejection(error) {
71360
- error[REJECT_STREAM_ERROR] = true;
71361
- return error;
71362
- }
71363
- function shouldRejectStream(error) {
71364
- return error[REJECT_STREAM_ERROR] === true;
71365
- }
71366
- /**
71367
- * Default values for durable agent execution
71368
- */
71369
- const DurableAgentDefaults = {
71370
- /** Default maximum number of agentic loop iterations */
71371
- MAX_STEPS: 5,
71372
- /**
71373
- * Default tool call concurrency.
71374
- * Applied by `resolveDurableToolCallConcurrency` when a run doesn't
71375
- * configure `toolCallConcurrency`. Approval / suspend-capable tool sets
71376
- * always run sequentially (concurrency: 1) regardless of this value.
71377
- */
71378
- TOOL_CALL_CONCURRENCY: 10
71379
- };
71380
- /**
71381
- * Step IDs used in the durable agentic workflow
71382
- */
71383
- const DurableStepIds = {
71384
- /** LLM execution step */
71385
- LLM_EXECUTION: "durable-llm-execution",
71386
- /** Tool call step */
71387
- TOOL_CALL: "durable-tool-call",
71388
- /** LLM mapping step (combines results) */
71389
- LLM_MAPPING: "durable-llm-mapping",
71390
- /** Agentic execution workflow (one iteration) */
71391
- AGENTIC_EXECUTION: "durable-agentic-execution",
71392
- /** Full agentic loop workflow */
71393
- AGENTIC_LOOP: "durable-agentic-loop",
71394
- /** Scorer execution step */
71395
- SCORER_EXECUTION: "durable-scorer-execution",
71396
- /** isTaskComplete evaluation step */
71397
- IS_TASK_COMPLETE: "durable-is-task-complete"
71398
- };
71399
- /** The loop's last step, which ends the run's spans when it succeeds. */
71400
- const MAP_FINAL_OUTPUT_STEP_ID = "map-final-output";
71401
- const RECOVER_ALREADY_IN_PROGRESS_ERROR_ID = "DURABLE_AGENT_RECOVER_ALREADY_IN_PROGRESS";
71402
- const RECOVER_SNAPSHOT_NOT_FOUND_ERROR_ID = "DURABLE_AGENT_RECOVER_SNAPSHOT_NOT_FOUND";
71403
- const RECOVER_CHECKPOINT_NOT_AVAILABLE_ERROR_ID = "DURABLE_AGENT_RECOVER_CHECKPOINT_NOT_AVAILABLE";
71404
- const RECOVER_RUN_SUSPENDED_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_SUSPENDED";
71405
- const RECOVER_RUN_NOT_ACTIVE_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_NOT_ACTIVE";
71406
- const RECOVER_SHUTDOWN_ERROR_ID = "DURABLE_AGENT_RECOVER_SHUTDOWN";
71407
72503
  // src/agent/durable/durable-stream-until-idle.ts
71408
72504
  /**
71409
72505
  * Run `DurableAgent.streamUntilIdle` (or `DurableAgent.stream({ untilIdle })`).
@@ -72947,8 +74043,9 @@ function releaseRunMessageRefs(runId) {
72947
74043
  /**
72948
74044
  * A `SaveQueueManager` `onSaved` callback that records the rows a run saved,
72949
74045
  * so its persisted transcript references them instead of repeating them. Only
72950
- * runs that store refs hold an entry (the transcript store creates it), so saves
72951
- * for other runs, or landing after the run released its entry, are not kept.
74046
+ * runs that store refs hold an entry (created before the run saves its input,
74047
+ * else by the transcript store), so saves for other runs, or landing after the
74048
+ * run released its entry, are not kept.
72952
74049
  */
72953
74050
  function recordRunSavedMessages(runId) {
72954
74051
  return (rows) => {
@@ -72970,6 +74067,15 @@ function recordRunSavedMessages(runId) {
72970
74067
  };
72971
74068
  }
72972
74069
  // src/agent/durable/utils/resolve-runtime.ts
74070
+ async function restoreWorkerToolsets(mastra, context, names) {
74071
+ const controller = context.get("controller");
74072
+ if (!isRestoredWorkerControllerContext(controller) || !names?.length) return;
74073
+ const toolsets = await mastra.getAgentControllerById(controller.controllerId)?.__restoreWorkerToolsets(context);
74074
+ if (!toolsets) return;
74075
+ const allowed = new Set(names);
74076
+ for (const [key, tools] of Object.entries(toolsets)) if (tools) toolsets[key] = Object.fromEntries(Object.entries(tools).filter(([name]) => allowed.has(name)));
74077
+ return toolsets;
74078
+ }
72973
74079
  /**
72974
74080
  * Build a SaveQueueManager for a run's memory, or `undefined` when no memory
72975
74081
  * is configured. Shared by `resolveRuntimeDependencies` and
@@ -73132,6 +74238,7 @@ async function resolveRuntimeDependencies(options) {
73132
74238
  backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
73133
74239
  tools = await agent.getToolsForExecution({
73134
74240
  runId,
74241
+ toolsets: await restoreWorkerToolsets(mastra, resolveRequestContext, input.options?.toolsetToolNames),
73135
74242
  threadId: input.state.threadId,
73136
74243
  resourceId: input.state.resourceId,
73137
74244
  requestContext: resolveRequestContext,
@@ -73253,6 +74360,7 @@ async function rebuildRunToolsFromMastra(options) {
73253
74360
  const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
73254
74361
  const tools = await agent.getToolsForExecution({
73255
74362
  runId,
74363
+ toolsets: await restoreWorkerToolsets(mastra, resolveRequestContext, execOptions?.toolsetToolNames),
73256
74364
  threadId: state.threadId,
73257
74365
  resourceId: state.resourceId,
73258
74366
  requestContext: resolveRequestContext,
@@ -73699,7 +74807,7 @@ function runTranscriptRefs(params) {
73699
74807
  async function runMemory(params, run) {
73700
74808
  const entry = run.runId ? getRunRegistryEntry(run.runId, params.mastra) : void 0;
73701
74809
  if (entry?.memory || !params.mastra || !run.agentId) return entry?.memory;
73702
- return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: restoreRequestContext(run.requestContextEntries, params.requestContext, getLiveRunRequestContext(entry)) });
74810
+ return params.mastra.getAgentById(run.agentId).getMemory({ requestContext: restoreRequestContext(run.requestContextEntries, params.requestContext, getLiveRunRequestContext(entry, run.runId, params.requestContext)) });
73703
74811
  }
73704
74812
  /** The most recent transcript in a snapshot: workflow state, else the last step output carrying one. */
73705
74813
  function latestMessageListState(snapshot) {
@@ -73722,7 +74830,11 @@ function mergeRequestContextForFinalization(entries, fallback, liveRunContext) {
73722
74830
  if (liveRunContext) return liveRunContext;
73723
74831
  if (!entries) return fallback ?? new RequestContext();
73724
74832
  const restored = new RequestContext(fallback?.entries());
73725
- for (const [key, value] of Object.entries(withoutLiveRequestKeys(entries))) restored.set(key, value);
74833
+ const controller = fallback?.get("controller");
74834
+ for (const [key, value] of Object.entries(withoutLiveRequestKeys(entries))) {
74835
+ if (key === "controller" && isRestoredWorkerControllerContext(controller)) continue;
74836
+ restored.set(key, value);
74837
+ }
73726
74838
  restoreRunAgentScopes(restored);
73727
74839
  return restored;
73728
74840
  }
@@ -73763,6 +74875,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73763
74875
  ...initData,
73764
74876
  messageListState
73765
74877
  },
74878
+ requestContext,
73766
74879
  logger: effectiveLogger
73767
74880
  });
73768
74881
  rebuiltSaveQueueManager = resolved.saveQueueManager;
@@ -73775,7 +74888,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
73775
74888
  error
73776
74889
  });
73777
74890
  }
73778
- const effectiveRequestContext = mergeRequestContextForFinalization(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry));
74891
+ const effectiveRequestContext = mergeRequestContextForFinalization(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext));
73779
74892
  if (!effectiveRequestContext.has("MastraMemory") && durableState?.threadId) effectiveRequestContext.set("MastraMemory", {
73780
74893
  thread: { id: durableState.threadId },
73781
74894
  resourceId: durableState.resourceId,
@@ -74072,9 +75185,9 @@ function deadlineMessageListState(entry, fallback) {
74072
75185
  * durable run. The run never reaches its finish step, so this runs over what the deadline saves
74073
75186
  * (see `deadlineMessageListState`), as the default loop's deadline pass does.
74074
75187
  */
74075
- async function runDurableDeadlineOutputPass({ runId, initData, messageListState, cutOffText, entry, mastra, tracingContext, logger }) {
75188
+ async function runDurableDeadlineOutputPass({ runId, initData, messageListState, cutOffText, entry, executionId, mastra, tracingContext, logger }) {
74076
75189
  const durableState = initData.state;
74077
- const requestContext = mergeRequestContextForFinalization(initData.requestContextEntries, void 0, getLiveRunRequestContext(entry));
75190
+ const requestContext = mergeRequestContextForFinalization(initData.requestContextEntries, void 0, getLiveRunRequestContext(entry, runId, void 0, executionId));
74078
75191
  if (!requestContext.has("MastraMemory") && durableState?.threadId) requestContext.set("MastraMemory", {
74079
75192
  thread: { id: durableState.threadId },
74080
75193
  resourceId: durableState.resourceId,
@@ -75767,6 +76880,15 @@ function buildMessagesFromChunks({ chunks, messageId, responseModelMetadata, too
75767
76880
  });
75768
76881
  break;
75769
76882
  }
76883
+ case "custom": {
76884
+ const p = chunk.payload;
76885
+ parts.push({
76886
+ type: "custom",
76887
+ kind: p.kind,
76888
+ ...p.providerMetadata ? { providerMetadata: p.providerMetadata } : {}
76889
+ });
76890
+ break;
76891
+ }
75770
76892
  case "tool-call": {
75771
76893
  const p = chunk.payload;
75772
76894
  const toolDef = tools?.[p.toolName] || findProviderToolByName(tools, p.toolName);
@@ -76092,7 +77214,7 @@ function createDurableLLMExecutionStep(_options) {
76092
77214
  const typedInput = inputData;
76093
77215
  const { agentId, messageId, options: execOptions } = typedInput;
76094
77216
  const runId = typedInput.runId;
76095
- const requestContext = getLiveRunRequestContext(getRunRegistryEntry(runId, mastra)) ?? params.requestContext;
77217
+ const requestContext = getLiveRunRequestContext(getRunRegistryEntry(runId, mastra), runId, params.requestContext) ?? params.requestContext;
76096
77218
  const logger = mastra?.getLogger?.();
76097
77219
  if (pubsub) await emitIterationStartEvent(pubsub, runId, inputData.stepIndex ?? 0);
76098
77220
  const { messageList, tools, model: resolvedModel, modelList: resolvedModelList, inputProcessors: resolvedInputProcessors, llmRequestInputProcessors: resolvedLlmRequestInputProcessors, outputProcessors: resolvedOutputProcessors } = await resolveRuntimeDependencies({
@@ -78989,6 +80111,15 @@ async function flushMessagesBeforeSuspension({ saveQueueManager, messageList, me
78989
80111
  return false;
78990
80112
  }
78991
80113
  }
80114
+ /**
80115
+ * Context for output processors on a tool result. A live context is reused only for the execution that
80116
+ * owns it. A context rebuilt from the run snapshot is returned as before; whether a rebuilt entry can
80117
+ * outlive a resume by another caller is tracked in COR-1660.
80118
+ */
80119
+ function toolResultRequestContext(registryEntry, runId, stepRequestContext) {
80120
+ if (registryEntry?.requestContextRebuilt) return registryEntry.requestContext;
80121
+ return getLiveRunRequestContext(registryEntry, runId, stepRequestContext) ?? stepRequestContext;
80122
+ }
78992
80123
  var DurableOutputProcessorError = class extends Error {
78993
80124
  constructor(error) {
78994
80125
  super(error instanceof Error ? error.message : String(error), { cause: error });
@@ -79010,7 +80141,7 @@ var DurableChunkPublishError = class extends Error {
79010
80141
  * Thin glue over the shared per-chunk pipeline core; mirrors the regular
79011
80142
  * agent's `processAndEnqueueChunk` in llm-mapping-step.ts.
79012
80143
  */
79013
- async function processChunkThroughOutputProcessors(chunk, registryEntry, pubsub, runId, agentName, logger, messageList, observabilityContext, collectDataPart, onEmit) {
80144
+ async function processChunkThroughOutputProcessors(chunk, registryEntry, stepRequestContext, pubsub, runId, agentName, logger, messageList, observabilityContext, collectDataPart, onEmit) {
79014
80145
  const runner = registryEntry?.outputProcessors?.length && registryEntry.processorStates ? new ProcessorRunner({
79015
80146
  inputProcessors: [],
79016
80147
  outputProcessors: registryEntry.outputProcessors,
@@ -79023,7 +80154,7 @@ async function processChunkThroughOutputProcessors(chunk, registryEntry, pubsub,
79023
80154
  runner,
79024
80155
  processorStates: registryEntry?.processorStates,
79025
80156
  observabilityContext,
79026
- requestContext: registryEntry?.requestContext,
80157
+ requestContext: toolResultRequestContext(registryEntry, runId, stepRequestContext),
79027
80158
  messageList,
79028
80159
  streamWriter: pubsub ? { custom: async (data, writerOptions) => {
79029
80160
  if (data.type.startsWith("data-") && !data.transient) collectDataPart?.({
@@ -79297,6 +80428,12 @@ function createDurableToolCallStep() {
79297
80428
  error
79298
80429
  };
79299
80430
  }
80431
+ if (typeof args === "object" && args !== null) args = sanitizeToolArguments({
80432
+ args,
80433
+ toolName,
80434
+ toolConfig: tool?.backgroundConfig,
80435
+ agentConfig: registryEntry?.backgroundTasksConfig
80436
+ });
79300
80437
  const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;
79301
80438
  const memory = registryEntry?.memory ?? rebuiltMemory;
79302
80439
  const workspace = registryEntry?.workspace ?? rebuiltWorkspace;
@@ -79374,7 +80511,7 @@ function createDurableToolCallStep() {
79374
80511
  }).add(invocation, "memory");
79375
80512
  }
79376
80513
  if (saveQueueManager && messagesToFlush && memory && state?.threadId && state.resourceId && !state.memoryConfig?.readOnly) {
79377
- const authorizationRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext);
80514
+ const authorizationRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext));
79378
80515
  const authorizeMemory = (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
79379
80516
  mastra,
79380
80517
  user: authorizationRequestContext.get("user"),
@@ -79418,10 +80555,10 @@ function createDurableToolCallStep() {
79418
80555
  };
79419
80556
  const registryRequireToolApproval = registryEntry?.requireToolApproval;
79420
80557
  const effectiveRequireToolApproval = registryRequireToolApproval !== void 0 ? registryRequireToolApproval : agentOptions.requireToolApproval;
79421
- const approvalRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext);
80558
+ const approvalRequestContext = restoreRequestContext(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext));
79422
80559
  const requiresApproval = await toolRequiresApproval(tool, effectiveRequireToolApproval, args, {
79423
80560
  toolName,
79424
- requestContext: Object.fromEntries([...approvalRequestContext.entries()].filter(([key]) => !INTERNAL_APPROVAL_KEYS.has(key))),
80561
+ requestContext: Object.fromEntries([...approvalRequestContext.entries()].filter(([key]) => key !== "__mastra_durableContextSegment" && !INTERNAL_APPROVAL_KEYS.has(key))),
79425
80562
  workspace
79426
80563
  });
79427
80564
  const addToolMetadata = (opts) => {
@@ -79601,7 +80738,7 @@ function createDurableToolCallStep() {
79601
80738
  toolTransform: tool?.transform,
79602
80739
  tools: toolsForTransform,
79603
80740
  logger
79604
- }), registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
80741
+ }), registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
79605
80742
  } catch (emitError) {
79606
80743
  if (emitError instanceof DurableOutputProcessorError) throw emitError;
79607
80744
  logger?.warn?.(`[DurableAgent] Failed to emit tool-result chunk for ${toolName}: ${emitError}`);
@@ -79703,7 +80840,7 @@ function createDurableToolCallStep() {
79703
80840
  policy: toolPayloadTransform,
79704
80841
  tools: toolsForTransform,
79705
80842
  logger
79706
- }), registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
80843
+ }), registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
79707
80844
  } catch (emitError) {
79708
80845
  if (emitError instanceof DurableOutputProcessorError) throw emitError;
79709
80846
  logger?.warn?.(`[DurableAgent] Failed to emit tool-output-denied chunk for ${toolName}: ${emitError}`);
@@ -80143,7 +81280,7 @@ function createDurableToolCallStep() {
80143
81280
  toolCallId: params.toolCallId,
80144
81281
  toolName: params.toolName,
80145
81282
  status: params.status === "failed" ? "failed" : "completed",
80146
- requestContext: restoreRequestContext(initData.requestContextEntries, requestContext, registryEntry?.requestContext)
81283
+ requestContext: restoreRequestContext(initData.requestContextEntries, requestContext, getLiveRunRequestContext(registryEntry, runId, requestContext))
80147
81284
  });
80148
81285
  } catch (error) {
80149
81286
  resolveReconciliation({ error });
@@ -80442,7 +81579,7 @@ function createDurableToolCallStep() {
80442
81579
  result,
80443
81580
  modelOutput: readModelOutput(providerMetadata),
80444
81581
  ...processorObservabilityContext ?? {},
80445
- requestContext: registryEntry.requestContext,
81582
+ requestContext: toolResultRequestContext(registryEntry, runId, requestContext),
80446
81583
  retryCount: 0,
80447
81584
  writer: pubsub ? { custom: async (data, writerOptions) => {
80448
81585
  if (data.type.startsWith("data-") && !data.transient) collectProcessorDataPart({
@@ -80547,7 +81684,7 @@ function createDurableToolCallStep() {
80547
81684
  logger
80548
81685
  });
80549
81686
  transformMetadata = resultChunk.metadata;
80550
- await processChunkThroughOutputProcessors(resultChunk, registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart, (chunk) => {
81687
+ await processChunkThroughOutputProcessors(resultChunk, registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart, (chunk) => {
80551
81688
  if (chunk.type === "tool-result" && chunk.payload.toolCallId === toolCallId) resultEmitted = true;
80552
81689
  });
80553
81690
  } catch (emitError) {
@@ -80619,7 +81756,7 @@ function createDurableToolCallStep() {
80619
81756
  logger
80620
81757
  });
80621
81758
  errorTransformMetadata = errorChunk.metadata;
80622
- await processChunkThroughOutputProcessors(errorChunk, registryEntry, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
81759
+ await processChunkThroughOutputProcessors(errorChunk, registryEntry, requestContext, pubsub, runId, initData.agentId, logger, messageList, processorObservabilityContext, collectProcessorDataPart);
80623
81760
  } catch (emitError) {
80624
81761
  ownership?.throwIfLost();
80625
81762
  if (emitError instanceof DurableOutputProcessorError) throw emitError;
@@ -81207,7 +82344,7 @@ function createDurableIsTaskCompleteStep(defaultMaxSteps = DurableAgentDefaults.
81207
82344
  const restored = await restoreCompletionPolicy({
81208
82345
  agent,
81209
82346
  persisted: initData.options.isTaskComplete,
81210
- requestContext: restoreRequestContext(initData.requestContextEntries, registryEntry?.requestContext, getLiveRunRequestContext(registryEntry)),
82347
+ requestContext: restoreRequestContext(initData.requestContextEntries, params.requestContext, getLiveRunRequestContext(registryEntry, state.runId, params.requestContext)),
81211
82348
  runId: state.runId,
81212
82349
  logger: mastra?.getLogger?.()
81213
82350
  });
@@ -81243,7 +82380,7 @@ function createDurableIsTaskCompleteStep(defaultMaxSteps = DurableAgentDefaults.
81243
82380
  agentName: initData.agentName,
81244
82381
  threadId: initData.state?.threadId,
81245
82382
  resourceId: initData.state?.resourceId,
81246
- customContext: restoreCustomContext(initData.requestContextEntries, registryEntry?.requestContext ?? params.requestContext),
82383
+ customContext: restoreCustomContext(initData.requestContextEntries, getLiveRunRequestContext(registryEntry, state.runId, params.requestContext) ?? params.requestContext),
81247
82384
  generateId: () => mastra?.generateId?.(),
81248
82385
  emitChunk: (chunk) => {
81249
82386
  if (!pubsub) return;
@@ -81291,7 +82428,7 @@ function createDurableGoalStep() {
81291
82428
  const registryEntry = getRunRegistryEntry(state.runId, mastra);
81292
82429
  let goalConfig = registryEntry?.goal;
81293
82430
  if (!goalConfig && initData.agentId) goalConfig = mastra?.getAgentById?.(initData.agentId)?.__getGoalConfig?.();
81294
- const liveRunContext = getLiveRunRequestContext(registryEntry);
82431
+ const liveRunContext = getLiveRunRequestContext(registryEntry, state.runId, params.requestContext);
81295
82432
  const currentRequestContext = liveRunContext ?? params.requestContext;
81296
82433
  const requestContext = restoreRequestContext(initData.requestContextEntries, params.requestContext, liveRunContext);
81297
82434
  const customContext = restoreCustomContext(initData.requestContextEntries, currentRequestContext);
@@ -83092,15 +84229,21 @@ async function persistDurableRunInput(runId, workflowInput, mastra, beforeSave)
83092
84229
  await beforeSave();
83093
84230
  }
83094
84231
  const inputCopy = entry.messageList.clone();
83095
- await entry.saveQueueManager.flushMessages(inputCopy, state.threadId, state.memoryConfig, {
83096
- throwOnError: true,
83097
- beforePersist: () => assertExecutionOwned({
83098
- runId,
83099
- agentId: workflowInput.agentId,
83100
- mastra,
83101
- requestContext
83102
- })
83103
- });
84232
+ if (state.fixedMemory) getRunMessageRefs(runId);
84233
+ try {
84234
+ await entry.saveQueueManager.flushMessages(inputCopy, state.threadId, state.memoryConfig, {
84235
+ throwOnError: true,
84236
+ beforePersist: () => assertExecutionOwned({
84237
+ runId,
84238
+ agentId: workflowInput.agentId,
84239
+ mastra,
84240
+ requestContext
84241
+ })
84242
+ });
84243
+ } catch (error) {
84244
+ if (state.fixedMemory) releaseRunMessageRefs(runId);
84245
+ throw error;
84246
+ }
83104
84247
  const embedded = entry.messageList.getEmbeddedMessages();
83105
84248
  for (const [messageId, textHash] of inputCopy.getEmbeddedMessages()) embedded.set(messageId, textHash);
83106
84249
  }
@@ -83427,7 +84570,7 @@ async function prepareForDurableExecution(options) {
83427
84570
  });
83428
84571
  let tripwireData;
83429
84572
  if (inputProcessors.length > 0) try {
83430
- const { ProcessorRunner } = await import("./stream-C5PagEDs.js").then((n) => n.I);
84573
+ const { ProcessorRunner } = await import("./stream-1DGoEkG2.js").then((n) => n.I);
83431
84574
  await new ProcessorRunner({
83432
84575
  inputProcessors,
83433
84576
  outputProcessors,
@@ -86187,6 +87330,11 @@ var Agent = class Agent extends MastraBase {
86187
87330
  const processors = [];
86188
87331
  const instructions = knowledge.getInstructions();
86189
87332
  if (instructions && !configuredIds.has("knowledge-instructions-processor")) processors.push(new KnowledgeInstructionsProcessor(instructions));
87333
+ const toolGroups = knowledge.__toolGroups;
87334
+ if (hasMemory && (toolGroups.read || toolGroups.write) && !hasConfiguredProcessor(configuredProcessors, (processor) => processor.id === "knowledge-scopes")) processors.push(new HeldScopesStateProcessor({
87335
+ principalsKey: (context) => knowledge.__principalsKey(context),
87336
+ readHeldScopes: (context) => knowledge.__heldScopes(context)
87337
+ }));
86190
87338
  if (knowledge.pinnedContextEnabled && !configuredIds.has("knowledge")) {
86191
87339
  if (!hasMemory) {
86192
87340
  if (!this.#warnedPinsWithoutMemory) {
@@ -86195,9 +87343,26 @@ var Agent = class Agent extends MastraBase {
86195
87343
  }
86196
87344
  return processors;
86197
87345
  }
87346
+ const contexts = /* @__PURE__ */ new WeakMap();
87347
+ const pinContext = (context) => {
87348
+ let resolved = contexts.get(context);
87349
+ if (!resolved) {
87350
+ const requestContext = context.requestContext instanceof RequestContext ? context.requestContext : void 0;
87351
+ resolved = this.resolveKnowledgePersona(knowledge, requestContext).then((persona) => ({
87352
+ ...context,
87353
+ agent: {
87354
+ ...context.agent,
87355
+ agentId: this.id,
87356
+ persona
87357
+ }
87358
+ }));
87359
+ contexts.set(context, resolved);
87360
+ }
87361
+ return resolved;
87362
+ };
86198
87363
  processors.push(new PinnedStateProcessor({
86199
- principalsKey: (context) => knowledge.__principalsKey(context),
86200
- readPins: (context) => knowledge.__deliveredPins(context),
87364
+ principalsKey: async (context) => knowledge.__principalsKey(await pinContext(context)),
87365
+ readPins: async (context) => knowledge.__deliveredPins(await pinContext(context)),
86201
87366
  ...knowledge.__toolGroups
86202
87367
  }));
86203
87368
  }
@@ -87154,7 +88319,8 @@ var Agent = class Agent extends MastraBase {
87154
88319
  }
87155
88320
  /**
87156
88321
  * Gets the metadata for this agent, resolving function-based metadata if necessary.
87157
- * Metadata is a classification bag for clients and is never read by the agent runtime.
88322
+ * Metadata is a classification bag for clients. The agent runtime reads only `metadata.persona`, to mint
88323
+ * Knowledge persona scopes; it reads nothing else in metadata.
87158
88324
  *
87159
88325
  * @example
87160
88326
  * ```typescript
@@ -87892,11 +89058,13 @@ var Agent = class Agent extends MastraBase {
87892
89058
  ...observabilityContext,
87893
89059
  messageList,
87894
89060
  agentId: this.id,
87895
- agentName: this.name
89061
+ agentName: this.name,
89062
+ resultType: "title_generation"
87896
89063
  }).text;
87897
89064
  } else text = (await llm.__text({
87898
89065
  requestContext,
87899
89066
  ...observabilityContext,
89067
+ resultType: "title_generation",
87900
89068
  messages: [{
87901
89069
  role: "system",
87902
89070
  content: systemInstructions
@@ -88043,10 +89211,34 @@ var Agent = class Agent extends MastraBase {
88043
89211
  backgroundConfig: tool.background,
88044
89212
  agentBackgroundConfig: this.#backgroundTasks
88045
89213
  };
88046
- converted[toolName] = makeCoreTool(tool, options, void 0, autoResumeSuspendedTools, backgroundTaskEnabled);
89214
+ const execute = tool.execute;
89215
+ const agentTool = execute ? {
89216
+ ...tool,
89217
+ execute: async (input, context) => {
89218
+ const persona = await this.resolveKnowledgePersona(knowledge, requestContext);
89219
+ const runContext = {
89220
+ ...context,
89221
+ agent: context?.agent ? {
89222
+ ...context.agent,
89223
+ agentId: this.id,
89224
+ persona
89225
+ } : void 0
89226
+ };
89227
+ return execute(input, runContext);
89228
+ }
89229
+ } : tool;
89230
+ converted[toolName] = makeCoreTool(agentTool, options, void 0, autoResumeSuspendedTools, backgroundTaskEnabled);
88047
89231
  }
88048
89232
  return converted;
88049
89233
  }
89234
+ async resolveKnowledgePersona(knowledge, requestContext) {
89235
+ if (!await knowledge.__needsAgentPersona()) return void 0;
89236
+ try {
89237
+ return (await this.getMetadata({ requestContext }))?.persona;
89238
+ } catch {
89239
+ return;
89240
+ }
89241
+ }
88050
89242
  /**
88051
89243
  * Lists workspace tools if a workspace is configured.
88052
89244
  * @internal
@@ -93530,6 +94722,7 @@ var Agent = class Agent extends MastraBase {
93530
94722
  initData: runInput,
93531
94723
  ...deadlineMessageListState(runInputEntry, runInput.messageListState),
93532
94724
  entry: runInputEntry,
94725
+ executionId: fence.executionId,
93533
94726
  mastra: this.#mastra,
93534
94727
  tracingContext: deadlineSpan ? { currentSpan: deadlineSpan } : void 0,
93535
94728
  logger: this.logger
@@ -94063,7 +95256,7 @@ var Agent = class Agent extends MastraBase {
94063
95256
  const threadId = workflowInput.state?.threadId ?? memoryInfo?.threadId;
94064
95257
  const resourceId = workflowInput.state?.resourceId ?? memoryInfo?.resourceId;
94065
95258
  if (sharedExecution && pubsub && entry?.requestContext && executionFence && threadId) {
94066
- await agentThreadStreamRuntime.claimDurableThreadLease(pubsub, runId, threadId, resourceId, executionFence.generation, executionFence.executionId);
95259
+ await agentThreadStreamRuntime.claimDurableThreadLease(pubsub, runId, threadId, resourceId, executionFence.generation, executionFence.executionId, true);
94067
95260
  try {
94068
95261
  await executionFence.verify();
94069
95262
  } catch (error) {
@@ -94337,7 +95530,13 @@ var Agent = class Agent extends MastraBase {
94337
95530
  messageListFollowsStream: () => !this.executionEngine.executesStepsLocally
94338
95531
  });
94339
95532
  streamCleanup = createdStreamCleanup;
94340
- const workflowExecution = executionFence.run(() => ready.then(async () => {
95533
+ const threadRegistration = agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
95534
+ continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
95535
+ generation: executionFence.generation,
95536
+ ownershipLost: () => executionFence.isLost(),
95537
+ stepOwner: () => getRunRegistryEntry(runId, this.#mastra)
95538
+ });
95539
+ const workflowExecution = executionFence.run(() => Promise.all([ready, threadRegistration]).then(async () => {
94341
95540
  if (await this.redeliverDeadlineError(registryEntry, executionFence)) return;
94342
95541
  await emitChunkEvent(fencePubSub(this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub, executionFence), runId, {
94343
95542
  type: "start",
@@ -94378,12 +95577,7 @@ var Agent = class Agent extends MastraBase {
94378
95577
  }).catch((error) => this.settleExecution(runId, executionFence, { error: this.executionEngine.workflowExecutionError(error, "Workflow execution failed") })));
94379
95578
  const trackedEntry = getRunRegistryEntry(runId, this.#mastra);
94380
95579
  if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
94381
- await agentThreadStreamRuntime.registerRun(this, output, options, this.getPubSub(), {
94382
- continuation: methodType === "stream" && !closeOnSuspend ? "across-suspension" : void 0,
94383
- generation: executionFence.generation,
94384
- ownershipLost: () => executionFence.isLost(),
94385
- stepOwner: () => getRunRegistryEntry(runId, this.#mastra)
94386
- });
95580
+ await threadRegistration;
94387
95581
  const cleanup = () => {
94388
95582
  if (methodType === "generate" || runCleanup.done || output.status !== "running") return performCleanup();
94389
95583
  Promise.race([workflowExecution, executionFence.whenSettled]).then(() => this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub.flush()).then(() => waitForEventDelivery()).catch(() => {}).finally(performCleanup);
@@ -95785,6 +96979,29 @@ var Agent = class Agent extends MastraBase {
95785
96979
  };
95786
96980
  }
95787
96981
  };
96982
+ // src/agent/merge-persona.ts
96983
+ function merge(metadata, persona) {
96984
+ const code = metadata?.persona;
96985
+ const base = code && typeof code === "object" && !Array.isArray(code) ? code : {};
96986
+ const set = Object.fromEntries(Object.entries(persona).filter(([, value]) => value !== void 0));
96987
+ return {
96988
+ ...metadata,
96989
+ persona: {
96990
+ ...base,
96991
+ ...set
96992
+ }
96993
+ };
96994
+ }
96995
+ /**
96996
+ * Overrides an Agent's `metadata.persona` field by field: a field `persona` sets wins, a field it leaves
96997
+ * unset keeps the code's value, and keys outside `persona` stay as they are. Function-form metadata is
96998
+ * wrapped so the override applies to whatever it resolves to.
96999
+ * @experimental
97000
+ */
97001
+ function mergeAgentPersona(metadata, persona) {
97002
+ if (typeof metadata !== "function") return merge(metadata, persona);
97003
+ return async (context) => merge(await metadata(context), persona);
97004
+ }
95788
97005
  // ../_internal-core/dist/fs-routing/index.js
95789
97006
  /**
95790
97007
  * Maximum nesting depth for declared subagents. A top-level agent is depth 0;
@@ -102451,6 +103668,12 @@ function createToolCallStep({ tools, messageList, options, outputWriter, control
102451
103668
  args = argsFromInput;
102452
103669
  resumeDataFromArgs = resumeDataFromInput;
102453
103670
  }
103671
+ if (typeof args === "object" && args !== null) args = sanitizeToolArguments({
103672
+ args,
103673
+ toolName: inputData.toolName,
103674
+ toolConfig: tool?.backgroundConfig,
103675
+ agentConfig: readScoped(scopeCtx, AGENT_BACKGROUND_CONFIG_KEY, "agentBackgroundConfig")
103676
+ });
102454
103677
  const resumeData = resumeDataFromArgs ?? workflowResumeData;
102455
103678
  const isResumeToolCall = resumeDataFromArgs != null;
102456
103679
  const approvalVerdicts = readScoped(scopeCtx, TOOL_APPROVAL_VERDICTS_KEY, "toolApprovalVerdicts");
@@ -104240,7 +105463,7 @@ var AgentThreadStreamRuntime = class {
104240
105463
  return state.leaseOwners.get(runId) ?? threadLeaseOwner(runId, state.threadRunsById.get(runId)?.generation);
104241
105464
  }
104242
105465
  /** @internal Qualify a shared thread lease before dispatching this execution. */
104243
- async claimDurableThreadLease(pubsub, runId, threadId, resourceId, generation, executionId) {
105466
+ async claimDurableThreadLease(pubsub, runId, threadId, resourceId, generation, executionId, workerFenced = false) {
104244
105467
  const key = this.#threadKey(resourceId, threadId);
104245
105468
  const owner = threadLeaseOwner(runId, generation, executionId);
104246
105469
  let lease = await this.#acquireThreadLease(pubsub, key, runId, owner);
@@ -104258,7 +105481,7 @@ var AgentThreadStreamRuntime = class {
104258
105481
  if (!lease.acquired) throw new AgentThreadLeaseConflictError(runId, lease.owner ?? "another owner");
104259
105482
  if (this.#getState(pubsub).leaseRenewalTimers.has(runId)) {
104260
105483
  this.#stopLeaseRenewal(pubsub, runId);
104261
- this.#startLeaseRenewal(pubsub, key, runId, owner);
105484
+ this.#startLeaseRenewal(pubsub, key, runId, owner, workerFenced);
104262
105485
  }
104263
105486
  }
104264
105487
  /** @internal Renew only the captured execution's thread lease; never acquire or transfer it. */
@@ -104274,6 +105497,11 @@ var AgentThreadStreamRuntime = class {
104274
105497
  const { acquired } = await this.#getLeaseProvider(pubsub).acquireLease(this.#threadKey(resourceId, threadId), threadLeaseOwner(runId, generation, executionId), AGENT_THREAD_LEASE_TTL_MS);
104275
105498
  return acquired;
104276
105499
  }
105500
+ /** @internal Missing ownership is not evidence that another run took the thread. */
105501
+ async isDurableThreadLeaseHeldByAnotherRun(pubsub, runId, threadId, resourceId) {
105502
+ const owner = await this.#getLeaseProvider(pubsub).getLeaseOwner(this.#threadKey(resourceId, threadId));
105503
+ return owner !== void 0 && threadLeaseRunId(owner) !== runId;
105504
+ }
104277
105505
  /** @internal Whether `error` from the thread lease backend means it is refusing every client, not just this one. */
104278
105506
  isThreadLeaseBackendUnavailableToAll(pubsub, error) {
104279
105507
  return this.#getLeaseProvider(pubsub).isUnavailableToAll?.(error) === true;
@@ -104487,7 +105715,7 @@ var AgentThreadStreamRuntime = class {
104487
105715
  * that point, so once it passes a successor may own the thread and the
104488
105716
  * run is aborted, even if the backend never answers.
104489
105717
  */
104490
- #startLeaseRenewal(pubsub, key, runId, owner = this.#threadLeaseOwner(pubsub, runId)) {
105718
+ #startLeaseRenewal(pubsub, key, runId, owner = this.#threadLeaseOwner(pubsub, runId), workerFenced = false, confirmedSentAt = Date.now()) {
104491
105719
  const state = this.#getState(pubsub);
104492
105720
  if (state.leaseRenewalTimers.has(runId)) {
104493
105721
  if (state.leaseOwners.get(runId) === owner) return;
@@ -104495,10 +105723,12 @@ var AgentThreadStreamRuntime = class {
104495
105723
  }
104496
105724
  const leaseProvider = this.#getLeaseProvider(pubsub);
104497
105725
  const timer = setInterval(() => {
105726
+ if (workerFenced && state.pendingLeaseRenewals.has(runId)) return;
104498
105727
  const sentAt = Date.now();
104499
105728
  state.pendingLeaseRenewals.set(runId, (state.pendingLeaseRenewals.get(runId) ?? 0) + 1);
104500
105729
  leaseProvider.renewLease(key, owner, AGENT_THREAD_LEASE_TTL_MS).then((renewed) => {
104501
105730
  if (!renewed) {
105731
+ if (workerFenced) return;
104502
105732
  if (state.leaseRenewalTimers.get(runId) !== timer) return;
104503
105733
  const confirmed = state.leaseDeadlines.get(runId)?.confirmedSentAt;
104504
105734
  (confirmed === void 0 || Date.now() >= confirmed + AGENT_THREAD_LEASE_TTL_MS ? this.#retakeLease(pubsub, key, runId, timer) : Promise.resolve(false)).then((kept) => {
@@ -104507,7 +105737,7 @@ var AgentThreadStreamRuntime = class {
104507
105737
  this.#abortLeaseLostRun(state, runId);
104508
105738
  });
104509
105739
  } else {
104510
- if (state.leaseRenewalTimers.get(runId) === timer) this.#armLeaseDeadline(pubsub, key, runId, sentAt);
105740
+ if (!workerFenced && state.leaseRenewalTimers.get(runId) === timer) this.#armLeaseDeadline(pubsub, key, runId, sentAt);
104511
105741
  if (state.sweptLeasedRunIds.has(runId)) state.sweptLeasedRunIds.set(runId, Date.now());
104512
105742
  }
104513
105743
  }).catch(() => {}).finally(() => {
@@ -104519,7 +105749,8 @@ var AgentThreadStreamRuntime = class {
104519
105749
  if (typeof timer === "object" && timer && typeof timer.unref === "function") timer.unref();
104520
105750
  state.leaseRenewalTimers.set(runId, timer);
104521
105751
  state.leaseOwners.set(runId, owner);
104522
- this.#armLeaseDeadline(pubsub, key, runId, Date.now());
105752
+ if (workerFenced) return;
105753
+ this.#armLeaseDeadline(pubsub, key, runId, confirmedSentAt);
104523
105754
  if (!this.#resolveLeaseProvider(pubsub).isFallback) {
104524
105755
  const fence = this.#leaseFence(pubsub, key, runId, timer, owner);
104525
105756
  state.leaseFences.set(runId, fence);
@@ -107239,7 +108470,14 @@ var AgentThreadStreamRuntime = class {
107239
108470
  async #publishRunSuspended(pubsub, key, record) {
107240
108471
  record.lifecycle = "suspended";
107241
108472
  record.suspendedAt = Date.now();
107242
- if (this.#getState(pubsub).shutdownStreams.has(record.streamId)) return;
108473
+ const state = this.#getState(pubsub);
108474
+ const owner = state.leaseOwners.get(record.runId);
108475
+ if (owner && state.threadRunsById.get(record.runId) === record && !state.leaseDeadlines.has(record.runId)) {
108476
+ const resolvedPubSub = this.#getPubSub(pubsub);
108477
+ this.#stopLeaseRenewal(resolvedPubSub, record.runId);
108478
+ this.#startLeaseRenewal(resolvedPubSub, key, record.runId, owner, false, record.suspendedAt - AGENT_THREAD_LEASE_TTL_MS);
108479
+ }
108480
+ if (state.shutdownStreams.has(record.streamId)) return;
107243
108481
  await this.#publishAndWait(pubsub, key, {
107244
108482
  type: "run-suspended",
107245
108483
  runId: record.runId,
@@ -107266,6 +108504,11 @@ var AgentThreadStreamRuntime = class {
107266
108504
  record.lifecycle = "completed";
107267
108505
  this.#clearSuspendedRun(state, record.runId);
107268
108506
  state.threadRunsByStreamId.delete(record.streamId);
108507
+ if (state.threadRunsById.get(record.runId) === record) for (const [streamId, other] of state.threadRunsByStreamId) {
108508
+ if (other.runId !== record.runId || other.lifecycle !== "suspended") continue;
108509
+ state.threadRunsByStreamId.delete(streamId);
108510
+ state.watchedThreadStreamIds.delete(streamId);
108511
+ }
107269
108512
  if (state.threadRunsById.get(record.runId) === record) {
107270
108513
  state.threadRunsById.delete(record.runId);
107271
108514
  state.threadKeysByRunId.delete(record.runId);
@@ -109711,8 +110954,26 @@ function getRunRegistryEntry(runId, mastra) {
109711
110954
  }
109712
110955
  return unwrapMastraTracingProxy(entry.mastra) === unwrapMastraTracingProxy(mastra) ? entry : void 0;
109713
110956
  }
109714
- function getLiveRunRequestContext(entry) {
109715
- return entry?.requestContextRebuilt ? void 0 : entry?.requestContext;
110957
+ /**
110958
+ * Request-context key that identifies a run segment on engines whose steps carry no Core execution
110959
+ * claim (Inngest). The engine stores the same value on the registry entry it seeds for the segment.
110960
+ */
110961
+ const DURABLE_CONTEXT_SEGMENT_KEY = "__mastra_durableContextSegment";
110962
+ /**
110963
+ * The registry's live request context, when it belongs to the execution running this step. Once
110964
+ * another process claims the run (for example an approval from another host), the context cached
110965
+ * here still belongs to the previous caller and must not be reused for the new execution.
110966
+ */
110967
+ function getLiveRunRequestContext(entry, runId, stepContext, executionId) {
110968
+ const live = entry?.requestContext;
110969
+ if (!live || entry.requestContextRebuilt) return void 0;
110970
+ const expectedExecutionId = executionId ?? (runId ? getExecutionClaim(stepContext, runId)?.executionId : void 0);
110971
+ if (!expectedExecutionId) {
110972
+ const stepSegment = stepContext?.get(DURABLE_CONTEXT_SEGMENT_KEY);
110973
+ if (stepSegment === void 0) return live;
110974
+ return stepSegment === entry.requestContextSegment ? live : void 0;
110975
+ }
110976
+ return runId && getExecutionClaim(live, runId)?.executionId === expectedExecutionId ? live : void 0;
109716
110977
  }
109717
110978
  /**
109718
110979
  * Publish an entry for `runId`, owned by `mastra`, unless the slot holds
@@ -110024,4 +111285,4 @@ var ExtendedRunRegistry = class extends RunRegistry {
110024
111285
  this.#memoryInfo.clear();
110025
111286
  }
110026
111287
  };
110027
- export { resolveDurableToolCallConcurrency as $, planSpanQuery as $a, getSingleStepEntryId as $c, createValidator as $i, resolveRunFence as $l, MessageHistory as $n, AgentsMDInjector as $o, MAX_NOTIFICATION_DELIVERY_ATTEMPTS as $r, AgentStreamBus as $s, validateModelTimeoutSettings as $t, assembleAgentFromFsEntry as A, TracePageError as Aa, repeatAfterSettled as Ac, MAX_KNOWLEDGE_PAGE_LINKS as Ai, ProcessorMessageSchema as Al, buildKnowledgeInstructions as An, chunkMessageText as Ao, createEmptyWorkflowSnapshot as Ar, PrefillErrorHandler as As, RUN_DEADLINE_KEY as At, createDurableGoalStep as B, threadQueryIdentitySchema as Ba, RESUME_SNAPSHOT_POLL_INTERVAL_MS as Bc, knowledgePositionBetween as Bi, TextPartSchema as Bl, formatToolApproval as Bn, augmentWithInit as Bo, SchedulesStorage as Br, createWorkflow$1 as Bs, getServerSideFallbackInfo as Bt, ScorerRunError as C, parseDuration as Ca, nestedRunStatusOf as Cc, KnowledgePageHasChildrenError as Ci, FilePartSchema as Cl, compileKnowledgeScopes as Cn, ObservabilityStorage as Co, FilesystemStore as Cr, isMalformedFunctionCallError as Cs, segmentEndedBySuspension as Ct, notScorable as D, transformRow as Da, validateScoringPredicate as Dc, MAX_KNOWLEDGE_PAGE_BODY_LINKS as Di, ProcessorInputPhaseSchema as Dl, strongerKnowledgeRole as Dn, DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS as Do, WorkflowsInMemory as Dr, StreamErrorRetryProcessor as Ds, DURABLE_STOP_WHEN_ERROR_ID as Dt, isNotScorable as E, storageMessageMatchesMetadataFilter as Ea, evaluateScoringPredicate as Ec, MAX_KNOWLEDGE_NOTE_TOKENS as Ei, MessagePartSchema as El, knowledgeScopeAddress as En, UniqueViolationError as Eo, MockStore as Er, FILE_UPLOAD_ERROR_CODES as Es, runResumeDurableStreamUntilIdle as Et, prepareForDurableExecution as F, tracePageResponseSchema as Fa, runWithConcurrency as Fc, assertKnowledgePageDescriptionWithinBound as Fi, ProcessorStepOutputSchema as Fl, ChatChannelProcessor as Fn, MastraMemory as Fo, InMemoryToolProviderConnectionsStorage as Fr, EventedRun as Fs, getScopeStreamSlot as Ft, serializeDurableOptions as G, SPAN_QUERY_MAX_CURSOR_BYTES as Ga, cleanStepResult as Gc, HarnessStorage as Gi, isWorkflowStepConflictError as Gl, createChannelTools as Gn, RESPONSE_CACHE_CONTEXT_KEY as Go, createNotificationSignal as Gr, diffResponseMessages as Gs, generateFinalResult as Gt, createDurableLLMMappingStep as H, threadQueryResponseSchema as Ha, abortableSleep as Hc, parseKnowledgePageRef as Hi, isAgentCompatible as Hl, DEFAULT_CHANNEL_TOOLS_SETTINGS as Hn, createBackgroundWorkSignalProcessor as Ho, InMemoryNotificationsStorage as Hr, StepExecutor as Hs, formatCompletionFeedback as Ht, applyReservedMemoryContextKeys as I, THREAD_QUERY_DEFAULT_LIMIT as Ia, createMappingStep as Ic, canonicalKnowledgeName as Ii, ProcessorStepSchema as Il, CHAT_CHANNEL_RENDER_CONTEXT_KEY as In, MemoryProcessor as Io, ToolProviderConnectionsStorage as Ir, EventedWorkflow as Is, untilIdleHandlesBackgroundTask as It, serializeToolsMetadata as J, SPAN_QUERY_ORDER_FIELDS as Ja, createTimeTravelExecutionParams as Jc, DatasetsInMemory as Ji, RunFenceConflictError as Jl, BaseProcessor as Jn, WorkspaceInstructionsProcessor as Jo, notificationSignalMetadata as Jr, emitErrorEvent as Js, runCompletionScorers as Jt, serializeDurableState as K, SPAN_QUERY_MAX_LIMIT as Ka, createDeprecationProxy as Kc, ExperimentsInMemory as Ki, RUN_FENCE_CONFLICT_ERROR_ID as Kl, resolveChannelToolsSettings as Kn, ResponseCache as Ko, createNotificationSummarySignal as Kr, emitAbortEvent as Ks, generateStructuredFinalResult as Kt, persistDurableRunInput as L, THREAD_QUERY_MAX_LIMIT as La, createStepFromAgent$1 as Lc, knowledgeLinkRefKey as Li, ReasoningPartSchema as Ll, renderBuiltInToolEvent as Ln, memoryDefaultOptions as Lo, ScoresInMemory as Lr, cloneStep as Ls, pruneAgentLoopSnapshot as Lt, AGENT_RESUME_CLAIM_STALE_MS as M, tracePageIdSchema as Ma, ExecutionEngine as Mc, MAX_KNOWLEDGE_PAGE_LIST_LIMIT as Mi, ProcessorOutputStepPhaseSchema as Ml, resolveWaitUntil as Mn, messageVectorId as Mo, mergeWorkflowStepResult as Mr, cloneWorkflow as Ms, readRunDeadline as Mt, Agent as N, tracePageNodeSchema as Na, createConcurrencyLimiter as Nc, MAX_KNOWLEDGE_PIN_LIST_DEPTH as Ni, ProcessorOutputStreamPhaseSchema as Nl, defaultTypingStatus as Nn, resolveMaxChunkChars as No, InMemoryWorkflowDefinitionsStorage as Nr, createEventedWorkflow as Ns, __registerMastraCtor as Nt, agentConfig as O, transformScoreRow as Oa, WORKFLOW_RUN_LEASE_TTL_MS as Oc, MAX_KNOWLEDGE_PAGE_DEPTH as Oi, ProcessorInputStepPhaseSchema as Ol, decodeKnowledgeScopeId as On, MESSAGE_EMBEDDING_CHARS_PER_TOKEN as Oo, cloneRunData as Or, isBadRequestError as Os, DurableAgentDefaults as Ot, normalizeResumeGenerateArgs as P, tracePageRequestSchema as Pa, normalizeConcurrency as Pc, assertKnowledgeNoteTextWithinBound as Pi, ProcessorStepInputSchema as Pl, MastraStateAdapter as Pn, upsertMessageVectors as Po, WorkflowDefinitionsStorage as Pr, createWorkflow as Ps, getRunStreamSlot as Pt, createDurableBackgroundTaskCheckStep as Q, parseSpanQueryRequest as Qa, getResumeLabelsByStepId as Qc, assertSupportedPatterns as Qi, matchesRunFence as Ql, WorkingMemory as Qn, ToolSearchProcessor as Qo, readNotificationRoutingRequirement as Qr, emitSuspendedEvent as Qs, loop as Qt, detachFullStreamOnEnd as R, encodeThreadQueryCursor as Ra, createStepFromClassifier as Rc, knowledgePagePath as Ri, SourcePartSchema as Rl, CONTINUE_RUN_ACTION_ID as Rn, filterSystemReminderMessages as Ro, ScoresStorage as Rr, cloneWorkflow$1 as Rs, DEFAULT_TOOL_DECLINE_REASON as Rt, MastraScorer as S, jsonValueEquals as Sa, nestedRunRecoveryAction as Sc, KnowledgePageDepthError as Si, isDurableAgentLike as Sl, KnowledgeDeclarationError as Sn, ObservabilityInMemory as So, createGitHubSourceControlProviderFromEnv as Sr, defaultStabilityErrorProcessors as Ss, liveSegmentSpan as St, filterRun as T, serializeDate as Ta, SCORING_PREDICATE_ROOTS as Tc, MAX_KNOWLEDGE_MOVE_PAGES as Ti, MessageContentSchema as Tl, knowledgeRunScopes as Tn, FactoryStorageDomain as To, InMemoryStore as Tr, FileUploadProcessor as Ts, runDurableStreamUntilIdle as Tt, createDurableToolCallStep as U, threadQueryRowSchema as Ua, applyStateDelta as Uc, KnowledgeInvalidCursorError as Ui, WorkflowStepConflictError as Ul, channelToolScopeResolver as Un, CyberRefusalHandler as Uo, NotificationsStorage as Ur, computeScheduleDefinitionHash as Us, formatStreamCompletionFeedback as Ut, createDurableIsTaskCompleteStep as V, threadQueryRequestSchema as Va, RESUME_SNAPSHOT_WAIT_STATUSES as Vc, knowledgeScopeReadable as Vi, ToolInvocationPartSchema as Vl, ChannelSessionRejectedError as Vn, getStorageSource as Vo, normalizeScheduleTarget as Vr, WorkflowEventProcessor as Vs, formatCheckFeedback as Vt, createWorkflowInput as W, SPAN_QUERY_MAX_COST_METRICS as Wa, assertTimeTravelGraphMatchesSnapshot as Wc, InMemoryHarness as Wi, assertWorkflowStepGuard as Wl, createChannelToolScope as Wn, DEFAULT_RESPONSE_CACHE_TTL_SECONDS as Wo, dispatchDueNotifications as Wr, __resetExecutionFencesForTests as Ws, formatValidationFeedback as Wt, MessagePartSpans as X, createSpanQueryPreview as Xa, defineStateAccessors as Xc, DatasetItemIdentityConflictError as Xi, currentRunGeneration as Xl, SemanticRecall as Xn, SkillsProcessor as Xo, notificationSummarySignalMetadata as Xr, emitStepFinishEvent as Xs, runStreamCompletionScorers as Xt, createDurableLLMExecutionStep as Y, buildSpanQueryResponse as Ya, defineLazyWriter as Yc, DatasetsStorage as Yi, coverNestedRun as Yl, MemoryInputFilter as Yn, SkillSearchProcessor as Yo, notificationSummaryContents as Yr, emitFinishEvent as Ys, runDefaultCompletionCheck as Yt, isSpanChunk as Z, encodeSpanQueryCursor as Za, getRestartStartIndex as Zc, SchemaValidator as Zi, isRunFenceConflictError as Zl, globalEmbeddingCache as Zn, formatSkillsCatalog as Zo, summarizeNotifications as Zr, emitStepStartEvent as Zs, runValidation as Zt, runEvals as _, ensureDate as _a, predicateToCondition as _c, assertKnowledgeSchemaCompatible as _i, assertDrainTimeout as _l, syncKnowledgePageBodyLinks as _n, buildUpdateSpanRecord as _o, knowledgeVisibleScopeKeys as _r, PIIDetector as _s, toolRequiresApproval as _t, endRunSpansWithError as a, ChannelsStorage as aa, AGENT_STREAM_TOPIC as ac, InMemoryKnowledgeStorage as ai, omitPriorSuspensionFields as al, addKnowledgeNote as an, spanQueryResponseSchema as ao, MAX_KNOWLEDGE_SCOPE_TAGS as ar, TokenLimiterProcessor as as, baseIterationStateSchema as at, validateAndSaveScore as b, getSqlType as ba, createNestedRunParentStatusLookup as bc, parseKnowledgeWikilinks as bi, hasDurableExecution as bl, knowledgeReadScopeFor as bn, serializeSpanAttributes as bo, StoreOperations as br, UnicodeNormalizer as bs, carrySegmentSpans as bt, globalRunRegistry as c, BackgroundTasksInMemory as ca, EventedExecutionEngine as cc, KnowledgeImportersStorage as ci, setLongTimeout as cl, removeKnowledgePage as cn, encodeTraceQueryDeltaCursor as co, assertKnowledgeRecordTextWithinBound as cr, advanceMemoryTokenBoundary as cs, modelListEntrySchema as ct, takeRunScorerInstances as d, resolveRetentionTargets as da, Run as dc, KnowledgeConflictError as di, validateStepResumeData as dl, KnowledgeSemanticIndex as dn, planTraceQuery as do, createKnowledgeNodeCursor as dr, normalizeMessageHistoryConfig as ds, loadRunStoredMessages as dt, getSchemaValidator as ea, publishAbortRequest as ec, defaultNotificationDeliveryDecision as ei, getStepIds as el, PINNED_READ_MEMO_KEY as en, resolveSpanQueryCost as eo, MemoryRunState as er, ToolCallFilter as es, buildStepRecord as et, runFencingNotSupportedError as eu, AgentThreadLeaseLostError as f, retentionCutoffMs as fa, Workflow as fc, KnowledgeNotFoundError$1 as fi, validateStepStateData as fl, embed$2 as fn, buildCreateSpanRecord as fo, expandKnowledgeScope as fr, BatchPartsProcessor as fs, rebuildRunToolsFromMastra as ft, describeNonSuccessFinishReason as g, createVectorErrorId as ga, mapVariable as gc, KnowledgeUnsupportedCapabilityError as gi, getEntryWorkflow as gl, reindexKnowledgeLinks as gn, buildScoreRecord as go, knowledgeSemanticIdempotencyKey as gr, LanguageDetector as gs, resolveTool$1 as gt, AGENTIC_LOOP_WORKFLOW_ID as h, createStoreErrorId as ha, isProcessor$1 as hc, KnowledgeTransactionDeadlineError as hi, getEntryId as hl, refreshKnowledgeLinksTo as hn, buildMetricRecord as ho, knowledgeSemanticDocumentId as hr, StructuredOutputProcessor as hs, resolveRuntimeDependencies as ht, deleteRunRegistryEntry as i, InMemoryChannelsStorage as ia, AGENT_CONTROL_TOPIC as ic, MemoryStorage as ii, omitPriorCompletionFields as il, knowledgeRunPrincipals as in, spanQueryRequestSchema as io, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH as ir, SystemPromptScrubber as is, baseDurableAgenticInputSchema as it, MAX_FS_SUBAGENT_DEPTH as j, readTracePage as ja, runFenceConflictOf as jc, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH as ji, ProcessorOutputResultPhaseSchema as jl, AgentChannels as jn, extractMessageEmbeddingText as jo, mergeStepResult as jr, getGoalActivityDurationMs as js, ensureRemoteAbortListener as jt, agentInstructions as k, validateStorageMetadataFilter as ka, renewWorkflowLease as kc, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS as ki, ProcessorMessageContentSchema as kl, encodeKnowledgeScopeId as kn, buildMessageEmbeddingRows as ko, WorkflowsStorage as kr, isRetryableOpenAIResponsesStreamError as ks, DurableStepIds as kt, isDurableAgentExecutionDetached as l, BackgroundTasksStorage as la, getNestedWorkflow as lc, KNOWLEDGE_STORAGE_CONTRACT_VERSION as li, validateStepInput as ll, updateKnowledgeNote as ln, getTraceQueryDeltaWatermark as lo, assertKnowledgeScopeWithinCeiling as lr, getMemoryTokenBoundary as ls, executeDurableAgentScorers as lt, AGENTIC_EXECUTION_WORKFLOW_ID as m, createStorageErrorId as ma, createStep$1 as mc, KnowledgeStorage as mi, waitForSuspendedSnapshot as ml, knowledgeSubtree as mn, buildLogRecord as mo, knowledgeScopeKey as mr, ClassifierProcessor as ms, resolveModel as mt, RunRegistry as n, SchemaUpdateValidationError as na, subscribeToAbortRequests as nc, resolveNotificationDeliveryDecision as ni, isEntryFinished as nl, buildKnowledgePageTools as nn, spanQueryIdentityKey as no, MockMemory as nr, CostGuardProcessor as ns, createBaseIterationStateUpdate as nt, setRunFenceContext as nu, getActiveDurableAgentWorkflowExecutions as o, InMemoryBlobStore as oa, AgentControlEventTypes as oc, KnowledgeImporterBindingConflictError as oi, resolveForeachConcurrency as ol, moveKnowledgePage as on, spanQueryRowSchema as oo, assertKnowledgeCeilingRaised as or, groupLinkedToolMessages as os, durableAgenticOutputSchema as ot, agentThreadStreamRuntime as p, runRetentionBatches as pa, cloneStep$1 as pc, KnowledgeSchemaResetRequiredError as pi, validateStepSuspendData as pl, KnowledgeLinkRefreshIncompleteError as pn, buildFeedbackRecord as po, isKnowledgeScopeVisible as pr, ModelSelectionProcessor as ps, resolveInternalState as pt, serializeModelConfig as q, SPAN_QUERY_MAX_PREVIEW_CHARACTERS as qa, createRestartExecutionParams as qc, ExperimentsStorage as qi, RUN_FENCING_NOT_SUPPORTED_ERROR_ID as ql, toChatLogger as qn, buildResponseCacheKey as qo, notificationSignalAttributes as qr, emitChunkEvent as qs, runChecks as qt, abandonDurableAgentExecutions as r, SchemaValidationError as ra, createRunAbortController as rc, InMemoryMemory as ri, isSingleStepEntry as rl, KnowledgeRun as rn, spanQueryIdentitySchema as ro, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH as rr, TokenCostControl as rs, accumulatedUsageSchema as rt, getRunRegistryEntry as s, BlobStore as sa, AgentStreamEventTypes as sc, KnowledgeImporterRunStateError as si, runCountDeprecationMessage as sl, removeKnowledgeNote as sn, encodeTraceQueryCursor as so, assertKnowledgeDescriptionWithinBound as sr, loadMessageHistory as ss, modelConfigSchema as st, ExtendedRunRegistry as t, UnsupportedSchemaPatternError as ta, requestAcknowledgedAbort as tc, resolveDeliveryFailureUpdate as ti, hydrateSerializedStepErrors as tl, knowledgeDeliveredPins as tn, spanQueryCostSchema as to, getMemoryRunState as tr, RegexFilterProcessor as ts, calculateAccumulatedUsage as tt, runOutsideRunFenceScope as tu, setRunRegistryEntry as u, executeRetentionPrune as ua, getStepEntry as uc, KNOWLEDGE_STORAGE_SCHEMA_VERSION as ui, validateStepRequestContext as ul, upsertKnowledgePage as un, planThreadQuery as uo, canonicalizeKnowledgeScope as ur, isAfterMemoryTokenBoundary as us, runDurableFinishSideEffects as ut, flushBeforeTraceRead as v, filterByDateRange as va, evaluatePredicate as vc, createKnowledgeUlid as vi, waitMs as vl, updateKnowledgeLinks as vn, getObjectOrNull as vo, parseKnowledgeNodeCursor as vr, PromptInjectionDetector as vs, resolveAgentById as vt, createScorer as w, safelyParseJSON as wa, DefaultExecutionEngine as wc, KnowledgePageKeyConflictError as wi, ImagePartSchema as wl, knowledgeMemoryScopes as wn, FactoryStorage as wo, FilesystemDB as wr, UnsupportedFileHandler as ws, segmentSpanData as wt, createClassifierScorer as x, hasErrorCode as xa, nestedRunParentOf as xc, KnowledgeMoveTooLargeError as xi, hasResumableStreams as xl, knowledgeRoleOn as xn, toEntityType as xo, GitHubSourceControlProvider as xr, STABILITY_ERROR_PROCESSOR_IDS as xs, endFailedSegmentSpans as xt, createOnScorerHook as y, getDefaultValue as ya, cancelNestedRun as yc, inspectKnowledgeSchema as yi, workflowTermination as yl, knowledgeAccessGrants as yn, getStringOrNull as yo, StoreOperationsInMemory as yr, ModerationProcessor as ys, createDurableAgentStream as yt, createDurableAgenticWorkflow as z, planThreadRowsQuery as za, createStepFromTool as zc, knowledgePinDepth as zi, StepStartPartSchema as zl, CONTINUE_RUN_MESSAGE as zn, isSystemReminderMessage as zo, InMemorySchedulesStorage as zr, createStep as zs, resolveDeclineReason as zt };
111288
+ export { isSpanChunk as $, SPAN_QUERY_MAX_CURSOR_BYTES as $a, RESUME_SNAPSHOT_POLL_INTERVAL_MS as $c, HarnessStorage as $i, TextPartSchema as $l, createChannelTools as $n, RESPONSE_CACHE_CONTEXT_KEY as $o, createNotificationSignal as $r, diffResponseMessages as $s, PINNED_READ_MEMO_KEY as $t, agentInstructions as A, jsonValueEquals as Aa, predicateToCondition as Ac, KnowledgePageDepthError as Ai, assertDrainTimeout as Al, strongerKnowledgeRole as An, ObservabilityInMemory as Ao, createGitHubSourceControlProviderFromEnv as Ar, defaultStabilityErrorProcessors as As, ensureRemoteAbortListener as At, detachFullStreamOnEnd as B, tracePageIdSchema as Ba, validateScoringPredicate as Bc, MAX_KNOWLEDGE_PAGE_LIST_LIMIT as Bi, ProcessorInputPhaseSchema as Bl, ChannelThreadLinkProcessor as Bn, messageVectorId as Bo, mergeWorkflowStepResult as Br, cloneWorkflow as Bs, formatCheckFeedback as Bt, MastraScorer as C, createStoreErrorId as Ca, getStepEntry as Cc, KnowledgeTransactionDeadlineError as Ci, validateStepRequestContext as Cl, knowledgeReadScopeFor as Cn, buildMetricRecord as Co, knowledgeSemanticDocumentId as Cr, StructuredOutputProcessor as Cs, endFailedSegmentSpans as Ct, isNotScorable as D, getDefaultValue as Da, createStep$1 as Dc, inspectKnowledgeSchema as Di, waitForSuspendedSnapshot as Dl, knowledgeMemoryScopes as Dn, getStringOrNull as Do, StoreOperationsInMemory as Dr, ModerationProcessor as Ds, runDurableStreamUntilIdle as Dt, filterRun as E, filterByDateRange as Ea, cloneStep$1 as Ec, createKnowledgeUlid as Ei, validateStepSuspendData as El, compileKnowledgeScopes as En, getObjectOrNull as Eo, parseKnowledgeNodeCursor as Er, PromptInjectionDetector as Es, segmentSpanData as Et, Agent as F, transformRow as Fa, nestedRunRecoveryAction as Fc, MAX_KNOWLEDGE_PAGE_BODY_LINKS as Fi, isDurableAgentLike as Fl, resolveWaitUntil as Fn, DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS as Fo, WorkflowsInMemory as Fr, StreamErrorRetryProcessor as Fs, untilIdleHandlesBackgroundTask as Ft, createDurableToolCallStep as G, THREAD_QUERY_MAX_LIMIT as Ga, ExecutionEngine as Gc, knowledgeLinkRefKey as Gi, ProcessorOutputStepPhaseSchema as Gl, renderBuiltInToolEvent as Gn, memoryDefaultOptions as Go, ScoresInMemory as Gr, cloneStep as Gs, generateStructuredFinalResult as Gt, createDurableGoalStep as H, tracePageRequestSchema as Ha, renewWorkflowLease as Hc, assertKnowledgeNoteTextWithinBound as Hi, ProcessorMessageContentSchema as Hl, markNewChannelThread as Hn, upsertMessageVectors as Ho, WorkflowDefinitionsStorage as Hr, createWorkflow as Hs, formatStreamCompletionFeedback as Ht, normalizeResumeGenerateArgs as I, transformScoreRow as Ia, nestedRunStatusOf as Ic, MAX_KNOWLEDGE_PAGE_DEPTH as Ii, FilePartSchema as Il, defaultTypingStatus as In, MESSAGE_EMBEDDING_CHARS_PER_TOKEN as Io, cloneRunData as Ir, isBadRequestError as Is, pruneAgentLoopSnapshot as It, serializeDurableState as J, threadQueryIdentitySchema as Ja, runWithConcurrency as Jc, knowledgePositionBetween as Ji, ProcessorStepOutputSchema as Jl, formatToolApproval as Jn, augmentWithInit as Jo, SchedulesStorage as Jr, createWorkflow$1 as Js, runDefaultCompletionCheck as Jt, createWorkflowInput as K, encodeThreadQueryCursor as Ka, createConcurrencyLimiter as Kc, knowledgePagePath as Ki, ProcessorOutputStreamPhaseSchema as Kl, CONTINUE_RUN_ACTION_ID as Kn, filterSystemReminderMessages as Ko, ScoresStorage as Kr, cloneWorkflow$1 as Ks, runChecks as Kt, prepareForDurableExecution as L, validateStorageMetadataFilter as La, DefaultExecutionEngine as Lc, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS as Li, ImagePartSchema as Ll, resolveChannelRenderContext as Ln, buildMessageEmbeddingRows as Lo, WorkflowsStorage as Lr, isRetryableOpenAIResponsesStreamError as Ls, DEFAULT_TOOL_DECLINE_REASON as Lt, MAX_FS_SUBAGENT_DEPTH as M, safelyParseJSON as Ma, cancelNestedRun as Mc, KnowledgePageKeyConflictError as Mi, workflowTermination as Ml, encodeKnowledgeScopeId as Mn, FactoryStorage as Mo, FilesystemDB as Mr, UnsupportedFileHandler as Ms, __registerMastraCtor as Mt, mergeAgentPersona as N, serializeDate as Na, createNestedRunParentStatusLookup as Nc, MAX_KNOWLEDGE_MOVE_PAGES as Ni, hasDurableExecution as Nl, buildKnowledgeInstructions as Nn, FactoryStorageDomain as No, InMemoryStore as Nr, FileUploadProcessor as Ns, getRunStreamSlot as Nt, notScorable as O, getSqlType as Oa, isProcessor$1 as Oc, parseKnowledgeWikilinks as Oi, getEntryId as Ol, knowledgeRunScopes as On, serializeSpanAttributes as Oo, StoreOperations as Or, UnicodeNormalizer as Os, runResumeDurableStreamUntilIdle as Ot, AGENT_RESUME_CLAIM_STALE_MS as P, storageMessageMatchesMetadataFilter as Pa, nestedRunParentOf as Pc, MAX_KNOWLEDGE_NOTE_TOKENS as Pi, hasResumableStreams as Pl, AgentChannels as Pn, UniqueViolationError as Po, MockStore as Pr, FILE_UPLOAD_ERROR_CODES as Ps, getScopeStreamSlot as Pt, MessagePartSpans as Q, SPAN_QUERY_MAX_COST_METRICS as Qa, createStepFromTool as Qc, InMemoryHarness as Qi, StepStartPartSchema as Ql, createChannelToolScope as Qn, DEFAULT_RESPONSE_CACHE_TTL_SECONDS as Qo, dispatchDueNotifications as Qr, __resetExecutionFencesForTests as Qs, validateModelTimeoutSettings as Qt, applyReservedMemoryContextKeys as R, TracePageError as Ra, SCORING_PREDICATE_ROOTS as Rc, MAX_KNOWLEDGE_PAGE_LINKS as Ri, MessageContentSchema as Rl, MastraStateAdapter as Rn, chunkMessageText as Ro, createEmptyWorkflowSnapshot as Rr, PrefillErrorHandler as Rs, resolveDeclineReason as Rt, createClassifierScorer as S, createStorageErrorId as Sa, getNestedWorkflow as Sc, KnowledgeStorage as Si, validateStepInput as Sl, knowledgeAccessGrants as Sn, buildLogRecord as So, knowledgeScopeKey as Sr, ClassifierProcessor as Ss, carrySegmentSpans as St, createScorer as T, ensureDate as Ta, Workflow as Tc, assertKnowledgeSchemaCompatible as Ti, validateStepStateData as Tl, KnowledgeDeclarationError as Tn, buildUpdateSpanRecord as To, knowledgeVisibleScopeKeys as Tr, PIIDetector as Ts, segmentEndedBySuspension as Tt, createDurableIsTaskCompleteStep as U, tracePageResponseSchema as Ua, repeatAfterSettled as Uc, assertKnowledgePageDescriptionWithinBound as Ui, ProcessorMessageSchema as Ul, ChatChannelProcessor as Un, MastraMemory as Uo, InMemoryToolProviderConnectionsStorage as Ur, EventedRun as Us, formatValidationFeedback as Ut, createDurableAgenticWorkflow as V, tracePageNodeSchema as Va, WORKFLOW_RUN_LEASE_TTL_MS as Vc, MAX_KNOWLEDGE_PIN_LIST_DEPTH as Vi, ProcessorInputStepPhaseSchema as Vl, NEW_CHANNEL_THREAD_KEY as Vn, resolveMaxChunkChars as Vo, InMemoryWorkflowDefinitionsStorage as Vr, createEventedWorkflow as Vs, formatCompletionFeedback as Vt, createDurableLLMMappingStep as W, THREAD_QUERY_DEFAULT_LIMIT as Wa, runFenceConflictOf as Wc, canonicalKnowledgeName as Wi, ProcessorOutputResultPhaseSchema as Wl, CHAT_CHANNEL_RENDER_CONTEXT_KEY as Wn, MemoryProcessor as Wo, ToolProviderConnectionsStorage as Wr, EventedWorkflow as Ws, generateFinalResult as Wt, serializeToolsMetadata as X, threadQueryResponseSchema as Xa, createStepFromAgent$1 as Xc, parseKnowledgePageRef as Xi, ReasoningPartSchema as Xl, DEFAULT_CHANNEL_TOOLS_SETTINGS as Xn, createBackgroundWorkSignalProcessor as Xo, InMemoryNotificationsStorage as Xr, StepExecutor as Xs, runValidation as Xt, serializeModelConfig as Y, threadQueryRequestSchema as Ya, createMappingStep as Yc, knowledgeScopeReadable as Yi, ProcessorStepSchema as Yl, ChannelSessionRejectedError as Yn, getStorageSource as Yo, normalizeScheduleTarget as Yr, WorkflowEventProcessor as Ys, runStreamCompletionScorers as Yt, createDurableLLMExecutionStep as Z, threadQueryRowSchema as Za, createStepFromClassifier as Zc, KnowledgeInvalidCursorError as Zi, SourcePartSchema as Zl, channelToolScopeResolver as Zn, CyberRefusalHandler as Zo, NotificationsStorage as Zr, computeScheduleDefinitionHash as Zs, loop as Zt, describeNonSuccessFinishReason as _, BackgroundTasksStorage as _a, AgentControlEventTypes as _c, KNOWLEDGE_STORAGE_CONTRACT_VERSION as _i, omitPriorCompletionFields as _l, knowledgeSubtree as _n, getTraceQueryDeltaWatermark as _o, assertKnowledgeScopeWithinCeiling as _r, getMemoryTokenBoundary as _s, resolveRuntimeDependencies as _t, deleteRunRegistryEntry as a, SchemaValidator as aa, emitStepStartEvent as ac, summarizeNotifications as ai, createDeprecationProxy as al, knowledgeRunPrincipals as an, encodeSpanQueryCursor as ao, globalEmbeddingCache as ar, formatSkillsCatalog as as, accumulatedUsageSchema as at, RUN_FENCE_CONFLICT_ERROR_ID as au, createOnScorerHook as b, retentionCutoffMs as ba, restoredWorkerControllerContexts as bc, KnowledgeNotFoundError$1 as bi, runCountDeprecationMessage as bl, syncKnowledgePageBodyLinks as bn, buildCreateSpanRecord as bo, expandKnowledgeScope as br, BatchPartsProcessor as bs, resolveAgentById as bt, getRunRegistryEntry as c, getSchemaValidator as ca, publishAbortRequest as cc, defaultNotificationDeliveryDecision as ci, defineLazyWriter as cl, addKnowledgeNote as cn, resolveSpanQueryCost as co, MemoryRunState as cr, ToolCallFilter as cs, durableAgenticOutputSchema as ct, coverNestedRun as cu, setRunRegistryEntry as d, SchemaValidationError as da, createRunAbortController as dc, InMemoryMemory as di, getResumeLabelsByStepId as dl, removeKnowledgePage as dn, spanQueryIdentitySchema as do, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH as dr, TokenCostControl as ds, executeDurableAgentScorers as dt, matchesRunFence as du, ExperimentsInMemory as ea, emitAbortEvent as ec, createNotificationSummarySignal as ei, RESUME_SNAPSHOT_WAIT_STATUSES as el, knowledgeDeliveredPins as en, SPAN_QUERY_MAX_LIMIT as eo, resolveChannelToolsSettings as er, ResponseCache as es, createDurableBackgroundTaskCheckStep as et, ToolInvocationPartSchema as eu, takeRunScorerInstances as f, InMemoryChannelsStorage as fa, DURABLE_STOP_WHEN_ERROR_ID as fc, MemoryStorage as fi, getSingleStepEntryId as fl, updateKnowledgeNote as fn, spanQueryRequestSchema as fo, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH as fr, SystemPromptScrubber as fs, runDurableFinishSideEffects as ft, resolveRunFence as fu, AGENTIC_LOOP_WORKFLOW_ID as g, BackgroundTasksInMemory as ga, AGENT_STREAM_TOPIC as gc, KnowledgeImportersStorage as gi, isSingleStepEntry as gl, KnowledgeLinkRefreshIncompleteError as gn, encodeTraceQueryDeltaCursor as go, assertKnowledgeRecordTextWithinBound as gr, advanceMemoryTokenBoundary as gs, resolveModel as gt, AGENTIC_EXECUTION_WORKFLOW_ID as h, BlobStore as ha, AGENT_CONTROL_TOPIC as hc, KnowledgeImporterRunStateError as hi, isEntryFinished as hl, embed$2 as hn, encodeTraceQueryCursor as ho, assertKnowledgeDescriptionWithinBound as hr, loadMessageHistory as hs, resolveInternalState as ht, setRunFenceContext as hu, abandonDurableAgentExecutions as i, DatasetItemIdentityConflictError as ia, emitStepFinishEvent as ic, notificationSummarySignalMetadata as ii, cleanStepResult as il, KnowledgeRunScopesError as in, createSpanQueryPreview as io, SemanticRecall as ir, SkillsProcessor as is, createBaseIterationStateUpdate as it, isWorkflowStepConflictError as iu, assembleAgentFromFsEntry as j, parseDuration as ja, evaluatePredicate as jc, KnowledgePageHasChildrenError as ji, waitMs as jl, decodeKnowledgeScopeId as jn, ObservabilityStorage as jo, FilesystemStore as jr, isMalformedFunctionCallError as js, readRunDeadline as jt, agentConfig as k, hasErrorCode as ka, mapVariable as kc, KnowledgeMoveTooLargeError as ki, getEntryWorkflow as kl, knowledgeScopeAddress as kn, toEntityType as ko, GitHubSourceControlProvider as kr, STABILITY_ERROR_PROCESSOR_IDS as ks, RUN_DEADLINE_KEY as kt, globalRunRegistry as l, UnsupportedSchemaPatternError as la, requestAcknowledgedAbort as lc, resolveDeliveryFailureUpdate as li, defineStateAccessors as ll, moveKnowledgePage as ln, spanQueryCostSchema as lo, getMemoryRunState as lr, RegexFilterProcessor as ls, modelConfigSchema as lt, currentRunGeneration as lu, agentThreadStreamRuntime as m, InMemoryBlobStore as ma, DurableStepIds as mc, KnowledgeImporterBindingConflictError as mi, hydrateSerializedStepErrors as ml, KnowledgeSemanticIndex as mn, spanQueryRowSchema as mo, assertKnowledgeCeilingRaised as mr, groupLinkedToolMessages as ms, rebuildRunToolsFromMastra as mt, runOutsideRunFenceScope as mu, ExtendedRunRegistry as n, DatasetsInMemory as na, emitErrorEvent as nc, notificationSignalMetadata as ni, applyStateDelta as nl, heldScopes as nn, SPAN_QUERY_ORDER_FIELDS as no, BaseProcessor as nr, WorkspaceInstructionsProcessor as ns, buildStepRecord as nt, WorkflowStepConflictError as nu, endRunSpansWithError as o, assertSupportedPatterns as oa, emitSuspendedEvent as oc, readNotificationRoutingRequirement as oi, createRestartExecutionParams as ol, knowledgeAgentScopes as on, parseSpanQueryRequest as oo, WorkingMemory as or, ToolSearchProcessor as os, baseDurableAgenticInputSchema as ot, RUN_FENCING_NOT_SUPPORTED_ERROR_ID as ou, AgentThreadLeaseLostError as p, ChannelsStorage as pa, DurableAgentDefaults as pc, InMemoryKnowledgeStorage as pi, getStepIds as pl, upsertKnowledgePage as pn, spanQueryResponseSchema as po, MAX_KNOWLEDGE_SCOPE_TAGS as pr, TokenLimiterProcessor as ps, loadRunStoredMessages as pt, runFencingNotSupportedError as pu, serializeDurableOptions as q, planThreadRowsQuery as qa, normalizeConcurrency as qc, knowledgePinDepth as qi, ProcessorStepInputSchema as ql, CONTINUE_RUN_MESSAGE as qn, isSystemReminderMessage as qo, InMemorySchedulesStorage as qr, createStep as qs, runCompletionScorers as qt, RunRegistry as r, DatasetsStorage as ra, emitFinishEvent as rc, notificationSummaryContents as ri, assertTimeTravelGraphMatchesSnapshot as rl, KnowledgeRun as rn, buildSpanQueryResponse as ro, MemoryInputFilter as rr, SkillSearchProcessor as rs, calculateAccumulatedUsage as rt, assertWorkflowStepGuard as ru, getActiveDurableAgentWorkflowExecutions as s, createValidator as sa, AgentStreamBus as sc, MAX_NOTIFICATION_DELIVERY_ATTEMPTS as si, createTimeTravelExecutionParams as sl, knowledgePersonaScopes as sn, planSpanQuery as so, MessageHistory as sr, AgentsMDInjector as ss, baseIterationStateSchema as st, RunFenceConflictError as su, DURABLE_CONTEXT_SEGMENT_KEY as t, ExperimentsStorage as ta, emitChunkEvent as tc, notificationSignalAttributes as ti, abortableSleep as tl, buildKnowledgePageTools as tn, SPAN_QUERY_MAX_PREVIEW_CHARACTERS as to, toChatLogger as tr, buildResponseCacheKey as ts, resolveDurableToolCallConcurrency as tt, isAgentCompatible as tu, isDurableAgentExecutionDetached as u, SchemaUpdateValidationError as ua, subscribeToAbortRequests as uc, resolveNotificationDeliveryDecision as ui, getRestartStartIndex as ul, removeKnowledgeNote as un, spanQueryIdentityKey as uo, MockMemory as ur, CostGuardProcessor as us, modelListEntrySchema as ut, isRunFenceConflictError as uu, runEvals as v, executeRetentionPrune as va, AgentStreamEventTypes as vc, KNOWLEDGE_STORAGE_SCHEMA_VERSION as vi, omitPriorSuspensionFields as vl, refreshKnowledgeLinksTo as vn, planThreadQuery as vo, canonicalizeKnowledgeScope as vr, isAfterMemoryTokenBoundary as vs, resolveTool$1 as vt, ScorerRunError as w, createVectorErrorId as wa, Run as wc, KnowledgeUnsupportedCapabilityError as wi, validateStepResumeData as wl, knowledgeRoleOn as wn, buildScoreRecord as wo, knowledgeSemanticIdempotencyKey as wr, LanguageDetector as ws, liveSegmentSpan as wt, validateAndSaveScore as x, runRetentionBatches as xa, EventedExecutionEngine as xc, KnowledgeSchemaResetRequiredError as xi, setLongTimeout as xl, updateKnowledgeLinks as xn, buildFeedbackRecord as xo, isKnowledgeScopeVisible as xr, ModelSelectionProcessor as xs, createDurableAgentStream as xt, flushBeforeTraceRead as y, resolveRetentionTargets as ya, CONTROLLER_RUN_BINDING_KEY as yc, KnowledgeConflictError as yi, resolveForeachConcurrency as yl, reindexKnowledgeLinks as yn, planTraceQuery as yo, createKnowledgeNodeCursor as yr, normalizeMessageHistoryConfig as ys, toolRequiresApproval as yt, persistDurableRunInput as z, readTracePage as za, evaluateScoringPredicate as zc, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH as zi, MessagePartSchema as zl, REPLY_TOOL_NAME as zn, extractMessageEmbeddingText as zo, mergeStepResult as zr, getGoalActivityDurationMs as zs, getServerSideFallbackInfo as zt };