@mastra/core 1.86.0-alpha.7 → 1.86.0-alpha.9

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 (509) hide show
  1. package/dist/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +363 -0
  2. package/dist/a2a/index.cjs +1 -1
  3. package/dist/a2a/index.js +1 -1
  4. package/dist/agent/agent.d.ts +72 -1
  5. package/dist/agent/agent.types.d.ts +30 -2
  6. package/dist/agent/durable/create-evented-agent.d.ts +6 -0
  7. package/dist/agent/durable/durable-agent.d.ts +1 -15
  8. package/dist/agent/durable/index.cjs +7 -26
  9. package/dist/agent/durable/index.js +7 -26
  10. package/dist/agent/durable/preparation.d.ts +2 -0
  11. package/dist/agent/durable/utils/resolve-runtime.d.ts +9 -0
  12. package/dist/agent/durable/workflows/durable-loop-builder.d.ts +4 -0
  13. package/dist/agent/durable/workflows/finalize-run.d.ts +3 -1
  14. package/dist/agent/durable/workflows/steps/llm-execution.d.ts +1 -0
  15. package/dist/agent/index.cjs +3 -3
  16. package/dist/agent/index.js +3 -3
  17. package/dist/agent/message-list/index.cjs +1 -1
  18. package/dist/agent/message-list/index.js +1 -1
  19. package/dist/agent/message-list/message-list.d.ts +11 -0
  20. package/dist/agent/message-list/utils/provider-compat.d.ts +1 -0
  21. package/dist/agent/request-context-snapshot.d.ts +1 -1
  22. package/dist/agent/streams/types.d.ts +10 -0
  23. package/dist/agent/thread-stream-runtime.d.ts +5 -0
  24. package/dist/agent/types.d.ts +25 -0
  25. package/dist/agent-builder/ee/index.cjs +1 -1
  26. package/dist/agent-builder/ee/index.js +1 -1
  27. package/dist/agent-controller/index.cjs +1 -1
  28. package/dist/agent-controller/index.js +1 -1
  29. package/dist/{agent-controller-K5vHtqfO.cjs → agent-controller-CrQ9OF80.cjs} +8 -8
  30. package/dist/{agent-controller-Cf3_IuY8.js → agent-controller-SSlKzE6A.js} +8 -8
  31. package/dist/background-tasks/index.cjs +1 -1
  32. package/dist/background-tasks/index.js +1 -1
  33. package/dist/{background-tasks-DqnQMfuf.cjs → background-tasks-BDrYBis-.cjs} +5 -3
  34. package/dist/{background-tasks-BgpX1P_s.js → background-tasks-BnJfNLFo.js} +5 -3
  35. package/dist/browser/index.cjs +2 -2
  36. package/dist/browser/index.js +2 -2
  37. package/dist/{builder-x295GDL6.js → builder-Cl-0BWkh.js} +2 -2
  38. package/dist/{builder-D8Osghdo.cjs → builder-Cw8u3pPl.cjs} +2 -2
  39. package/dist/capabilities/302ai.json +192 -192
  40. package/dist/capabilities/abliteratedllm.json +34 -34
  41. package/dist/capabilities/abliteration-ai.json +11 -11
  42. package/dist/capabilities/above.json +17 -17
  43. package/dist/capabilities/adaption.json +12 -12
  44. package/dist/capabilities/adzuki.json +30 -30
  45. package/dist/capabilities/agentrouter.json +10 -10
  46. package/dist/capabilities/agnes.json +4 -4
  47. package/dist/capabilities/ai-router.json +9 -9
  48. package/dist/capabilities/aiand.json +19 -11
  49. package/dist/capabilities/aigrow.json +11 -11
  50. package/dist/capabilities/aimlapi.json +146 -149
  51. package/dist/capabilities/aipg.json +2 -2
  52. package/dist/capabilities/aixy.json +14 -14
  53. package/dist/capabilities/aki-io.json +11 -11
  54. package/dist/capabilities/alibaba-cn.json +128 -109
  55. package/dist/capabilities/alibaba-coding-plan-cn.json +7 -19
  56. package/dist/capabilities/alibaba-coding-plan.json +7 -19
  57. package/dist/capabilities/alibaba-token-plan-cn.json +49 -67
  58. package/dist/capabilities/alibaba-token-plan.json +51 -69
  59. package/dist/capabilities/alibaba.json +71 -118
  60. package/dist/capabilities/ambient.json +14 -14
  61. package/dist/capabilities/amd.json +11 -11
  62. package/dist/capabilities/anthropic.json +48 -48
  63. package/dist/capabilities/anyapi.json +18 -18
  64. package/dist/capabilities/apiko.json +2 -2
  65. package/dist/capabilities/arcee.json +10 -10
  66. package/dist/capabilities/augure.json +6 -6
  67. package/dist/capabilities/auriko.json +20 -20
  68. package/dist/capabilities/bailing.json +5 -5
  69. package/dist/capabilities/baseten.json +46 -16
  70. package/dist/capabilities/bee.json +5 -5
  71. package/dist/capabilities/berget.json +4 -4
  72. package/dist/capabilities/bothub.json +16 -16
  73. package/dist/capabilities/boundless.json +36 -36
  74. package/dist/capabilities/bumo.json +40 -40
  75. package/dist/capabilities/byteplus.json +32 -32
  76. package/dist/capabilities/cerebras.json +4 -4
  77. package/dist/capabilities/cheapaimodel.json +5 -5
  78. package/dist/capabilities/cheapest-token.json +24 -24
  79. package/dist/capabilities/chutes.json +9 -9
  80. package/dist/capabilities/cline-pass.json +37 -37
  81. package/dist/capabilities/cloudcode.json +4 -4
  82. package/dist/capabilities/cloudflare-workers-ai.json +24 -24
  83. package/dist/capabilities/commandcode.json +152 -152
  84. package/dist/capabilities/concentrate.json +290 -266
  85. package/dist/capabilities/cortecs.json +105 -105
  86. package/dist/capabilities/crossmodel.json +160 -160
  87. package/dist/capabilities/crusoe.json +10 -10
  88. package/dist/capabilities/daoxe.json +7 -7
  89. package/dist/capabilities/databricks.json +318 -62
  90. package/dist/capabilities/deepinfra.json +73 -129
  91. package/dist/capabilities/deepseek.json +2 -2
  92. package/dist/capabilities/digitalocean.json +114 -114
  93. package/dist/capabilities/dothoosh.json +28 -28
  94. package/dist/capabilities/doubleword.json +24 -24
  95. package/dist/capabilities/edenai.json +458 -458
  96. package/dist/capabilities/empiriolabs.json +166 -166
  97. package/dist/capabilities/engy.json +20 -20
  98. package/dist/capabilities/evroc.json +8 -8
  99. package/dist/capabilities/ezkielyna.json +8 -8
  100. package/dist/capabilities/fastrouter.json +85 -85
  101. package/dist/capabilities/fireworks-ai.json +107 -44
  102. package/dist/capabilities/freemodel.json +23 -23
  103. package/dist/capabilities/friendli.json +9 -9
  104. package/dist/capabilities/frogbot.json +94 -94
  105. package/dist/capabilities/gisoo.json +16 -16
  106. package/dist/capabilities/gmicloud.json +17 -17
  107. package/dist/capabilities/google.json +57 -57
  108. package/dist/capabilities/graphn.json +10 -10
  109. package/dist/capabilities/greenpt.json +36 -36
  110. package/dist/capabilities/groq.json +2 -2
  111. package/dist/capabilities/helicone.json +68 -68
  112. package/dist/capabilities/hopper.json +2 -2
  113. package/dist/capabilities/hostinger-router.json +12 -12
  114. package/dist/capabilities/hpc-ai.json +13 -13
  115. package/dist/capabilities/huawei-maas.json +17 -17
  116. package/dist/capabilities/hubris.json +30 -30
  117. package/dist/capabilities/huggingface.json +193 -37
  118. package/dist/capabilities/hyper.json +23 -23
  119. package/dist/capabilities/impossibl.json +140 -140
  120. package/dist/capabilities/inception.json +2 -2
  121. package/dist/capabilities/inceptron.json +4 -4
  122. package/dist/capabilities/inco.json +3 -3
  123. package/dist/capabilities/infer.json +15 -15
  124. package/dist/capabilities/inferall.json +10 -10
  125. package/dist/capabilities/inference-coop.json +9 -9
  126. package/dist/capabilities/inferenceapis.json +9 -9
  127. package/dist/capabilities/inferris.json +3 -3
  128. package/dist/capabilities/infersia.json +2 -2
  129. package/dist/capabilities/inferx.json +3 -3
  130. package/dist/capabilities/infomaniak.json +4 -4
  131. package/dist/capabilities/io-net.json +2 -2
  132. package/dist/capabilities/isoquant.json +4 -4
  133. package/dist/capabilities/iteracompute.json +60 -60
  134. package/dist/capabilities/jad-ai.json +3 -3
  135. package/dist/capabilities/jalapeno.json +12 -12
  136. package/dist/capabilities/jiekou.json +63 -63
  137. package/dist/capabilities/jzstoken.json +50 -50
  138. package/dist/capabilities/keln.json +14 -21
  139. package/dist/capabilities/kenari.json +123 -120
  140. package/dist/capabilities/kilo.json +622 -647
  141. package/dist/capabilities/kimi-code-plan-cn.json +5 -5
  142. package/dist/capabilities/kimi-code-plan-global.json +5 -5
  143. package/dist/capabilities/kitani.json +6 -6
  144. package/dist/capabilities/klavo.json +18 -18
  145. package/dist/capabilities/korouter.json +29 -29
  146. package/dist/capabilities/kunavo.json +10 -10
  147. package/dist/capabilities/liquid.json +11 -11
  148. package/dist/capabilities/lithosai.json +2 -2
  149. package/dist/capabilities/llmgateway-providers.json +932 -905
  150. package/dist/capabilities/llmgateway.json +336 -336
  151. package/dist/capabilities/llmtr.json +22 -22
  152. package/dist/capabilities/logits.json +2 -2
  153. package/dist/capabilities/longcat.json +2 -7
  154. package/dist/capabilities/lowrouter.json +54 -54
  155. package/dist/capabilities/lyceum.json +12 -12
  156. package/dist/capabilities/melious.json +13 -13
  157. package/dist/capabilities/merge-gateway.json +260 -260
  158. package/dist/capabilities/meta.json +7 -7
  159. package/dist/capabilities/mistral.json +20 -20
  160. package/dist/capabilities/mixlayer.json +4 -4
  161. package/dist/capabilities/modal.json +10 -10
  162. package/dist/capabilities/model-oracle-ai.json +25 -25
  163. package/dist/capabilities/modelis.json +20 -20
  164. package/dist/capabilities/modular.json +6 -6
  165. package/dist/capabilities/moneo.json +16 -16
  166. package/dist/capabilities/moonshotai-cn.json +7 -7
  167. package/dist/capabilities/moonshotai.json +7 -7
  168. package/dist/capabilities/morph.json +11 -11
  169. package/dist/capabilities/munito-eu.json +6 -6
  170. package/dist/capabilities/munito.json +6 -6
  171. package/dist/capabilities/nan.json +27 -27
  172. package/dist/capabilities/nano-gpt.json +578 -578
  173. package/dist/capabilities/nearai.json +84 -84
  174. package/dist/capabilities/nebius.json +37 -28
  175. package/dist/capabilities/neon.json +126 -126
  176. package/dist/capabilities/neuralwatt.json +41 -41
  177. package/dist/capabilities/nokeep.json +4 -4
  178. package/dist/capabilities/novita-ai.json +154 -154
  179. package/dist/capabilities/nvidia.json +35 -35
  180. package/dist/capabilities/oathbreaker.json +2 -2
  181. package/dist/capabilities/obscurify.json +32 -32
  182. package/dist/capabilities/oci.json +7 -7
  183. package/dist/capabilities/ofox.json +357 -357
  184. package/dist/capabilities/ollama-cloud.json +56 -56
  185. package/dist/capabilities/openai.json +51 -51
  186. package/dist/capabilities/opencode-go.json +85 -84
  187. package/dist/capabilities/openrouter.json +542 -567
  188. package/dist/capabilities/opper.json +30 -24
  189. package/dist/capabilities/orcarouter.json +236 -236
  190. package/dist/capabilities/outerlabs.json +32 -32
  191. package/dist/capabilities/ovhcloud.json +7 -7
  192. package/dist/capabilities/pareto.json +6 -6
  193. package/dist/capabilities/pendra.json +4 -4
  194. package/dist/capabilities/perplexity-agent.json +61 -61
  195. package/dist/capabilities/phala.json +34 -34
  196. package/dist/capabilities/pioneer.json +30 -30
  197. package/dist/capabilities/poe.json +136 -136
  198. package/dist/capabilities/powerspring.json +13 -13
  199. package/dist/capabilities/primalabs.json +10 -10
  200. package/dist/capabilities/prime.json +124 -107
  201. package/dist/capabilities/privatemode-ai.json +14 -14
  202. package/dist/capabilities/proxystacks.json +6 -6
  203. package/dist/capabilities/qiniu-ai.json +16 -16
  204. package/dist/capabilities/refuseless.json +6 -6
  205. package/dist/capabilities/regolo-ai.json +6 -6
  206. package/dist/capabilities/requesty.json +172 -172
  207. package/dist/capabilities/ruapi.json +17 -17
  208. package/dist/capabilities/runcrate.json +5 -5
  209. package/dist/capabilities/runinfra.json +13 -13
  210. package/dist/capabilities/sakana.json +6 -6
  211. package/dist/capabilities/sambanova.json +9 -9
  212. package/dist/capabilities/sandbase.json +27 -27
  213. package/dist/capabilities/sarvam.json +12 -12
  214. package/dist/capabilities/scaleway.json +14 -14
  215. package/dist/capabilities/scnet-token-plan.json +9 -9
  216. package/dist/capabilities/scx-ai.json +26 -26
  217. package/dist/capabilities/sensenova.json +12 -12
  218. package/dist/capabilities/siliconflow-cn.json +49 -49
  219. package/dist/capabilities/siliconflow.json +46 -46
  220. package/dist/capabilities/snowflake-cortex.json +20 -20
  221. package/dist/capabilities/sokkan.json +7 -7
  222. package/dist/capabilities/sparrowcodes.json +25 -25
  223. package/dist/capabilities/standardcompute.json +102 -102
  224. package/dist/capabilities/steadyrouter.json +40 -40
  225. package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
  226. package/dist/capabilities/stepfun-ai.json +15 -8
  227. package/dist/capabilities/stepfun-step-plan.json +15 -8
  228. package/dist/capabilities/stepfun.json +15 -8
  229. package/dist/capabilities/stepping-stone.json +16 -16
  230. package/dist/capabilities/synthetic.json +13 -13
  231. package/dist/capabilities/synthorai.json +19 -19
  232. package/dist/capabilities/teamorouter.json +24 -24
  233. package/dist/capabilities/teapot-router.json +13 -13
  234. package/dist/capabilities/tencent-coding-plan.json +1 -23
  235. package/dist/capabilities/tencent-token-plan.json +60 -23
  236. package/dist/capabilities/tencent-tokenhub.json +182 -7
  237. package/dist/capabilities/tensorx.json +50 -50
  238. package/dist/capabilities/tenstorrent.json +6 -6
  239. package/dist/capabilities/the-grid-ai.json +28 -28
  240. package/dist/capabilities/thinkingmachines.json +72 -55
  241. package/dist/capabilities/tinfoil.json +13 -13
  242. package/dist/capabilities/toapis.json +2 -2
  243. package/dist/capabilities/togetherai.json +54 -83
  244. package/dist/capabilities/tokengo.json +25 -25
  245. package/dist/capabilities/tokenify.json +9 -9
  246. package/dist/capabilities/trustedrouter.json +4 -4
  247. package/dist/capabilities/trustedtokens.json +17 -17
  248. package/dist/capabilities/umans-ai-coding-plan.json +13 -13
  249. package/dist/capabilities/umans-ai.json +10 -10
  250. package/dist/capabilities/unrestricted.json +6 -6
  251. package/dist/capabilities/uplinkswitch.json +21 -21
  252. package/dist/capabilities/upstage.json +4 -4
  253. package/dist/capabilities/vancine.json +23 -23
  254. package/dist/capabilities/vercel.json +540 -527
  255. package/dist/capabilities/vivgrid.json +80 -80
  256. package/dist/capabilities/volcengine-coding-plan.json +24 -54
  257. package/dist/capabilities/volcengine.json +55 -60
  258. package/dist/capabilities/vultr.json +24 -24
  259. package/dist/capabilities/wafer.ai.json +19 -19
  260. package/dist/capabilities/wallaby.json +5 -5
  261. package/dist/capabilities/wally.json +11 -11
  262. package/dist/capabilities/wandb.json +21 -21
  263. package/dist/capabilities/watt.json +24 -24
  264. package/dist/capabilities/xai.json +7 -7
  265. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -12
  266. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -12
  267. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -12
  268. package/dist/capabilities/xiaomi.json +3 -25
  269. package/dist/capabilities/xpersona.json +13 -13
  270. package/dist/capabilities/xxapi.json +31 -31
  271. package/dist/capabilities/zai-coding-plan.json +18 -18
  272. package/dist/capabilities/zai.json +49 -26
  273. package/dist/capabilities/zenifra.json +26 -26
  274. package/dist/capabilities/zenmux.json +205 -205
  275. package/dist/capabilities/zerogpu.json +11 -11
  276. package/dist/capabilities/zhipuai-coding-plan.json +6 -6
  277. package/dist/capabilities/zhipuai.json +39 -24
  278. package/dist/capabilities/zro.json +6 -6
  279. package/dist/channels/index.cjs +2 -2
  280. package/dist/channels/index.js +2 -2
  281. package/dist/{channels-Dx4jiXeK.js → channels-Cz1y3W6u.js} +1 -1
  282. package/dist/{channels-q6qnuRNV.cjs → channels-DQg4v_gm.cjs} +1 -1
  283. package/dist/coding-agent/index.cjs +2 -2
  284. package/dist/coding-agent/index.js +2 -2
  285. package/dist/datasets/dataset.d.ts +13 -6
  286. package/dist/datasets/experiment/durable.d.ts +16 -0
  287. package/dist/datasets/experiment/index.d.ts +2 -1
  288. package/dist/datasets/experiment/item.d.ts +26 -4
  289. package/dist/datasets/experiment/retries.d.ts +18 -0
  290. package/dist/datasets/experiment/types.d.ts +18 -0
  291. package/dist/datasets/experiment/workflow-id.d.ts +7 -0
  292. package/dist/datasets/experiment/workflow.d.ts +74 -0
  293. package/dist/datasets/index.cjs +3 -2
  294. package/dist/datasets/index.d.ts +2 -1
  295. package/dist/datasets/index.js +3 -3
  296. package/dist/docs/SKILL.md +4 -3
  297. package/dist/docs/assets/SOURCE_MAP.json +928 -903
  298. package/dist/docs/references/docs-deployment-workers.md +1 -1
  299. package/dist/docs/references/docs-evals-experiments.md +29 -1
  300. package/dist/docs/references/docs-harness-background-tasks.md +4 -1
  301. package/dist/docs/references/docs-harness-durable-agents.md +9 -5
  302. package/dist/docs/references/docs-knowledge-agents-and-tools.md +1 -0
  303. package/dist/docs/references/docs-knowledge-importers.md +195 -0
  304. package/dist/docs/references/docs-knowledge-load-your-content.md +2 -2
  305. package/dist/docs/references/docs-knowledge-overview.md +1 -1
  306. package/dist/docs/references/docs-mastra-platform-observability-overview.md +1 -1
  307. package/dist/docs/references/docs-sandbox-filesystem.md +1 -1
  308. package/dist/docs/references/docs-server-pubsub.md +51 -8
  309. package/dist/docs/references/docs-signals-running-across-processes.md +2 -0
  310. package/dist/docs/references/docs-signals-thread-streams.md +1 -1
  311. package/dist/docs/references/docs-studio-auth.md +54 -7
  312. package/dist/docs/references/docs-workflows-overview.md +1 -1
  313. package/dist/docs/references/docs-workflows-scheduled-workflows.md +1 -1
  314. package/dist/docs/references/integrations-auth-clerk.md +48 -4
  315. package/dist/docs/references/integrations-channels-slack.md +4 -2
  316. package/dist/docs/references/integrations.md +6 -0
  317. package/dist/docs/references/reference-agents-agent.md +3 -1
  318. package/dist/docs/references/reference-agents-channels.md +116 -27
  319. package/dist/docs/references/reference-agents-durable-agent.md +12 -4
  320. package/dist/docs/references/reference-auth-clerk.md +21 -1
  321. package/dist/docs/references/reference-datasets-runExperimentItem.md +13 -1
  322. package/dist/docs/references/reference-datasets-startExperimentAsync.md +3 -1
  323. package/dist/docs/references/reference-editor-mastra-editor.md +3 -1
  324. package/dist/docs/references/reference-knowledge-knowledge-class.md +13 -6
  325. package/dist/docs/references/reference-knowledge-knowledge-tools.md +43 -20
  326. package/dist/docs/references/reference-memory-observational-memory.md +2 -2
  327. package/dist/docs/references/reference-processors-moderation-processor.md +2 -2
  328. package/dist/docs/references/reference-pubsub-base.md +5 -1
  329. package/dist/docs/references/reference-pubsub-event-emitter.md +2 -0
  330. package/dist/docs/references/reference-pubsub-redis-streams.md +1 -1
  331. package/dist/docs/references/reference-pubsub-unix-socket-pubsub.md +2 -0
  332. package/dist/docs/references/reference-streaming-ChunkType.md +3 -3
  333. package/dist/docs/references/reference-workers-overview.md +1 -1
  334. package/dist/docs/references/reference-workflows-run-methods-start.md +23 -0
  335. package/dist/docs/references/reference-workflows-run-methods-timeTravel.md +4 -0
  336. package/dist/docs/references/reference-workflows-run.md +1 -1
  337. package/dist/docs/references/reference-workspace-local-sandbox.md +2 -0
  338. package/dist/error/index.cjs +1 -1
  339. package/dist/error/index.js +1 -1
  340. package/dist/{error-C9d_24w-.js → error-BLwEXqOK.js} +2 -2
  341. package/dist/{error-BRQf2ku0.cjs → error-BdEvO8za.cjs} +2 -2
  342. package/dist/evals/index.cjs +1 -1
  343. package/dist/evals/index.js +1 -1
  344. package/dist/evals/scoreTraces/index.cjs +1 -1
  345. package/dist/evals/scoreTraces/index.js +1 -1
  346. package/dist/events/caching-pubsub.d.ts +1 -0
  347. package/dist/events/event-emitter/index.d.ts +12 -5
  348. package/dist/events/index.cjs +15 -1
  349. package/dist/events/index.js +15 -1
  350. package/dist/events/pubsub.d.ts +29 -0
  351. package/dist/events/reach.d.ts +11 -0
  352. package/dist/events/unix-socket-pubsub.d.ts +14 -0
  353. package/dist/features/index.cjs +1 -0
  354. package/dist/features/index.js +1 -0
  355. package/dist/{filesystem-B5X-5G0x.js → filesystem-B8ad6kAW.js} +1 -1
  356. package/dist/{filesystem-BDSpwBke.cjs → filesystem-BB5YWXH-.cjs} +1 -1
  357. package/dist/{filesystem-DzM9pcQ8.js → filesystem-BDHUxbHn.js} +1 -1
  358. package/dist/{filesystem-B0AZrbj8.cjs → filesystem-BP5yz5LG.cjs} +1 -1
  359. package/dist/{filesystem-BsdkC311.js → filesystem-B_afSgYk.js} +1 -1
  360. package/dist/{filesystem-C-cyJfi1.cjs → filesystem-BaOJOc-V.cjs} +1 -1
  361. package/dist/{filesystem-B3s0WRud.js → filesystem-BhYgU8qg.js} +1 -1
  362. package/dist/{filesystem-DzfqVTO_.js → filesystem-CLBVmR5j.js} +1 -1
  363. package/dist/{filesystem-CEbD_77-.cjs → filesystem-Cgxc2a_-.cjs} +1 -1
  364. package/dist/{filesystem-Cv79mHRk.js → filesystem-ClBOBoDc.js} +1 -1
  365. package/dist/{filesystem-DsCQiBl2.cjs → filesystem-DVVecqZt.cjs} +1 -1
  366. package/dist/{filesystem-CUAgLugE.cjs → filesystem-Fpsu7e24.cjs} +1 -1
  367. package/dist/{filesystem-versioned-Bijb_p9l.js → filesystem-versioned-BL1ojJLo.js} +1 -1
  368. package/dist/{filesystem-versioned-DZGyPbNC.cjs → filesystem-versioned-BavRtYWJ.cjs} +1 -1
  369. package/dist/harness/index.cjs +1 -1
  370. package/dist/harness/index.js +1 -1
  371. package/dist/index.cjs +1 -1
  372. package/dist/index.js +1 -1
  373. package/dist/knowledge/config.d.ts +10 -0
  374. package/dist/knowledge/host-writes.d.ts +10 -0
  375. package/dist/knowledge/importers/conformance.d.ts +25 -0
  376. package/dist/knowledge/importers/define.d.ts +204 -0
  377. package/dist/knowledge/importers/host.d.ts +143 -0
  378. package/dist/knowledge/importers/index.d.ts +12 -0
  379. package/dist/knowledge/importers/local-host.d.ts +106 -0
  380. package/dist/knowledge/importers/manifest.d.ts +25 -0
  381. package/dist/knowledge/importers/runner.d.ts +61 -0
  382. package/dist/knowledge/importers/sink.d.ts +105 -0
  383. package/dist/knowledge/importers/types.d.ts +144 -0
  384. package/dist/knowledge/index.cjs +2715 -8
  385. package/dist/knowledge/index.d.ts +54 -4
  386. package/dist/knowledge/index.js +2692 -9
  387. package/dist/knowledge/instructions.d.ts +1 -1
  388. package/dist/knowledge/links.d.ts +8 -0
  389. package/dist/knowledge/pinned-state-processor.d.ts +5 -0
  390. package/dist/knowledge/pinned.d.ts +4 -1
  391. package/dist/knowledge/scope-runtime.d.ts +10 -0
  392. package/dist/llm/index.cjs +3 -3
  393. package/dist/llm/index.js +3 -3
  394. package/dist/llm/model/provider-types.generated.d.ts +7812 -7831
  395. package/dist/llm/model/shared.types.d.ts +31 -0
  396. package/dist/{llm-CsQuqKPc.cjs → llm-8Av3mSjD.cjs} +2 -2
  397. package/dist/{llm-DnXK3Pmw.js → llm-B5A5cwJr.js} +2 -2
  398. package/dist/loop/index.cjs +2 -2
  399. package/dist/loop/index.js +2 -2
  400. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +2 -2
  401. package/dist/{manager-BsghM-UL.js → manager-DfWQCJUK.js} +460 -94
  402. package/dist/{manager-DwFnIrI6.cjs → manager-sv35JY-z.cjs} +476 -92
  403. package/dist/mastra/index.cjs +1 -1
  404. package/dist/mastra/index.d.ts +13 -0
  405. package/dist/mastra/index.js +1 -1
  406. package/dist/mastra/resolve-agent.d.ts +3 -1
  407. package/dist/{mastra-B8i1UDZs.js → mastra-CigBrT7X.js} +32 -23
  408. package/dist/{mastra-Cn5NC6Es.cjs → mastra-D4hvfuxX.cjs} +34 -25
  409. package/dist/memory/index.cjs +3 -3
  410. package/dist/memory/index.js +3 -3
  411. package/dist/{message-list-DPXPXvin.cjs → message-list-Cj0Sq_JP.cjs} +63 -8
  412. package/dist/{message-list-DEuRl82K.js → message-list-KRbg-TnI.js} +63 -8
  413. package/dist/{model-CNPfry_X.cjs → model-BK93CMtl.cjs} +1 -1
  414. package/dist/{model-CsOcWMUt.js → model-CYtXw861.js} +1 -1
  415. package/dist/{netlify-C-83Fxus.cjs → netlify-BAnn3ouY.cjs} +1 -1
  416. package/dist/{netlify-C-OpNSGp.js → netlify-CuI1ZrwR.js} +1 -1
  417. package/dist/notifications/index.cjs +1 -1
  418. package/dist/notifications/index.js +1 -1
  419. package/dist/{output-helpers-JL-HeCbT.cjs → output-helpers-1Zu4Vt9C.cjs} +68 -25
  420. package/dist/{output-helpers-D4II19No.js → output-helpers-CedRCE17.js} +69 -26
  421. package/dist/processor-provider/index.cjs +1 -1
  422. package/dist/processor-provider/index.js +1 -1
  423. package/dist/processors/abort-signal-scope.d.ts +6 -0
  424. package/dist/processors/index.cjs +2 -2
  425. package/dist/processors/index.js +2 -2
  426. package/dist/{provider-registry-9O-H9osy.cjs → provider-registry-BwuI_IpT.cjs} +21690 -21811
  427. package/dist/{provider-registry-RZ8EgSe8.js → provider-registry-CmQLzLF_.js} +21690 -21811
  428. package/dist/provider-registry.json +22113 -22215
  429. package/dist/{registry-generator-e8sltJls.js → registry-generator-C17V4WfG.js} +1 -1
  430. package/dist/{registry-generator-DxCX-FiO.cjs → registry-generator-C_0ae7Ce.cjs} +1 -1
  431. package/dist/{rehydrate-B-wrAN7C.cjs → rehydrate-CDQ4dOYj.cjs} +2 -2
  432. package/dist/{rehydrate-D3fPgJwp.js → rehydrate-PnaVawGX.js} +2 -2
  433. package/dist/relevance/index.cjs +2 -2
  434. package/dist/relevance/index.js +2 -2
  435. package/dist/{run-registry-5_LQBGn_.cjs → run-registry-BmckDVBk.cjs} +1698 -497
  436. package/dist/{run-registry-DC03XLeZ.js → run-registry-BwEcwYlU.js} +1614 -467
  437. package/dist/{source-DDwx-87N.cjs → source-BVOi8Xhp.cjs} +1 -1
  438. package/dist/{source-Did_2XQc.js → source-fNa6u1kH.js} +1 -1
  439. package/dist/storage/domains/agents/index.cjs +1 -1
  440. package/dist/storage/domains/agents/index.js +1 -1
  441. package/dist/storage/domains/knowledge/base.d.ts +72 -0
  442. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +146 -0
  443. package/dist/storage/domains/knowledge/importers.d.ts +287 -0
  444. package/dist/storage/domains/knowledge/index.d.ts +1 -0
  445. package/dist/storage/domains/knowledge/inmemory.d.ts +12 -0
  446. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +12 -1
  447. package/dist/storage/domains/knowledge/pages.d.ts +25 -7
  448. package/dist/storage/domains/mcp-clients/index.cjs +1 -1
  449. package/dist/storage/domains/mcp-clients/index.js +1 -1
  450. package/dist/storage/domains/mcp-servers/index.cjs +1 -1
  451. package/dist/storage/domains/mcp-servers/index.js +1 -1
  452. package/dist/storage/domains/prompt-blocks/index.cjs +1 -1
  453. package/dist/storage/domains/prompt-blocks/index.js +1 -1
  454. package/dist/storage/domains/scorer-definitions/index.cjs +1 -1
  455. package/dist/storage/domains/scorer-definitions/index.js +1 -1
  456. package/dist/storage/domains/skills/index.cjs +1 -1
  457. package/dist/storage/domains/skills/index.js +1 -1
  458. package/dist/storage/domains/workspaces/index.cjs +1 -1
  459. package/dist/storage/domains/workspaces/index.js +1 -1
  460. package/dist/storage/index.cjs +15 -10
  461. package/dist/storage/index.js +11 -11
  462. package/dist/stream/base/output.d.ts +59 -15
  463. package/dist/stream/index.cjs +2 -2
  464. package/dist/stream/index.js +2 -2
  465. package/dist/stream/types.d.ts +24 -2
  466. package/dist/{stream-4aNIw_TQ.cjs → stream-0kdqBOOn.cjs} +64 -9
  467. package/dist/{stream-CJUm6EAH.js → stream-D1y9GzoD.js} +29 -10
  468. package/dist/test-utils/llm-mock.cjs +1 -1
  469. package/dist/test-utils/llm-mock.js +1 -1
  470. package/dist/tool-loop-agent/index.cjs +1 -1
  471. package/dist/tool-loop-agent/index.js +1 -1
  472. package/dist/{tool-loop-agent-FEEwHfmg.js → tool-loop-agent-BdjWGVIb.js} +4 -4
  473. package/dist/{tool-loop-agent-Dn0QCB9n.cjs → tool-loop-agent-kWaZAT6Q.cjs} +4 -4
  474. package/dist/tools/types.d.ts +27 -1
  475. package/dist/{utils-DY01hxVd.cjs → utils-BKUCaZ12.cjs} +1 -1
  476. package/dist/{utils-Bd_y1_a-.js → utils-GHY3hmLx.js} +1 -1
  477. package/dist/utils.cjs +1 -1
  478. package/dist/utils.js +1 -1
  479. package/dist/{validate-CX0yQo_q.js → validate-CB-q-R2F.js} +1 -1
  480. package/dist/{validate-CuB_1Zd3.cjs → validate-De92squ7.cjs} +1 -1
  481. package/dist/vector/index.cjs +2 -2
  482. package/dist/vector/index.js +2 -2
  483. package/dist/worker/index.cjs +1 -1
  484. package/dist/worker/index.js +1 -1
  485. package/dist/{worker-CbaSmip-.cjs → worker-BbWPQuPR.cjs} +2 -2
  486. package/dist/{worker-B80xkcKG.js → worker-C3u_xzY2.js} +2 -2
  487. package/dist/{worker-GsGIxPMa.cjs → worker-CAKvQj9_.cjs} +2 -2
  488. package/dist/{worker-DSEfMPmq.js → worker-Kwm8EKcj.js} +2 -2
  489. package/dist/{workflow-CnBPXTpv.cjs → workflow-CSjXeNcR.cjs} +4 -4
  490. package/dist/{workflow-CZHY_C85.js → workflow-CVmI1Sw-.js} +4 -4
  491. package/dist/workflows/builder/index.cjs +1 -1
  492. package/dist/workflows/builder/index.js +1 -1
  493. package/dist/workflows/evented/index.cjs +1 -1
  494. package/dist/workflows/evented/index.js +1 -1
  495. package/dist/workflows/evented/setup-warning.d.ts +18 -0
  496. package/dist/workflows/evented/workflow-event-processor/run-status.d.ts +37 -0
  497. package/dist/workflows/evented/workflow.d.ts +10 -0
  498. package/dist/workflows/index.cjs +4 -4
  499. package/dist/workflows/index.js +4 -4
  500. package/dist/workflows/workflow.d.ts +6 -1
  501. package/dist/workspace/filesystem/filesystem.d.ts +5 -0
  502. package/dist/workspace/index.cjs +1 -1
  503. package/dist/workspace/index.js +1 -1
  504. package/dist/workspace/sandbox/local-sandbox.d.ts +16 -7
  505. package/dist/workspace/sandbox/native-sandbox/types.d.ts +11 -1
  506. package/dist/{workspace-D7TIleIt.js → workspace-DY2Nxiyi.js} +235 -34
  507. package/dist/{workspace-D2drutNg.cjs → workspace-X2RHJZU9.cjs} +235 -34
  508. package/package.json +7 -7
  509. package/src/llm/model/provider-types.generated.d.ts +7812 -7831
@@ -1,17 +1,17 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-BrhgMLW6.cjs");
2
2
  const require_logger = require("./logger-CvzZYuJd.cjs");
3
3
  const require_base = require("./base-BIzR1D3_.cjs");
4
- const require_output_helpers = require("./output-helpers-JL-HeCbT.cjs");
5
4
  const require_observability = require("./observability-B0R_D1PZ.cjs");
6
5
  const require_error = require("./error-D90lJ6M7.cjs");
7
- const require_error$1 = require("./error-BRQf2ku0.cjs");
8
- const require_stream = require("./stream-4aNIw_TQ.cjs");
6
+ const require_error$1 = require("./error-BdEvO8za.cjs");
7
+ const require_stream = require("./stream-0kdqBOOn.cjs");
9
8
  const require_request_context = require("./request-context-D9RXYCy8.cjs");
10
- const require_message_list = require("./message-list-DPXPXvin.cjs");
9
+ const require_output_helpers = require("./output-helpers-1Zu4Vt9C.cjs");
10
+ const require_message_list = require("./message-list-Cj0Sq_JP.cjs");
11
11
  const require_storage = require("./storage-CfG0I2aF.cjs");
12
12
  const require_utils = require("./utils-D-eNsgDM.cjs");
13
13
  const require_error_count = require("./error-count-DeDpeWU2.cjs");
14
- const require_llm = require("./llm-CsQuqKPc.cjs");
14
+ const require_llm = require("./llm-8Av3mSjD.cjs");
15
15
  const require_payload_transform = require("./payload-transform-CWgnsO9w.cjs");
16
16
  const require_utils_safe_stringify = require("./utils/safe-stringify.cjs");
17
17
  const require_signals = require("./signals-CWxAMEmE.cjs");
@@ -23,13 +23,13 @@ const require_tool = require("./tool-CYlT2UA-.cjs");
23
23
  const require_toolchecks = require("./toolchecks-MFU48cit.cjs");
24
24
  const require_fetchWithRetry = require("./fetchWithRetry-f5k4p7_1.cjs");
25
25
  const require_model = require("./model-jBymoqGa.cjs");
26
- const require_provider_registry = require("./provider-registry-9O-H9osy.cjs");
26
+ const require_provider_registry = require("./provider-registry-BwuI_IpT.cjs");
27
27
  const require_inmemory = require("./inmemory-fgR8sq-U.cjs");
28
28
  const require_dynamic_argument = require("./dynamic-argument-CUc1BBOS.cjs");
29
- const require_model$1 = require("./model-CNPfry_X.cjs");
30
- const require_utils$1 = require("./utils-DY01hxVd.cjs");
29
+ const require_model$1 = require("./model-BK93CMtl.cjs");
30
+ const require_utils$1 = require("./utils-BKUCaZ12.cjs");
31
31
  const require_ee_iTj2bRDt = require("./ee-iTj2bRDt-D3-QLGDF.cjs");
32
- const require_background_tasks = require("./background-tasks-DqnQMfuf.cjs");
32
+ const require_background_tasks = require("./background-tasks-BDrYBis-.cjs");
33
33
  const require_stream$1 = require("./stream-BGbj9jAU.cjs");
34
34
  const require_predicate_index = require("./predicate/index.cjs");
35
35
  const require_classifier_index = require("./classifier/index.cjs");
@@ -41,26 +41,26 @@ const require_state_processor = require("./state-processor-kRNZ38Nf.cjs");
41
41
  const require_constants = require("./constants-B9ZDvXZ4.cjs");
42
42
  const require_signal_provider = require("./signal-provider-BFAvh_AJ.cjs");
43
43
  const require_slugify = require("./slugify-B_WzG9IY.cjs");
44
- const require_workspace = require("./workspace-D2drutNg.cjs");
44
+ const require_workspace = require("./workspace-X2RHJZU9.cjs");
45
45
  const require_tools = require("./tools-CGF5Ik6j.cjs");
46
46
  const require_workspace_skills = require("./workspace-skills-BcquhPDn.cjs");
47
- const require_filesystem_versioned = require("./filesystem-versioned-DZGyPbNC.cjs");
47
+ const require_filesystem_versioned = require("./filesystem-versioned-BavRtYWJ.cjs");
48
48
  const require_features_index = require("./features/index.cjs");
49
49
  const require_dashboard = require("./dashboard-17UeClzI.cjs");
50
- const require_source = require("./source-DDwx-87N.cjs");
50
+ const require_source = require("./source-BVOi8Xhp.cjs");
51
51
  const require_inmemory$1 = require("./inmemory-CxBWpoVB.cjs");
52
- const require_filesystem = require("./filesystem-DsCQiBl2.cjs");
53
- const require_filesystem$1 = require("./filesystem-BDSpwBke.cjs");
54
- const require_filesystem$2 = require("./filesystem-CEbD_77-.cjs");
55
- const require_filesystem$3 = require("./filesystem-C-cyJfi1.cjs");
56
- const require_filesystem$4 = require("./filesystem-B0AZrbj8.cjs");
57
- const require_filesystem$5 = require("./filesystem-CUAgLugE.cjs");
52
+ const require_filesystem = require("./filesystem-DVVecqZt.cjs");
53
+ const require_filesystem$1 = require("./filesystem-BB5YWXH-.cjs");
54
+ const require_filesystem$2 = require("./filesystem-Cgxc2a_-.cjs");
55
+ const require_filesystem$3 = require("./filesystem-BaOJOc-V.cjs");
56
+ const require_filesystem$4 = require("./filesystem-BP5yz5LG.cjs");
57
+ const require_filesystem$5 = require("./filesystem-Fpsu7e24.cjs");
58
58
  const require_agent_skills_resolver = require("./agent-skills-resolver-BMoCDoaK.cjs");
59
59
  const require_voice = require("./voice-Cuev6Md3.cjs");
60
60
  let _isaacs_ttlcache = require("@isaacs/ttlcache");
61
+ let zod_v4 = require("zod/v4");
61
62
  let events = require("events");
62
63
  events = require_rolldown_runtime.__toESM(events, 1);
63
- let zod_v4 = require("zod/v4");
64
64
  let stream_web = require("stream/web");
65
65
  let _ai_sdk_provider_utils_v6 = require("@ai-sdk/provider-utils-v6");
66
66
  let zod = require("zod");
@@ -81,6 +81,18 @@ xxhash_wasm = require_rolldown_runtime.__toESM(xxhash_wasm, 1);
81
81
  let re2js = require("re2js");
82
82
  let lru_cache = require("lru-cache");
83
83
  let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
84
+ // src/events/reach.ts
85
+ /**
86
+ * Whether events published on `pubsub` can reach a subscriber in another
87
+ * process, read from the transport under any decorator.
88
+ *
89
+ * Only an explicit `false` counts as no. A pubsub built against a copy of
90
+ * `@mastra/core` that predates `deliversAcrossProcesses` has no such getter, and
91
+ * must keep being treated as a shared transport.
92
+ */
93
+ function reachesOtherProcesses(pubsub) {
94
+ return pubsub.__rawBus().deliversAcrossProcesses !== false;
95
+ }
84
96
  // src/storage/run-fencing.ts
85
97
  const RUN_FENCE_CONFLICT_ERROR_ID = "STORAGE_RUN_FENCE_CONFLICT";
86
98
  const RUN_FENCING_NOT_SUPPORTED_ERROR_ID = "STORAGE_RUN_FENCING_NOT_SUPPORTED";
@@ -765,6 +777,12 @@ function hasResumableStreams(agent) {
765
777
  if (typeof agent.hasResumableStreams === "function") return agent.hasResumableStreams();
766
778
  return isDurableAgentLike(agent);
767
779
  }
780
+ // src/agent/streams/execution-capability.ts
781
+ /** Native engine selection or the released structural adapter contract (including Inngest). */
782
+ function hasDurableExecution(obj) {
783
+ if (isDurableAgentLike(obj)) return true;
784
+ return typeof obj === "object" && obj !== null && "__hasDurableExecution" in obj && typeof obj.__hasDurableExecution === "function" && obj.__hasDurableExecution() === true;
785
+ }
768
786
  // src/workflows/stream-utils.ts
769
787
  async function forwardAgentStreamChunk({ writer, chunk }) {
770
788
  if (!writer) return;
@@ -793,8 +811,9 @@ function resolveEntryActor(stepOptions, runActor) {
793
811
  * unwrapped to the agent it wraps. Warns because the step runs non-durably.
794
812
  */
795
813
  function resolveLegacyAgent(agent, mastra) {
796
- if (!isDurableAgentLike(agent)) return agent;
814
+ if (!hasDurableExecution(agent)) return agent;
797
815
  mastra?.getLogger()?.warn(`Agent "${agent.id}" is durable but uses a legacy v1 model, which has no durable execution path, so the step runs it non-durably.`);
816
+ if (!isDurableAgentLike(agent)) return agent;
798
817
  const inner = agent.agent;
799
818
  return inner !== agent ? inner : agent;
800
819
  }
@@ -1665,6 +1684,37 @@ const assertTimeTravelGraphMatchesSnapshot = (params) => {
1665
1684
  }
1666
1685
  if (missingStepIds.length > 0) throw new Error(`Cannot time travel to step '${targetStepId}': step(s) ${missingStepIds.map((id) => `'${id}'`).join(", ")} precede the target in the current execution graph but were not recorded in the snapshot. Either the workflow definition changed since the run was recorded (renamed steps, or unnamed .map() steps whose generated ids changed across processes), or the recorded run never reached these steps (it failed, was canceled, or was suspended before them). Steps recorded in the snapshot: ${reportedIdsSuffix}. The stored snapshot has not been modified.`);
1667
1686
  };
1687
+ const nestedRunIdentity = (stored, isForeach) => {
1688
+ const metadata = stored?.metadata;
1689
+ const foreachNestedRunIds = metadata?.foreachNestedRunIds && typeof metadata.foreachNestedRunIds === "object" ? metadata.foreachNestedRunIds : void 0;
1690
+ const keepNestedRunId = !isForeach || !foreachNestedRunIds && Array.isArray(stored?.payload) && stored.payload.length === 1;
1691
+ const identity = require_utils$1.removeUndefinedValues({
1692
+ nestedRunId: keepNestedRunId && typeof metadata?.nestedRunId === "string" ? metadata.nestedRunId : void 0,
1693
+ foreachNestedRunIds
1694
+ });
1695
+ return Object.keys(identity).length > 0 ? identity : void 0;
1696
+ };
1697
+ const withSettledForeachRecords = (suspendPayload, output) => {
1698
+ const records = suspendPayload?.__workflow_meta?.foreachOutput;
1699
+ if (!Array.isArray(records) || !Array.isArray(output)) return suspendPayload;
1700
+ let changed = false;
1701
+ const foreachOutput = output.map((slot, index) => {
1702
+ const record = records[index];
1703
+ if (record || slot === null || slot === void 0 || slot?.status === "suspended") return record ?? null;
1704
+ changed = true;
1705
+ return {
1706
+ status: "success",
1707
+ output: slot
1708
+ };
1709
+ });
1710
+ return changed ? {
1711
+ ...suspendPayload,
1712
+ __workflow_meta: {
1713
+ ...suspendPayload.__workflow_meta,
1714
+ foreachOutput
1715
+ }
1716
+ } : suspendPayload;
1717
+ };
1668
1718
  const createTimeTravelExecutionParams = (params) => {
1669
1719
  const { steps, inputData, resumeData, context, nestedStepsContext, snapshot, initialState, graph, perStep } = params;
1670
1720
  const firstStepId = steps[0];
@@ -1726,12 +1776,13 @@ const createTimeTravelExecutionParams = (params) => {
1726
1776
  payload: isFirstEntryTarget ? firstEntryInput : context?.[stepId]?.payload ?? stepPayload ?? snapshotContext[stepId]?.payload ?? {},
1727
1777
  output: isCompleteStatus ? context?.[stepId]?.output ?? stepOutput ?? snapshotContext[stepId]?.output ?? {} : void 0,
1728
1778
  resumePayload: stepContext?.resumePayload,
1729
- suspendPayload: stepContext?.suspendPayload,
1779
+ suspendPayload: withSettledForeachRecords(stepContext?.suspendPayload, stepContext?.output),
1730
1780
  suspendOutput: stepContext?.suspendOutput,
1731
1781
  startedAt: stepContext?.startedAt ?? Date.now(),
1732
1782
  endedAt: isCompleteStatus ? stepContext?.endedAt ?? Date.now() : void 0,
1733
1783
  suspendedAt: stepContext?.suspendedAt,
1734
- resumedAt: stepContext?.resumedAt
1784
+ resumedAt: stepContext?.resumedAt,
1785
+ metadata: nestedRunIdentity(snapshotContext[stepId], entry.type === "foreach")
1735
1786
  };
1736
1787
  if ((perStep ? executionPath.length : currentExecPathLength) > 0 && !steps?.includes(stepId) && !context?.[stepId] && (!snapshotContext[stepId] || snapshotContext[stepId] && snapshotContext[stepId].status !== "suspended")) result = void 0;
1737
1788
  if (result) {
@@ -7491,6 +7542,7 @@ function createStepFromProcessor$1(processor) {
7491
7542
  };
7492
7543
  const passThrough = {
7493
7544
  agent,
7545
+ abortSignal,
7494
7546
  lateSignalSink,
7495
7547
  phase,
7496
7548
  runId: agentRunId,
@@ -8865,6 +8917,7 @@ var Workflow = class Workflow extends require_base.MastraBase {
8865
8917
  snapshot: initialSnapshot,
8866
8918
  workflowStatus: "pending"
8867
8919
  }) : initialSnapshot, options?.resourceId, { stateBase: nestedRunStart?.inheritedState?.ref });
8920
+ if (nestedRun) nestedRun.inserted = true;
8868
8921
  }
8869
8922
  run.inheritedState = nestedRunStart?.inheritedState;
8870
8923
  return run;
@@ -8924,19 +8977,20 @@ var Workflow = class Workflow extends require_base.MastraBase {
8924
8977
  const nestedPubsub = useSharedPubsub ? pubsub : void 0;
8925
8978
  let startState = state;
8926
8979
  let startedFrom;
8927
- if (!restart && !isResume) {
8980
+ if (!isResume) {
8928
8981
  startedFrom = toJsonState(state);
8929
8982
  if (startedFrom) startState = copyState(state);
8930
8983
  }
8931
8984
  const inheritedState = !restart && !isResume ? await parentState?.(startState) : void 0;
8932
8985
  this.#nestedRun = {
8933
8986
  storageVersion: parentState ? 2 : 1,
8934
- start: !restart && !isResume ? {
8987
+ start: !isResume ? {
8935
8988
  input: inputData,
8936
8989
  state: startState,
8937
8990
  inheritedState
8938
8991
  } : void 0
8939
8992
  };
8993
+ const nestedRunHandoff = this.#nestedRun;
8940
8994
  const run = isResume ? await this.createRun({
8941
8995
  runId: resume.runId,
8942
8996
  resourceId,
@@ -8977,6 +9031,7 @@ var Workflow = class Workflow extends require_base.MastraBase {
8977
9031
  try {
8978
9032
  let restartNested = !!restart;
8979
9033
  let resumeNested = isResume;
9034
+ let storedPending = false;
8980
9035
  if ((restart || isResume) && !isTimeTravel) {
8981
9036
  const nestedSnapshot = await run.runStorage.loadHeader();
8982
9037
  let nestedStatus = nestedSnapshot?.status;
@@ -8994,7 +9049,8 @@ var Workflow = class Workflow extends require_base.MastraBase {
8994
9049
  else if (restart && nestedStatus === "suspended") {
8995
9050
  restartNested = false;
8996
9051
  resumeNested = true;
8997
- }
9052
+ } else if (restart && !isResume && (!nestedSnapshot || nestedRunHandoff.inserted)) restartNested = false;
9053
+ storedPending = nestedStatus === "pending" && !nestedRunHandoff.inserted;
8998
9054
  }
8999
9055
  if (isTimeTravel) {
9000
9056
  res = await run.timeTravel({
@@ -9017,6 +9073,7 @@ var Workflow = class Workflow extends require_base.MastraBase {
9017
9073
  handBackBase = startedFrom;
9018
9074
  } else if (restartNested) {
9019
9075
  handBackBase = await run.runStorage.loadDriveStartState();
9076
+ if (!handBackBase && storedPending) handBackBase = toJsonState((await run.runStorage.loadFull())?.value);
9020
9077
  res = await run.restart({
9021
9078
  requestContext,
9022
9079
  actor,
@@ -11331,6 +11388,34 @@ var EventedExecutionEngine = class extends ExecutionEngine {
11331
11388
  return result;
11332
11389
  }
11333
11390
  };
11391
+ // src/workflows/evented/setup-warning.ts
11392
+ const DOCS_URL = "https://mastra.ai/docs/server/pubsub#evented-workflows-and-agents";
11393
+ const warnedHosts = /* @__PURE__ */ new WeakSet();
11394
+ /**
11395
+ * Evented runs spread over several processes need a pubsub that hands a stopped
11396
+ * worker's event to another worker, and a store whose step guards let one
11397
+ * delivery of a step commit. Logs once per Mastra instance when the pubsub
11398
+ * reaches other processes and one of the two is missing.
11399
+ *
11400
+ * It judges the setup, not how many processes use it: Mastra can't count them.
11401
+ * A pubsub that stays inside the process is left alone, since no other process
11402
+ * can take part in its runs. `MASTRA_DISABLE_EVENTED_SETUP_WARNING=true`
11403
+ * disables it for a shared transport used by one process.
11404
+ *
11405
+ * The message names no supported pubsub or store. The docs page it links to is
11406
+ * the one place that lists them.
11407
+ */
11408
+ function warnUnsupportedEventedSetup(mastra, workflowsStore) {
11409
+ if (warnedHosts.has(mastra) || process.env.MASTRA_DISABLE_EVENTED_SETUP_WARNING === "true") return;
11410
+ if (!reachesOtherProcesses(mastra.pubsub)) return;
11411
+ const pubsub = mastra.pubsub.__rawBus();
11412
+ let missing;
11413
+ if (!pubsub.redeliversUnacked) missing = `${pubsub.constructor.name} doesn't redeliver unacknowledged events`;
11414
+ else if (workflowsStore && !workflowsStore.supportsWorkflowStepGuards()) missing = `the workflows store has no step guards`;
11415
+ if (!missing) return;
11416
+ warnedHosts.add(mastra);
11417
+ mastra.getLogger()?.warn(`Evented workflows and agents aren't supported on several processes with this setup: ${missing}. See ${DOCS_URL}`);
11418
+ }
11334
11419
  // src/agent/scopes.ts
11335
11420
  /**
11336
11421
  * Scope types Memory reads as the run's identity. Every other scope type is
@@ -11608,7 +11693,7 @@ const MASTRA_DURABLE_SEGMENTS_KEY = "mastra__durableSegments";
11608
11693
  * round-trip are skipped so a single non-serializable value can't break the
11609
11694
  * snapshot.
11610
11695
  */
11611
- function snapshotRequestContextEntries(requestContext) {
11696
+ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
11612
11697
  if (!requestContext) return void 0;
11613
11698
  const out = {};
11614
11699
  let any = false;
@@ -11620,7 +11705,10 @@ function snapshotRequestContextEntries(requestContext) {
11620
11705
  if (key === "mastra__durableExecutions") continue;
11621
11706
  if (key === "mastra__durableSegments") continue;
11622
11707
  const json = require_utils_safe_stringify.boundedStringify(value);
11623
- if (json === void 0) continue;
11708
+ if (json === void 0) {
11709
+ onEntryOmitted?.();
11710
+ continue;
11711
+ }
11624
11712
  out[key] = JSON.parse(json);
11625
11713
  any = true;
11626
11714
  }
@@ -14920,7 +15008,7 @@ var StepExecutor = class extends require_base.MastraBase {
14920
15008
  const cache = this.mastra?.serverCache;
14921
15009
  if (inner instanceof require_output_helpers.CachingPubSub) this.#stepPubsub = inner;
14922
15010
  else if (cache) {
14923
- const processLocalLogs = cache instanceof require_inmemory.InMemoryServerCache && !(inner.__rawBus() instanceof require_output_helpers.EventEmitterPubSub);
15011
+ const processLocalLogs = cache instanceof require_inmemory.InMemoryServerCache && reachesOtherProcesses(inner);
14924
15012
  this.#stepPubsub = new require_output_helpers.CachingPubSub(inner, cache, {
14925
15013
  shouldCache: (topic) => !require_output_helpers.isRunLocalTopic(topic),
14926
15014
  extendExistingLogsOnly: processLocalLogs,
@@ -15198,7 +15286,7 @@ var StepExecutor = class extends require_base.MastraBase {
15198
15286
  }),
15199
15287
  error: errorInstance
15200
15288
  } });
15201
- if (isExecutionFenceError(error) && this.mastra && !(this.mastra.pubsub.__rawBus() instanceof require_output_helpers.EventEmitterPubSub)) {
15289
+ if (isExecutionFenceError(error) && this.mastra && reachesOtherProcesses(this.mastra.pubsub)) {
15202
15290
  if (isStorageFencedExecution(requestContext, runId, params.parentWorkflow)) throw error;
15203
15291
  }
15204
15292
  const mastraError = new require_error.MastraError({
@@ -15429,6 +15517,58 @@ var StepExecutor = class extends require_base.MastraBase {
15429
15517
  }
15430
15518
  }
15431
15519
  };
15520
+ // src/workflows/evented/workflow-event-processor/run-status.ts
15521
+ const ENDED_RUN_STATUSES = /* @__PURE__ */ new Set([
15522
+ "success",
15523
+ "failed",
15524
+ "canceled",
15525
+ "tripwire"
15526
+ ]);
15527
+ /** The statuses of a run that has not ended yet. */
15528
+ const UNENDED_RUN_STATUSES = [
15529
+ "running",
15530
+ "waiting",
15531
+ "suspended",
15532
+ "pending",
15533
+ "paused",
15534
+ "bailed",
15535
+ "skipped"
15536
+ ];
15537
+ /** Whether a run stored with `status` has ended. */
15538
+ function isEndedRunStatus(status) {
15539
+ return ENDED_RUN_STATUSES.has(status);
15540
+ }
15541
+ /** Whether the stored run `run` has ended. */
15542
+ function hasRunEnded(run) {
15543
+ return !!run && isEndedRunStatus(run.status);
15544
+ }
15545
+ /** Whether `executionPath` points past the last entry of `stepGraph`: a step run there ends the run. */
15546
+ function isPastLastEntry(stepGraph, executionPath) {
15547
+ return (executionPath?.[0] ?? -1) >= stepGraph.length;
15548
+ }
15549
+ /**
15550
+ * Whether a step event is the one that ended the stored run `run`, which a worker still handles
15551
+ * when the run has ended. Only a successful run has one: its worker stores the end before
15552
+ * publishing it and may stop in between, and handling the event again publishes the end. The
15553
+ * stored active path names it: the step end the run ended at, or the step run past the last entry.
15554
+ * A failed run's end is stored by its own `workflow.fail`, which a redelivery of that event
15555
+ * finishes.
15556
+ *
15557
+ * This can't tell an end that was stored and not published from one that was already handled, so
15558
+ * a late copy of the event publishes the end again (and, for a nested run, hands it to the parent
15559
+ * again).
15560
+ */
15561
+ function isRunEndingEvent(type, executionPath, run, stepGraph) {
15562
+ return run.status === "success" && samePath(run.activePaths, executionPath) && (type === "workflow.step.end" || !!stepGraph && isPastLastEntry(stepGraph, executionPath));
15563
+ }
15564
+ /**
15565
+ * Whether two execution paths name the same position in the step graph. A missing path matches
15566
+ * only another missing path: a run stored without active paths was ended by an event without one.
15567
+ */
15568
+ function samePath(a, b) {
15569
+ if (!a || !b) return a === b;
15570
+ return a.length === b.length && a.every((index, depth) => index === b[depth]);
15571
+ }
15432
15572
  // src/workflows/evented/workflow-event-processor/finished-occurrence.ts
15433
15573
  const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
15434
15574
  "success",
@@ -15447,10 +15587,6 @@ const BRANCH_SETTLED_STATUSES = /* @__PURE__ */ new Set([
15447
15587
  "skipped",
15448
15588
  "suspended"
15449
15589
  ]);
15450
- /** Whether two execution paths name the same position in the step graph. */
15451
- function samePath(a, b) {
15452
- return !!a && a.length === b.length && a.every((index, depth) => index === b[depth]);
15453
- }
15454
15590
  /** The record of one foreach item, kept in the foreach step's resume metadata. */
15455
15591
  function foreachItem(result, index) {
15456
15592
  if (index === void 0) return;
@@ -16412,6 +16548,18 @@ function routeStepRun(stepGraph, { executionPath, restart }) {
16412
16548
  }
16413
16549
  }
16414
16550
  // src/workflows/evented/workflow-event-processor/sleep.ts
16551
+ /**
16552
+ * Records the sleep as the run's active step. Returns false when the run ended after the sleep
16553
+ * was dispatched: the write is refused, so the ended run is not reopened, and the sleep stops.
16554
+ */
16555
+ async function markSleepRunning(runStorage, executionPath, activeStepsPath) {
16556
+ return !!await runStorage.updateHeader({
16557
+ status: "running",
16558
+ activePaths: executionPath,
16559
+ activeStepsPath,
16560
+ expectedStatus: UNENDED_RUN_STATUSES
16561
+ }) || !hasRunEnded(await runStorage.loadHeader());
16562
+ }
16415
16563
  async function processWorkflowWaitForEvent(workflowData, { pubsub, eventName, currentState }) {
16416
16564
  const executionPath = currentState?.waitingPaths[eventName];
16417
16565
  if (!executionPath) return;
@@ -16464,14 +16612,10 @@ async function processWorkflowSleep({ workflow, workflowId, runId, executionPath
16464
16612
  },
16465
16613
  requestContext: withoutAuthToken(requestContext ?? {})
16466
16614
  });
16467
- await runStorage.updateHeader({
16468
- status: "running",
16469
- activePaths: executionPath,
16470
- activeStepsPath: {
16471
- ...activeStepsPath,
16472
- [step.id]: executionPath
16473
- }
16474
- });
16615
+ if (!await markSleepRunning(runStorage, executionPath, {
16616
+ ...activeStepsPath,
16617
+ [step.id]: executionPath
16618
+ })) return;
16475
16619
  const reqContext = new require_request_context.RequestContext(Object.entries(requestContext ?? {}));
16476
16620
  setLongTimeout(async () => {
16477
16621
  if (emitStepEvents) {
@@ -16545,14 +16689,10 @@ async function processWorkflowSleepUntil({ workflow, workflowId, runId, executio
16545
16689
  },
16546
16690
  requestContext: withoutAuthToken(requestContext ?? {})
16547
16691
  });
16548
- await runStorage.updateHeader({
16549
- status: "running",
16550
- activePaths: executionPath,
16551
- activeStepsPath: {
16552
- ...activeStepsPath,
16553
- [step.id]: executionPath
16554
- }
16555
- });
16692
+ if (!await markSleepRunning(runStorage, executionPath, {
16693
+ ...activeStepsPath,
16694
+ [step.id]: executionPath
16695
+ })) return;
16556
16696
  const reqContext = new require_request_context.RequestContext(Object.entries(requestContext ?? {}));
16557
16697
  const duration = await stepExecutor.resolveSleepUntil({
16558
16698
  workflowId,
@@ -17480,12 +17620,12 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
17480
17620
  stepResults: stepResults ?? {},
17481
17621
  workflowStatus: finalStatus
17482
17622
  }) ?? true;
17483
- if (shouldPersist) await runStorage.updateHeader({
17623
+ if (shouldPersist && !await this.#writeRunEnd("endWorkflow", args, runStorage, {
17484
17624
  status: finalStatus,
17485
17625
  result: normalizedPrevResult,
17486
17626
  activePaths: executionPath,
17487
17627
  activeStepsPath
17488
- });
17628
+ })) return;
17489
17629
  this.endRunSpans(args, finalStatus);
17490
17630
  if (finalStatus === "paused") await this.#pubsub.publish(`workflow.events.v2.${runId}`, {
17491
17631
  type: "watch",
@@ -17519,6 +17659,35 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
17519
17659
  }
17520
17660
  });
17521
17661
  }
17662
+ /**
17663
+ * Stores a run's end only while the run has not ended, so a late or second end can't replace
17664
+ * the first one. Returns true when the end is to be published: it was stored, the run is not
17665
+ * stored (as before), or the run already ended the same way at the same path, which is this end
17666
+ * handled again after its worker stopped before publishing it. Returns false, after logging, for
17667
+ * any other refusal: the run ended another way, or it was reopened (time travel writes `running`
17668
+ * on an ended run) between the write and the read, and an old end must not replace it.
17669
+ */
17670
+ async #writeRunEnd(handler, { workflowId, runId, executionPath, eventId }, runStorage, end) {
17671
+ const expectedStatus = end.status === "canceled" ? [...UNENDED_RUN_STATUSES, "canceled"] : UNENDED_RUN_STATUSES;
17672
+ if (await runStorage.updateHeader({
17673
+ ...end,
17674
+ expectedStatus
17675
+ })) return true;
17676
+ const stored = await runStorage.loadHeader();
17677
+ if (!stored) return true;
17678
+ if (hasRunEnded(stored) && stored.status === end.status && samePath(stored.activePaths, executionPath)) return true;
17679
+ this.mastra.getLogger()?.warn("Dropping a workflow end: the run already ended or was reopened", {
17680
+ handler,
17681
+ workflowId,
17682
+ runId,
17683
+ eventId,
17684
+ executionPath,
17685
+ status: end.status,
17686
+ storedStatus: stored.status,
17687
+ storedActivePaths: stored.activePaths
17688
+ });
17689
+ return false;
17690
+ }
17522
17691
  async publishFinishEvent(event) {
17523
17692
  for (;;) try {
17524
17693
  await this.#pubsub.publish("workflows-finish", event);
@@ -17655,6 +17824,17 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
17655
17824
  const step = liveParentWorkflow?.stepGraph?.[parentWorkflow.executionPath[0]];
17656
17825
  if (liveParentWorkflow && step?.type === "loop") {
17657
17826
  const parentStorage = this.#runStorage(parentWorkflow.workflowId, parentWorkflow.runId);
17827
+ const parentHeader = await parentStorage.loadHeader();
17828
+ if (hasRunEnded(parentHeader)) {
17829
+ this.mastra.getLogger()?.warn("Dropping a nested loop iteration end: the parent run already ended", {
17830
+ workflowId: parentWorkflow.workflowId,
17831
+ runId: parentWorkflow.runId,
17832
+ nestedRunId,
17833
+ executionPath: parentWorkflow.executionPath,
17834
+ storedStatus: parentHeader.status
17835
+ });
17836
+ return;
17837
+ }
17658
17838
  const loopStepResults = {
17659
17839
  ...parentWorkflow.stepResults ?? (await parentStorage.loadFull())?.context,
17660
17840
  __state: state
@@ -17790,21 +17970,19 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
17790
17970
  workflowStatus: "failed"
17791
17971
  }) ?? true;
17792
17972
  const ownershipLost = workflow?.options?.isOwnershipLostError?.(prevResult?.error);
17793
- if (ownershipLost) {} else if (shouldPersist) {
17794
- await runStorage.updateHeader({
17795
- status: "failed",
17796
- error: prevResult.error,
17797
- activePaths: executionPath,
17798
- activeStepsPath
17799
- });
17800
- if (currentStorageVersion() === 2) await this.pruneAndRepersistSnapshot({
17801
- workflow,
17802
- workflowId,
17803
- runId,
17804
- finished: true,
17805
- fence: await this.currentRunFence(runId)
17806
- });
17807
- }
17973
+ if (ownershipLost) {} else if (shouldPersist && !await this.#writeRunEnd("processWorkflowFail", args, runStorage, {
17974
+ status: "failed",
17975
+ error: prevResult.error,
17976
+ activePaths: executionPath,
17977
+ activeStepsPath
17978
+ })) return;
17979
+ else if (shouldPersist && currentStorageVersion() === 2) await this.pruneAndRepersistSnapshot({
17980
+ workflow,
17981
+ workflowId,
17982
+ runId,
17983
+ finished: true,
17984
+ fence: await this.currentRunFence(runId)
17985
+ });
17808
17986
  if (parentWorkflow) await this.#pubsub.publish("workflows", {
17809
17987
  type: "workflow.step.end",
17810
17988
  runId: parentWorkflow.runId,
@@ -17908,7 +18086,7 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
17908
18086
  restart
17909
18087
  });
17910
18088
  if (!rawStep || route.kind === "missing") {
17911
- if (executionPath[0] >= stepGraph.length) return this.endWorkflow({
18089
+ if (isPastLastEntry(stepGraph, executionPath)) return this.endWorkflow({
17912
18090
  workflow,
17913
18091
  parentWorkflow,
17914
18092
  workflowId,
@@ -18493,12 +18671,7 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
18493
18671
  workflowName: workflowId,
18494
18672
  runId
18495
18673
  });
18496
- if (snapshot && [
18497
- "success",
18498
- "failed",
18499
- "canceled",
18500
- "tripwire"
18501
- ].includes(snapshot.status)) return true;
18674
+ if (hasRunEnded(snapshot)) return true;
18502
18675
  if (snapshot?.status === "suspended" && snapshot.context[leafId]?.status === "suspended") return true;
18503
18676
  if (guardStart) try {
18504
18677
  assertWorkflowStepGuard({
@@ -18536,7 +18709,8 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
18536
18709
  nestedRunId = stepResults[leafId]?.suspendPayload?.__workflow_meta?.runId;
18537
18710
  } else if (timeTravel && timeTravel.steps?.length > 1 && timeTravel.steps[0] === leafId) {
18538
18711
  nestedDispatch = "time-travel";
18539
- nestedRunId = stepResults[leafId]?.metadata?.nestedRunId ?? globalThis.crypto.randomUUID();
18712
+ const recordedMetadata = stepResults[leafId]?.metadata;
18713
+ nestedRunId = (step.type === "foreach" ? recordedMetadata?.foreachNestedRunIds?.[executionPath[1]] ?? (recordedMetadata?.foreachNestedRunIds || executionPath[1] !== 0 ? void 0 : recordedMetadata?.nestedRunId) : recordedMetadata?.nestedRunId) ?? globalThis.crypto.randomUUID();
18540
18714
  } else if (restart && !!restart.activeStepsPath?.[leafId]) {
18541
18715
  nestedDispatch = "restart";
18542
18716
  nestedRunId = (step.type === "foreach" ? stepResults[leafId]?.metadata?.foreachNestedRunIds?.[executionPath[1]] : void 0) ?? stepResults[leafId]?.metadata?.nestedRunId ?? globalThis.crypto.randomUUID();
@@ -18665,12 +18839,23 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
18665
18839
  };
18666
18840
  return step.type === "loop" ? this.#processLoop(continuation, step, completedResult, args.eventId) : this.processWorkflowStepEnd(continuation);
18667
18841
  }
18668
- await runStorage.updateHeader({
18842
+ const stored = await runStorage.updateHeader({
18669
18843
  status: "running",
18670
18844
  activePaths: executionPath,
18671
18845
  activeStepsPath,
18672
18846
  expectedStatus: "running"
18673
- });
18847
+ }) ? void 0 : await runStorage.loadHeader();
18848
+ if (hasRunEnded(stored) && stored.status !== "canceled") {
18849
+ this.mastra.getLogger()?.warn("Not running a step: the run already ended", {
18850
+ type: "workflow.step.run",
18851
+ workflowId,
18852
+ runId,
18853
+ eventId: args.eventId,
18854
+ executionPath,
18855
+ storedStatus: stored.status
18856
+ });
18857
+ return;
18858
+ }
18674
18859
  }
18675
18860
  if (step.type === "foreach" && workflowsStore && authorizedEventId) {
18676
18861
  const storedResult = (await runStorage.loadSteps([leafId]))[leafId] ?? stepResults[leafId];
@@ -20274,7 +20459,7 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
20274
20459
  * should drop the event (or return 4xx for HTTP push).
20275
20460
  */
20276
20461
  async handle(event) {
20277
- if (this.mastra.pubsub.__rawBus() instanceof require_output_helpers.EventEmitterPubSub) return this.#handleDelivery(event);
20462
+ if (!reachesOtherProcesses(this.mastra.pubsub)) return this.#handleDelivery(event);
20278
20463
  if (!isStorageFencedExecution(new require_request_context.RequestContext(Object.entries(event.data?.requestContext ?? {})), event.runId, event.data?.parentWorkflow)) return this.#handleDelivery(event);
20279
20464
  try {
20280
20465
  if (await retrySettledDurableExecution(this.mastra, event)) return { ok: true };
@@ -20608,6 +20793,19 @@ var WorkflowEventProcessor = class WorkflowEventProcessor extends EventProcessor
20608
20793
  return;
20609
20794
  }
20610
20795
  const workflow = this.#resolveLiveWorkflow(workflowData);
20796
+ if ((type === "workflow.step.end" || type === "workflow.step.run") && hasRunEnded(currentState) && !isRunEndingEvent(type, workflowData.executionPath, currentState, workflow?.stepGraph)) {
20797
+ this.mastra.getLogger()?.warn("Dropping a step event: the run already ended", {
20798
+ type,
20799
+ workflowId: workflowData.workflowId,
20800
+ runId: workflowData.runId,
20801
+ eventId: event.id,
20802
+ executionPath: workflowData.executionPath,
20803
+ storedStatus: currentState.status,
20804
+ storedActivePaths: currentState.activePaths,
20805
+ deliveryAttempt: event.deliveryAttempt
20806
+ });
20807
+ return;
20808
+ }
20611
20809
  if (!workflow) {
20612
20810
  if (type === "workflow.fail" || type === "workflow.end" || type === "workflow.cancel") {} else return this.errorWorkflow(workflowData, new require_error.MastraError({
20613
20811
  id: "MASTRA_WORKFLOW",
@@ -20975,15 +21173,17 @@ function createStepFromProcessor(processor) {
20975
21173
  description: processor.name ?? `Processor ${processor.id}`,
20976
21174
  inputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepSchema),
20977
21175
  outputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepOutputSchema),
20978
- execute: async ({ inputData, requestContext, outputWriter, tracing, tracingContext, loggerVNext, metrics, mastra, runId: workflowRunId }) => {
21176
+ execute: async ({ inputData, requestContext, outputWriter, tracing, tracingContext, loggerVNext, metrics, mastra, runId: workflowRunId, abortSignal: runAbortSignal }) => {
20979
21177
  const observabilityContext = require_observability.resolveObservabilityContext({
20980
21178
  tracing,
20981
21179
  tracingContext,
20982
21180
  loggerVNext,
20983
21181
  metrics
20984
21182
  });
21183
+ const scopedSignal = mastra?.__getRunScope(workflowRunId)?.get(require_stream.PROCESSOR_ABORT_SIGNAL);
21184
+ const abortSignal = scopedSignal && runAbortSignal ? AbortSignal.any([scopedSignal, runAbortSignal]) : scopedSignal ?? runAbortSignal;
20985
21185
  const input = inputData;
20986
- const { phase, messages, messageList, stepNumber, runId: agentRunId, systemMessages, part, streamParts, state, result: outputResult, finishReason, providerMetadata, toolCalls, text, retryCount, model, tools, toolChoice, activeTools, providerOptions, modelSettings, structuredOutput, steps, usage, messageId, rotateResponseMessageId, toolName, toolCallId, args: toolCallArgs, toolResultValue, modelOutput, providerExecuted, processorStates, abortSignal, lateSignalSink } = input;
21186
+ const { phase, messages, messageList, stepNumber, runId: agentRunId, systemMessages, part, streamParts, state, result: outputResult, finishReason, providerMetadata, toolCalls, text, retryCount, model, tools, toolChoice, activeTools, providerOptions, modelSettings, structuredOutput, steps, usage, messageId, rotateResponseMessageId, toolName, toolCallId, args: toolCallArgs, toolResultValue, modelOutput, providerExecuted, processorStates, lateSignalSink } = input;
20987
21187
  const abort = (reason, options) => {
20988
21188
  throw new require_stream.TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
20989
21189
  };
@@ -21599,6 +21799,16 @@ function createStepFromProcessor(processor) {
21599
21799
  component: "PROCESSOR"
21600
21800
  };
21601
21801
  }
21802
+ /**
21803
+ * Builds a workflow on the evented execution engine: each step is an event on
21804
+ * the Mastra host's pubsub, so any worker can run the next one.
21805
+ *
21806
+ * In one process it runs on any pubsub, including the default one. Running it
21807
+ * on several processes needs a pubsub that redelivers unacknowledged events and
21808
+ * a workflows store with step guards.
21809
+ *
21810
+ * @see https://mastra.ai/docs/server/pubsub#evented-workflows-and-agents
21811
+ */
21602
21812
  function createWorkflow$1(params) {
21603
21813
  const eventProcessor = new WorkflowEventProcessor({ mastra: params.mastra });
21604
21814
  const executionEngine = new EventedExecutionEngine({
@@ -21655,6 +21865,7 @@ var EventedWorkflow = class extends Workflow {
21655
21865
  }
21656
21866
  });
21657
21867
  }
21868
+ if (!this.isInternal) warnUnsupportedEventedSetup(this.mastra, workflowsStore);
21658
21869
  const cachedRun = this.runs.get(runIdToUse);
21659
21870
  const shouldPersistSnapshot = this.options?.shouldPersistSnapshot?.({
21660
21871
  workflowStatus: cachedRun?.workflowRunStatus ?? "pending",
@@ -37835,10 +38046,19 @@ var DatasetsInMemory = class extends DatasetsStorage {
37835
38046
  field: "createdAt",
37836
38047
  direction: "DESC"
37837
38048
  });
37838
- items.sort(require_filesystem_versioned.compareByField(orderBy.field, orderBy.direction));
37839
38049
  const { page, perPage: perPageInput } = args.pagination;
37840
38050
  const perPage = require_filesystem_versioned.normalizePerPage(perPageInput, 100);
37841
38051
  const { offset: start, perPage: perPageForResponse } = require_filesystem_versioned.calculatePagination(page, perPageInput, perPage);
38052
+ if (perPage === 0) return {
38053
+ items: [],
38054
+ pagination: {
38055
+ total: items.length,
38056
+ page,
38057
+ perPage: perPageForResponse,
38058
+ hasMore: items.length > 0
38059
+ }
38060
+ };
38061
+ items.sort(require_filesystem_versioned.compareByField(orderBy.field, orderBy.direction));
37842
38062
  const end = perPageInput === false ? items.length : start + perPage;
37843
38063
  return {
37844
38064
  items: items.slice(start, end),
@@ -38424,6 +38644,321 @@ var InMemoryHarness = class extends HarnessStorage {
38424
38644
  return cloneSessionRecord(next);
38425
38645
  }
38426
38646
  };
38647
+ const KNOWLEDGE_TABLE_NAMES = [
38648
+ "mastra_knowledge_nodes",
38649
+ "mastra_knowledge_records",
38650
+ "mastra_knowledge_mentions",
38651
+ "mastra_knowledge_activity",
38652
+ "mastra_knowledge_semantic_outbox",
38653
+ "mastra_knowledge_node_scopes",
38654
+ "mastra_knowledge_record_scopes",
38655
+ "mastra_knowledge_scope_grants",
38656
+ "mastra_knowledge_access_state",
38657
+ "mastra_knowledge_scope_addresses",
38658
+ "mastra_knowledge_node_addresses",
38659
+ "mastra_knowledge_import_state",
38660
+ "mastra_knowledge_import_runs",
38661
+ "mastra_knowledge_proposals"
38662
+ ];
38663
+ /** Knowledge v1 tables with no v2 equivalent; an explicit schema reset drops them. */
38664
+ const RETIRED_KNOWLEDGE_TABLE_NAMES = ["mastra_knowledge_cursors"];
38665
+ const KNOWLEDGE_PAGES_TABLE_NAMES = [
38666
+ "mastra_knowledge_pages",
38667
+ "mastra_knowledge_notes",
38668
+ "mastra_knowledge_note_stamps",
38669
+ "mastra_knowledge_mentions",
38670
+ "mastra_knowledge_pins",
38671
+ "mastra_knowledge_activity",
38672
+ "mastra_knowledge_access_state"
38673
+ ];
38674
+ [.../* @__PURE__ */ new Set([
38675
+ ...KNOWLEDGE_PAGES_TABLE_NAMES,
38676
+ ...KNOWLEDGE_TABLE_NAMES,
38677
+ ...RETIRED_KNOWLEDGE_TABLE_NAMES
38678
+ ])];
38679
+ new Set([...KNOWLEDGE_TABLE_NAMES, ...RETIRED_KNOWLEDGE_TABLE_NAMES].filter((name) => !KNOWLEDGE_PAGES_TABLE_NAMES.includes(name)));
38680
+ KNOWLEDGE_TABLE_NAMES.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
38681
+ /**
38682
+ * A list cursor the store cannot decode (malformed, or from another store or version). Defined
38683
+ * here so every adapter can throw it on any core version; core re-exports it from
38684
+ * `@mastra/core/storage`. Recognise it by `name`.
38685
+ * @experimental
38686
+ */
38687
+ var KnowledgeInvalidCursorError = class extends Error {
38688
+ cursor;
38689
+ constructor(cursor) {
38690
+ super("Invalid Knowledge cursor: this store cannot decode it");
38691
+ this.cursor = cursor;
38692
+ this.name = "KnowledgeInvalidCursorError";
38693
+ }
38694
+ };
38695
+ /**
38696
+ * Keyword-search words: the query split on whitespace, lowercased, deduplicated, keeping the first
38697
+ * {@link KNOWLEDGE_SEARCH_MAX_WORDS}. A hit needs at least one of them (as a case-insensitive
38698
+ * substring); an empty list means the search returns nothing.
38699
+ */
38700
+ function knowledgeSearchWords(query) {
38701
+ return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))].slice(0, 16);
38702
+ }
38703
+ /**
38704
+ * Points one matched search word earns on a page, by the best field it appears in: name, then
38705
+ * description, then body. A page whose name contains the whole query ranks first; below that, pages
38706
+ * rank by how many query words they match, and these points only break ties between pages that
38707
+ * match the same number of words.
38708
+ */
38709
+ const KNOWLEDGE_SEARCH_WEIGHTS = {
38710
+ name: 3,
38711
+ description: 2,
38712
+ body: 1
38713
+ };
38714
+ /**
38715
+ * Why `key` can't be a Knowledge page key, or undefined when it can. Keys are one path segment:
38716
+ * non-empty, with no `/` (path separator), `#` (scope/path separator) or `%` (escape character).
38717
+ */
38718
+ function knowledgePageKeyProblem(key) {
38719
+ if (!key) return "Knowledge page key must not be empty";
38720
+ if (/[/#%]/.test(key)) return `Knowledge page key "${key}" must not contain "/", "#" or "%"`;
38721
+ }
38722
+ // src/storage/domains/knowledge/pages.ts
38723
+ /**
38724
+ * Knowledge storage contract, schema 4: pages, notes, stamps, mentions, body links and pins.
38725
+ *
38726
+ * The store holds structure and filters by a read scope that core computes from the run's scopes and
38727
+ * the Knowledge declarations; it holds no access policy of its own (no grant rows, no roles). Core
38728
+ * checks roles before every write, and resolves every write target through the run's read scope first,
38729
+ * so a page or note the run can't read behaves exactly like a missing id.
38730
+ *
38731
+ * Every adapter must implement these semantics; the physical layout (tables, columns, denormalized
38732
+ * filter columns, how a large read scope is passed to the database) is the adapter's choice. Any
38733
+ * denormalized scope column (a note's page scope, its stamp scopes' addresses, its mentions' home
38734
+ * scopes) must be updated in the same transaction as the move or merge that changes it.
38735
+ *
38736
+ * The body-link table came after schema 4 shipped and is additive: adapters create it with idempotent
38737
+ * DDL in `init()` (as the pin-audience index was), without a schema version change, so existing
38738
+ * stores keep their data. Links for pages written before it fill in on `knowledge.reindexLinks()` or the
38739
+ * page's next write.
38740
+ *
38741
+ * @experimental Knowledge APIs are experimental and may change without notice.
38742
+ */
38743
+ /** Most levels a pinned listing walks below its page. @experimental */
38744
+ const MAX_KNOWLEDGE_PIN_LIST_DEPTH = 3;
38745
+ /**
38746
+ * The depth a pin of `kind` stores: undefined for `page` pins, `depth` (default 1) for `list` pins.
38747
+ * Throws when a `list` depth isn't a whole number from 1 to {@link MAX_KNOWLEDGE_PIN_LIST_DEPTH}.
38748
+ *
38749
+ * @experimental
38750
+ */
38751
+ function knowledgePinDepth(kind, depth) {
38752
+ if (kind === "page") return void 0;
38753
+ const value = depth ?? 1;
38754
+ if (!Number.isInteger(value) || value < 1 || value > 3) throw new Error(`A Knowledge list pin's depth must be a whole number from 1 to 3`);
38755
+ return value;
38756
+ }
38757
+ /**
38758
+ * The key a `[[ref]]` is matched by when core looks for links a new or moved page now resolves:
38759
+ * `scope#key/key` refs as written (trimmed), every other ref (id, address, name) by
38760
+ * {@link canonicalKnowledgeName}. Core computes both sides with this function; a key collision only
38761
+ * makes core re-resolve a source page, never links it wrongly.
38762
+ *
38763
+ * @experimental
38764
+ */
38765
+ function knowledgeLinkRefKey(ref) {
38766
+ const trimmed = ref.trim();
38767
+ return trimmed.includes("#") ? trimmed : canonicalKnowledgeName(trimmed);
38768
+ }
38769
+ /**
38770
+ * Most levels an ordinary page may sit below its home scope page: a page directly under its scope
38771
+ * is depth 1. Scope pages (including scopes nested under scopes by `belongsTo` or as template
38772
+ * children) don't count and reset the count. Creates and moves past it are refused.
38773
+ *
38774
+ * @experimental
38775
+ */
38776
+ const MAX_KNOWLEDGE_PAGE_DEPTH = 10;
38777
+ /**
38778
+ * Most pages one move may carry (the page and everything under it). Larger moves are refused with
38779
+ * {@link KnowledgeMoveTooLargeError} instead of running in the background.
38780
+ *
38781
+ * @experimental
38782
+ */
38783
+ const MAX_KNOWLEDGE_MOVE_PAGES = 500;
38784
+ /** @experimental */
38785
+ const MAX_KNOWLEDGE_PAGE_LIST_LIMIT = 100;
38786
+ /** Most edges one {@link KnowledgePageStore.listPageLinks} call returns. @experimental */
38787
+ const MAX_KNOWLEDGE_PAGE_LINKS = 1e4;
38788
+ /** Distinct `[[refs]]` core indexes per page body; further refs stay plain text. @experimental */
38789
+ const MAX_KNOWLEDGE_PAGE_BODY_LINKS = 1e3;
38790
+ /** Longest body-link ref key core stores; a longer `[[ref]]` stays plain text. Stores may size the column to it. @experimental */
38791
+ const MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH = 512;
38792
+ /**
38793
+ * Maximum page description in estimated tokens (tokenx), enforced by every adapter on create and
38794
+ * update.
38795
+ *
38796
+ * @experimental
38797
+ */
38798
+ const MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS = 100;
38799
+ /**
38800
+ * Maximum note text in estimated tokens (tokenx), enforced by every adapter on add. Long-form text
38801
+ * belongs in a page body.
38802
+ *
38803
+ * @experimental
38804
+ */
38805
+ const MAX_KNOWLEDGE_NOTE_TOKENS = 250;
38806
+ /**
38807
+ * Rejects a page description over {@link MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS} before any write.
38808
+ * Every adapter calls this so all stores share one estimator and one error.
38809
+ *
38810
+ * @experimental
38811
+ */
38812
+ function assertKnowledgePageDescriptionWithinBound(description) {
38813
+ if (description === void 0) return;
38814
+ if (require_workspace.estimateTokenCount(description) > 100) throw new Error(`Knowledge page description exceeds the 100 token limit; put long-form text in the page body`);
38815
+ }
38816
+ /**
38817
+ * Rejects note text over {@link MAX_KNOWLEDGE_NOTE_TOKENS} before any write.
38818
+ *
38819
+ * @experimental
38820
+ */
38821
+ function assertKnowledgeNoteTextWithinBound(text) {
38822
+ if (require_workspace.estimateTokenCount(text) > 250) throw new Error(`Knowledge note text exceeds the 250 token limit; split it into separate notes or put long-form text in the page body`);
38823
+ }
38824
+ /** @experimental */
38825
+ var KnowledgeMoveTooLargeError = class extends Error {
38826
+ pageId;
38827
+ pages;
38828
+ constructor(pageId, pages) {
38829
+ super(`Moving page ${pageId} would move ${pages} pages; at most 500 move at once. Move smaller subtrees one at a time.`);
38830
+ this.pageId = pageId;
38831
+ this.pages = pages;
38832
+ this.name = "KnowledgeMoveTooLargeError";
38833
+ }
38834
+ };
38835
+ /** @experimental */
38836
+ var KnowledgePageDepthError = class extends Error {
38837
+ constructor(pageId) {
38838
+ super(`Page ${pageId} would sit more than 10 levels below its home scope.`);
38839
+ this.name = "KnowledgePageDepthError";
38840
+ }
38841
+ };
38842
+ /**
38843
+ * Splits a page reference `<scope>#<key>[/<key>…]` into the scope address and the key path, or
38844
+ * returns null when it isn't one (no scope, an empty or invalid key segment, a second `#`).
38845
+ * @experimental
38846
+ */
38847
+ function parseKnowledgePageRef(ref) {
38848
+ const hash = ref.indexOf("#");
38849
+ if (hash <= 0) return null;
38850
+ const path = knowledgePagePath(ref.slice(hash + 1));
38851
+ if (path.length === 0 || path.some((key) => knowledgePageKeyProblem(key))) return null;
38852
+ return {
38853
+ scope: ref.slice(0, hash),
38854
+ path
38855
+ };
38856
+ }
38857
+ /**
38858
+ * The keys of a key path. Empty segments are dropped, so a leading, trailing or doubled `/`
38859
+ * (`guides/`, `/guides`, `guides//cli`) names the same page as the clean path.
38860
+ * @experimental
38861
+ */
38862
+ function knowledgePagePath(path) {
38863
+ return path.split("/").filter((key) => key !== "");
38864
+ }
38865
+ /** @experimental */
38866
+ var KnowledgePageKeyConflictError = class extends Error {
38867
+ key;
38868
+ parentId;
38869
+ constructor(key, parentId) {
38870
+ super(`Knowledge page key "${key}" already exists under page ${parentId}. Keys are unique among siblings; pick another key or move one of the pages.`);
38871
+ this.key = key;
38872
+ this.parentId = parentId;
38873
+ this.name = "KnowledgePageKeyConflictError";
38874
+ }
38875
+ };
38876
+ /** @experimental */
38877
+ var KnowledgePageHasChildrenError = class extends Error {
38878
+ constructor(pageId) {
38879
+ super(`Page ${pageId} has child pages. Move or delete them first.`);
38880
+ this.name = "KnowledgePageHasChildrenError";
38881
+ }
38882
+ };
38883
+ /**
38884
+ * Canonical form used for exact-name lookup. Computed in JS so every adapter (and SQL collations)
38885
+ * agree on non-ASCII names; adapters store it rather than computing `lower()` in SQL.
38886
+ *
38887
+ * @experimental
38888
+ */
38889
+ function canonicalKnowledgeName(name) {
38890
+ return name.normalize("NFKC").trim().replace(/\s+/g, " ").toLowerCase();
38891
+ }
38892
+ /**
38893
+ * Whether a scope page is readable under `read`. Adapters that filter in memory use this; SQL
38894
+ * adapters must match it exactly.
38895
+ *
38896
+ * @experimental
38897
+ */
38898
+ function knowledgeScopeReadable(scope, read) {
38899
+ if (read === "all") return true;
38900
+ const { address, declaration, parentId } = scope;
38901
+ if (!address) return false;
38902
+ if (read.addresses.includes(address)) return true;
38903
+ if (read.prefixes.some((entry) => entry.declaration === declaration && address.startsWith(entry.prefix))) return true;
38904
+ return read.children.some((entry) => entry.declaration === declaration && entry.parentId === parentId);
38905
+ }
38906
+ const POSITION_DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz";
38907
+ /** Digits of an appended key's integer part: base 35, no `0`, so the key never ends in `0`. */
38908
+ const POSITION_INTEGER_DIGITS = POSITION_DIGITS.slice(1);
38909
+ function positionMidpoint(low, high) {
38910
+ let prefix = "";
38911
+ for (;;) {
38912
+ if (high !== null) {
38913
+ let common = 0;
38914
+ while ((low[common] ?? "0") === high[common]) common++;
38915
+ if (common > 0) {
38916
+ prefix += high.slice(0, common);
38917
+ low = low.slice(common);
38918
+ high = high.slice(common);
38919
+ }
38920
+ }
38921
+ const lowDigit = low ? POSITION_DIGITS.indexOf(low[0]) : 0;
38922
+ const highDigit = high !== null ? POSITION_DIGITS.indexOf(high[0]) : 36;
38923
+ if (highDigit - lowDigit > 1) return prefix + POSITION_DIGITS[Math.round((lowDigit + highDigit) / 2)];
38924
+ if (high !== null && high.length > 1) return prefix + high[0];
38925
+ prefix += POSITION_DIGITS[lowDigit];
38926
+ low = low.slice(1);
38927
+ high = null;
38928
+ }
38929
+ }
38930
+ function positionInteger(length) {
38931
+ return POSITION_DIGITS[length] + POSITION_INTEGER_DIGITS[0].repeat(length);
38932
+ }
38933
+ /**
38934
+ * A key after `before`. Appended keys are integers: a head digit giving the digit count, then that
38935
+ * many base-35 digits, so they grow logarithmically instead of by one character per few appends.
38936
+ * Any key (including one inserted between two integers) appends after the integer it starts with.
38937
+ */
38938
+ function positionAfter(before) {
38939
+ if (!before) return positionInteger(1);
38940
+ const length = POSITION_DIGITS.indexOf(before[0]);
38941
+ const digits = before.slice(1, 1 + length);
38942
+ if (length < 1 || digits.length < length || [...digits].some((digit) => !POSITION_INTEGER_DIGITS.includes(digit))) return length >= 0 && length + 1 < 36 ? positionInteger(length + 1) : positionMidpoint(before, null);
38943
+ const top = POSITION_INTEGER_DIGITS.length - 1;
38944
+ let at = length - 1;
38945
+ while (at >= 0 && digits[at] === POSITION_INTEGER_DIGITS[top]) at--;
38946
+ if (at < 0) return length + 1 < 36 ? positionInteger(length + 1) : positionMidpoint(before, null);
38947
+ const next = POSITION_INTEGER_DIGITS[POSITION_INTEGER_DIGITS.indexOf(digits[at]) + 1];
38948
+ return POSITION_DIGITS[length] + digits.slice(0, at) + next + POSITION_INTEGER_DIGITS[0].repeat(length - at - 1);
38949
+ }
38950
+ /**
38951
+ * A position key strictly between `before` and `after` (either may be absent), for fractional
38952
+ * sibling ordering. Keys are base-36 strings compared by code unit and never end in `0`, so there's
38953
+ * always room between two keys. Appends stay short; prepends (no `before`) still halve toward `0`
38954
+ * and grow by about a character every few calls, so nothing should prepend in a loop.
38955
+ *
38956
+ * @experimental
38957
+ */
38958
+ function knowledgePositionBetween(before, after) {
38959
+ if (before !== void 0 && after !== void 0 && before >= after) throw new Error(`Invalid position range: ${before} >= ${after}`);
38960
+ return after === void 0 ? positionAfter(before ?? "") : positionMidpoint(before ?? "", after);
38961
+ }
38427
38962
  // src/storage/domains/knowledge/base.ts
38428
38963
  /** @experimental Knowledge APIs are experimental and may change without notice. */
38429
38964
  const KNOWLEDGE_STORAGE_CONTRACT_VERSION = 4;
@@ -38482,6 +39017,14 @@ var KnowledgeUnsupportedCapabilityError = class extends Error {
38482
39017
  this.name = "KnowledgeUnsupportedCapabilityError";
38483
39018
  }
38484
39019
  };
39020
+ /** A transaction ran past its `deadlineAt` and was rolled back; nothing in it was applied. Retrying is safe. */
39021
+ var KnowledgeTransactionDeadlineError = class extends Error {
39022
+ retryable = true;
39023
+ constructor(options) {
39024
+ super("The Knowledge transaction ran past its deadline and was rolled back.", options);
39025
+ this.name = "KnowledgeTransactionDeadlineError";
39026
+ }
39027
+ };
38485
39028
  function assertKnowledgeSchemaCompatible(inspection) {
38486
39029
  if (inspection.status === "compatible" || inspection.status === "uninitialized") return;
38487
39030
  if (inspection.status === "incompatible-reset-required") throw new KnowledgeSchemaResetRequiredError(inspection);
@@ -38552,6 +39095,70 @@ var KnowledgeStorage = class extends require_filesystem_versioned.StorageDomain
38552
39095
  supportsExplicitReset: false
38553
39096
  };
38554
39097
  }
39098
+ /**
39099
+ * Runs `operation` against a view of this store whose reads and writes all belong to one
39100
+ * transaction: it commits when `operation` resolves and rolls back when it throws, and no other
39101
+ * connection sees its writes until it commits. A store method that fails inside the view undoes
39102
+ * only its own writes, so the caller can catch it and go on. `transaction` on the view joins the
39103
+ * same transaction the same way. Adapters in the same package can write their own tables through
39104
+ * the view, so they commit with the page writes.
39105
+ *
39106
+ * Calls on this store (not the view) while `operation` runs are outside the transaction. Await
39107
+ * calls on the view one at a time, as on a single connection.
39108
+ *
39109
+ * @experimental
39110
+ */
39111
+ transaction(_operation, _options) {
39112
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("transactions"));
39113
+ }
39114
+ /**
39115
+ * On a {@link transaction} view: locks the pages' rows against other writers until commit. A no-op
39116
+ * on stores whose transactions already exclude every other writer (one write transaction at a
39117
+ * time).
39118
+ *
39119
+ * @experimental
39120
+ */
39121
+ lockPages(_ids) {
39122
+ return Promise.resolve();
39123
+ }
39124
+ /**
39125
+ * On a {@link transaction} view: the ids of the live pages under `rootId` (not the root itself),
39126
+ * locked so no page can be added under, moved out of or removed from that subtree until commit.
39127
+ * A later {@link movePage} of `rootId` in the same transaction moves exactly these pages. Throws
39128
+ * {@link KnowledgeMoveTooLargeError} past {@link MAX_KNOWLEDGE_MOVE_PAGES}. The default walks the
39129
+ * children without locking, which holds on stores whose transactions exclude every other writer.
39130
+ *
39131
+ * @experimental
39132
+ */
39133
+ async lockSubtree(rootId) {
39134
+ const ids = [];
39135
+ const parents = [rootId];
39136
+ while (parents.length) {
39137
+ const parentId = parents.shift();
39138
+ let cursor;
39139
+ do {
39140
+ const page = await this.listChildPages({
39141
+ parentId,
39142
+ read: "all",
39143
+ ...cursor ? { cursor } : {}
39144
+ });
39145
+ for (const child of page.pages) {
39146
+ ids.push(child.id);
39147
+ parents.push(child.id);
39148
+ }
39149
+ if (ids.length >= 500) throw new KnowledgeMoveTooLargeError(rootId, ids.length + 1);
39150
+ cursor = page.nextCursor ?? void 0;
39151
+ } while (cursor);
39152
+ }
39153
+ return ids;
39154
+ }
39155
+ /**
39156
+ * Importer bookkeeping on the same database and namespace as the pages, or undefined when the
39157
+ * adapter has none. On a {@link transaction} view it belongs to that transaction.
39158
+ *
39159
+ * @experimental
39160
+ */
39161
+ get importers() {}
38555
39162
  async inspectSchema() {
38556
39163
  return {
38557
39164
  status: "unavailable",
@@ -38679,307 +39286,340 @@ var KnowledgeStorage = class extends require_filesystem_versioned.StorageDomain
38679
39286
  return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPins"));
38680
39287
  }
38681
39288
  };
38682
- const KNOWLEDGE_TABLE_NAMES = [
38683
- "mastra_knowledge_nodes",
38684
- "mastra_knowledge_records",
38685
- "mastra_knowledge_mentions",
38686
- "mastra_knowledge_activity",
38687
- "mastra_knowledge_semantic_outbox",
38688
- "mastra_knowledge_node_scopes",
38689
- "mastra_knowledge_record_scopes",
38690
- "mastra_knowledge_scope_grants",
38691
- "mastra_knowledge_access_state",
38692
- "mastra_knowledge_scope_addresses",
38693
- "mastra_knowledge_node_addresses",
38694
- "mastra_knowledge_import_state",
38695
- "mastra_knowledge_import_runs",
38696
- "mastra_knowledge_proposals"
38697
- ];
38698
- /** Knowledge v1 tables with no v2 equivalent; an explicit schema reset drops them. */
38699
- const RETIRED_KNOWLEDGE_TABLE_NAMES = ["mastra_knowledge_cursors"];
38700
- const KNOWLEDGE_PAGES_TABLE_NAMES = [
38701
- "mastra_knowledge_pages",
38702
- "mastra_knowledge_notes",
38703
- "mastra_knowledge_note_stamps",
38704
- "mastra_knowledge_mentions",
38705
- "mastra_knowledge_pins",
38706
- "mastra_knowledge_activity",
38707
- "mastra_knowledge_access_state"
38708
- ];
38709
- [.../* @__PURE__ */ new Set([
38710
- ...KNOWLEDGE_PAGES_TABLE_NAMES,
38711
- ...KNOWLEDGE_TABLE_NAMES,
38712
- ...RETIRED_KNOWLEDGE_TABLE_NAMES
38713
- ])];
38714
- new Set([...KNOWLEDGE_TABLE_NAMES, ...RETIRED_KNOWLEDGE_TABLE_NAMES].filter((name) => !KNOWLEDGE_PAGES_TABLE_NAMES.includes(name)));
38715
- KNOWLEDGE_TABLE_NAMES.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
38716
- /**
38717
- * Keyword-search words: the query split on whitespace, lowercased, deduplicated, keeping the first
38718
- * {@link KNOWLEDGE_SEARCH_MAX_WORDS}. A hit needs at least one of them (as a case-insensitive
38719
- * substring); an empty list means the search returns nothing.
38720
- */
38721
- function knowledgeSearchWords(query) {
38722
- return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))].slice(0, 16);
38723
- }
38724
- /**
38725
- * Points one matched search word earns on a page, by the best field it appears in: name, then
38726
- * description, then body. A page whose name contains the whole query ranks first; below that, pages
38727
- * rank by how many query words they match, and these points only break ties between pages that
38728
- * match the same number of words.
38729
- */
38730
- const KNOWLEDGE_SEARCH_WEIGHTS = {
38731
- name: 3,
38732
- description: 2,
38733
- body: 1
39289
+ // src/storage/domains/knowledge/importers.ts
39290
+ /** A binding was registered again with a different importer or target. */
39291
+ var KnowledgeImporterBindingConflictError = class extends Error {
39292
+ bindingId;
39293
+ constructor(bindingId) {
39294
+ super(`Knowledge importer binding ${bindingId} already exists with a different importer or target`);
39295
+ this.bindingId = bindingId;
39296
+ this.name = "KnowledgeImporterBindingConflictError";
39297
+ }
38734
39298
  };
38735
- /**
38736
- * Why `key` can't be a Knowledge page key, or undefined when it can. Keys are one path segment:
38737
- * non-empty, with no `/` (path separator), `#` (scope/path separator) or `%` (escape character).
38738
- */
38739
- function knowledgePageKeyProblem(key) {
38740
- if (!key) return "Knowledge page key must not be empty";
38741
- if (/[/#%]/.test(key)) return `Knowledge page key "${key}" must not contain "/", "#" or "%"`;
38742
- }
38743
- // src/storage/domains/knowledge/pages.ts
38744
- /**
38745
- * Knowledge storage contract, schema 4: pages, notes, stamps, mentions, body links and pins.
38746
- *
38747
- * The store holds structure and filters by a read scope that core computes from the run's scopes and
38748
- * the Knowledge declarations; it holds no access policy of its own (no grant rows, no roles). Core
38749
- * checks roles before every write, and resolves every write target through the run's read scope first,
38750
- * so a page or note the run can't read behaves exactly like a missing id.
38751
- *
38752
- * Every adapter must implement these semantics; the physical layout (tables, columns, denormalized
38753
- * filter columns, how a large read scope is passed to the database) is the adapter's choice. Any
38754
- * denormalized scope column (a note's page scope, its stamp scopes' addresses, its mentions' home
38755
- * scopes) must be updated in the same transaction as the move or merge that changes it.
38756
- *
38757
- * The body-link table came after schema 4 shipped and is additive: adapters create it with idempotent
38758
- * DDL in `init()` (as the pin-audience index was), without a schema version change, so existing
38759
- * stores keep their data. Links for pages written before it fill in on `knowledge.reindexLinks()` or the
38760
- * page's next write.
38761
- *
38762
- * @experimental Knowledge APIs are experimental and may change without notice.
38763
- */
38764
- /** Most levels a pinned listing walks below its page. @experimental */
38765
- const MAX_KNOWLEDGE_PIN_LIST_DEPTH = 3;
38766
- /**
38767
- * The depth a pin of `kind` stores: undefined for `page` pins, `depth` (default 1) for `list` pins.
38768
- * Throws when a `list` depth isn't a whole number from 1 to {@link MAX_KNOWLEDGE_PIN_LIST_DEPTH}.
38769
- *
38770
- * @experimental
38771
- */
38772
- function knowledgePinDepth(kind, depth) {
38773
- if (kind === "page") return void 0;
38774
- const value = depth ?? 1;
38775
- if (!Number.isInteger(value) || value < 1 || value > 3) throw new Error(`A Knowledge list pin's depth must be a whole number from 1 to 3`);
38776
- return value;
38777
- }
38778
- /**
38779
- * The key a `[[ref]]` is matched by when core looks for links a new or moved page now resolves:
38780
- * `scope#key/key` refs as written (trimmed), every other ref (id, address, name) by
38781
- * {@link canonicalKnowledgeName}. Core computes both sides with this function; a key collision only
38782
- * makes core re-resolve a source page, never links it wrongly.
38783
- *
38784
- * @experimental
38785
- */
38786
- function knowledgeLinkRefKey(ref) {
38787
- const trimmed = ref.trim();
38788
- return trimmed.includes("#") ? trimmed : canonicalKnowledgeName(trimmed);
38789
- }
38790
- /**
38791
- * Most levels an ordinary page may sit below its home scope page: a page directly under its scope
38792
- * is depth 1. Scope pages (including scopes nested under scopes by `belongsTo` or as template
38793
- * children) don't count and reset the count. Creates and moves past it are refused.
38794
- *
38795
- * @experimental
38796
- */
38797
- const MAX_KNOWLEDGE_PAGE_DEPTH = 10;
38798
- /**
38799
- * Most pages one move may carry (the page and everything under it). Larger moves are refused with
38800
- * {@link KnowledgeMoveTooLargeError} instead of running in the background.
38801
- *
38802
- * @experimental
38803
- */
38804
- const MAX_KNOWLEDGE_MOVE_PAGES = 500;
38805
- /** @experimental */
38806
- const MAX_KNOWLEDGE_PAGE_LIST_LIMIT = 100;
38807
- /** Most edges one {@link KnowledgePageStore.listPageLinks} call returns. @experimental */
38808
- const MAX_KNOWLEDGE_PAGE_LINKS = 1e4;
38809
- /** Distinct `[[refs]]` core indexes per page body; further refs stay plain text. @experimental */
38810
- const MAX_KNOWLEDGE_PAGE_BODY_LINKS = 1e3;
38811
- /** Longest body-link ref key core stores; a longer `[[ref]]` stays plain text. Stores may size the column to it. @experimental */
38812
- const MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH = 512;
38813
- /**
38814
- * Maximum page description in estimated tokens (tokenx), enforced by every adapter on create and
38815
- * update.
38816
- *
38817
- * @experimental
38818
- */
38819
- const MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS = 100;
38820
- /**
38821
- * Maximum note text in estimated tokens (tokenx), enforced by every adapter on add. Long-form text
38822
- * belongs in a page body.
38823
- *
38824
- * @experimental
38825
- */
38826
- const MAX_KNOWLEDGE_NOTE_TOKENS = 250;
38827
- /**
38828
- * Rejects a page description over {@link MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS} before any write.
38829
- * Every adapter calls this so all stores share one estimator and one error.
38830
- *
38831
- * @experimental
38832
- */
38833
- function assertKnowledgePageDescriptionWithinBound(description) {
38834
- if (description === void 0) return;
38835
- if (require_workspace.estimateTokenCount(description) > 100) throw new Error(`Knowledge page description exceeds the 100 token limit; put long-form text in the page body`);
38836
- }
38837
- /**
38838
- * Rejects note text over {@link MAX_KNOWLEDGE_NOTE_TOKENS} before any write.
38839
- *
38840
- * @experimental
38841
- */
38842
- function assertKnowledgeNoteTextWithinBound(text) {
38843
- if (require_workspace.estimateTokenCount(text) > 250) throw new Error(`Knowledge note text exceeds the 250 token limit; split it into separate notes or put long-form text in the page body`);
38844
- }
38845
- /** @experimental */
38846
- var KnowledgeMoveTooLargeError = class extends Error {
38847
- pageId;
38848
- pages;
38849
- constructor(pageId, pages) {
38850
- super(`Moving page ${pageId} would move ${pages} pages; at most 500 move at once. Move smaller subtrees one at a time.`);
38851
- this.pageId = pageId;
38852
- this.pages = pages;
38853
- this.name = "KnowledgeMoveTooLargeError";
39299
+ /** A conditional run write found the run in another state (see each method). */
39300
+ var KnowledgeImporterRunStateError = class extends Error {
39301
+ runId;
39302
+ reason;
39303
+ constructor(runId, reason) {
39304
+ super(`Knowledge importer run ${runId} refused the write: ${reason}`);
39305
+ this.runId = runId;
39306
+ this.reason = reason;
39307
+ this.name = "KnowledgeImporterRunStateError";
38854
39308
  }
38855
39309
  };
38856
39310
  /** @experimental */
38857
- var KnowledgePageDepthError = class extends Error {
38858
- constructor(pageId) {
38859
- super(`Page ${pageId} would sit more than 10 levels below its home scope.`);
38860
- this.name = "KnowledgePageDepthError";
39311
+ var KnowledgeImportersStorage = class {
39312
+ /**
39313
+ * The store's clock, which every run timestamp it writes (`startedAt`, `heartbeatAt`) comes from:
39314
+ * a host compares leases against it rather than its own clock. Defaults to this process's clock,
39315
+ * which is the store's own for an in-process store.
39316
+ */
39317
+ async now() {
39318
+ return /* @__PURE__ */ new Date();
38861
39319
  }
38862
39320
  };
39321
+ // src/storage/domains/knowledge/importers-inmemory.ts
39322
+ const empty = () => ({
39323
+ bindings: /* @__PURE__ */ new Map(),
39324
+ nodes: /* @__PURE__ */ new Map(),
39325
+ state: /* @__PURE__ */ new Map(),
39326
+ runs: /* @__PURE__ */ new Map(),
39327
+ flushes: /* @__PURE__ */ new Map(),
39328
+ changes: /* @__PURE__ */ new Map(),
39329
+ guard: {
39330
+ activePath: "new",
39331
+ generation: 1,
39332
+ firstWriteAt: null
39333
+ },
39334
+ order: 0
39335
+ });
39336
+ const key = (...parts) => JSON.stringify(parts);
38863
39337
  /**
38864
- * Splits a page reference `<scope>#<key>[/<key>…]` into the scope address and the key path, or
38865
- * returns null when it isn't one (no scope, an empty or invalid key segment, a second `#`).
38866
- * @experimental
38867
- */
38868
- function parseKnowledgePageRef(ref) {
38869
- const hash = ref.indexOf("#");
38870
- if (hash <= 0) return null;
38871
- const path = knowledgePagePath(ref.slice(hash + 1));
38872
- if (path.length === 0 || path.some((key) => knowledgePageKeyProblem(key))) return null;
38873
- return {
38874
- scope: ref.slice(0, hash),
38875
- path
38876
- };
38877
- }
38878
- /**
38879
- * The keys of a key path. Empty segments are dropped, so a leading, trailing or doubled `/`
38880
- * (`guides/`, `/guides`, `guides//cli`) names the same page as the clean path.
38881
- * @experimental
39338
+ * UTF-8 byte order, the order PostgreSQL's `COLLATE "C"` and SQLite's BINARY give. Code point order
39339
+ * is the same thing; JavaScript's `<` compares UTF-16 code units, which puts characters above U+FFFF
39340
+ * (surrogate pairs) before U+E000–U+FFFF.
38882
39341
  */
38883
- function knowledgePagePath(path) {
38884
- return path.split("/").filter((key) => key !== "");
38885
- }
38886
- /** @experimental */
38887
- var KnowledgePageKeyConflictError = class extends Error {
38888
- key;
38889
- parentId;
38890
- constructor(key, parentId) {
38891
- super(`Knowledge page key "${key}" already exists under page ${parentId}. Keys are unique among siblings; pick another key or move one of the pages.`);
38892
- this.key = key;
38893
- this.parentId = parentId;
38894
- this.name = "KnowledgePageKeyConflictError";
39342
+ const byteOrder = (a, b) => {
39343
+ for (let i = 0, j = 0; i < a.length && j < b.length;) {
39344
+ const x = a.codePointAt(i);
39345
+ const y = b.codePointAt(j);
39346
+ if (x !== y) return x < y ? -1 : 1;
39347
+ i += x > 65535 ? 2 : 1;
39348
+ j += y > 65535 ? 2 : 1;
38895
39349
  }
39350
+ return a.length === b.length ? 0 : a.length < b.length ? -1 : 1;
38896
39351
  };
38897
- /** @experimental */
38898
- var KnowledgePageHasChildrenError = class extends Error {
38899
- constructor(pageId) {
38900
- super(`Page ${pageId} has child pages. Move or delete them first.`);
38901
- this.name = "KnowledgePageHasChildrenError";
38902
- }
38903
- };
38904
- /**
38905
- * Canonical form used for exact-name lookup. Computed in JS so every adapter (and SQL collations)
38906
- * agree on non-ASCII names; adapters store it rather than computing `lower()` in SQL.
38907
- *
38908
- * @experimental
38909
- */
38910
- function canonicalKnowledgeName(name) {
38911
- return name.normalize("NFKC").trim().replace(/\s+/g, " ").toLowerCase();
39352
+ function addCounts(into, add) {
39353
+ const out = { ...into };
39354
+ for (const [name, value] of Object.entries(add)) out[name] = (out[name] ?? 0) + value;
39355
+ return out;
38912
39356
  }
38913
39357
  /**
38914
- * Whether a scope page is readable under `read`. Adapters that filter in memory use this; SQL
38915
- * adapters must match it exactly.
38916
- *
38917
- * @experimental
39358
+ * In-memory importer bookkeeping. One process, no locks: the owning store runs transactions one at
39359
+ * a time and rolls them back by restoring {@link snapshot}.
38918
39360
  */
38919
- function knowledgeScopeReadable(scope, read) {
38920
- if (read === "all") return true;
38921
- const { address, declaration, parentId } = scope;
38922
- if (!address) return false;
38923
- if (read.addresses.includes(address)) return true;
38924
- if (read.prefixes.some((entry) => entry.declaration === declaration && address.startsWith(entry.prefix))) return true;
38925
- return read.children.some((entry) => entry.declaration === declaration && entry.parentId === parentId);
38926
- }
38927
- const POSITION_DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz";
38928
- /** Digits of an appended key's integer part: base 35, no `0`, so the key never ends in `0`. */
38929
- const POSITION_INTEGER_DIGITS = POSITION_DIGITS.slice(1);
38930
- function positionMidpoint(low, high) {
38931
- let prefix = "";
38932
- for (;;) {
38933
- if (high !== null) {
38934
- let common = 0;
38935
- while ((low[common] ?? "0") === high[common]) common++;
38936
- if (common > 0) {
38937
- prefix += high.slice(0, common);
38938
- low = low.slice(common);
38939
- high = high.slice(common);
38940
- }
39361
+ var InMemoryKnowledgeImportersStorage = class extends KnowledgeImportersStorage {
39362
+ #s = empty();
39363
+ snapshot() {
39364
+ return structuredClone(this.#s);
39365
+ }
39366
+ restore(state) {
39367
+ this.#s = state;
39368
+ }
39369
+ async init() {}
39370
+ async dangerouslyClearAll() {
39371
+ this.#s = empty();
39372
+ }
39373
+ /** Part of the Knowledge store's reset: empties everything and moves the generation forward. */
39374
+ clearOnReset() {
39375
+ const { activePath, generation } = this.#s.guard;
39376
+ this.#s = empty();
39377
+ this.#s.guard = {
39378
+ activePath,
39379
+ generation: generation + 1,
39380
+ firstWriteAt: null
39381
+ };
39382
+ }
39383
+ async registerBinding(input) {
39384
+ const existing = this.#s.bindings.get(input.id);
39385
+ if (existing) {
39386
+ if (existing.importer !== input.importer || existing.target !== input.target) throw new KnowledgeImporterBindingConflictError(input.id);
39387
+ return {
39388
+ status: "unchanged",
39389
+ binding: { ...existing }
39390
+ };
38941
39391
  }
38942
- const lowDigit = low ? POSITION_DIGITS.indexOf(low[0]) : 0;
38943
- const highDigit = high !== null ? POSITION_DIGITS.indexOf(high[0]) : 36;
38944
- if (highDigit - lowDigit > 1) return prefix + POSITION_DIGITS[Math.round((lowDigit + highDigit) / 2)];
38945
- if (high !== null && high.length > 1) return prefix + high[0];
38946
- prefix += POSITION_DIGITS[lowDigit];
38947
- low = low.slice(1);
38948
- high = null;
39392
+ const binding = {
39393
+ ...input,
39394
+ anchorPageId: null,
39395
+ createdAt: /* @__PURE__ */ new Date()
39396
+ };
39397
+ this.#s.bindings.set(input.id, binding);
39398
+ return {
39399
+ status: "created",
39400
+ binding: { ...binding }
39401
+ };
38949
39402
  }
38950
- }
38951
- function positionInteger(length) {
38952
- return POSITION_DIGITS[length] + POSITION_INTEGER_DIGITS[0].repeat(length);
38953
- }
38954
- /**
38955
- * A key after `before`. Appended keys are integers: a head digit giving the digit count, then that
38956
- * many base-35 digits, so they grow logarithmically instead of by one character per few appends.
38957
- * Any key (including one inserted between two integers) appends after the integer it starts with.
38958
- */
38959
- function positionAfter(before) {
38960
- if (!before) return positionInteger(1);
38961
- const length = POSITION_DIGITS.indexOf(before[0]);
38962
- const digits = before.slice(1, 1 + length);
38963
- if (length < 1 || digits.length < length || [...digits].some((digit) => !POSITION_INTEGER_DIGITS.includes(digit))) return length >= 0 && length + 1 < 36 ? positionInteger(length + 1) : positionMidpoint(before, null);
38964
- const top = POSITION_INTEGER_DIGITS.length - 1;
38965
- let at = length - 1;
38966
- while (at >= 0 && digits[at] === POSITION_INTEGER_DIGITS[top]) at--;
38967
- if (at < 0) return length + 1 < 36 ? positionInteger(length + 1) : positionMidpoint(before, null);
38968
- const next = POSITION_INTEGER_DIGITS[POSITION_INTEGER_DIGITS.indexOf(digits[at]) + 1];
38969
- return POSITION_DIGITS[length] + digits.slice(0, at) + next + POSITION_INTEGER_DIGITS[0].repeat(length - at - 1);
38970
- }
38971
- /**
38972
- * A position key strictly between `before` and `after` (either may be absent), for fractional
38973
- * sibling ordering. Keys are base-36 strings compared by code unit and never end in `0`, so there's
38974
- * always room between two keys. Appends stay short; prepends (no `before`) still halve toward `0`
38975
- * and grow by about a character every few calls, so nothing should prepend in a loop.
38976
- *
38977
- * @experimental
38978
- */
38979
- function knowledgePositionBetween(before, after) {
38980
- if (before !== void 0 && after !== void 0 && before >= after) throw new Error(`Invalid position range: ${before} >= ${after}`);
38981
- return after === void 0 ? positionAfter(before ?? "") : positionMidpoint(before ?? "", after);
38982
- }
39403
+ async getBinding(id) {
39404
+ const binding = this.#s.bindings.get(id);
39405
+ return binding ? { ...binding } : null;
39406
+ }
39407
+ async setBindingAnchor(input) {
39408
+ const binding = this.#s.bindings.get(input.bindingId);
39409
+ if (!binding || binding.anchorPageId !== input.expected) return false;
39410
+ binding.anchorPageId = input.pageId;
39411
+ return true;
39412
+ }
39413
+ async listBindings() {
39414
+ return [...this.#s.bindings.values()].sort((a, b) => byteOrder(a.id, b.id)).map((b) => ({ ...b }));
39415
+ }
39416
+ async retireBinding(id) {
39417
+ this.#s.bindings.delete(id);
39418
+ for (const [k, node] of this.#s.nodes) if (node.bindingId === id) this.#s.nodes.delete(k);
39419
+ this.#s.state.delete(id);
39420
+ const runs = /* @__PURE__ */ new Set();
39421
+ for (const [runId, run] of this.#s.runs) {
39422
+ if (run.bindingId !== id) continue;
39423
+ runs.add(runId);
39424
+ this.#s.runs.delete(runId);
39425
+ }
39426
+ for (const [k, flush] of this.#s.flushes) if (runs.has(flush.runId)) this.#s.flushes.delete(k);
39427
+ for (const [k, { change }] of this.#s.changes) if (runs.has(change.runId)) this.#s.changes.delete(k);
39428
+ }
39429
+ async startRun(input) {
39430
+ const runs = [...this.#s.runs.values()].filter((r) => r.bindingId === input.bindingId);
39431
+ if (input.fireKey) {
39432
+ const fired = runs.find((r) => r.fireKey === input.fireKey);
39433
+ if (fired) return {
39434
+ status: "duplicate",
39435
+ run: structuredClone(fired)
39436
+ };
39437
+ }
39438
+ const running = runs.some((r) => r.status === "running");
39439
+ const now = /* @__PURE__ */ new Date();
39440
+ const run = {
39441
+ id: input.runId,
39442
+ bindingId: input.bindingId,
39443
+ generation: input.generation,
39444
+ status: running ? "skipped" : "running",
39445
+ fireKey: input.fireKey ?? null,
39446
+ deadlineAt: input.deadlineAt ?? null,
39447
+ cancelRequestedAt: null,
39448
+ heartbeatAt: null,
39449
+ lastSeq: 0,
39450
+ finish: null,
39451
+ counts: {},
39452
+ startedAt: now,
39453
+ completedAt: running ? now : null
39454
+ };
39455
+ this.#s.runs.set(run.id, run);
39456
+ return {
39457
+ status: running ? "skipped" : "started",
39458
+ run: structuredClone(run)
39459
+ };
39460
+ }
39461
+ async getRun(runId) {
39462
+ const run = this.#s.runs.get(runId);
39463
+ return run ? structuredClone(run) : null;
39464
+ }
39465
+ async listRuns(bindingId, options = {}) {
39466
+ return [...this.#s.runs.values()].filter((r) => r.bindingId === bindingId).sort((a, b) => b.startedAt.getTime() - a.startedAt.getTime()).slice(0, options.limit ?? 50).map((r) => structuredClone(r));
39467
+ }
39468
+ async requestCancel(runId) {
39469
+ const run = this.#s.runs.get(runId);
39470
+ if (!run || run.status !== "running") return null;
39471
+ run.cancelRequestedAt ??= /* @__PURE__ */ new Date();
39472
+ return structuredClone(run);
39473
+ }
39474
+ async heartbeat(runId) {
39475
+ const run = this.#s.runs.get(runId);
39476
+ if (!run || run.status !== "running") return null;
39477
+ run.heartbeatAt = /* @__PURE__ */ new Date();
39478
+ return structuredClone(run);
39479
+ }
39480
+ async abandonRun(input) {
39481
+ const run = this.#s.runs.get(input.runId);
39482
+ if (!run || run.status !== "running") return null;
39483
+ run.status = input.status ?? "failed";
39484
+ run.finish = structuredClone(input.finish);
39485
+ run.completedAt = /* @__PURE__ */ new Date();
39486
+ return structuredClone(run);
39487
+ }
39488
+ /** Transactions run one at a time in memory, so a read is as good as a lock. */
39489
+ async lockRun(runId) {
39490
+ return this.getRun(runId);
39491
+ }
39492
+ #activeRun(runId, generation) {
39493
+ const run = this.#s.runs.get(runId);
39494
+ if (!run) throw new KnowledgeImporterRunStateError(runId, "not_found");
39495
+ if (run.status !== "running") throw new KnowledgeImporterRunStateError(runId, "not_running");
39496
+ if (run.generation !== generation) throw new KnowledgeImporterRunStateError(runId, "generation");
39497
+ if (this.#s.guard.generation !== generation) throw new KnowledgeImporterRunStateError(runId, "stale_guard");
39498
+ return run;
39499
+ }
39500
+ async getFlush(runId, generation, seq) {
39501
+ const flush = this.#s.flushes.get(key(runId, generation, seq));
39502
+ return flush ? structuredClone(flush) : null;
39503
+ }
39504
+ async recordFlush(input) {
39505
+ const run = this.#activeRun(input.runId, input.generation);
39506
+ if (run.lastSeq !== input.seq - 1) throw new KnowledgeImporterRunStateError(input.runId, "seq");
39507
+ const { counts, ...flush } = input;
39508
+ this.#s.flushes.set(key(input.runId, input.generation, input.seq), structuredClone(flush));
39509
+ run.lastSeq = input.seq;
39510
+ run.counts = addCounts(run.counts, counts);
39511
+ }
39512
+ async finishRun(input) {
39513
+ const run = this.#activeRun(input.runId, input.generation);
39514
+ if (run.lastSeq !== input.lastSeq) throw new KnowledgeImporterRunStateError(input.runId, "seq");
39515
+ run.status = input.status;
39516
+ run.finish = structuredClone(input.finish);
39517
+ run.completedAt = /* @__PURE__ */ new Date();
39518
+ return structuredClone(run);
39519
+ }
39520
+ async getNode(bindingId, sourceId) {
39521
+ const node = this.#s.nodes.get(key(bindingId, sourceId));
39522
+ return node ? structuredClone(node) : null;
39523
+ }
39524
+ async getNodeByPage(pageId) {
39525
+ const node = [...this.#s.nodes.values()].find((n) => n.pageId === pageId);
39526
+ return node ? structuredClone(node) : null;
39527
+ }
39528
+ async saveNode(node) {
39529
+ const owner = [...this.#s.nodes.values()].find((n) => n.pageId === node.pageId);
39530
+ if (owner && (owner.bindingId !== node.bindingId || owner.sourceId !== node.sourceId)) throw new Error(`Knowledge page ${node.pageId} is already mapped to another imported node`);
39531
+ this.#s.nodes.set(key(node.bindingId, node.sourceId), structuredClone({
39532
+ ...node,
39533
+ updatedAt: /* @__PURE__ */ new Date()
39534
+ }));
39535
+ }
39536
+ async deleteNode(bindingId, sourceId) {
39537
+ this.#s.nodes.delete(key(bindingId, sourceId));
39538
+ }
39539
+ async listNodes(bindingId, options = {}) {
39540
+ const limit = options.limit ?? 500;
39541
+ const nodes = [...this.#s.nodes.values()].filter((n) => n.bindingId === bindingId && (options.after === void 0 || byteOrder(n.sourceId, options.after) > 0) && (!options.unsettled || n.unsettled)).sort((a, b) => byteOrder(a.sourceId, b.sourceId));
39542
+ const items = nodes.slice(0, limit).map((n) => structuredClone(n));
39543
+ return {
39544
+ items,
39545
+ next: nodes.length > limit ? items[items.length - 1].sourceId : null
39546
+ };
39547
+ }
39548
+ #linking(bindingId, targetSourceIds) {
39549
+ const targets = new Set(targetSourceIds);
39550
+ return [...this.#s.nodes.values()].filter((n) => n.bindingId === bindingId && n.links.some((link) => targets.has(link.sourceId)));
39551
+ }
39552
+ async listLinkingNodes(bindingId, targetSourceIds, options = {}) {
39553
+ const limit = options.limit ?? 500;
39554
+ const ids = this.#linking(bindingId, targetSourceIds).map((n) => n.sourceId).filter((id) => options.after === void 0 || byteOrder(id, options.after) > 0).sort(byteOrder);
39555
+ const items = ids.slice(0, limit);
39556
+ return {
39557
+ items,
39558
+ next: ids.length > limit ? items[items.length - 1] : null
39559
+ };
39560
+ }
39561
+ async markLinkingNodesUnsettled(bindingId, targetSourceIds) {
39562
+ for (const n of this.#linking(bindingId, targetSourceIds)) n.unsettled = true;
39563
+ }
39564
+ async findNodeByAlias(bindingId, alias) {
39565
+ const node = [...this.#s.nodes.values()].find((n) => n.bindingId === bindingId && n.aliases.includes(alias));
39566
+ return node ? structuredClone(node) : null;
39567
+ }
39568
+ async getState(bindingId) {
39569
+ const out = {};
39570
+ for (const [name, value] of this.#s.state.get(bindingId) ?? []) Object.defineProperty(out, name, {
39571
+ value,
39572
+ enumerable: true,
39573
+ writable: true,
39574
+ configurable: true
39575
+ });
39576
+ return out;
39577
+ }
39578
+ async setState(bindingId, state) {
39579
+ const stored = this.#s.state.get(bindingId) ?? /* @__PURE__ */ new Map();
39580
+ for (const name of Object.keys(state)) stored.set(name, state[name]);
39581
+ this.#s.state.set(bindingId, stored);
39582
+ }
39583
+ async recordRunChange(change) {
39584
+ const id = key(change.runId, change.sourceId);
39585
+ const order = this.#s.changes.get(id)?.order ?? ++this.#s.order;
39586
+ this.#s.changes.set(id, {
39587
+ order,
39588
+ change: structuredClone(change)
39589
+ });
39590
+ }
39591
+ async listRunChanges(runId, options = {}) {
39592
+ const limit = options.limit ?? 500;
39593
+ const after = options.after === void 0 ? 0 : Number(options.after);
39594
+ const rows = [...this.#s.changes.values()].filter((c) => c.change.runId === runId && c.order > after).sort((a, b) => a.order - b.order);
39595
+ const page = rows.slice(0, limit);
39596
+ return {
39597
+ items: page.map((c) => structuredClone(c.change)),
39598
+ next: rows.length > limit ? String(page[page.length - 1].order) : null
39599
+ };
39600
+ }
39601
+ async readWriterGuard() {
39602
+ return { ...this.#s.guard };
39603
+ }
39604
+ async lockWriterGuard(_mode) {
39605
+ return { ...this.#s.guard };
39606
+ }
39607
+ /** Transactions are serialized here, so holding one is the lock. */
39608
+ async markFirstWrite() {
39609
+ if (this.#s.guard.firstWriteAt) return false;
39610
+ this.#s.guard.firstWriteAt = /* @__PURE__ */ new Date();
39611
+ return true;
39612
+ }
39613
+ async advanceWriterGuard(input) {
39614
+ if (input.generation <= this.#s.guard.generation) throw new Error(`Knowledge importer writer generation must move forward (${this.#s.guard.generation} -> ${input.generation})`);
39615
+ this.#s.guard = {
39616
+ activePath: input.activePath,
39617
+ generation: input.generation,
39618
+ firstWriteAt: null
39619
+ };
39620
+ return { ...this.#s.guard };
39621
+ }
39622
+ };
38983
39623
  // src/storage/domains/knowledge/pages-inmemory.ts
38984
39624
  const DEFAULT_SEARCH_LIMIT = 20;
38985
39625
  function pageSize(limit) {
@@ -38988,8 +39628,9 @@ function pageSize(limit) {
38988
39628
  return Math.min(limit, 100);
38989
39629
  }
38990
39630
  function paginate(items, cursor, limit) {
39631
+ if (cursor !== void 0 && !/^(0|[1-9]\d*)$/.test(cursor)) throw new KnowledgeInvalidCursorError(cursor);
38991
39632
  const start = cursor === void 0 ? 0 : Number(cursor);
38992
- if (!Number.isInteger(start) || start < 0) throw new RangeError(`Invalid Knowledge cursor: ${cursor}`);
39633
+ if (!Number.isSafeInteger(start)) throw new KnowledgeInvalidCursorError(String(cursor));
38993
39634
  const size = pageSize(limit);
38994
39635
  return {
38995
39636
  items: items.slice(start, start + size),
@@ -39004,12 +39645,6 @@ const oldestFirst = (a, b) => newestFirst(b, a);
39004
39645
  const clone$1 = (value) => structuredClone(value);
39005
39646
  const PIN_KINDS = ["page", "list"];
39006
39647
  const pinKey = (pageId, kind) => `${kind}:${pageId}`;
39007
- /**
39008
- * In-memory schema-4 page store: the reference implementation of {@link KnowledgePageStore} that the
39009
- * shared contract suite checks every adapter against.
39010
- *
39011
- * @experimental
39012
- */
39013
39648
  var InMemoryKnowledgePageStore = class {
39014
39649
  #pages = /* @__PURE__ */ new Map();
39015
39650
  #notes = /* @__PURE__ */ new Map();
@@ -39017,6 +39652,25 @@ var InMemoryKnowledgePageStore = class {
39017
39652
  #activity = [];
39018
39653
  #bodyLinks = /* @__PURE__ */ new Map();
39019
39654
  #clock = 0;
39655
+ /** A deep copy of every page, note, pin, body link and event, for {@link restore}. */
39656
+ snapshot() {
39657
+ return structuredClone({
39658
+ pages: this.#pages,
39659
+ notes: this.#notes,
39660
+ pins: this.#pins,
39661
+ activity: this.#activity,
39662
+ bodyLinks: this.#bodyLinks
39663
+ });
39664
+ }
39665
+ /** Puts back what {@link snapshot} copied. */
39666
+ restore(snapshot) {
39667
+ const copy = structuredClone(snapshot);
39668
+ this.#pages = copy.pages;
39669
+ this.#notes = copy.notes;
39670
+ this.#pins = copy.pins;
39671
+ this.#activity = copy.activity;
39672
+ this.#bodyLinks = copy.bodyLinks;
39673
+ }
39020
39674
  /** Drops every page, note, pin, body link and event. */
39021
39675
  clear() {
39022
39676
  this.#pages.clear();
@@ -39625,6 +40279,7 @@ var InMemoryKnowledgePageStore = class {
39625
40279
  }))].slice(0, limit);
39626
40280
  }
39627
40281
  async listPageActivity(input) {
40282
+ if (input.before !== void 0 && input.cursor !== void 0) throw new RangeError("Knowledge activity takes either a cursor or a before position, not both");
39628
40283
  const { items, nextCursor } = paginate(this.#activity.filter((event) => {
39629
40284
  const page = this.#pages.get(event.pageId);
39630
40285
  if (!page || !this.#pageReadable(page, input.read)) return false;
@@ -39634,6 +40289,9 @@ var InMemoryKnowledgePageStore = class {
39634
40289
  const note = this.#notes.get(event.noteId);
39635
40290
  if (!note || !this.#noteVisible(note, input.read)) return false;
39636
40291
  }
40292
+ if (input.since !== void 0 && event.createdAt.getTime() < input.since.getTime()) return false;
40293
+ if (input.until !== void 0 && event.createdAt.getTime() >= input.until.getTime()) return false;
40294
+ if (input.before !== void 0 && newestFirst(event, input.before) <= 0) return false;
39637
40295
  return true;
39638
40296
  }).sort(newestFirst), input.cursor, input.limit);
39639
40297
  return {
@@ -39713,6 +40371,10 @@ var InMemoryKnowledgePageStore = class {
39713
40371
  // src/storage/domains/knowledge/inmemory.ts
39714
40372
  var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
39715
40373
  #pageStore = new InMemoryKnowledgePageStore();
40374
+ #importers = new InMemoryKnowledgeImportersStorage();
40375
+ get importers() {
40376
+ return this.#importers;
40377
+ }
39716
40378
  materializeScope(input) {
39717
40379
  return this.#pageStore.materializeScope(input);
39718
40380
  }
@@ -39818,16 +40480,50 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
39818
40480
  listPins(input) {
39819
40481
  return this.#pageStore.listPins(input);
39820
40482
  }
40483
+ #transactionTail = Promise.resolve();
39821
40484
  constructor(_config) {
39822
40485
  super();
39823
40486
  }
40487
+ /**
40488
+ * In memory there is no second connection: transactions run one at a time and roll back by
40489
+ * restoring a snapshot of pages and importer rows, and a read on this store (or a write from
40490
+ * outside the transaction) while one runs sees and shares its state: an outside write made during
40491
+ * a transaction that rolls back is rolled back with it. Each store call
40492
+ * on the view, and each nested `transaction`, undoes its own writes when it fails.
40493
+ */
40494
+ transaction(operation) {
40495
+ const run = this.#transactionTail.then(() => this.#savepoint(() => operation(this.#view())));
40496
+ this.#transactionTail = run.catch(() => void 0);
40497
+ return run;
40498
+ }
40499
+ async #savepoint(operation) {
40500
+ const before = this.#pageStore.snapshot();
40501
+ const importersBefore = this.#importers.snapshot();
40502
+ try {
40503
+ return await operation();
40504
+ } catch (error) {
40505
+ this.#pageStore.restore(before);
40506
+ this.#importers.restore(importersBefore);
40507
+ throw error;
40508
+ }
40509
+ }
40510
+ #view() {
40511
+ return new Proxy(this, { get: (target, property, receiver) => {
40512
+ if (property === "transaction") return (operation) => target.#savepoint(() => operation(receiver));
40513
+ const value = Reflect.get(target, property, target);
40514
+ if (typeof value !== "function" || !(property in target.#pageStore)) return value;
40515
+ return (...args) => target.#savepoint(() => value.apply(target, args));
40516
+ } });
40517
+ }
39824
40518
  getCapabilities() {
39825
40519
  return {
39826
40520
  contractVersion: 4,
39827
40521
  schemaVersion: 4,
39828
40522
  supportsSchemaInspection: true,
39829
40523
  supportsExplicitReset: true,
39830
- supportsPinKinds: true
40524
+ supportsPinKinds: true,
40525
+ supportsTransactions: true,
40526
+ supportsActivityDateRange: true
39831
40527
  };
39832
40528
  }
39833
40529
  async inspectSchema() {
@@ -39838,6 +40534,7 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
39838
40534
  }
39839
40535
  async dangerouslyReset() {
39840
40536
  await this.dangerouslyClearAll();
40537
+ this.#importers.clearOnReset();
39841
40538
  }
39842
40539
  async dangerouslyClearAll() {
39843
40540
  this.#pageStore.clear();
@@ -44974,7 +45671,14 @@ var MessageHistory = class {
44974
45671
  const persistenceMessageList = messageList.cloneForPersistence();
44975
45672
  const newInput = persistenceMessageList.get.input.db();
44976
45673
  const newOutput = persistenceMessageList.get.response.db();
44977
- const messagesToSave = persistenceMessageList.transformMessagesForTranscript([...newInput, ...newOutput]);
45674
+ const resaveIds = new Set(persistenceMessageList.getMessagesToResave().map((message) => message.id));
45675
+ const newIds = new Set([...newInput, ...newOutput].map((message) => message.id));
45676
+ const resaved = persistenceMessageList.get.all.db().filter((message) => resaveIds.has(message.id) && !newIds.has(message.id));
45677
+ const messagesToSave = persistenceMessageList.transformMessagesForTranscript([
45678
+ ...newInput,
45679
+ ...newOutput,
45680
+ ...resaved
45681
+ ]);
44978
45682
  if (messagesToSave.length === 0) return messageList;
44979
45683
  this.memorySpan(observabilityContext)?.update({ attributes: { messageCount: messagesToSave.length } });
44980
45684
  await this.persistMessages({
@@ -50870,14 +51574,16 @@ async function storedAttachmentBytes(fs, dir, root = true) {
50870
51574
  return total;
50871
51575
  }
50872
51576
  // src/knowledge/instructions.ts
50873
- const KNOWLEDGE_READ_INSTRUCTIONS = `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, 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.`;
51577
+ function readInstructions(canEdit) {
51578
+ 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.`;
51579
+ }
50874
51580
  const KNOWLEDGE_WRITE_INSTRUCTIONS = `When you write to Knowledge, add one durable fact per note with knowledge_note, on the page it is about. Add notes to an existing page before creating a new one. Put long-form text such as specs and runbooks in a page body with knowledge_page. A body write replaces the whole body. When a read returns only part of a body (numbered lines from a long page, a section, or matches), each part comes with its range: to edit those lines, write the new text, without the line numbers, with that range (or a smaller one inside it) and the version you read, and only those lines are replaced. Never write a partial body back without its range. Write page bodies in markdown (headings, lists, links); notes may use inline markdown such as links and code. Record a change as a new dated note rather than rewriting an old one, and remove only notes that are wrong.`;
50875
51581
  const KNOWLEDGE_PINS_INSTRUCTIONS = `Maintain pinned pages with knowledge_pin (op pin or unpin). Pinned pages are delivered to the main agent on every turn, so they cost tokens permanently and must stay short. Pin only knowledge that should apply without being asked for, such as standing instructions, durable preferences, and hard constraints. Pin only knowledge that is BOTH costly to rediscover AND not the kind of thing a future agent would think to search for; anything a reminder can surface on demand does not belong in the pin set. Unpin a page as soon as it stops being unconditionally true.`;
50876
51582
  function buildKnowledgeInstructions(groups, option) {
50877
51583
  if (option === false) return "";
50878
51584
  if (typeof option === "string") return option;
50879
51585
  const parts = {
50880
- read: groups.read ? KNOWLEDGE_READ_INSTRUCTIONS : "",
51586
+ read: groups.read ? readInstructions(groups.write) : "",
50881
51587
  write: groups.write ? KNOWLEDGE_WRITE_INSTRUCTIONS : "",
50882
51588
  pins: groups.pins ? KNOWLEDGE_PINS_INSTRUCTIONS : ""
50883
51589
  };
@@ -51663,6 +52369,17 @@ async function knowledgeSubtree(storage, root) {
51663
52369
  */
51664
52370
  const MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES = 99;
51665
52371
  /**
52372
+ * A link refresh that landed but stopped at {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES} linking pages
52373
+ * or {@link MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES} namesakes: the rest keep their links until they're
52374
+ * next written or `knowledge.reindexLinks()` runs.
52375
+ */
52376
+ var KnowledgeLinkRefreshIncompleteError = class extends Error {
52377
+ constructor(message) {
52378
+ super(message);
52379
+ this.name = "KnowledgeLinkRefreshIncompleteError";
52380
+ }
52381
+ };
52382
+ /**
51666
52383
  * Re-resolves the pages whose body links one of `pages` or names a ref one of them answers to now,
51667
52384
  * after they were created, renamed, moved, merged or deleted, in page id order up to
51668
52385
  * {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES}. With `withDescendants`, the pages' subtrees count too
@@ -51692,7 +52409,7 @@ async function refreshKnowledgeLinksTo(storage, pages, options = {}) {
51692
52409
  refs: [...refs],
51693
52410
  toPageIds: [...targets]
51694
52411
  })).sort();
51695
- const crowdedError = () => /* @__PURE__ */ new Error(`More than ${MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES} pages are named ${crowded.join(", ")}; links to the rest were left as they were`);
52412
+ const crowdedError = () => new KnowledgeLinkRefreshIncompleteError(`More than ${MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES} pages are named ${crowded.join(", ")}; links to the rest were left as they were`);
51696
52413
  if (!sources.length) {
51697
52414
  if (crowded.length) throw crowdedError();
51698
52415
  return;
@@ -51715,10 +52432,7 @@ async function refreshKnowledgeLinksTo(storage, pages, options = {}) {
51715
52432
  done++;
51716
52433
  }
51717
52434
  const left = sources.length - done;
51718
- if (left > 0) {
51719
- const names = pages.map((page) => `"${page.name}"`).join(", ");
51720
- throw new Error(`${left} more pages link to ${names}; their links were left as they were`);
51721
- }
52435
+ if (left > 0) throw new KnowledgeLinkRefreshIncompleteError(`${left} more pages link to ${pages.map((page) => `"${page.name}"`).join(", ")}; their links were left as they were`);
51722
52436
  if (crowded.length) throw crowdedError();
51723
52437
  }
51724
52438
  /**
@@ -60922,12 +61636,13 @@ async function removeKnowledgePage(host, input) {
60922
61636
  await host.runtime.checkDeclarations();
60923
61637
  const storage = await host.getStorage();
60924
61638
  const [scope] = await storage.getScopesByAddress([input.scope]);
60925
- if (!scope) return null;
60926
- const page = await storage.getPageByPath({
61639
+ const page = scope ? await storage.getPageByPath({
60927
61640
  scopeId: scope.id,
60928
61641
  path: keys,
60929
61642
  read: "all"
60930
- });
61643
+ }) : null;
61644
+ const expected = input.expected;
61645
+ if (expected && (page?.id !== expected.id || page.version !== expected.version)) throw new KnowledgeConflictError(expected.id);
60931
61646
  if (!page) return null;
60932
61647
  const template = await host.runtime.templatePageRef(page);
60933
61648
  if (template) throw new Error(`"${template}" is declared in config; change the scope's pages to remove it.`);
@@ -60939,6 +61654,7 @@ async function removeKnowledgePage(host, input) {
60939
61654
  deletedBy: input.author ?? "host"
60940
61655
  });
60941
61656
  } catch (error) {
61657
+ if (expected && error?.name === "KnowledgeNotFoundError") throw new KnowledgeConflictError(expected.id);
60942
61658
  if (error?.name === "KnowledgePageHasChildrenError") throw new Error(`"${input.scope}#${input.path}" has child pages; remove them first.`);
60943
61659
  throw error;
60944
61660
  }
@@ -61639,7 +62355,7 @@ function bodyView(body, input) {
61639
62355
  const headings = knowledgeBodyOutline(body);
61640
62356
  const skeleton = headings.length ? knowledgeBodySkeleton(lines, headings.map((heading) => heading.line), input.maxTokens) : void 0;
61641
62357
  if (skeleton !== void 0) {
61642
- more.push(`body: the page is ${lines.count} lines, too long to show whole, so \`lines\` shows every heading and the first lines under it; \u22EF marks lines left out and \u2026 a line cut short. Read the part you need with section (a heading) or from (a line number), then answer. To edit, read that part first: this view has no range to write back.`);
62358
+ more.push(`body: the page is ${lines.count} lines, too long to show whole, so \`lines\` shows every heading and the first lines under it; \u22EF marks lines left out and \u2026 a line cut short. Read the part you need with section (a heading) or from (a line number), then answer.${input.canEdit ? " To edit, read that part first: this view has no range to write back." : ""}`);
61643
62359
  return {
61644
62360
  lines: skeleton,
61645
62361
  lineCount: lines.count
@@ -61669,10 +62385,10 @@ function bodyView(body, input) {
61669
62385
  ...outline.length ? { outline } : {}
61670
62386
  };
61671
62387
  }
61672
- function readTool(host) {
62388
+ function readTool(host, canEdit) {
61673
62389
  return require_tool.createTool({
61674
62390
  id: "knowledge_read",
61675
- 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. To edit part of a long body, pass the \`range\` a read gave you to knowledge_page.`,
62391
+ 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." : ""),
61676
62392
  inputSchema: {
61677
62393
  type: "object",
61678
62394
  properties: {
@@ -61769,7 +62485,8 @@ function readTool(host) {
61769
62485
  context: matchContext,
61770
62486
  from,
61771
62487
  more,
61772
- maxTokens: maxTokensOf(host)
62488
+ maxTokens: maxTokensOf(host),
62489
+ canEdit
61773
62490
  });
61774
62491
  return {
61775
62492
  page: {
@@ -61872,7 +62589,8 @@ function readTool(host) {
61872
62589
  const view = bodyView(page.body ?? "", {
61873
62590
  context: matchContext,
61874
62591
  more,
61875
- maxTokens: maxTokensOf(host)
62592
+ maxTokens: maxTokensOf(host),
62593
+ canEdit
61876
62594
  });
61877
62595
  const noteList = await noteSummaries(run, notes.notes, mentionCache);
61878
62596
  const mentionList = (await noteSummaries(run, mentioning.notes, mentionCache)).map((note, i) => ({
@@ -62153,11 +62871,12 @@ const NUMBERED_LINE = /^\s*\d+\u2502/;
62153
62871
  * Without one, a body longer than one read returns is refused: the writer can only have seen part
62154
62872
  * of it, and writing that part back would drop the rest.
62155
62873
  */
62156
- function writtenBody(args, page, maxTokens) {
62874
+ function writtenBody(args, page, maxTokens, canRead) {
62875
+ const read = canRead ? "knowledge_read" : "read";
62157
62876
  const stored = page.body ?? "";
62158
62877
  if (args.body !== void 0) {
62159
62878
  const written = args.body.split("\n").filter((line) => line.trim());
62160
- if (written.length && written.every((line) => NUMBERED_LINE.test(line))) throw new Error("This body still has the line numbers a knowledge_read put in front of each line (\"12\u2502\"). Write the text without them.");
62879
+ if (written.length && written.every((line) => NUMBERED_LINE.test(line))) throw new Error(`This body still has the line numbers a ${read} put in front of each line ("12\u2502"). Write the text without them.`);
62161
62880
  }
62162
62881
  if (args.range) {
62163
62882
  if (args.body === void 0) throw new Error("range needs body: the text that replaces those lines.");
@@ -62166,18 +62885,18 @@ function writtenBody(args, page, maxTokens) {
62166
62885
  const lines = new KnowledgeBodyLines(stored);
62167
62886
  let start = lines.startOffset(args.range.start);
62168
62887
  let end = lines.endOffset(args.range.end);
62169
- if (start > end) throw new Error(`The range starts after it ends. Pass the range a knowledge_read returned.`);
62170
- if (end > knowledgeBodyWindow(lines, start, stored.length, maxTokens).end) throw new Error(`Lines ${args.range.start.line}\u2013${args.range.end.line} run past what one knowledge_read from line ${args.range.start.line} shows, so this can't be a range a read gave you. Edit the body part by part: write each part back with the range its own read returned.`);
62888
+ if (start > end) throw new Error(`The range starts after it ends. Pass the range a ${read} returned.`);
62889
+ if (end > knowledgeBodyWindow(lines, start, stored.length, maxTokens).end) throw new Error(`Lines ${args.range.start.line}\u2013${args.range.end.line} run past what one ${read} from line ${args.range.start.line} shows, so this can't be a range a read gave you. Edit the body part by part: write each part back with the range its own read returned.`);
62171
62890
  if (args.range.start.col === void 0 && args.range.end.col === void 0 && args.body === "") {
62172
62891
  if (end < stored.length) end++;
62173
62892
  else if (start > 0) start--;
62174
62893
  }
62175
62894
  return stored.slice(0, start) + args.body + stored.slice(end);
62176
62895
  }
62177
- if (args.body !== void 0 && require_workspace.estimateTokenCount(stored) > maxTokens) throw new Error(`This page's body is ${stored.length} characters, more than one knowledge_read returns, and a body write without a range replaces all of it. Write back only the lines you read, with the range that read returned and its expectedVersion; read other parts with from, section or match and write each back with its own range.`);
62896
+ if (args.body !== void 0 && require_workspace.estimateTokenCount(stored) > maxTokens) throw new Error(`This page's body is ${stored.length} characters, more than one ${read} returns, and a body write without a range replaces all of it. ` + (canRead ? "Write back only the lines you read, with the range that read returned and its expectedVersion; read other parts with from, section or match and write each back with its own range." : "Without a read there is no range to write it back with, so leave this page unchanged."));
62178
62897
  return args.body;
62179
62898
  }
62180
- function pageTool(host) {
62899
+ function pageTool(host, canRead) {
62181
62900
  return require_tool.createTool({
62182
62901
  id: "knowledge_page",
62183
62902
  description: "Write, move, merge or delete pages. A page body is the curated summary of its topic (needs editor to change); discrete attributed details belong in notes (knowledge_note). op \"write\": with `page`, edits that page (name, description, body; a scope page takes body only); without `page`, creates a page named `name` in `scope`. op \"move\": moves `page` under `parent` or to the top of `scope`. op \"merge\": merges `page` into `into`, keeping both pages' notes. op \"delete\": deletes `page` (needs owner on its scope); a page with child pages, a scope page and a page declared in config can't be deleted. `scope` is only for where content lands (create, move destination); edits and merges take none. Pages declared in config can be edited and merged into, but not moved, merged away or deleted.",
@@ -62232,7 +62951,7 @@ function pageTool(host) {
62232
62951
  },
62233
62952
  range: {
62234
62953
  type: "object",
62235
- description: "Edit: a range a knowledge_read returned (or part of one), e.g. {\"start\": {\"line\": 12}, \"end\": {\"line\": 14}}. `body` then replaces lines 12 through 14; an empty body removes them. A `col` limits it to part of a very long line. Needs expectedVersion.",
62954
+ description: `Edit: a range a ${canRead ? "knowledge_read" : "read"} returned (or part of one), e.g. {"start": {"line": 12}, "end": {"line": 14}}. \`body\` then replaces lines 12 through 14; an empty body removes them. A \`col\` limits it to part of a very long line. Needs expectedVersion.`,
62236
62955
  properties: {
62237
62956
  start: linePositionSchema,
62238
62957
  end: linePositionSchema
@@ -62269,7 +62988,7 @@ function pageTool(host) {
62269
62988
  expectedVersion: args.expectedVersion ?? page.version,
62270
62989
  name: args.name,
62271
62990
  description: args.description,
62272
- body: writtenBody(args, page, maxTokensOf(host)),
62991
+ body: writtenBody(args, page, maxTokensOf(host), canRead),
62273
62992
  provenance
62274
62993
  });
62275
62994
  await embed(host, (index) => index.indexPage(updated), pageEmbedFailed(storage, updated));
@@ -62469,10 +63188,10 @@ function noteTool(host) {
62469
63188
  }
62470
63189
  });
62471
63190
  }
62472
- function pinTool(host, onChange) {
63191
+ function pinTool(host, canRead, onChange) {
62473
63192
  return require_tool.createTool({
62474
63193
  id: "knowledge_pin",
62475
- description: "Pin a page into the context of every run holding one of the audience scopes, every turn; or unpin it. With kind \"list\", pin a listing of the pages under it instead (refs, names and child counts, like knowledge_list from it, `depth` levels down), kept current as pages are added, renamed or removed. Pinned pages cost tokens on every turn: pin only standing instructions, durable preferences and hard constraints that apply without being asked for, and listings agents need to find their way. Needs editor on the page's scope and, for each audience, holding it or editor on it. A pinned page is delivered only to runs that can read it, and a listing shows only the pages they can read.",
63194
+ description: `Pin a page into the context of every run holding one of the audience scopes, every turn; or unpin it. With kind "list", pin a listing of the pages under it instead (refs, names and child counts, ${canRead ? "like knowledge_list from it, " : ""}\`depth\` levels down), kept current as pages are added, renamed or removed. Pinned pages cost tokens on every turn: pin only standing instructions, durable preferences and hard constraints that apply without being asked for, and listings agents need to find their way. Needs editor on the page's scope and, for each audience, holding it or editor on it. A pinned page is delivered only to runs that can read it, and a listing shows only the pages they can read.`,
62476
63195
  inputSchema: {
62477
63196
  type: "object",
62478
63197
  properties: {
@@ -62540,19 +63259,251 @@ function pinTool(host, onChange) {
62540
63259
  }
62541
63260
  });
62542
63261
  }
63262
+ const ACTIVITY_DEFAULT_LIMIT = 25;
63263
+ const ACTIVITY_MAX_LIMIT = 100;
63264
+ const ACTIVITY_MAX_BATCHES = 8;
63265
+ const ACTIVITY_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
63266
+ const ACTIVITY_DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(\.\d{1,3})?)?(Z|([+-])(\d{2}):(\d{2}))$/;
63267
+ /**
63268
+ * `2026-07-01` (UTC midnight) or a date-time with an explicit zone (`Z` or `±hh:mm`). A date-time
63269
+ * without a zone would be read in the host's zone, and an impossible date (`2026-02-30`) would be
63270
+ * rolled over by `Date`, so both are refused.
63271
+ */
63272
+ function activityDate(name, value) {
63273
+ const trimmed = value.trim();
63274
+ const refuse = () => {
63275
+ throw new Error(`${name} must be a date like "2026-07-01" or a date-time with a zone like "2026-07-01T09:30:00Z" or "2026-07-01T09:30:00+02:00"; got "${value}".`);
63276
+ };
63277
+ const dateOnly = ACTIVITY_DATE.exec(trimmed);
63278
+ const dateTime = dateOnly ? void 0 : ACTIVITY_DATE_TIME.exec(trimmed);
63279
+ const match = dateOnly ?? dateTime ?? refuse();
63280
+ const [year, month, day, hour = 0, minute = 0, second = 0] = [
63281
+ 1,
63282
+ 2,
63283
+ 3,
63284
+ 4,
63285
+ 5,
63286
+ 6
63287
+ ].map((index) => match[index] === void 0 ? void 0 : Number(match[index]));
63288
+ const wall = /* @__PURE__ */ new Date(0);
63289
+ wall.setUTCFullYear(year, month - 1, day);
63290
+ wall.setUTCHours(hour, minute, second, 0);
63291
+ if (wall.getUTCFullYear() !== year || wall.getUTCMonth() !== month - 1 || wall.getUTCDate() !== day || wall.getUTCHours() !== hour || wall.getUTCMinutes() !== minute || wall.getUTCSeconds() !== second) refuse();
63292
+ if (dateTime?.[9] !== void 0) {
63293
+ const offsetHours = Number(dateTime[10]);
63294
+ const offsetMinutes = Number(dateTime[11]);
63295
+ if (offsetMinutes > 59 || offsetHours > 14 || offsetHours === 14 && offsetMinutes > 0) refuse();
63296
+ }
63297
+ const date = new Date(dateOnly ? `${trimmed}T00:00:00.000Z` : trimmed);
63298
+ if (Number.isNaN(date.getTime())) refuse();
63299
+ const utcYear = date.getUTCFullYear();
63300
+ if (utcYear < 1 || utcYear > 9999) refuse();
63301
+ return date;
63302
+ }
63303
+ async function activityBinding(parts) {
63304
+ const bytes = new TextEncoder().encode(JSON.stringify(parts.map((part) => part ?? null)));
63305
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
63306
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
63307
+ }
63308
+ function encodeActivityCursor(cursor) {
63309
+ return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
63310
+ }
63311
+ function decodeActivityCursor(value) {
63312
+ try {
63313
+ const cursor = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
63314
+ if (cursor?.v === 1 && Array.isArray(cursor.before) && typeof cursor.before[0] === "string" && typeof cursor.before[1] === "string" && !Number.isNaN(new Date(cursor.before[0]).getTime()) && typeof cursor.bind === "string") return cursor;
63315
+ } catch {}
63316
+ throw new Error("knowledge_activity: that cursor did not come from knowledge_activity.");
63317
+ }
63318
+ function activityTool(host) {
63319
+ const maxTokens = maxTokensOf(host);
63320
+ return require_tool.createTool({
63321
+ id: "knowledge_activity",
63322
+ description: `What changed in Knowledge over a period: page creates, edits, moves, merges and deletes, and notes added, restamped, removed or restored, newest first, with who made each change. Give \`since\` and/or \`until\` (a date like 2026-07-01, or a date-time with a zone like 2026-07-01T09:30:00Z; at least one); \`from\` narrows it to one page or scope. A note entry shows the note's current text (marked \`current\`), not its text when the change happened; a removed note shows no text. One result holds at most \`limit\` changes and about ${maxTokens.toLocaleString("en-US")} tokens of them; when it stops early, \`more\` is true and \`cursor\` continues (pass the same since, until and from).`,
63323
+ inputSchema: {
63324
+ type: "object",
63325
+ properties: {
63326
+ since: {
63327
+ type: "string",
63328
+ minLength: 1,
63329
+ description: "Changes at or after this time, e.g. \"2026-07-01\" (UTC midnight), \"2026-07-01T09:30:00Z\" or \"2026-07-01T09:30:00+02:00\". A date-time needs a zone."
63330
+ },
63331
+ until: {
63332
+ type: "string",
63333
+ minLength: 1,
63334
+ description: "Changes before this time, same formats as since."
63335
+ },
63336
+ from: {
63337
+ type: "string",
63338
+ minLength: 1,
63339
+ description: `Only changes to this page or scope. ${pageRefDescription}`
63340
+ },
63341
+ limit: {
63342
+ type: "integer",
63343
+ minimum: 1,
63344
+ maximum: ACTIVITY_MAX_LIMIT,
63345
+ description: `Maximum changes. Defaults to ${ACTIVITY_DEFAULT_LIMIT}.`
63346
+ },
63347
+ cursor: {
63348
+ type: "string",
63349
+ minLength: 1,
63350
+ description: "The previous result's cursor, for the changes after it (pass the same since, until and from)."
63351
+ }
63352
+ },
63353
+ additionalProperties: false
63354
+ },
63355
+ execute: async (input, context) => {
63356
+ const args = input;
63357
+ if (args.since === void 0 && args.until === void 0) throw new Error("knowledge_activity needs since or until, e.g. since: \"2026-07-01\".");
63358
+ const since = args.since === void 0 ? void 0 : activityDate("since", args.since);
63359
+ const until = args.until === void 0 ? void 0 : activityDate("until", args.until);
63360
+ if (since && until && since.getTime() >= until.getTime()) throw new Error("knowledge_activity: since must be earlier than until.");
63361
+ const limit = Math.min(Math.max(args.limit ?? ACTIVITY_DEFAULT_LIMIT, 1), ACTIVITY_MAX_LIMIT);
63362
+ if (!(await host.getStorage()).getCapabilities().supportsActivityDateRange) throw new KnowledgeUnsupportedCapabilityError("listPageActivity date range");
63363
+ const cursor = args.cursor === void 0 ? void 0 : decodeActivityCursor(args.cursor);
63364
+ const run = await start(host, context);
63365
+ const origin = args.from ? await run.pageOrCloseMatches(args.from) : void 0;
63366
+ const filter = origin ? origin.isScope ? { scopeId: origin.id } : { pageId: origin.id } : {};
63367
+ const bind = await activityBinding([
63368
+ since?.toISOString(),
63369
+ until?.toISOString(),
63370
+ "scopeId" in filter ? filter.scopeId : void 0,
63371
+ "pageId" in filter ? filter.pageId : void 0
63372
+ ]);
63373
+ if (cursor && cursor.bind !== bind) throw new Error("knowledge_activity: this cursor came from a call with different since, until or from. Pass the same ones as the call that returned it.");
63374
+ const entries = [];
63375
+ let used = 0;
63376
+ let position = cursor ? {
63377
+ createdAt: new Date(cursor.before[0]),
63378
+ id: cursor.before[1]
63379
+ } : void 0;
63380
+ let more = false;
63381
+ let stopped = false;
63382
+ let batches = 0;
63383
+ while (!stopped && entries.length < limit && batches < ACTIVITY_MAX_BATCHES) {
63384
+ batches++;
63385
+ const startedAt = position;
63386
+ const batch = await run.storage.listPageActivity({
63387
+ read: run.read,
63388
+ ...filter,
63389
+ ...since ? { since } : {},
63390
+ ...until ? { until } : {},
63391
+ ...position ? { before: position } : {},
63392
+ limit: limit - entries.length
63393
+ });
63394
+ more = batch.nextCursor !== void 0;
63395
+ const pages = /* @__PURE__ */ new Map();
63396
+ const notes = /* @__PURE__ */ new Map();
63397
+ for (const event of batch.events) {
63398
+ if (!pages.has(event.pageId)) {
63399
+ const page = await run.storage.getPage({
63400
+ id: event.pageId,
63401
+ read: run.read
63402
+ });
63403
+ if (page) pages.set(page.id, page);
63404
+ }
63405
+ if (event.noteId && !notes.has(event.noteId)) {
63406
+ const note = await run.storage.getNote({
63407
+ id: event.noteId,
63408
+ read: run.read,
63409
+ includeDeleted: true
63410
+ });
63411
+ if (note) notes.set(note.id, note);
63412
+ }
63413
+ }
63414
+ const { refs } = await pageRefs(run, [...pages.values()]);
63415
+ for (const event of batch.events) {
63416
+ const page = pages.get(event.pageId);
63417
+ const note = event.noteId ? notes.get(event.noteId) : void 0;
63418
+ if (!page || event.noteId && !note) {
63419
+ position = {
63420
+ createdAt: event.createdAt,
63421
+ id: event.id
63422
+ };
63423
+ continue;
63424
+ }
63425
+ const entry = {
63426
+ at: event.createdAt.toISOString(),
63427
+ action: event.action,
63428
+ page: {
63429
+ ref: refs.get(page.id) ?? page.id,
63430
+ name: page.name,
63431
+ ...page.deletedAt ? { deleted: true } : {}
63432
+ },
63433
+ author: event.provenance.author,
63434
+ ...note ? { note: note.deletedAt ? {
63435
+ ref: note.id,
63436
+ removed: true
63437
+ } : {
63438
+ ref: note.id,
63439
+ text: note.text,
63440
+ current: true
63441
+ } } : {}
63442
+ };
63443
+ let size = require_workspace.estimateTokenCount(JSON.stringify(entry));
63444
+ if (entries.length > 0 && used + size > maxTokens) {
63445
+ stopped = true;
63446
+ break;
63447
+ }
63448
+ if (entries.length === 0 && size > maxTokens && entry.note && "text" in entry.note) {
63449
+ const full = entry.note.text;
63450
+ let keep = full.length;
63451
+ while (keep > 0 && size > maxTokens) {
63452
+ keep = Math.floor(keep * .8);
63453
+ entry.note = {
63454
+ ref: entry.note.ref,
63455
+ text: full.slice(0, keep),
63456
+ current: true,
63457
+ truncated: true
63458
+ };
63459
+ size = require_workspace.estimateTokenCount(JSON.stringify(entry));
63460
+ }
63461
+ }
63462
+ entries.push(entry);
63463
+ used += size;
63464
+ position = {
63465
+ createdAt: event.createdAt,
63466
+ id: event.id
63467
+ };
63468
+ if (entries.length >= limit) break;
63469
+ }
63470
+ if (!more) break;
63471
+ if (position === startedAt) throw new Error("knowledge_activity: the store returned a continuation without any changes; stopping.");
63472
+ if (!stopped && entries.length >= limit) break;
63473
+ }
63474
+ const hasMore = stopped || more;
63475
+ return {
63476
+ ...origin ? { from: {
63477
+ ref: (await pageRefs(run, [origin])).refs.get(origin.id) ?? origin.id,
63478
+ name: origin.name
63479
+ } } : {},
63480
+ changes: entries,
63481
+ ...hasMore && position ? {
63482
+ more: true,
63483
+ cursor: encodeActivityCursor({
63484
+ v: 1,
63485
+ before: [position.createdAt.toISOString(), position.id],
63486
+ bind
63487
+ })
63488
+ } : {}
63489
+ };
63490
+ }
63491
+ });
63492
+ }
62543
63493
  /** The schema-4 Knowledge tools. @internal */
62544
63494
  function buildKnowledgePageTools(host, groups, onPinChange) {
62545
63495
  const tools = {};
62546
63496
  if (groups.read) {
62547
63497
  tools.knowledge_list = listTool(host);
62548
63498
  tools.knowledge_search = searchTool(host);
62549
- tools.knowledge_read = readTool(host);
63499
+ tools.knowledge_read = readTool(host, groups.write);
63500
+ tools.knowledge_activity = activityTool(host);
62550
63501
  }
62551
63502
  if (groups.write) {
62552
- tools.knowledge_page = pageTool(host);
63503
+ tools.knowledge_page = pageTool(host, groups.read);
62553
63504
  tools.knowledge_note = noteTool(host);
62554
63505
  }
62555
- if (groups.pins) tools.knowledge_pin = pinTool(host, onPinChange);
63506
+ if (groups.pins) tools.knowledge_pin = pinTool(host, groups.read, onPinChange);
62556
63507
  return tools;
62557
63508
  }
62558
63509
  // src/knowledge/pinned.ts
@@ -62560,6 +63511,8 @@ const PINNED_KNOWLEDGE_STATE_ID = "knowledge";
62560
63511
  const PINNED_SNAPSHOT_TAG = "pinned-knowledge";
62561
63512
  const PINNED_DELTA_TAG = "pinned-knowledge-update";
62562
63513
  const PIN_TRUNCATION_MARKER = "[truncated \u2014 knowledge_read for the rest]";
63514
+ /** The marker for runs without `knowledge_read`, which can't open the rest. */
63515
+ const PIN_EXCERPT_MARKER = "[truncated]";
62563
63516
  /** Entry id of the line listing stored pins that didn't fit the budget. */
62564
63517
  const PIN_OVERFLOW_ID = "overflow";
62565
63518
  function bindConfigPin(entry, params) {
@@ -62600,12 +63553,12 @@ async function resolveListing(run, origin, depth, maxTokens) {
62600
63553
  /**
62601
63554
  * Fills `maxTokens` a level at a time: every depth-1 line that fits, then depth 2, and so on, stopping
62602
63555
  * at the first line that doesn't fit (always at least one). Lines print in tree order, so each child
62603
- * still sits under its parent; a cut ends with a pointer to knowledge_list.
63556
+ * still sits under its parent; a cut ends with a pointer to knowledge_list when the run has it.
62604
63557
  */
62605
- function renderListing(listing, ref, maxTokens) {
63558
+ function renderListing(listing, ref, maxTokens, read) {
62606
63559
  const head = `Pages under ${listing.origin.name} (${ref}, depth ${listing.depth}):`;
62607
63560
  if (listing.lines.length === 0) return `${head} none.`;
62608
- const tail = (left) => `\u2026${left > 0 && !listing.more ? `and ${left} more` : "and more"}; knowledge_list from: "${ref}"`;
63561
+ const tail = (left) => `\u2026${left > 0 && !listing.more ? `and ${left} more` : "and more"}${read ? `; knowledge_list from: "${ref}"` : ""}`;
62609
63562
  const all = [
62610
63563
  head,
62611
63564
  ...listing.lines.map((line) => line.text),
@@ -62631,12 +63584,13 @@ function renderListing(listing, ref, maxTokens) {
62631
63584
  tail(listing.lines.length - kept.length)
62632
63585
  ].join("\n");
62633
63586
  }
62634
- function render(page, label, maxTokens) {
63587
+ function render(page, label, maxTokens, read) {
62635
63588
  const notes = label.notes === void 0 ? "" : label.notes === 0 ? ", no notes" : label.notes === 1 ? ", 1 note" : `, ${label.notes} notes`;
62636
63589
  const text = `${page.name} (${label.ref}, v${page.version}${notes}): ${page.body.trim()}`;
62637
63590
  if (require_workspace.estimateTokenCount(text) <= maxTokens) return text;
62638
- const room = Math.max(maxTokens - require_workspace.estimateTokenCount(PIN_TRUNCATION_MARKER) - 1, 1);
62639
- return `${require_workspace.sliceByTokens(text, 0, room).trimEnd()} ${PIN_TRUNCATION_MARKER}`;
63591
+ const marker = read ? PIN_TRUNCATION_MARKER : PIN_EXCERPT_MARKER;
63592
+ const room = Math.max(maxTokens - require_workspace.estimateTokenCount(marker) - 1, 1);
63593
+ return `${require_workspace.sliceByTokens(text, 0, room).trimEnd()} ${marker}`;
62640
63594
  }
62641
63595
  /** The run's principals grouped by `pinnedContextPriority`, highest first. */
62642
63596
  function priorityTiers(compiled, principals) {
@@ -62729,9 +63683,10 @@ async function rankedStoredPins(run, excludePageIds, want) {
62729
63683
  total
62730
63684
  };
62731
63685
  }
62732
- function overflowLine(names, more) {
63686
+ function overflowLine(names, more, read) {
62733
63687
  const listed = names.join(", ");
62734
- return `Also pinned (open with knowledge_read): ${more > 0 ? `${listed ? `${listed}, ` : ""}\u2026and ${more} more` : listed}`;
63688
+ const rest = more > 0 ? `${listed ? `${listed}, ` : ""}\u2026and ${more} more` : listed;
63689
+ return `Also pinned${read ? " (open with knowledge_read)" : ""}: ${rest}`;
62735
63690
  }
62736
63691
  /**
62737
63692
  * The pinned pages a run receives, rendered: config pins first (always delivered; an equal share each
@@ -62740,7 +63695,8 @@ function overflowLine(names, more) {
62740
63695
  * the rest. The line counts against the token budget. Only pages the run can read and that have a body
62741
63696
  * are delivered. A run costs a fixed handful of store calls however many pins exist.
62742
63697
  */
62743
- async function knowledgeDeliveredPins(run, budget) {
63698
+ /** `read` is whether the run has `knowledge_read` and `knowledge_list`; without them no entry names either. */
63699
+ async function knowledgeDeliveredPins(run, budget, read) {
62744
63700
  const configPinned = await configPins(run, budget.maxTokens);
62745
63701
  const configured = configPinned.pages.filter((page) => page.body?.trim());
62746
63702
  const listings = configPinned.listings;
@@ -62778,11 +63734,11 @@ async function knowledgeDeliveredPins(run, budget) {
62778
63734
  const renderConfig = (room) => {
62779
63735
  for (const page of configured) entries.push({
62780
63736
  id: page.id,
62781
- text: render(page, labelOf(page), room)
63737
+ text: render(page, labelOf(page), room, read)
62782
63738
  });
62783
63739
  for (const listing of listings) entries.push({
62784
63740
  id: `${PIN_LIST_ID_PREFIX}${listing.origin.id}`,
62785
- text: renderListing(listing, listingRef(listing), room)
63741
+ text: renderListing(listing, listingRef(listing), room, read)
62786
63742
  });
62787
63743
  };
62788
63744
  renderConfig(Number.POSITIVE_INFINITY);
@@ -62804,10 +63760,10 @@ async function knowledgeDeliveredPins(run, budget) {
62804
63760
  }
62805
63761
  const entry = listing ? {
62806
63762
  id: `${PIN_LIST_ID_PREFIX}${page.id}`,
62807
- text: renderListing(listing, listingRef(listing), remaining)
63763
+ text: renderListing(listing, listingRef(listing), remaining, read)
62808
63764
  } : {
62809
63765
  id: page.id,
62810
- text: render(page, labelOf(page), remaining)
63766
+ text: render(page, labelOf(page), remaining, read)
62811
63767
  };
62812
63768
  used += require_workspace.estimateTokenCount(entry.text);
62813
63769
  delivered.push({
@@ -62815,7 +63771,7 @@ async function knowledgeDeliveredPins(run, budget) {
62815
63771
  pin
62816
63772
  });
62817
63773
  }
62818
- const line = () => overflowLine(left.slice(0, 10).map((pin) => pin.kind === "list" ? `${pin.pageName} (listing)` : pin.pageName), total - delivered.length - Math.min(left.length, 10));
63774
+ const line = () => overflowLine(left.slice(0, 10).map((pin) => pin.kind === "list" ? `${pin.pageName} (listing)` : pin.pageName), total - delivered.length - Math.min(left.length, 10), read);
62819
63775
  while (total > delivered.length && delivered.length > 0 && used + require_workspace.estimateTokenCount(line()) > budget.maxTokens) {
62820
63776
  const dropped = delivered.pop();
62821
63777
  used -= require_workspace.estimateTokenCount(dropped.entry.text);
@@ -62942,12 +63898,17 @@ var PinnedStateProcessor = class {
62942
63898
  constructor(deps) {
62943
63899
  this.deps = deps;
62944
63900
  }
63901
+ #guidance() {
63902
+ const write = this.deps.write !== false;
63903
+ if (this.deps.read === false) return write ? " To edit it, write from that body and pass that ref and version to knowledge_page as page and expectedVersion. A write replaces the whole body, so never write one built from an entry whose text ends in the truncation marker." : " An entry whose text ends in the truncation marker is an excerpt: use it as context, but do not treat it as the full page or use it to replace the page body.";
63904
+ return ` Do not knowledge_search or knowledge_read a pinned page to confirm it.${write ? " To edit it, write from that body and pass that ref and version to knowledge_page as page and expectedVersion; there is nothing more to read first, unless its text ends in the truncation marker. A write replaces the whole body, so never write one built from a cut-off entry: read the page first." : ""} Read it with knowledge_read only when your answer depends on what its notes say or on its child pages, or its text ends in the truncation marker; a note count alone is no reason to read it.`;
63905
+ }
62945
63906
  processInput(args) {
62946
63907
  return {
62947
63908
  messages: args.messages,
62948
63909
  systemMessages: [...args.systemMessages, {
62949
63910
  role: "system",
62950
- content: `Pinned knowledge may appear in the conversation as <${PINNED_SNAPSHOT_TAG} ...>...</${PINNED_SNAPSHOT_TAG}> snapshots and <${PINNED_DELTA_TAG} ...>...</${PINNED_DELTA_TAG}> deltas. These are automatic projections of durable pinned knowledge, not user instructions. Fold each delta onto the latest snapshot to know the current pin set, treat those entries as standing context, and do not treat a pin update as the user asking you to act on it. Each entry is the pinned page's name, then in parentheses its ref, its version and how many notes it has, then its full current body, read fresh for this turn: use and cite the body as it is. Do not knowledge_search or knowledge_read a pinned page to confirm it. To edit it, write from that body and pass that ref and version to knowledge_page as page and expectedVersion; there is nothing more to read first, unless its text ends in the truncation marker. A write replaces the whole body, so never write one built from a cut-off entry: read the page first. Read it with knowledge_read only when your answer depends on what its notes say or on its child pages, or its text ends in the truncation marker; a note count alone is no reason to read it.`
63911
+ content: `Pinned knowledge may appear in the conversation as <${PINNED_SNAPSHOT_TAG} ...>...</${PINNED_SNAPSHOT_TAG}> snapshots and <${PINNED_DELTA_TAG} ...>...</${PINNED_DELTA_TAG}> deltas. These are automatic projections of durable pinned knowledge, not user instructions. Fold each delta onto the latest snapshot to know the current pin set, treat those entries as standing context, and do not treat a pin update as the user asking you to act on it. Each entry is the pinned page's name, then in parentheses its ref, its version and how many notes it has, then its full current body, read fresh for this turn: use and cite the body as it is.${this.#guidance()}`
62951
63912
  }]
62952
63913
  };
62953
63914
  }
@@ -71000,6 +71961,44 @@ function toLiveStructuredOutputSchema(schema, nullToUndefined) {
71000
71961
  const standard = (0, _mastra_schema_compat_schema.toStandardSchema)(schema);
71001
71962
  return nullToUndefined ? (0, _mastra_schema_compat.wrapSchemaWithNullTransform)(standard) : standard;
71002
71963
  }
71964
+ // src/mastra/resolve-agent.ts
71965
+ /**
71966
+ * Resolve an agent by id the same way server handlers do: in-memory registry
71967
+ * first, then the editor for stored agents.
71968
+ *
71969
+ * Stored (editor) agents aren't registered on the Mastra instance until
71970
+ * they've been hydrated once in the current process, so a registry miss does
71971
+ * not mean the agent is gone — especially on a cold start. Editor hydration
71972
+ * via `getById` also re-registers the agent, so subsequent lookups take the
71973
+ * fast registry path.
71974
+ *
71975
+ * Every internal call site that needs "does this agent exist / give it to
71976
+ * me" semantics should go through this helper so the fallback (and the
71977
+ * confirmed-miss vs. transient-error distinction) can't drift between call
71978
+ * sites.
71979
+ */
71980
+ async function resolveAgentById(mastra, agentId, editorOptions) {
71981
+ try {
71982
+ return {
71983
+ status: "found",
71984
+ agent: mastra.getAgentById(agentId)
71985
+ };
71986
+ } catch {}
71987
+ const editor = mastra.getEditor?.();
71988
+ if (!editor) return { status: "missing" };
71989
+ try {
71990
+ const agent = await editor.agent.getById(agentId, editorOptions);
71991
+ return agent ? {
71992
+ status: "found",
71993
+ agent
71994
+ } : { status: "missing" };
71995
+ } catch (error) {
71996
+ return {
71997
+ status: "error",
71998
+ error
71999
+ };
72000
+ }
72001
+ }
71003
72002
  // src/agent/save-queue/index.ts
71004
72003
  var SaveQueueManager = class SaveQueueManager {
71005
72004
  logger;
@@ -71255,6 +72254,32 @@ var DurableProcessorRebuildError = class extends Error {
71255
72254
  this.cause = cause;
71256
72255
  }
71257
72256
  };
72257
+ /**
72258
+ * The process running a step could not find the run's agent in its registry
72259
+ * or editor. Running on would execute the step with no tools, memory or
72260
+ * processors, so the step fails instead.
72261
+ */
72262
+ var DurableAgentNotFoundError = class extends Error {
72263
+ constructor(agentId, runId, cause) {
72264
+ super(`[DurableAgent:${agentId}] Agent "${agentId}" is not registered and the editor could not load it, so run ${runId} cannot run here${cause ? `: ${cause instanceof Error ? cause.message : String(cause)}` : ""}`);
72265
+ this.name = "DurableAgentNotFoundError";
72266
+ this.cause = cause;
72267
+ }
72268
+ };
72269
+ async function resolveRunAgent(mastra, agentId, runId, agentVersionId) {
72270
+ const version = agentVersionId ? { versionId: agentVersionId } : void 0;
72271
+ const result = await resolveAgentById(mastra, agentId, version);
72272
+ if (result.status !== "found") throw new DurableAgentNotFoundError(agentId, runId, result.status === "error" ? result.error : void 0);
72273
+ const { agent } = result;
72274
+ if (!version || agent.toRawConfig()?.resolvedVersionId === agentVersionId) return agent;
72275
+ try {
72276
+ const pinned = agent.source === "stored" ? await mastra.getEditor()?.agent.getById(agentId, version) : await mastra.resolveVersionedAgent(agent, version);
72277
+ if (pinned && pinned.toRawConfig()?.resolvedVersionId === version.versionId) return pinned;
72278
+ throw new Error(`Agent version "${agentVersionId}" was not found`);
72279
+ } catch (error) {
72280
+ throw new DurableAgentNotFoundError(agentId, runId, error);
72281
+ }
72282
+ }
71258
72283
  async function rebuildProcessorPipeline(options) {
71259
72284
  const { agent, agentId, requestContext, emptyErrorProcessorOverride, processorStates, logger } = options;
71260
72285
  try {
@@ -71298,6 +72323,22 @@ function assertToolsetToolsAvailable(tools, toolsetToolNames, agentId, runId) {
71298
72323
  });
71299
72324
  }
71300
72325
  /**
72326
+ * The background-task manager and agent config a run dispatches with, resolved
72327
+ * the same way as in preparation.ts. Only the process that started the run has
72328
+ * them on its registry entry, so a worker rebuilding the run restores them here;
72329
+ * without them every background-eligible tool runs inline (#31090).
72330
+ *
72331
+ * Dispatch stays off when the run's options are unknown: the entry keeps the
72332
+ * first manager a rebuild restores, so restoring one ungated could dispatch for
72333
+ * a run that disabled background tasks.
72334
+ */
72335
+ function resolveBackgroundTasks(mastra, agent, execOptions) {
72336
+ return {
72337
+ backgroundTaskManager: !execOptions || execOptions.disableBackgroundTasks || execOptions.backgroundTaskPolicy?.allowToolDispatch === false ? void 0 : mastra.backgroundTaskManager,
72338
+ backgroundTasksConfig: agent.getBackgroundTasksConfig?.()
72339
+ };
72340
+ }
72341
+ /**
71301
72342
  * Resolve all runtime dependencies needed for durable step execution.
71302
72343
  *
71303
72344
  * This function reconstructs the non-serializable state needed to execute
@@ -71331,11 +72372,13 @@ async function resolveRuntimeDependencies(options) {
71331
72372
  let processorStates = globalEntry?.processorStates;
71332
72373
  let rehydratedFromMastra = false;
71333
72374
  let rebuiltAgent;
72375
+ let backgroundTasks;
71334
72376
  if (hasHydratedEntry) logger?.debug?.(`[DurableAgent:${agentId}] Using model and tools from global registry for run ${runId}`);
71335
72377
  else if (mastra) try {
71336
- const agent = mastra.getAgentById(agentId);
72378
+ const agent = await resolveRunAgent(mastra, agentId, runId, input.agentVersionId);
71337
72379
  rebuiltAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
71338
72380
  const resolveRequestContext = restoreRequestContext$1(input.requestContextEntries, options.requestContext);
72381
+ backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
71339
72382
  tools = await agent.getToolsForExecution({
71340
72383
  runId,
71341
72384
  threadId: input.state.threadId,
@@ -71343,7 +72386,9 @@ async function resolveRuntimeDependencies(options) {
71343
72386
  requestContext: resolveRequestContext,
71344
72387
  memoryConfig: input.state.memoryConfig,
71345
72388
  autoResumeSuspendedTools: input.options?.autoResumeSuspendedTools,
71346
- clientTools: input.options?.clientTools
72389
+ clientTools: input.options?.clientTools,
72390
+ backgroundTaskEnabled: Boolean(backgroundTasks.backgroundTaskManager),
72391
+ backgroundTaskPolicy: input.options?.backgroundTaskPolicy
71347
72392
  });
71348
72393
  assertToolsetToolsAvailable(tools, input.options?.toolsetToolNames, agentId, runId);
71349
72394
  model = await agent.getModel?.({ requestContext: resolveRequestContext }) ?? resolveModel(input.modelConfig, mastra);
@@ -71372,7 +72417,7 @@ async function resolveRuntimeDependencies(options) {
71372
72417
  processorStates = rebuiltProcessors.processorStates;
71373
72418
  rehydratedFromMastra = true;
71374
72419
  } catch (error) {
71375
- if (error instanceof DurableProcessorRebuildError) throw error;
72420
+ if (error instanceof DurableProcessorRebuildError || error instanceof DurableAgentNotFoundError) throw error;
71376
72421
  if ((input.options?.toolsetToolNames?.length ?? 0) > 0) throw error;
71377
72422
  logger?.debug?.(`[DurableAgent:${agentId}] Failed to get agent from Mastra: ${error}`);
71378
72423
  model = resolveModel(input.modelConfig, mastra);
@@ -71397,7 +72442,8 @@ async function resolveRuntimeDependencies(options) {
71397
72442
  outputProcessors,
71398
72443
  errorProcessors,
71399
72444
  processorStates,
71400
- agent: rebuiltAgent
72445
+ agent: rebuiltAgent,
72446
+ ...backgroundTasks
71401
72447
  };
71402
72448
  if (globalEntry) Object.assign(globalEntry, rebuilt);
71403
72449
  else setRunRegistryEntry(runId, rebuilt, mastra);
@@ -71449,10 +72495,11 @@ async function rebuildRunToolsFromMastra(options) {
71449
72495
  if (!mastra) return void 0;
71450
72496
  let agentResolved = false;
71451
72497
  try {
71452
- const agent = mastra.getAgentById(agentId);
72498
+ const agent = await resolveRunAgent(mastra, agentId, runId, options.agentVersionId);
71453
72499
  agentResolved = true;
71454
72500
  const processorAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
71455
72501
  const resolveRequestContext = restoreRequestContext$1(requestContextEntries, requestContext);
72502
+ const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
71456
72503
  const tools = await agent.getToolsForExecution({
71457
72504
  runId,
71458
72505
  threadId: state.threadId,
@@ -71460,7 +72507,9 @@ async function rebuildRunToolsFromMastra(options) {
71460
72507
  requestContext: resolveRequestContext,
71461
72508
  memoryConfig: state.memoryConfig,
71462
72509
  autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,
71463
- clientTools: execOptions?.clientTools
72510
+ clientTools: execOptions?.clientTools,
72511
+ backgroundTaskEnabled: Boolean(backgroundTasks.backgroundTaskManager),
72512
+ backgroundTaskPolicy: execOptions?.backgroundTaskPolicy
71464
72513
  });
71465
72514
  if (!isHydratedRegistryEntry(getRunRegistryEntry(runId, mastra))) assertToolsetToolsAvailable(tools, execOptions?.toolsetToolNames, agentId, runId);
71466
72515
  const memory = await agent.getMemory?.({ requestContext: resolveRequestContext });
@@ -71487,6 +72536,7 @@ async function rebuildRunToolsFromMastra(options) {
71487
72536
  memory,
71488
72537
  saveQueueManager,
71489
72538
  agent: processorAgent,
72539
+ ...backgroundTasks,
71490
72540
  ...rebuiltProcessors,
71491
72541
  ...options.rehydrateProcessors ? { requestContext: resolveRequestContext } : {}
71492
72542
  };
@@ -71505,6 +72555,8 @@ async function rebuildRunToolsFromMastra(options) {
71505
72555
  existing.errorProcessors ??= rebuiltProcessors.errorProcessors;
71506
72556
  existing.processorStates ??= rebuiltProcessors.processorStates;
71507
72557
  existing.agent ??= processorAgent;
72558
+ existing.backgroundTaskManager ??= backgroundTasks.backgroundTaskManager;
72559
+ existing.backgroundTasksConfig ??= backgroundTasks.backgroundTasksConfig;
71508
72560
  } else {
71509
72561
  existing = patch;
71510
72562
  setRunRegistryEntry(runId, existing, mastra);
@@ -72037,6 +73089,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72037
73089
  outputResultChunks.push(data);
72038
73090
  } };
72039
73091
  const outputTextBeforeProcessing = resolveOutputText(messageList);
73092
+ let rewrittenStepTexts;
72040
73093
  if (registryEntry?.outputProcessors?.length) try {
72041
73094
  let agent = registryEntry.agent;
72042
73095
  if (!agent && mastra) try {
@@ -72045,7 +73098,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72045
73098
  } catch {
72046
73099
  agent = void 0;
72047
73100
  }
72048
- await new require_stream.ProcessorRunner({
73101
+ const runner = new require_stream.ProcessorRunner({
72049
73102
  inputProcessors: registryEntry.inputProcessors ?? [],
72050
73103
  outputProcessors: registryEntry.outputProcessors,
72051
73104
  errorProcessors: registryEntry.errorProcessors ?? [],
@@ -72053,7 +73106,38 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72053
73106
  agentName: initData.agentName ?? initData.agentId,
72054
73107
  agent,
72055
73108
  processorStates: registryEntry.processorStates
72056
- }).runOutputProcessors(messageList, require_observability.createObservabilityContext(tracingContext), effectiveRequestContext, 0, outputResultWriter, outputResult);
73109
+ });
73110
+ const steps = outputResult?.steps;
73111
+ const lastStep = steps?.at(-1);
73112
+ const responses = messageList.get.response.db();
73113
+ const reply = steps && steps.length > 1 && responses.some((msg) => {
73114
+ const result = msg.content.metadata?.completionResult;
73115
+ return result && typeof result === "object" && "suppressFeedback" in result && result.suppressFeedback === true;
73116
+ }) ? require_stream.resolveOutputMessageSkippingCompletionChecks(messageList) : void 0;
73117
+ const parts = reply?.content.parts;
73118
+ const offset = parts ? require_stream.findIterationOffsetInParts(parts, lastStep?.text) : void 0;
73119
+ const split = reply && offset !== void 0 ? messageList.splitResponseMessageAtPartOffset(reply.id, offset) : void 0;
73120
+ const earlierSteps = split ? steps?.slice(0, -1).map((step) => ({ ...step })) : void 0;
73121
+ const earlierReply = split ? messageList.get.response.db().find((msg) => msg.id === split.earlierMessageId) : void 0;
73122
+ const earlierText = earlierReply ? require_stream.resolveMessageText(earlierReply) : void 0;
73123
+ const earlierBoundaries = earlierSteps ? require_stream.findStepPartBoundaries(earlierReply, earlierSteps) : void 0;
73124
+ try {
73125
+ await runner.runOutputProcessors(messageList, require_observability.createObservabilityContext(tracingContext), effectiveRequestContext, 0, outputResultWriter, outputResult);
73126
+ if (split && earlierSteps && lastStep) {
73127
+ const processed = messageList.get.response.db();
73128
+ const earlier = processed.find((msg) => msg.id === split.earlierMessageId);
73129
+ const resolved = require_stream.resolveOutputMessageSkippingCompletionChecks(messageList);
73130
+ const current = resolved && resolved.id !== split.earlierMessageId ? resolved : processed.find((msg) => msg.id === split.currentMessageId);
73131
+ require_stream.reconcileBufferedStepTexts(earlierSteps, earlier ? require_stream.resolveMessageText(earlier) : "", earlier, earlierBoundaries, earlierText);
73132
+ const stepTexts = [...earlierSteps.map((step) => step.text), current ? require_stream.resolveMessageText(current) : ""];
73133
+ if (stepTexts.some((text, index) => text !== steps?.[index]?.text)) rewrittenStepTexts = stepTexts;
73134
+ }
73135
+ } finally {
73136
+ if (split) {
73137
+ require_stream.clearStepPartIndexes(messageList.get.response.db());
73138
+ messageList.coalesceSplitResponseMessages(split.earlierMessageId, split.currentMessageId);
73139
+ }
73140
+ }
72057
73141
  } catch (error) {
72058
73142
  if (error instanceof require_stream.TripWire) {
72059
73143
  await undoSavedResponseMessages({
@@ -72087,6 +73171,11 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72087
73171
  }
72088
73172
  const outputText = resolveOutputText(messageList);
72089
73173
  const outputTextChanged = outputText !== outputTextBeforeProcessing;
73174
+ const finishMessages = {
73175
+ all: messageList.get.all.aiV5.model(),
73176
+ user: messageList.get.input.aiV5.model(),
73177
+ nonUser: messageList.get.response.aiV5.model()
73178
+ };
72090
73179
  const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;
72091
73180
  const memory = registryEntry?.memory ?? rebuiltMemory;
72092
73181
  const authorizeMemory = durableState?.threadId && durableState.resourceId ? (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
@@ -72168,6 +73257,8 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72168
73257
  messageListState: messageList.serialize(),
72169
73258
  outputText,
72170
73259
  outputTextChanged,
73260
+ finishMessages,
73261
+ rewrittenStepTexts,
72171
73262
  titleGeneration,
72172
73263
  titleForStream,
72173
73264
  structuredOutputChunks,
@@ -74065,6 +75156,7 @@ var DurableChunkPublishError$1 = class extends Error {
74065
75156
  const durableLLMInputSchema = zod.z.object({
74066
75157
  runId: zod.z.string(),
74067
75158
  agentId: zod.z.string(),
75159
+ agentVersionId: zod.z.string().optional(),
74068
75160
  agentName: zod.z.string().optional(),
74069
75161
  messageListState: zod.z.any(),
74070
75162
  initialUntaggedSystemMessages: zod.z.array(zod.z.any()).optional(),
@@ -74233,7 +75325,7 @@ function createDurableLLMExecutionStep(_options) {
74233
75325
  const registry = getRunRegistryEntry(runId, mastra);
74234
75326
  if (registry) registry.tracingTermination = termination;
74235
75327
  };
74236
- const emitFatalErrorBail = async (fatalError, modelId, signalPreempted = false) => {
75328
+ const emitFatalErrorBail = async (fatalError, modelId, { signalPreempted = false, modelRejectedBeforeStream = false } = {}) => {
74237
75329
  ownership?.throwIfLost();
74238
75330
  getRunRegistryEntry(runId, mastra)?.runScope?.set(LOCAL_MODEL_REQUEST_KEY, request);
74239
75331
  const usage = {
@@ -74259,7 +75351,8 @@ function createDurableLLMExecutionStep(_options) {
74259
75351
  payload: {
74260
75352
  stepResult: {
74261
75353
  reason: "error",
74262
- isContinued: false
75354
+ isContinued: false,
75355
+ ...modelRejectedBeforeStream && !require_stream.isMastraTimeoutError(fatalError) ? { warnings: [] } : {}
74263
75356
  },
74264
75357
  output: { usage },
74265
75358
  metadata: {}
@@ -74286,7 +75379,7 @@ function createDurableLLMExecutionStep(_options) {
74286
75379
  ownership?.throwIfLost();
74287
75380
  if (executionAbortSignalEarly?.aborted) {
74288
75381
  const earlyTimeout = resolveTotalTimeoutAbort(executionAbortSignalEarly);
74289
- if (earlyTimeout) return emitFatalErrorBail(earlyTimeout, typedInput.modelConfig?.modelId ?? "unknown", inputData.signalPreempted === true);
75382
+ if (earlyTimeout) return emitFatalErrorBail(earlyTimeout, typedInput.modelConfig?.modelId ?? "unknown", { signalPreempted: inputData.signalPreempted === true });
74290
75383
  return {
74291
75384
  ...await storeStepTranscript(),
74292
75385
  text: "",
@@ -74346,6 +75439,7 @@ function createDurableLLMExecutionStep(_options) {
74346
75439
  }];
74347
75440
  if (modelList.length === 0) throw new Error("No enabled models available for execution");
74348
75441
  let lastError;
75442
+ let modelRejectedBeforeStream = false;
74349
75443
  let skipUnavailableAttachments = false;
74350
75444
  const maxProcessorRetries = resolveMaxProcessorRetries({
74351
75445
  maxProcessorRetries: typedInput.options?.maxProcessorRetries,
@@ -74398,7 +75492,7 @@ function createDurableLLMExecutionStep(_options) {
74398
75492
  payload: { id }
74399
75493
  }, true);
74400
75494
  const totalTimeout = resolveTotalTimeoutAbort(executionAbortSignalEarly, error instanceof Error ? error : void 0);
74401
- if (totalTimeout) return emitFatalErrorBail(totalTimeout, modelId, true);
75495
+ if (totalTimeout) return emitFatalErrorBail(totalTimeout, modelId, { signalPreempted: true });
74402
75496
  return {
74403
75497
  ...await storeStepTranscript(),
74404
75498
  text: "",
@@ -74448,6 +75542,7 @@ function createDurableLLMExecutionStep(_options) {
74448
75542
  const modelEntry = modelList[modelIndex];
74449
75543
  const maxRetries = hasModelList || (typedInput.options?.agentMaxRetriesConfigured ?? false) ? modelEntry.maxRetries || 0 : typedInput.options?.modelSettings?.maxRetries ?? modelEntry.maxRetries ?? 0;
74450
75544
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
75545
+ let modelRequestRejected = false;
74451
75546
  ownership?.throwIfLost();
74452
75547
  request = {};
74453
75548
  const attemptMessageId = currentMessageId;
@@ -75086,6 +76181,9 @@ function createDurableLLMExecutionStep(_options) {
75086
76181
  includeRawChunks: execOptions.includeRawChunks,
75087
76182
  methodType: "stream",
75088
76183
  structuredOutput,
76184
+ onRequestFailed: () => {
76185
+ modelRequestRejected = true;
76186
+ },
75089
76187
  onResult: ({ warnings: w, request: r, rawResponse: rr }) => {
75090
76188
  warnings = w || [];
75091
76189
  request = r || {};
@@ -75634,6 +76732,7 @@ function createDurableLLMExecutionStep(_options) {
75634
76732
  };
75635
76733
  }
75636
76734
  lastError = errorObj;
76735
+ modelRejectedBeforeStream = modelRequestRejected;
75637
76736
  const registryEntryInner = getRunRegistryEntry(runId, mastra);
75638
76737
  const canRetryErrorInner = maxProcessorRetries !== void 0 && processorRetryCount < maxProcessorRetries;
75639
76738
  if (registryEntryInner?.errorProcessors?.length) try {
@@ -75712,6 +76811,7 @@ function createDurableLLMExecutionStep(_options) {
75712
76811
  };
75713
76812
  }
75714
76813
  lastError = streamErrorObj;
76814
+ modelRejectedBeforeStream = modelRequestRejected;
75715
76815
  if (attempt < maxRetries) continue;
75716
76816
  break;
75717
76817
  }
@@ -75934,6 +77034,7 @@ function createDurableLLMExecutionStep(_options) {
75934
77034
  if (interruption.signal.aborted) return finishInterruptedRequest(error, modelEntry.config.modelId);
75935
77035
  if (error instanceof require_stream.TripWire) throw error;
75936
77036
  lastError = error instanceof Error ? error : new Error(String(error));
77037
+ modelRejectedBeforeStream = modelRequestRejected;
75937
77038
  const selectedOuterAbortSignal = getRunRegistryEntry(runId, mastra)?.abortSignal ?? abortSignal;
75938
77039
  const outerAbortSignal = ownership?.composeSignal(selectedOuterAbortSignal) ?? selectedOuterAbortSignal;
75939
77040
  const totalTimeout = resolveTotalTimeoutAbort(outerAbortSignal, lastError);
@@ -76033,7 +77134,7 @@ function createDurableLLMExecutionStep(_options) {
76033
77134
  }
76034
77135
  const fatalError = lastError ?? /* @__PURE__ */ new Error("Exhausted all fallback models and reached the maximum number of retries.");
76035
77136
  terminalAttemptContext?.recordTerminalError(fatalError);
76036
- return emitFatalErrorBail(fatalError, modelList.at(-1)?.config.modelId ?? "unknown");
77137
+ return emitFatalErrorBail(fatalError, modelList.at(-1)?.config.modelId ?? "unknown", { modelRejectedBeforeStream });
76037
77138
  })
76038
77139
  });
76039
77140
  }
@@ -77258,6 +78359,7 @@ function createDurableToolCallStep() {
77258
78359
  mastra,
77259
78360
  runId,
77260
78361
  agentId: initData.agentId,
78362
+ agentVersionId: initData.agentVersionId,
77261
78363
  state,
77262
78364
  options: agentOptions,
77263
78365
  requestContextEntries: initData.requestContextEntries,
@@ -77277,8 +78379,9 @@ function createDurableToolCallStep() {
77277
78379
  if (!tool && !hasAuthoritativeToolSnapshot) tool = Object.values(rebuiltTools).find((t) => t && typeof t === "object" && "id" in t && t.id === toolName);
77278
78380
  }
77279
78381
  }
77280
- if (!tool && !hasAuthoritativeToolSnapshot) tool = resolveTool$1(toolName, mastra);
77281
- if (!tool && !hasAuthoritativeToolSnapshot && mastra) {
78382
+ const canUseGlobalTools = !hasAuthoritativeToolSnapshot && (!initData.agentVersionId || rebuiltTools !== void 0);
78383
+ if (!tool && canUseGlobalTools) tool = resolveTool$1(toolName, mastra);
78384
+ if (!tool && canUseGlobalTools && mastra) {
77282
78385
  mastraTools = mastra.listTools?.();
77283
78386
  if (mastraTools) {
77284
78387
  tool = findProviderToolByName(mastraTools, toolName);
@@ -78979,7 +80082,9 @@ function createDurableLLMMappingStep() {
78979
80082
  mastra,
78980
80083
  runId: _runId,
78981
80084
  agentId: _agentId,
80085
+ agentVersionId: getInitData()?.agentVersionId,
78982
80086
  state,
80087
+ options: (getInitData?.())?.options,
78983
80088
  requestContext
78984
80089
  });
78985
80090
  saveQueueManager = rebuilt?.saveQueueManager;
@@ -79428,7 +80533,10 @@ const durableAgenticInputSchema = zod.z.object({
79428
80533
  * Schema for the iteration state that flows through the dowhile loop.
79429
80534
  * Extends base schema with model list for fallback support.
79430
80535
  */
79431
- const iterationStateSchema = baseIterationStateSchema.extend({ modelList: zod.z.array(zod.z.any()).optional() });
80536
+ const iterationStateSchema = baseIterationStateSchema.extend({
80537
+ agentVersionId: zod.z.string().optional(),
80538
+ modelList: zod.z.array(zod.z.any()).optional()
80539
+ });
79432
80540
  /**
79433
80541
  * Whether a reader that attaches mid-run can read the run's earlier events. Steps publish on the
79434
80542
  * engine's bus, but `observe()` reads through the agent's own stream bus, which has no replay
@@ -79437,7 +80545,8 @@ const iterationStateSchema = baseIterationStateSchema.extend({ modelList: zod.z.
79437
80545
  function runTopicReplays(rt) {
79438
80546
  const topic = AGENT_STREAM_TOPIC(rt.runId);
79439
80547
  if (!rt.pubsub?.__replaysTopic(topic)) return false;
79440
- return (Object.values(rt.mastra?.listAgents() ?? {}).find((registered) => registered.id === rt.agentId)?.pubsub)?.__replaysTopic?.(topic) ?? true;
80548
+ const agent = Object.values(rt.mastra?.listAgents() ?? {}).find((registered) => registered.id === rt.agentId);
80549
+ return (agent?.pubsub ?? agent?.__getStreamBus?.()?.pubsub)?.__replaysTopic?.(topic) ?? true;
79441
80550
  }
79442
80551
  function liveOrRebuiltAgentSpan(agentSpanData, reg, observability) {
79443
80552
  if (!agentSpanData) return void 0;
@@ -79678,6 +80787,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
79678
80787
  return params.bail({
79679
80788
  ...update,
79680
80789
  ...await storeAccumulatedSteps(params, accumulatedSteps),
80790
+ agentVersionId: initData.agentVersionId,
79681
80791
  modelList: initData.modelList
79682
80792
  });
79683
80793
  }
@@ -79708,6 +80818,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
79708
80818
  return {
79709
80819
  runId: state.runId,
79710
80820
  agentId: state.agentId,
80821
+ agentVersionId: state.agentVersionId,
79711
80822
  agentName: state.agentName,
79712
80823
  messageListState: state.messageListState,
79713
80824
  initialUntaggedSystemMessages: state.initialUntaggedSystemMessages,
@@ -79768,6 +80879,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
79768
80879
  return {
79769
80880
  ...baseUpdate,
79770
80881
  ...await storeAccumulatedSteps(params, accumulatedSteps),
80882
+ agentVersionId: initData.agentVersionId,
79771
80883
  modelList: initData.modelList
79772
80884
  };
79773
80885
  }, { id: "update-iteration-state" }).then(isTaskCompleteStep).then(goalStep).commit();
@@ -80060,8 +81172,21 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80060
81172
  steps
80061
81173
  }
80062
81174
  });
80063
- const textRewritten = !!lastStep && finishResult.outputTextChanged;
80064
- if (lastStep && finishResult.outputTextChanged) {
81175
+ const rewrittenStepTexts = finishResult.rewrittenStepTexts;
81176
+ const textRewritten = !!lastStep && (finishResult.outputTextChanged || !!rewrittenStepTexts);
81177
+ if (rewrittenStepTexts) {
81178
+ for (const [index, text] of rewrittenStepTexts.entries()) {
81179
+ storedSteps[index] = {
81180
+ ...storedSteps[index],
81181
+ text
81182
+ };
81183
+ steps[index] = {
81184
+ ...steps[index],
81185
+ text
81186
+ };
81187
+ }
81188
+ finalText = finishResult.outputText;
81189
+ } else if (lastStep && finishResult.outputTextChanged) {
80065
81190
  lastStep.text = finishResult.outputText;
80066
81191
  steps[steps.length - 1] = {
80067
81192
  ...steps[steps.length - 1],
@@ -80116,7 +81241,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80116
81241
  if (pubsub) await emitFinishEvent(pubsub, state.runId, {
80117
81242
  output: finalOutput.output,
80118
81243
  stepResult: finalOutput.stepResult,
80119
- messages: finishMessages,
81244
+ messages: finishResult.finishMessages ?? finishMessages,
80120
81245
  ...textRewritten && { textRewritten },
80121
81246
  ...stopCause && { stopCause }
80122
81247
  });
@@ -80621,6 +81746,11 @@ var DefaultAgentExecutionEngine = class {
80621
81746
  };
80622
81747
  getWorkflow(options) {
80623
81748
  if (!this.#workflow) {
81749
+ if (options.storesRunsInJournal) {
81750
+ const storage = this.mastra?.getStorage();
81751
+ const workflowsStore = storage?.stores?.workflows;
81752
+ if (workflowsStore && !workflowsStore.supportsRunJournal()) options.guardrailLogger?.warn(`DurableAgent '${this.id}' sets storageVersion: 2, which ${storage?.name ?? "the configured"} storage doesn't support yet; storing new runs as version 1.`);
81753
+ }
80624
81754
  this.#workflow = this.createWorkflow(options);
80625
81755
  this.warnOnRiskyPersistencePolicy(options.shouldPersistSnapshot, options.guardrailLogger);
80626
81756
  if (this.mastra) {
@@ -80914,7 +82044,11 @@ var EventedAgentExecutionEngine = class extends DefaultAgentExecutionEngine {
80914
82044
  }
80915
82045
  prepareExecution(pubsub, fence, workflowEngine, logger, guardrailLogger) {
80916
82046
  const engine = this.resolveWorkflowEngine(workflowEngine, logger);
80917
- const sharedTransport = engine === "evented" && pubsub !== void 0 && !(pubsub.__rawBus() instanceof require_output_helpers.EventEmitterPubSub);
82047
+ const sharedTransport = engine === "evented" && pubsub !== void 0 && reachesOtherProcesses(pubsub);
82048
+ if (sharedTransport && this.mastra) {
82049
+ const mastra = this.mastra;
82050
+ Promise.resolve(mastra.getStorage()?.getStore("workflows")).catch(() => void 0).then((store) => warnUnsupportedEventedSetup(mastra, store)).catch(() => {});
82051
+ }
80918
82052
  const sharedExecution = sharedTransport && fence?.generation !== void 0;
80919
82053
  if (sharedTransport && !sharedExecution && !this.#warnedUnfencedSharedExecution) {
80920
82054
  this.#warnedUnfencedSharedExecution = true;
@@ -81360,7 +82494,7 @@ async function prepareForDurableExecution(options) {
81360
82494
  });
81361
82495
  let tripwireData;
81362
82496
  if (inputProcessors.length > 0) try {
81363
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-4aNIw_TQ.cjs")).then((n) => n.runner_exports);
82497
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-0kdqBOOn.cjs")).then((n) => n.runner_exports);
81364
82498
  await new ProcessorRunner({
81365
82499
  inputProcessors,
81366
82500
  outputProcessors,
@@ -81399,7 +82533,7 @@ async function prepareForDurableExecution(options) {
81399
82533
  throw inputProcessorError;
81400
82534
  }
81401
82535
  }
81402
- let requestContextEntriesSnapshot = snapshotRequestContextEntries(requestContext);
82536
+ let requestContextEntriesSnapshot = snapshotRequestContextEntries(requestContext, options.onRequestContextEntryOmitted);
81403
82537
  if (!Array.isArray(requestContextEntriesSnapshot?.["mastra__scopes"])) requestContextEntriesSnapshot = {
81404
82538
  ...requestContextEntriesSnapshot,
81405
82539
  [require_request_context.MASTRA_SCOPES_KEY]: []
@@ -83280,11 +84414,7 @@ var Agent = class Agent extends require_base.MastraBase {
83280
84414
  }
83281
84415
  const durable = config.durable;
83282
84416
  if (durable && typeof durable === "object") {
83283
- const legacyKeys = [
83284
- "maxSteps",
83285
- "id",
83286
- "name"
83287
- ].filter((key) => Object.hasOwn(durable, key));
84417
+ const legacyKeys = ["id", "name"].filter((key) => Object.hasOwn(durable, key));
83288
84418
  if (legacyKeys.length) this.logger.warn(`Agent "${this.id}" ignores durable execution options: ${legacyKeys.join(", ")}. Use createDurableAgent({ agent, ...executionOptions }) to configure wrapper-specific options. On native Agent, durable configures resumable streams and the execution engine.`);
83289
84419
  }
83290
84420
  this.#scopes = config.scopes;
@@ -83782,7 +84912,7 @@ var Agent = class Agent extends require_base.MastraBase {
83782
84912
  #warnInheritedExecutionOptions(options) {
83783
84913
  if (!this.#executionEnginePolicy.inherited) return;
83784
84914
  if (options.eagerToolExecution === true) this.#warnExecutionPolicy("eager", "Mastra-inherited execution engine policy does not support eagerToolExecution.");
83785
- if (this.#executionEnginePolicy.engine === "evented" && options.stopWhen !== void 0) this.#warnExecutionPolicy("stopWhen", "Mastra-inherited evented policy does not support stopWhen.");
84915
+ if (this.#executionEnginePolicy.engine === "evented" && options.stopWhen !== void 0) this.#warnExecutionPolicy("stopWhen", "Mastra-inherited evented execution does not carry stopWhen to another process. Set maxSteps to bound the run across processes.");
83786
84916
  }
83787
84917
  #beginExecutionPolicy() {
83788
84918
  this.#executionEnginePolicy.freeze();
@@ -84114,7 +85244,8 @@ var Agent = class Agent extends require_base.MastraBase {
84114
85244
  }
84115
85245
  processors.push(new PinnedStateProcessor({
84116
85246
  principalsKey: (context) => knowledge.__principalsKey(context),
84117
- readPins: (context) => knowledge.__deliveredPins(context)
85247
+ readPins: (context) => knowledge.__deliveredPins(context),
85248
+ ...knowledge.__toolGroups
84118
85249
  }));
84119
85250
  }
84120
85251
  return processors;
@@ -89463,6 +90594,17 @@ var Agent = class Agent extends require_base.MastraBase {
89463
90594
  return agentThreadStreamRuntime.listActiveThreadRuns(this.getPubSub());
89464
90595
  }
89465
90596
  /**
90597
+ * The resource and thread that a `runId`-only `sendSignal`, `sendMessage` or `queueMessage`
90598
+ * target resolves to, or undefined when this process doesn't track the run. Servers use it to
90599
+ * check that a caller owns the run before sending to it. Core rejects a target whose `resourceId` doesn't own
90600
+ * its `runId`, but that is a consistency check, not authorization: Core doesn't know who is calling and trusts a
90601
+ * `runId`-only target. Callers that take `runId` from untrusted input must authenticate the caller and compare
90602
+ * this owner with the caller's trusted resource before sending.
90603
+ */
90604
+ getThreadRunTarget(runId) {
90605
+ return agentThreadStreamRuntime.getThreadRunTarget(runId, this.getPubSub());
90606
+ }
90607
+ /**
89466
90608
  * Lists suspended agent runs from workflow snapshot storage — runs waiting on
89467
90609
  * a tool-call approval (`requireApproval` / `requireToolApproval`) or on a
89468
90610
  * tool that called `suspend()`.
@@ -90811,6 +91953,7 @@ var Agent = class Agent extends require_base.MastraBase {
90811
91953
  - always produce a title, even when the transcript is only a greeting or trivial exchange
90812
91954
  - ensure it is not more than 80 characters long
90813
91955
  - the title should be a summary of the user's message
91956
+ - write the title in the same language the user's messages are written in
90814
91957
  - do not use quotes or colons
90815
91958
  - the entire text you return will be used as the title`;
90816
91959
  if (!instructions) return DEFAULT_TITLE_INSTRUCTIONS;
@@ -90837,10 +91980,13 @@ var Agent = class Agent extends require_base.MastraBase {
90837
91980
  return this.#executionEnginePolicy.engine === "evented" ? "evented" : "default";
90838
91981
  }
90839
91982
  getWorkflow() {
91983
+ const durable = this.durable;
91984
+ const config = typeof durable === "object" ? durable : void 0;
90840
91985
  return this.executionEngine.getWorkflow({
91986
+ maxSteps: config?.maxSteps,
90841
91987
  workflowEngine: this.workflowEngine,
90842
- storesRunsInJournal: false,
90843
- shouldPersistSnapshot: typeof this.durable === "object" ? this.durable.shouldPersistSnapshot : void 0,
91988
+ storesRunsInJournal: config?.storageVersion === 2,
91989
+ shouldPersistSnapshot: config?.shouldPersistSnapshot,
90844
91990
  logger: this.logger,
90845
91991
  guardrailLogger: this.guardrailLogger
90846
91992
  });
@@ -91825,8 +92971,8 @@ var Agent = class Agent extends require_base.MastraBase {
91825
92971
  async #resolveDurableRunOptions(options, snapshot) {
91826
92972
  if (options?.[RESOLVED_EXECUTION_OPTIONS]) return options;
91827
92973
  const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });
91828
- this.#warnInheritedExecutionOptions(defaultOptions);
91829
92974
  const resolvedOptions = require_utils$1.deepMerge(withDefaultToolCallConcurrencyLimit(defaultOptions ?? {}, options), options ?? {});
92975
+ this.#warnInheritedExecutionOptions(resolvedOptions);
91830
92976
  if (options?.actor !== void 0) resolvedOptions.actor = options.actor;
91831
92977
  const scopedOptions = await this.#applyScopes(resolvedOptions, {
91832
92978
  callScopes: options?.scopes,
@@ -92122,6 +93268,7 @@ var Agent = class Agent extends require_base.MastraBase {
92122
93268
  optionsAreResolved: true,
92123
93269
  resolvedDefaultOptions: options?.[RESOLVED_DEFAULT_OPTIONS],
92124
93270
  scopesResolved: true,
93271
+ onRequestContextEntryOmitted: this.#executionEnginePolicy.inherited ? () => this.#warnExecutionPolicy("requestContextSnapshot", "Mastra-inherited durable execution omitted a value from the request context snapshot. Use JSON-safe values that fit in the snapshot if another process needs them.") : void 0,
92125
93272
  mastra: this.#mastra,
92126
93273
  methodType,
92127
93274
  durableAgentId: this.id,
@@ -93232,7 +94379,7 @@ var Agent = class Agent extends require_base.MastraBase {
93232
94379
  *
93233
94380
  * @internal
93234
94381
  */
93235
- async subscribeToDurableRunStream(runId, options, onEvent) {
94382
+ async __subscribeToRunStream(runId, options, onEvent) {
93236
94383
  const pubsub = this.#executionStreamBus.forRun(this.__usesSharedRunLog()).pubsub;
93237
94384
  const replayFloor = await this.#readReplayFloor(runId, options.offset);
93238
94385
  const keepGeneration = createRunGenerationFilter(replayFloor);
@@ -95408,44 +96555,6 @@ function resolveRegisteredClassifier(mastra, classifierId, scorerId) {
95408
96555
  throw new Error(`Classifier '${classifierId}' not found for scorer '${scorerId}'. Register it with Mastra classifiers or pass the classifier instance directly.`, { cause: error });
95409
96556
  }
95410
96557
  }
95411
- // src/mastra/resolve-agent.ts
95412
- /**
95413
- * Resolve an agent by id the same way server handlers do: in-memory registry
95414
- * first, then the editor for stored agents.
95415
- *
95416
- * Stored (editor) agents aren't registered on the Mastra instance until
95417
- * they've been hydrated once in the current process, so a registry miss does
95418
- * not mean the agent is gone — especially on a cold start. Editor hydration
95419
- * via `getById` also re-registers the agent, so subsequent lookups take the
95420
- * fast registry path.
95421
- *
95422
- * Every internal call site that needs "does this agent exist / give it to
95423
- * me" semantics should go through this helper so the fallback (and the
95424
- * confirmed-miss vs. transient-error distinction) can't drift between call
95425
- * sites.
95426
- */
95427
- async function resolveAgentById(mastra, agentId) {
95428
- try {
95429
- return {
95430
- status: "found",
95431
- agent: mastra.getAgentById(agentId)
95432
- };
95433
- } catch {}
95434
- const editor = mastra.getEditor?.();
95435
- if (!editor) return { status: "missing" };
95436
- try {
95437
- const agent = await editor.agent.getById(agentId);
95438
- return agent ? {
95439
- status: "found",
95440
- agent
95441
- } : { status: "missing" };
95442
- } catch (error) {
95443
- return {
95444
- status: "error",
95445
- error
95446
- };
95447
- }
95448
- }
95449
96558
  // src/mastra/hooks.ts
95450
96559
  function toScorerTargetEntityType(entityType) {
95451
96560
  switch (entityType) {
@@ -102129,7 +103238,7 @@ var AgentThreadStreamRuntime = class {
102129
103238
  * `generation` only to name the owner a new acquisition takes.
102130
103239
  */
102131
103240
  #threadLeaseOwner(pubsub, runId, generation) {
102132
- if (this.#getPubSub(pubsub).__rawBus() instanceof require_output_helpers.EventEmitterPubSub) return threadLeaseOwner(runId);
103241
+ if (!reachesOtherProcesses(this.#getPubSub(pubsub))) return threadLeaseOwner(runId);
102133
103242
  if (generation !== void 0) return threadLeaseOwner(runId, generation);
102134
103243
  const state = this.#getState(pubsub);
102135
103244
  return state.leaseOwners.get(runId) ?? threadLeaseOwner(runId, state.threadRunsById.get(runId)?.generation);
@@ -102261,6 +103370,12 @@ var AgentThreadStreamRuntime = class {
102261
103370
  type: "run-suspended",
102262
103371
  runId,
102263
103372
  streamId
103373
+ } : hasDurableExecution(record.agent) ? {
103374
+ type: "run-completed",
103375
+ runId,
103376
+ streamId,
103377
+ persisted: false,
103378
+ status: "interrupted"
102264
103379
  } : {
102265
103380
  type: "run-completed",
102266
103381
  runId,
@@ -102796,14 +103911,20 @@ var AgentThreadStreamRuntime = class {
102796
103911
  if (!answersTo(runId)) return;
102797
103912
  const queues = data.preRun ? state.preRunSignalsByThread : state.pendingSignalsByThread;
102798
103913
  if ([state.preRunSignalsByThread.get(key), state.pendingSignalsByThread.get(key)].some((queue) => queue?.some((signal) => signal.id === data.signal.id))) return;
102799
- const queue = queues.get(key) ?? [];
102800
103914
  const signal = require_signals.createSignal(data.signal);
103915
+ if (this.#pendingUserMessageChunk(runId, signal, "pending")) this.#publish(pubsub, key, {
103916
+ type: "user-message-admitted",
103917
+ signalId: signal.id,
103918
+ admittedRunId: runId
103919
+ });
103920
+ const queue = queues.get(key) ?? [];
102801
103921
  queue.push(signal);
102802
103922
  queues.set(key, queue);
102803
103923
  subscription.admittedSignalIds.add(data.signal.id);
102804
103924
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
102805
103925
  this.#notifyPendingSignals(state, key, signal);
102806
- } else if (data?.type === "user-message-presentation") {
103926
+ } else if (data?.type === "user-message-admitted") this.#settleForwardedIdleSignal(state, key, data.signalId, data.admittedRunId);
103927
+ else if (data?.type === "user-message-presentation") {
102807
103928
  const { chunk } = data;
102808
103929
  if (chunk.type === "data-user-message-pending" && chunk.data.metadata?.status === "pending") this.#settleForwardedIdleSignal(state, key, chunk.data.id, chunk.runId);
102809
103930
  } else if (data?.type === "signals-cancelled") {
@@ -102856,7 +103977,7 @@ var AgentThreadStreamRuntime = class {
102856
103977
  const onEvent = (event, ack) => {
102857
103978
  const type = event.data?.type;
102858
103979
  const awaitingForwards = state.forwardedIdleSignalsByThread.has(key);
102859
- if (type !== "signal-enqueued" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !(type === "user-message-presentation" && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
103980
+ if (type !== "signal-enqueued" && type !== "signals-cancelled" && type !== "run-abort-requested" && type !== "run-registered" && !((type === "user-message-presentation" || type === "user-message-admitted") && awaitingForwards) && !((type === "run-completed" || type === "run-failed") && (awaitingForwards || subscription.successorRunIds.has(event.data.runId) || this.#localActiveRunId(state, key) !== void 0)) && !((type === "run-aborted" || type === "run-discarded") && this.#localActiveRunId(state, key) !== void 0) && !(type === "run-discarded" && awaitingForwards)) return ack?.();
102860
103981
  subscription.references++;
102861
103982
  const handled = tail.then(() => handleEvent(event));
102862
103983
  tail = handled.catch(() => {});
@@ -102933,6 +104054,17 @@ var AgentThreadStreamRuntime = class {
102933
104054
  }
102934
104055
  for (const key of state.threadControlSubscriptions.keys()) this.#releaseUnusedThreadControlSubscription(state, key);
102935
104056
  }
104057
+ /**
104058
+ * A `runId` target that also names a `resourceId` must name the run's own resource. Without this, the signal
104059
+ * would be created for the caller's resource and delivered into another resource's run. Core cannot know who the
104060
+ * caller is: a target naming only a `runId` is trusted, so callers exposing `runId` targets to untrusted input
104061
+ * must pass the caller's `resourceId` or check ownership with `getThreadRunTarget()` first.
104062
+ */
104063
+ #assertRunTargetOwner(state, target) {
104064
+ if (!target.runId || !target.resourceId) return;
104065
+ const owner = state.threadRunsById.get(target.runId)?.resourceId;
104066
+ if (owner && owner !== target.resourceId) throw new Error(`Agent run ${target.runId} belongs to a different resource`);
104067
+ }
102936
104068
  #threadKey(resourceId, threadId) {
102937
104069
  return agentThreadStreamKey(resourceId, threadId);
102938
104070
  }
@@ -103829,7 +104961,7 @@ var AgentThreadStreamRuntime = class {
103829
104961
  const topic = this.#threadTopic(key);
103830
104962
  await resolvedPubSub.publish(topic, {
103831
104963
  type: event.type,
103832
- runId: "runId" in event ? event.runId : key,
104964
+ runId: ("runId" in event ? event.runId : void 0) ?? key,
103833
104965
  data: event
103834
104966
  });
103835
104967
  }
@@ -104436,6 +105568,14 @@ var AgentThreadStreamRuntime = class {
104436
105568
  hasThreadRun(runId, pubsub) {
104437
105569
  return this.#getState(pubsub).threadRunsById.has(runId);
104438
105570
  }
105571
+ /** The resource and thread a `runId`-only signal or message target resolves to in this process. */
105572
+ getThreadRunTarget(runId, pubsub) {
105573
+ const record = this.#getState(pubsub).threadRunsById.get(runId);
105574
+ return record ? {
105575
+ resourceId: record.resourceId,
105576
+ threadId: record.threadId
105577
+ } : void 0;
105578
+ }
104439
105579
  /** Whether the run's original stream is still live and carries its resumed segments. */
104440
105580
  hasRunContinuation(runId, pubsub) {
104441
105581
  return this.#getState(pubsub).threadRunsById.get(runId)?.continuation?.canContinue() === true;
@@ -104668,6 +105808,7 @@ var AgentThreadStreamRuntime = class {
104668
105808
  const chunk = this.#pendingUserMessageChunk(runId, signal, status);
104669
105809
  if (chunk) this.#publish(pubsub, key, {
104670
105810
  type: "user-message-presentation",
105811
+ runId,
104671
105812
  chunk
104672
105813
  });
104673
105814
  }
@@ -105785,6 +106926,7 @@ var AgentThreadStreamRuntime = class {
105785
106926
  const statuses = [];
105786
106927
  const settledRunIds = /* @__PURE__ */ new Map();
105787
106928
  const reportedSuspensions = /* @__PURE__ */ new Set();
106929
+ const reportedInterruptions = /* @__PURE__ */ new Set();
105788
106930
  const presentations = [];
105789
106931
  const presentedSignalIds = /* @__PURE__ */ new Set();
105790
106932
  const settledSignalIds = /* @__PURE__ */ new Set();
@@ -105806,6 +106948,9 @@ var AgentThreadStreamRuntime = class {
105806
106948
  if (status === "suspended") {
105807
106949
  if (reportedSuspensions.has(streamId)) return;
105808
106950
  reportedSuspensions.add(streamId);
106951
+ } else if (status === "interrupted") {
106952
+ if (reportedInterruptions.has(streamId)) return;
106953
+ reportedInterruptions.add(streamId);
105809
106954
  } else settledRunIds.set(runId, streamId);
105810
106955
  if (!options.withRunStatus) return;
105811
106956
  statuses.push({
@@ -106290,7 +107435,7 @@ var AgentThreadStreamRuntime = class {
106290
107435
  if (data.type !== "run-suspended") parkedPromptRunIds.delete(data.runId);
106291
107436
  if (data.type === "run-completed") await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
106292
107437
  if (data.type !== "run-suspended" || !suspendedRunEnded) {
106293
- const status = data.type === "run-aborted" ? "aborted" : data.type === "run-suspended" || data.status === "suspended" ? "suspended" : data.status === "canceled" ? "aborted" : data.status === "success" || data.status === void 0 && data.persisted !== false ? "success" : "failed";
107438
+ const status = data.type === "run-aborted" ? "aborted" : data.type === "run-suspended" || data.status === "suspended" ? "suspended" : data.status === "canceled" ? "aborted" : data.status === "interrupted" ? "interrupted" : data.status === "success" || data.status === void 0 && data.persisted !== false ? "success" : "failed";
106294
107439
  enqueueStatus(data.runId, eventStreamId, status);
106295
107440
  }
106296
107441
  wake();
@@ -106776,6 +107921,7 @@ var AgentThreadStreamRuntime = class {
106776
107921
  activeRecord ??= state.threadRunsById.get(runId);
106777
107922
  if (activeRecord) key ??= this.#threadKey(activeRecord.resourceId, activeRecord.threadId);
106778
107923
  }
107924
+ this.#assertRunTargetOwner(state, target);
106779
107925
  const resourceId = target.resourceId ?? activeRecord?.resourceId;
106780
107926
  const threadId = target.threadId ?? activeRecord?.threadId;
106781
107927
  if (!resourceId || !threadId) throw new Error("resourceId and threadId are required to queue a message");
@@ -106935,6 +108081,7 @@ var AgentThreadStreamRuntime = class {
106935
108081
  activeRecord ??= state.threadRunsById.get(runId);
106936
108082
  if (activeRecord) key ??= this.#threadKey(activeRecord.resourceId, activeRecord.threadId);
106937
108083
  }
108084
+ this.#assertRunTargetOwner(state, target);
106938
108085
  const resourceId = target.resourceId ?? activeRecord?.resourceId;
106939
108086
  const threadId = target.threadId ?? activeRecord?.threadId;
106940
108087
  if (!resourceId || !threadId) throw new Error("No active agent run found for signal target");
@@ -107636,7 +108783,7 @@ function getActiveDurableAgentWorkflowExecutions(mastra) {
107636
108783
  * execution behind a broker, which another process may be executing.
107637
108784
  */
107638
108785
  function detachesOnShutdown(mastra, entry) {
107639
- return !!entry.eventedExecution && !(mastra.pubsub.__rawBus() instanceof require_output_helpers.EventEmitterPubSub);
108786
+ return !!entry.eventedExecution && reachesOtherProcesses(mastra.pubsub);
107640
108787
  }
107641
108788
  function isDurableAgentExecutionDetached(mastra, runId) {
107642
108789
  const entry = globalRunRegistry.has(runId) ? globalRunRegistry.get(runId) : void 0;
@@ -108208,6 +109355,36 @@ Object.defineProperty(exports, "KnowledgeDeclarationError", {
108208
109355
  return KnowledgeDeclarationError;
108209
109356
  }
108210
109357
  });
109358
+ Object.defineProperty(exports, "KnowledgeImporterBindingConflictError", {
109359
+ enumerable: true,
109360
+ get: function() {
109361
+ return KnowledgeImporterBindingConflictError;
109362
+ }
109363
+ });
109364
+ Object.defineProperty(exports, "KnowledgeImporterRunStateError", {
109365
+ enumerable: true,
109366
+ get: function() {
109367
+ return KnowledgeImporterRunStateError;
109368
+ }
109369
+ });
109370
+ Object.defineProperty(exports, "KnowledgeImportersStorage", {
109371
+ enumerable: true,
109372
+ get: function() {
109373
+ return KnowledgeImportersStorage;
109374
+ }
109375
+ });
109376
+ Object.defineProperty(exports, "KnowledgeInvalidCursorError", {
109377
+ enumerable: true,
109378
+ get: function() {
109379
+ return KnowledgeInvalidCursorError;
109380
+ }
109381
+ });
109382
+ Object.defineProperty(exports, "KnowledgeLinkRefreshIncompleteError", {
109383
+ enumerable: true,
109384
+ get: function() {
109385
+ return KnowledgeLinkRefreshIncompleteError;
109386
+ }
109387
+ });
108211
109388
  Object.defineProperty(exports, "KnowledgeMoveTooLargeError", {
108212
109389
  enumerable: true,
108213
109390
  get: function() {
@@ -108262,6 +109439,12 @@ Object.defineProperty(exports, "KnowledgeStorage", {
108262
109439
  return KnowledgeStorage;
108263
109440
  }
108264
109441
  });
109442
+ Object.defineProperty(exports, "KnowledgeTransactionDeadlineError", {
109443
+ enumerable: true,
109444
+ get: function() {
109445
+ return KnowledgeTransactionDeadlineError;
109446
+ }
109447
+ });
108265
109448
  Object.defineProperty(exports, "KnowledgeUnsupportedCapabilityError", {
108266
109449
  enumerable: true,
108267
109450
  get: function() {
@@ -109936,6 +111119,12 @@ Object.defineProperty(exports, "groupLinkedToolMessages", {
109936
111119
  return groupLinkedToolMessages;
109937
111120
  }
109938
111121
  });
111122
+ Object.defineProperty(exports, "hasDurableExecution", {
111123
+ enumerable: true,
111124
+ get: function() {
111125
+ return hasDurableExecution;
111126
+ }
111127
+ });
109939
111128
  Object.defineProperty(exports, "hasErrorCode", {
109940
111129
  enumerable: true,
109941
111130
  get: function() {
@@ -110158,6 +111347,12 @@ Object.defineProperty(exports, "knowledgeSemanticIdempotencyKey", {
110158
111347
  return knowledgeSemanticIdempotencyKey;
110159
111348
  }
110160
111349
  });
111350
+ Object.defineProperty(exports, "knowledgeSubtree", {
111351
+ enumerable: true,
111352
+ get: function() {
111353
+ return knowledgeSubtree;
111354
+ }
111355
+ });
110161
111356
  Object.defineProperty(exports, "knowledgeVisibleScopeKeys", {
110162
111357
  enumerable: true,
110163
111358
  get: function() {
@@ -110794,6 +111989,12 @@ Object.defineProperty(exports, "summarizeNotifications", {
110794
111989
  return summarizeNotifications;
110795
111990
  }
110796
111991
  });
111992
+ Object.defineProperty(exports, "syncKnowledgePageBodyLinks", {
111993
+ enumerable: true,
111994
+ get: function() {
111995
+ return syncKnowledgePageBodyLinks;
111996
+ }
111997
+ });
110797
111998
  Object.defineProperty(exports, "takeRunScorerInstances", {
110798
111999
  enumerable: true,
110799
112000
  get: function() {