@mastra/core 1.86.0-alpha.8 → 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 (459) 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 +12 -0
  5. package/dist/agent/durable/index.cjs +1 -13
  6. package/dist/agent/durable/index.js +1 -13
  7. package/dist/agent/durable/preparation.d.ts +2 -0
  8. package/dist/agent/durable/utils/resolve-runtime.d.ts +9 -0
  9. package/dist/agent/durable/workflows/durable-loop-builder.d.ts +4 -0
  10. package/dist/agent/durable/workflows/finalize-run.d.ts +3 -1
  11. package/dist/agent/durable/workflows/steps/llm-execution.d.ts +1 -0
  12. package/dist/agent/index.cjs +3 -3
  13. package/dist/agent/index.js +3 -3
  14. package/dist/agent/message-list/index.cjs +1 -1
  15. package/dist/agent/message-list/index.js +1 -1
  16. package/dist/agent/message-list/message-list.d.ts +11 -0
  17. package/dist/agent/message-list/utils/provider-compat.d.ts +1 -0
  18. package/dist/agent/request-context-snapshot.d.ts +1 -1
  19. package/dist/agent/streams/types.d.ts +10 -0
  20. package/dist/agent/thread-stream-runtime.d.ts +5 -0
  21. package/dist/agent-builder/ee/index.cjs +1 -1
  22. package/dist/agent-builder/ee/index.js +1 -1
  23. package/dist/agent-controller/index.cjs +1 -1
  24. package/dist/agent-controller/index.js +1 -1
  25. package/dist/{agent-controller-DEPayioq.cjs → agent-controller-CrQ9OF80.cjs} +7 -7
  26. package/dist/{agent-controller-B7POPub5.js → agent-controller-SSlKzE6A.js} +7 -7
  27. package/dist/background-tasks/index.cjs +1 -1
  28. package/dist/background-tasks/index.js +1 -1
  29. package/dist/{background-tasks-7iftnRK_.cjs → background-tasks-BDrYBis-.cjs} +5 -3
  30. package/dist/{background-tasks-Cv1ecD6S.js → background-tasks-BnJfNLFo.js} +5 -3
  31. package/dist/browser/index.cjs +2 -2
  32. package/dist/browser/index.js +2 -2
  33. package/dist/{builder-Gg-xnX_E.js → builder-Cl-0BWkh.js} +2 -2
  34. package/dist/{builder-DuJBbQDH.cjs → builder-Cw8u3pPl.cjs} +2 -2
  35. package/dist/capabilities/302ai.json +204 -204
  36. package/dist/capabilities/abliteratedllm.json +30 -30
  37. package/dist/capabilities/above.json +21 -21
  38. package/dist/capabilities/adaption.json +15 -15
  39. package/dist/capabilities/adzuki.json +24 -24
  40. package/dist/capabilities/agentrouter.json +9 -9
  41. package/dist/capabilities/agnes.json +3 -3
  42. package/dist/capabilities/ai-router.json +8 -8
  43. package/dist/capabilities/aiand.json +31 -23
  44. package/dist/capabilities/aigrow.json +14 -14
  45. package/dist/capabilities/aimlapi.json +144 -147
  46. package/dist/capabilities/aipg.json +2 -2
  47. package/dist/capabilities/aixy.json +21 -21
  48. package/dist/capabilities/aki-io.json +10 -10
  49. package/dist/capabilities/alibaba-cn.json +136 -117
  50. package/dist/capabilities/alibaba-coding-plan-cn.json +7 -19
  51. package/dist/capabilities/alibaba-coding-plan.json +7 -19
  52. package/dist/capabilities/alibaba-token-plan-cn.json +49 -67
  53. package/dist/capabilities/alibaba-token-plan.json +50 -68
  54. package/dist/capabilities/alibaba.json +72 -119
  55. package/dist/capabilities/ambient.json +8 -8
  56. package/dist/capabilities/amd.json +10 -10
  57. package/dist/capabilities/anthropic.json +47 -47
  58. package/dist/capabilities/anyapi.json +19 -19
  59. package/dist/capabilities/apiko.json +5 -5
  60. package/dist/capabilities/arcee.json +11 -11
  61. package/dist/capabilities/augure.json +2 -2
  62. package/dist/capabilities/auriko.json +23 -23
  63. package/dist/capabilities/bailing.json +4 -4
  64. package/dist/capabilities/baseten.json +55 -25
  65. package/dist/capabilities/bee.json +4 -4
  66. package/dist/capabilities/berget.json +5 -5
  67. package/dist/capabilities/bothub.json +17 -17
  68. package/dist/capabilities/boundless.json +37 -37
  69. package/dist/capabilities/bumo.json +41 -41
  70. package/dist/capabilities/byteplus.json +26 -26
  71. package/dist/capabilities/cerebras.json +4 -4
  72. package/dist/capabilities/cheapaimodel.json +3 -3
  73. package/dist/capabilities/cheapest-token.json +30 -30
  74. package/dist/capabilities/chutes.json +10 -10
  75. package/dist/capabilities/cline-pass.json +39 -39
  76. package/dist/capabilities/cloudcode.json +9 -9
  77. package/dist/capabilities/cloudferro-sherlock.json +4 -4
  78. package/dist/capabilities/cloudflare-workers-ai.json +33 -33
  79. package/dist/capabilities/commandcode.json +139 -139
  80. package/dist/capabilities/concentrate.json +274 -274
  81. package/dist/capabilities/cortecs.json +108 -108
  82. package/dist/capabilities/crossmodel.json +189 -189
  83. package/dist/capabilities/crusoe.json +10 -10
  84. package/dist/capabilities/daoxe.json +9 -9
  85. package/dist/capabilities/databricks.json +315 -59
  86. package/dist/capabilities/deepinfra.json +90 -155
  87. package/dist/capabilities/deepseek.json +2 -2
  88. package/dist/capabilities/digitalocean.json +114 -114
  89. package/dist/capabilities/dothoosh.json +34 -34
  90. package/dist/capabilities/doubleword.json +28 -28
  91. package/dist/capabilities/edenai.json +433 -433
  92. package/dist/capabilities/empiriolabs.json +176 -176
  93. package/dist/capabilities/engy.json +17 -17
  94. package/dist/capabilities/entrim.json +6 -6
  95. package/dist/capabilities/evroc.json +13 -13
  96. package/dist/capabilities/ezkielyna.json +12 -12
  97. package/dist/capabilities/fastrouter.json +88 -88
  98. package/dist/capabilities/fireworks-ai.json +104 -41
  99. package/dist/capabilities/freemodel.json +20 -20
  100. package/dist/capabilities/friendli.json +9 -9
  101. package/dist/capabilities/frogbot.json +93 -93
  102. package/dist/capabilities/gisoo.json +19 -19
  103. package/dist/capabilities/gmicloud.json +21 -21
  104. package/dist/capabilities/google.json +55 -55
  105. package/dist/capabilities/graphn.json +11 -11
  106. package/dist/capabilities/greenpt.json +36 -36
  107. package/dist/capabilities/groq.json +9 -9
  108. package/dist/capabilities/helicone.json +83 -83
  109. package/dist/capabilities/hostinger-router.json +13 -13
  110. package/dist/capabilities/hpc-ai.json +8 -8
  111. package/dist/capabilities/huawei-maas.json +17 -17
  112. package/dist/capabilities/hubris.json +28 -28
  113. package/dist/capabilities/huggingface.json +200 -53
  114. package/dist/capabilities/humain.json +2 -2
  115. package/dist/capabilities/hyper.json +26 -26
  116. package/dist/capabilities/impossibl.json +127 -127
  117. package/dist/capabilities/inception.json +2 -2
  118. package/dist/capabilities/inceptron.json +8 -8
  119. package/dist/capabilities/inco.json +4 -4
  120. package/dist/capabilities/infer.json +14 -14
  121. package/dist/capabilities/inference-coop.json +15 -15
  122. package/dist/capabilities/inferenceapis.json +22 -22
  123. package/dist/capabilities/inferris.json +3 -3
  124. package/dist/capabilities/infersia.json +9 -9
  125. package/dist/capabilities/inferx.json +3 -3
  126. package/dist/capabilities/infomaniak.json +4 -4
  127. package/dist/capabilities/io-net.json +5 -5
  128. package/dist/capabilities/isoquant.json +4 -4
  129. package/dist/capabilities/iteracompute.json +51 -51
  130. package/dist/capabilities/jalapeno.json +12 -12
  131. package/dist/capabilities/jiekou.json +65 -65
  132. package/dist/capabilities/joingonka.json +4 -4
  133. package/dist/capabilities/jzstoken.json +54 -54
  134. package/dist/capabilities/keln.json +21 -28
  135. package/dist/capabilities/kenari.json +124 -121
  136. package/dist/capabilities/kilo.json +635 -636
  137. package/dist/capabilities/kimi-code-plan-cn.json +6 -6
  138. package/dist/capabilities/kimi-code-plan-global.json +6 -6
  139. package/dist/capabilities/kitani.json +4 -4
  140. package/dist/capabilities/klavo.json +13 -13
  141. package/dist/capabilities/korouter.json +31 -31
  142. package/dist/capabilities/kunavo.json +9 -9
  143. package/dist/capabilities/liquid.json +10 -10
  144. package/dist/capabilities/llmgateway-providers.json +909 -909
  145. package/dist/capabilities/llmgateway.json +333 -333
  146. package/dist/capabilities/llmtr.json +19 -19
  147. package/dist/capabilities/logits.json +2 -2
  148. package/dist/capabilities/longcat.json +1 -6
  149. package/dist/capabilities/lowrouter.json +52 -52
  150. package/dist/capabilities/lyceum.json +7 -7
  151. package/dist/capabilities/melious.json +16 -16
  152. package/dist/capabilities/merge-gateway.json +275 -275
  153. package/dist/capabilities/meta.json +9 -9
  154. package/dist/capabilities/minimax-cn-coding-plan.json +6 -6
  155. package/dist/capabilities/minimax-coding-plan.json +6 -6
  156. package/dist/capabilities/mistral.json +18 -18
  157. package/dist/capabilities/mixlayer.json +5 -5
  158. package/dist/capabilities/modal.json +13 -13
  159. package/dist/capabilities/model-oracle-ai.json +26 -26
  160. package/dist/capabilities/modelis.json +24 -24
  161. package/dist/capabilities/modelscope.json +2 -2
  162. package/dist/capabilities/modular.json +9 -9
  163. package/dist/capabilities/moneo.json +14 -14
  164. package/dist/capabilities/moonshotai-cn.json +6 -6
  165. package/dist/capabilities/moonshotai.json +6 -6
  166. package/dist/capabilities/morph.json +13 -13
  167. package/dist/capabilities/munito-eu.json +6 -6
  168. package/dist/capabilities/munito.json +10 -10
  169. package/dist/capabilities/nan.json +24 -24
  170. package/dist/capabilities/nano-gpt.json +577 -577
  171. package/dist/capabilities/nearai.json +82 -82
  172. package/dist/capabilities/nebius.json +29 -29
  173. package/dist/capabilities/neon.json +134 -134
  174. package/dist/capabilities/neuralwatt.json +43 -43
  175. package/dist/capabilities/nokeep.json +4 -4
  176. package/dist/capabilities/novita-ai.json +135 -135
  177. package/dist/capabilities/nvidia.json +38 -38
  178. package/dist/capabilities/oathbreaker.json +2 -2
  179. package/dist/capabilities/obscurify.json +26 -26
  180. package/dist/capabilities/oci.json +5 -5
  181. package/dist/capabilities/ofox.json +338 -338
  182. package/dist/capabilities/ollama-cloud.json +55 -55
  183. package/dist/capabilities/openai.json +48 -48
  184. package/dist/capabilities/opencode-go.json +81 -81
  185. package/dist/capabilities/openreason.json +5 -5
  186. package/dist/capabilities/openrouter.json +548 -563
  187. package/dist/capabilities/opper.json +23 -23
  188. package/dist/capabilities/orcarouter.json +212 -212
  189. package/dist/capabilities/outerlabs.json +30 -30
  190. package/dist/capabilities/ovhcloud.json +8 -8
  191. package/dist/capabilities/pareto.json +5 -5
  192. package/dist/capabilities/pendra.json +4 -4
  193. package/dist/capabilities/perplexity-agent.json +59 -59
  194. package/dist/capabilities/perplexity.json +2 -2
  195. package/dist/capabilities/phala.json +27 -27
  196. package/dist/capabilities/pioneer.json +24 -24
  197. package/dist/capabilities/poe.json +136 -136
  198. package/dist/capabilities/powerspring.json +14 -14
  199. package/dist/capabilities/primalabs.json +7 -7
  200. package/dist/capabilities/prime.json +108 -108
  201. package/dist/capabilities/privatemode-ai.json +12 -12
  202. package/dist/capabilities/proxystacks.json +6 -6
  203. package/dist/capabilities/qiniu-ai.json +15 -15
  204. package/dist/capabilities/refuseless.json +9 -9
  205. package/dist/capabilities/regolo-ai.json +6 -6
  206. package/dist/capabilities/requesty.json +171 -171
  207. package/dist/capabilities/ruapi.json +20 -20
  208. package/dist/capabilities/runcrate.json +16 -16
  209. package/dist/capabilities/runinfra.json +17 -17
  210. package/dist/capabilities/sakana.json +6 -6
  211. package/dist/capabilities/sambanova.json +6 -6
  212. package/dist/capabilities/sandbase.json +16 -16
  213. package/dist/capabilities/sarvam.json +12 -12
  214. package/dist/capabilities/scaleway.json +17 -17
  215. package/dist/capabilities/scnet-token-plan.json +8 -8
  216. package/dist/capabilities/scx-ai.json +29 -29
  217. package/dist/capabilities/sensenova.json +14 -14
  218. package/dist/capabilities/siliconflow-cn.json +61 -61
  219. package/dist/capabilities/siliconflow.json +57 -57
  220. package/dist/capabilities/snowflake-cortex.json +24 -24
  221. package/dist/capabilities/sokkan.json +10 -10
  222. package/dist/capabilities/sparrowcodes.json +24 -24
  223. package/dist/capabilities/standardcompute.json +89 -89
  224. package/dist/capabilities/steadyrouter.json +38 -38
  225. package/dist/capabilities/stepfun-ai-step-plan.json +7 -7
  226. package/dist/capabilities/stepfun-ai.json +16 -9
  227. package/dist/capabilities/stepfun-step-plan.json +16 -9
  228. package/dist/capabilities/stepfun.json +16 -9
  229. package/dist/capabilities/stepping-stone.json +18 -18
  230. package/dist/capabilities/subconscious.json +2 -2
  231. package/dist/capabilities/synthetic.json +12 -12
  232. package/dist/capabilities/synthorai.json +26 -26
  233. package/dist/capabilities/teamorouter.json +21 -21
  234. package/dist/capabilities/teapot-router.json +9 -9
  235. package/dist/capabilities/tencent-coding-plan.json +1 -23
  236. package/dist/capabilities/tencent-token-plan.json +57 -20
  237. package/dist/capabilities/tencent-tokenhub.json +182 -7
  238. package/dist/capabilities/tensorx.json +36 -36
  239. package/dist/capabilities/the-grid-ai.json +29 -29
  240. package/dist/capabilities/thinkingmachines.json +73 -56
  241. package/dist/capabilities/tinfoil.json +9 -9
  242. package/dist/capabilities/toapis.json +3 -3
  243. package/dist/capabilities/togetherai.json +61 -90
  244. package/dist/capabilities/tokengo.json +21 -21
  245. package/dist/capabilities/tokenify.json +9 -9
  246. package/dist/capabilities/trustedrouter.json +7 -7
  247. package/dist/capabilities/trustedtokens.json +14 -14
  248. package/dist/capabilities/umans-ai-coding-plan.json +13 -13
  249. package/dist/capabilities/umans-ai.json +10 -10
  250. package/dist/capabilities/uncensuredai.json +4 -4
  251. package/dist/capabilities/unrestricted.json +4 -4
  252. package/dist/capabilities/uplinkswitch.json +19 -19
  253. package/dist/capabilities/upstage.json +6 -6
  254. package/dist/capabilities/vancine.json +19 -19
  255. package/dist/capabilities/vercel.json +558 -537
  256. package/dist/capabilities/vivgrid.json +78 -78
  257. package/dist/capabilities/volcengine-coding-plan.json +26 -56
  258. package/dist/capabilities/volcengine.json +57 -62
  259. package/dist/capabilities/vultr.json +28 -28
  260. package/dist/capabilities/wafer.ai.json +18 -18
  261. package/dist/capabilities/wallaby.json +5 -5
  262. package/dist/capabilities/wally.json +14 -14
  263. package/dist/capabilities/wandb.json +20 -20
  264. package/dist/capabilities/watt.json +22 -22
  265. package/dist/capabilities/xai.json +4 -4
  266. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -12
  267. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -12
  268. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -12
  269. package/dist/capabilities/xiaomi.json +3 -25
  270. package/dist/capabilities/xpersona.json +11 -11
  271. package/dist/capabilities/xxapi.json +27 -27
  272. package/dist/capabilities/zai-coding-plan.json +14 -14
  273. package/dist/capabilities/zai.json +47 -24
  274. package/dist/capabilities/zenifra.json +24 -24
  275. package/dist/capabilities/zenmux.json +185 -185
  276. package/dist/capabilities/zerogpu.json +12 -12
  277. package/dist/capabilities/zhipuai-coding-plan.json +8 -8
  278. package/dist/capabilities/zhipuai.json +35 -20
  279. package/dist/capabilities/zro.json +7 -7
  280. package/dist/channels/index.cjs +2 -2
  281. package/dist/channels/index.js +2 -2
  282. package/dist/{channels-BRVCOutx.js → channels-Cz1y3W6u.js} +1 -1
  283. package/dist/{channels-MjTA9bFp.cjs → channels-DQg4v_gm.cjs} +1 -1
  284. package/dist/coding-agent/index.cjs +2 -2
  285. package/dist/coding-agent/index.js +2 -2
  286. package/dist/datasets/index.cjs +2 -2
  287. package/dist/datasets/index.js +2 -2
  288. package/dist/docs/SKILL.md +3 -2
  289. package/dist/docs/assets/SOURCE_MAP.json +895 -870
  290. package/dist/docs/references/docs-harness-background-tasks.md +4 -1
  291. package/dist/docs/references/docs-knowledge-importers.md +195 -0
  292. package/dist/docs/references/docs-knowledge-load-your-content.md +1 -1
  293. package/dist/docs/references/docs-knowledge-overview.md +1 -1
  294. package/dist/docs/references/docs-sandbox-filesystem.md +1 -1
  295. package/dist/docs/references/docs-signals-thread-streams.md +1 -1
  296. package/dist/docs/references/docs-studio-auth.md +54 -7
  297. package/dist/docs/references/integrations-auth-clerk.md +48 -4
  298. package/dist/docs/references/reference-agents-agent.md +1 -1
  299. package/dist/docs/references/reference-agents-durable-agent.md +10 -4
  300. package/dist/docs/references/reference-auth-clerk.md +21 -1
  301. package/dist/docs/references/reference-knowledge-knowledge-class.md +11 -4
  302. package/dist/docs/references/reference-memory-observational-memory.md +2 -2
  303. package/dist/docs/references/reference-streaming-ChunkType.md +2 -2
  304. package/dist/docs/references/reference-workspace-local-sandbox.md +2 -0
  305. package/dist/error/index.cjs +1 -1
  306. package/dist/error/index.js +1 -1
  307. package/dist/{error-C9d_24w-.js → error-BLwEXqOK.js} +2 -2
  308. package/dist/{error-BRQf2ku0.cjs → error-BdEvO8za.cjs} +2 -2
  309. package/dist/evals/index.cjs +1 -1
  310. package/dist/evals/index.js +1 -1
  311. package/dist/evals/scoreTraces/index.cjs +1 -1
  312. package/dist/evals/scoreTraces/index.js +1 -1
  313. package/dist/features/index.cjs +1 -0
  314. package/dist/features/index.js +1 -0
  315. package/dist/{filesystem-B5X-5G0x.js → filesystem-B8ad6kAW.js} +1 -1
  316. package/dist/{filesystem-BDSpwBke.cjs → filesystem-BB5YWXH-.cjs} +1 -1
  317. package/dist/{filesystem-DzM9pcQ8.js → filesystem-BDHUxbHn.js} +1 -1
  318. package/dist/{filesystem-B0AZrbj8.cjs → filesystem-BP5yz5LG.cjs} +1 -1
  319. package/dist/{filesystem-BsdkC311.js → filesystem-B_afSgYk.js} +1 -1
  320. package/dist/{filesystem-C-cyJfi1.cjs → filesystem-BaOJOc-V.cjs} +1 -1
  321. package/dist/{filesystem-B3s0WRud.js → filesystem-BhYgU8qg.js} +1 -1
  322. package/dist/{filesystem-DzfqVTO_.js → filesystem-CLBVmR5j.js} +1 -1
  323. package/dist/{filesystem-CEbD_77-.cjs → filesystem-Cgxc2a_-.cjs} +1 -1
  324. package/dist/{filesystem-Cv79mHRk.js → filesystem-ClBOBoDc.js} +1 -1
  325. package/dist/{filesystem-DsCQiBl2.cjs → filesystem-DVVecqZt.cjs} +1 -1
  326. package/dist/{filesystem-CUAgLugE.cjs → filesystem-Fpsu7e24.cjs} +1 -1
  327. package/dist/{filesystem-versioned-Bijb_p9l.js → filesystem-versioned-BL1ojJLo.js} +1 -1
  328. package/dist/{filesystem-versioned-DZGyPbNC.cjs → filesystem-versioned-BavRtYWJ.cjs} +1 -1
  329. package/dist/harness/index.cjs +1 -1
  330. package/dist/harness/index.js +1 -1
  331. package/dist/index.cjs +1 -1
  332. package/dist/index.js +1 -1
  333. package/dist/knowledge/config.d.ts +10 -0
  334. package/dist/knowledge/host-writes.d.ts +10 -0
  335. package/dist/knowledge/importers/conformance.d.ts +25 -0
  336. package/dist/knowledge/importers/define.d.ts +204 -0
  337. package/dist/knowledge/importers/host.d.ts +143 -0
  338. package/dist/knowledge/importers/index.d.ts +12 -0
  339. package/dist/knowledge/importers/local-host.d.ts +106 -0
  340. package/dist/knowledge/importers/manifest.d.ts +25 -0
  341. package/dist/knowledge/importers/runner.d.ts +61 -0
  342. package/dist/knowledge/importers/sink.d.ts +105 -0
  343. package/dist/knowledge/importers/types.d.ts +144 -0
  344. package/dist/knowledge/index.cjs +2715 -8
  345. package/dist/knowledge/index.d.ts +54 -4
  346. package/dist/knowledge/index.js +2692 -9
  347. package/dist/knowledge/instructions.d.ts +1 -1
  348. package/dist/knowledge/links.d.ts +8 -0
  349. package/dist/knowledge/pinned-state-processor.d.ts +5 -0
  350. package/dist/knowledge/pinned.d.ts +4 -1
  351. package/dist/knowledge/scope-runtime.d.ts +10 -0
  352. package/dist/llm/index.cjs +3 -3
  353. package/dist/llm/index.js +3 -3
  354. package/dist/llm/model/provider-types.generated.d.ts +7705 -7727
  355. package/dist/{llm-DmUucguC.cjs → llm-8Av3mSjD.cjs} +2 -2
  356. package/dist/{llm-Djd8Qzi0.js → llm-B5A5cwJr.js} +2 -2
  357. package/dist/loop/index.cjs +2 -2
  358. package/dist/loop/index.js +2 -2
  359. package/dist/{manager-CO_Xz2zR.js → manager-DfWQCJUK.js} +2 -2
  360. package/dist/{manager-D27PkIPo.cjs → manager-sv35JY-z.cjs} +2 -2
  361. package/dist/mastra/index.cjs +1 -1
  362. package/dist/mastra/index.js +1 -1
  363. package/dist/mastra/resolve-agent.d.ts +3 -1
  364. package/dist/{mastra-Ch00nEAJ.js → mastra-CigBrT7X.js} +17 -23
  365. package/dist/{mastra-qsVWpOTi.cjs → mastra-D4hvfuxX.cjs} +19 -25
  366. package/dist/memory/index.cjs +3 -3
  367. package/dist/memory/index.js +3 -3
  368. package/dist/{message-list-DPXPXvin.cjs → message-list-Cj0Sq_JP.cjs} +63 -8
  369. package/dist/{message-list-DEuRl82K.js → message-list-KRbg-TnI.js} +63 -8
  370. package/dist/{model-Do6DTJoj.cjs → model-BK93CMtl.cjs} +1 -1
  371. package/dist/{model-CW-mfGYA.js → model-CYtXw861.js} +1 -1
  372. package/dist/{netlify-DU32SDT6.cjs → netlify-BAnn3ouY.cjs} +1 -1
  373. package/dist/{netlify-DZSAbdve.js → netlify-CuI1ZrwR.js} +1 -1
  374. package/dist/notifications/index.cjs +1 -1
  375. package/dist/notifications/index.js +1 -1
  376. package/dist/processor-provider/index.cjs +1 -1
  377. package/dist/processor-provider/index.js +1 -1
  378. package/dist/processors/abort-signal-scope.d.ts +6 -0
  379. package/dist/processors/index.cjs +2 -2
  380. package/dist/processors/index.js +2 -2
  381. package/dist/{provider-registry-zGezZVsL.cjs → provider-registry-BwuI_IpT.cjs} +21696 -21828
  382. package/dist/{provider-registry-deA0x-Gd.js → provider-registry-CmQLzLF_.js} +21696 -21828
  383. package/dist/provider-registry.json +22300 -22417
  384. package/dist/{registry-generator-VvBfOKAD.js → registry-generator-C17V4WfG.js} +1 -1
  385. package/dist/{registry-generator-BkQ1AxZn.cjs → registry-generator-C_0ae7Ce.cjs} +1 -1
  386. package/dist/{rehydrate-DDYFpQsV.cjs → rehydrate-CDQ4dOYj.cjs} +2 -2
  387. package/dist/{rehydrate-BjLV643n.js → rehydrate-PnaVawGX.js} +2 -2
  388. package/dist/relevance/index.cjs +2 -2
  389. package/dist/relevance/index.js +2 -2
  390. package/dist/{run-registry-5Suldxz3.cjs → run-registry-BmckDVBk.cjs} +1156 -403
  391. package/dist/{run-registry-CGRPldLH.js → run-registry-BwEcwYlU.js} +1103 -404
  392. package/dist/{source-DDwx-87N.cjs → source-BVOi8Xhp.cjs} +1 -1
  393. package/dist/{source-Did_2XQc.js → source-fNa6u1kH.js} +1 -1
  394. package/dist/storage/domains/agents/index.cjs +1 -1
  395. package/dist/storage/domains/agents/index.js +1 -1
  396. package/dist/storage/domains/knowledge/base.d.ts +67 -0
  397. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +146 -0
  398. package/dist/storage/domains/knowledge/importers.d.ts +287 -0
  399. package/dist/storage/domains/knowledge/index.d.ts +1 -0
  400. package/dist/storage/domains/knowledge/inmemory.d.ts +11 -0
  401. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +12 -1
  402. package/dist/storage/domains/knowledge/pages.d.ts +1 -0
  403. package/dist/storage/domains/mcp-clients/index.cjs +1 -1
  404. package/dist/storage/domains/mcp-clients/index.js +1 -1
  405. package/dist/storage/domains/mcp-servers/index.cjs +1 -1
  406. package/dist/storage/domains/mcp-servers/index.js +1 -1
  407. package/dist/storage/domains/prompt-blocks/index.cjs +1 -1
  408. package/dist/storage/domains/prompt-blocks/index.js +1 -1
  409. package/dist/storage/domains/scorer-definitions/index.cjs +1 -1
  410. package/dist/storage/domains/scorer-definitions/index.js +1 -1
  411. package/dist/storage/domains/skills/index.cjs +1 -1
  412. package/dist/storage/domains/skills/index.js +1 -1
  413. package/dist/storage/domains/workspaces/index.cjs +1 -1
  414. package/dist/storage/domains/workspaces/index.js +1 -1
  415. package/dist/storage/index.cjs +15 -10
  416. package/dist/storage/index.js +11 -11
  417. package/dist/stream/base/output.d.ts +17 -0
  418. package/dist/stream/index.cjs +2 -2
  419. package/dist/stream/index.js +2 -2
  420. package/dist/stream/types.d.ts +5 -2
  421. package/dist/{stream-Dvy_0o14.cjs → stream-0kdqBOOn.cjs} +64 -9
  422. package/dist/{stream-Dpwx0whf.js → stream-D1y9GzoD.js} +29 -10
  423. package/dist/test-utils/llm-mock.cjs +1 -1
  424. package/dist/test-utils/llm-mock.js +1 -1
  425. package/dist/tool-loop-agent/index.cjs +1 -1
  426. package/dist/tool-loop-agent/index.js +1 -1
  427. package/dist/{tool-loop-agent-PbWrEj1k.js → tool-loop-agent-BdjWGVIb.js} +4 -4
  428. package/dist/{tool-loop-agent-UxOv3FoK.cjs → tool-loop-agent-kWaZAT6Q.cjs} +4 -4
  429. package/dist/{utils-BbMTlyBO.cjs → utils-BKUCaZ12.cjs} +1 -1
  430. package/dist/{utils-BnNi1BYM.js → utils-GHY3hmLx.js} +1 -1
  431. package/dist/utils.cjs +1 -1
  432. package/dist/utils.js +1 -1
  433. package/dist/{validate-HSBcm96b.js → validate-CB-q-R2F.js} +1 -1
  434. package/dist/{validate-Skps-cM3.cjs → validate-De92squ7.cjs} +1 -1
  435. package/dist/vector/index.cjs +2 -2
  436. package/dist/vector/index.js +2 -2
  437. package/dist/worker/index.cjs +1 -1
  438. package/dist/worker/index.js +1 -1
  439. package/dist/{worker-BNS5A3qP.cjs → worker-BbWPQuPR.cjs} +2 -2
  440. package/dist/{worker-DehaD4qD.js → worker-C3u_xzY2.js} +2 -2
  441. package/dist/{worker-BE-0DyKL.cjs → worker-CAKvQj9_.cjs} +2 -2
  442. package/dist/{worker-BKrKHZzU.js → worker-Kwm8EKcj.js} +2 -2
  443. package/dist/{workflow-BjUTwaK9.cjs → workflow-CSjXeNcR.cjs} +3 -3
  444. package/dist/{workflow-Bvw6yDjc.js → workflow-CVmI1Sw-.js} +3 -3
  445. package/dist/workflows/builder/index.cjs +1 -1
  446. package/dist/workflows/builder/index.js +1 -1
  447. package/dist/workflows/evented/index.cjs +1 -1
  448. package/dist/workflows/evented/index.js +1 -1
  449. package/dist/workflows/index.cjs +4 -4
  450. package/dist/workflows/index.js +4 -4
  451. package/dist/workspace/filesystem/filesystem.d.ts +5 -0
  452. package/dist/workspace/index.cjs +1 -1
  453. package/dist/workspace/index.js +1 -1
  454. package/dist/workspace/sandbox/local-sandbox.d.ts +16 -7
  455. package/dist/workspace/sandbox/native-sandbox/types.d.ts +11 -1
  456. package/dist/{workspace-C05xDH60.js → workspace-DY2Nxiyi.js} +75 -27
  457. package/dist/{workspace-D1OzzlLw.cjs → workspace-X2RHJZU9.cjs} +75 -27
  458. package/package.json +3 -3
  459. package/src/llm/model/provider-types.generated.d.ts +7705 -7727
@@ -3,15 +3,15 @@ const require_logger = require("./logger-CvzZYuJd.cjs");
3
3
  const require_base = require("./base-BIzR1D3_.cjs");
4
4
  const require_observability = require("./observability-B0R_D1PZ.cjs");
5
5
  const require_error = require("./error-D90lJ6M7.cjs");
6
- const require_error$1 = require("./error-BRQf2ku0.cjs");
7
- const require_stream = require("./stream-Dvy_0o14.cjs");
6
+ const require_error$1 = require("./error-BdEvO8za.cjs");
7
+ const require_stream = require("./stream-0kdqBOOn.cjs");
8
8
  const require_request_context = require("./request-context-D9RXYCy8.cjs");
9
9
  const require_output_helpers = require("./output-helpers-1Zu4Vt9C.cjs");
10
- const require_message_list = require("./message-list-DPXPXvin.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-DmUucguC.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-zGezZVsL.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-Do6DTJoj.cjs");
30
- const require_utils$1 = require("./utils-BbMTlyBO.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-7iftnRK_.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,20 +41,20 @@ 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-D1OzzlLw.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");
@@ -777,6 +777,12 @@ function hasResumableStreams(agent) {
777
777
  if (typeof agent.hasResumableStreams === "function") return agent.hasResumableStreams();
778
778
  return isDurableAgentLike(agent);
779
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
+ }
780
786
  // src/workflows/stream-utils.ts
781
787
  async function forwardAgentStreamChunk({ writer, chunk }) {
782
788
  if (!writer) return;
@@ -805,8 +811,9 @@ function resolveEntryActor(stepOptions, runActor) {
805
811
  * unwrapped to the agent it wraps. Warns because the step runs non-durably.
806
812
  */
807
813
  function resolveLegacyAgent(agent, mastra) {
808
- if (!isDurableAgentLike(agent)) return agent;
814
+ if (!hasDurableExecution(agent)) return agent;
809
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;
810
817
  const inner = agent.agent;
811
818
  return inner !== agent ? inner : agent;
812
819
  }
@@ -7535,6 +7542,7 @@ function createStepFromProcessor$1(processor) {
7535
7542
  };
7536
7543
  const passThrough = {
7537
7544
  agent,
7545
+ abortSignal,
7538
7546
  lateSignalSink,
7539
7547
  phase,
7540
7548
  runId: agentRunId,
@@ -11685,7 +11693,7 @@ const MASTRA_DURABLE_SEGMENTS_KEY = "mastra__durableSegments";
11685
11693
  * round-trip are skipped so a single non-serializable value can't break the
11686
11694
  * snapshot.
11687
11695
  */
11688
- function snapshotRequestContextEntries(requestContext) {
11696
+ function snapshotRequestContextEntries(requestContext, onEntryOmitted) {
11689
11697
  if (!requestContext) return void 0;
11690
11698
  const out = {};
11691
11699
  let any = false;
@@ -11697,7 +11705,10 @@ function snapshotRequestContextEntries(requestContext) {
11697
11705
  if (key === "mastra__durableExecutions") continue;
11698
11706
  if (key === "mastra__durableSegments") continue;
11699
11707
  const json = require_utils_safe_stringify.boundedStringify(value);
11700
- if (json === void 0) continue;
11708
+ if (json === void 0) {
11709
+ onEntryOmitted?.();
11710
+ continue;
11711
+ }
11701
11712
  out[key] = JSON.parse(json);
11702
11713
  any = true;
11703
11714
  }
@@ -21162,15 +21173,17 @@ function createStepFromProcessor(processor) {
21162
21173
  description: processor.name ?? `Processor ${processor.id}`,
21163
21174
  inputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepSchema),
21164
21175
  outputSchema: (0, _mastra_schema_compat_schema.toStandardSchema)(ProcessorStepOutputSchema),
21165
- 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 }) => {
21166
21177
  const observabilityContext = require_observability.resolveObservabilityContext({
21167
21178
  tracing,
21168
21179
  tracingContext,
21169
21180
  loggerVNext,
21170
21181
  metrics
21171
21182
  });
21183
+ const scopedSignal = mastra?.__getRunScope(workflowRunId)?.get(require_stream.PROCESSOR_ABORT_SIGNAL);
21184
+ const abortSignal = scopedSignal && runAbortSignal ? AbortSignal.any([scopedSignal, runAbortSignal]) : scopedSignal ?? runAbortSignal;
21172
21185
  const input = inputData;
21173
- 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;
21174
21187
  const abort = (reason, options) => {
21175
21188
  throw new require_stream.TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
21176
21189
  };
@@ -38631,261 +38644,6 @@ var InMemoryHarness = class extends HarnessStorage {
38631
38644
  return cloneSessionRecord(next);
38632
38645
  }
38633
38646
  };
38634
- // src/storage/domains/knowledge/base.ts
38635
- /** @experimental Knowledge APIs are experimental and may change without notice. */
38636
- const KNOWLEDGE_STORAGE_CONTRACT_VERSION = 4;
38637
- /** @experimental Knowledge APIs are experimental and may change without notice. */
38638
- const KNOWLEDGE_STORAGE_SCHEMA_VERSION = 4;
38639
- /**
38640
- * Classifies an adapter-provided, read-only schema snapshot. Adapters own the physical probe; this
38641
- * helper owns version negotiation and never mutates the snapshot or backing store.
38642
- *
38643
- * @experimental Knowledge APIs are experimental and may change without notice.
38644
- */
38645
- function inspectKnowledgeSchema(snapshot) {
38646
- if (!snapshot.available) return {
38647
- status: "unavailable",
38648
- schemaVersion: null,
38649
- reason: snapshot.reason ?? "The Knowledge storage adapter is unavailable."
38650
- };
38651
- if (snapshot.tableNames.length === 0) return {
38652
- status: "uninitialized",
38653
- schemaVersion: null
38654
- };
38655
- if (snapshot.schemaVersion === 4) return {
38656
- status: "compatible",
38657
- schemaVersion: 4
38658
- };
38659
- return {
38660
- status: "incompatible-reset-required",
38661
- schemaVersion: snapshot.schemaVersion ?? null,
38662
- reason: snapshot.reason ?? `Existing experimental Knowledge tables are not compatible with schema version 4.`
38663
- };
38664
- }
38665
- /** @experimental Knowledge APIs are experimental and may change without notice. */
38666
- var KnowledgeConflictError = class extends Error {
38667
- constructor(id) {
38668
- super(`Knowledge record version conflict: ${id}`);
38669
- this.name = "KnowledgeConflictError";
38670
- }
38671
- };
38672
- var KnowledgeNotFoundError$1 = class extends Error {
38673
- constructor(type, id) {
38674
- super(`Knowledge ${type} not found: ${id}`);
38675
- this.name = "KnowledgeNotFoundError";
38676
- }
38677
- };
38678
- var KnowledgeSchemaResetRequiredError = class extends Error {
38679
- inspection;
38680
- constructor(inspection) {
38681
- super(`Knowledge schema reset required: ${inspection.reason}. Existing Knowledge data is not migrated. To replace it, call \`await storage.stores?.knowledge?.dangerouslyReset()\`, which deletes every Knowledge row and nothing else.`);
38682
- this.name = "KnowledgeSchemaResetRequiredError";
38683
- this.inspection = inspection;
38684
- }
38685
- };
38686
- var KnowledgeUnsupportedCapabilityError = class extends Error {
38687
- constructor(capability) {
38688
- super(`This Knowledge storage adapter does not expose ${capability}.`);
38689
- this.name = "KnowledgeUnsupportedCapabilityError";
38690
- }
38691
- };
38692
- function assertKnowledgeSchemaCompatible(inspection) {
38693
- if (inspection.status === "compatible" || inspection.status === "uninitialized") return;
38694
- if (inspection.status === "incompatible-reset-required") throw new KnowledgeSchemaResetRequiredError(inspection);
38695
- throw new Error(`Knowledge schema inspection unavailable: ${inspection.reason}`);
38696
- }
38697
- const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
38698
- let lastUlidTime = -1;
38699
- let lastUlidRandom = 0n;
38700
- function parseKnowledgeWikilinks(text) {
38701
- const names = [];
38702
- const seen = /* @__PURE__ */ new Set();
38703
- let contentStart = -1;
38704
- for (let index = 0; index < text.length - 1; index++) {
38705
- const pair = text.slice(index, index + 2);
38706
- if (pair === "[[") {
38707
- contentStart = index + 2;
38708
- index++;
38709
- continue;
38710
- }
38711
- if (pair !== "]]" || contentStart < 0) continue;
38712
- const name = text.slice(contentStart, index).trim();
38713
- const key = name.toLocaleLowerCase();
38714
- if (name && !seen.has(key)) {
38715
- seen.add(key);
38716
- names.push(name);
38717
- }
38718
- contentStart = -1;
38719
- index++;
38720
- }
38721
- return names;
38722
- }
38723
- function encodeCrockford(value, length) {
38724
- let encoded = "";
38725
- for (let index = 0; index < length; index++) {
38726
- encoded = CROCKFORD[Number(value & 31n)] + encoded;
38727
- value >>= 5n;
38728
- }
38729
- return encoded;
38730
- }
38731
- function createKnowledgeUlid(now = Date.now()) {
38732
- if (now <= lastUlidTime) {
38733
- now = lastUlidTime;
38734
- lastUlidRandom = lastUlidRandom + 1n & (1n << 80n) - 1n;
38735
- } else {
38736
- lastUlidTime = now;
38737
- lastUlidRandom = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(10)).reduce((value, byte) => value << 8n | BigInt(byte), 0n);
38738
- }
38739
- return `${encodeCrockford(BigInt(now), 10)}${encodeCrockford(lastUlidRandom, 16)}`;
38740
- }
38741
- var KnowledgeStorage = class extends require_filesystem_versioned.StorageDomain {
38742
- #storageIsolationKey;
38743
- constructor(config = {}) {
38744
- super({
38745
- component: "STORAGE",
38746
- name: "KNOWLEDGE"
38747
- });
38748
- this.#storageIsolationKey = config.storageIsolationKey ?? this;
38749
- }
38750
- /** Identifies the physical Knowledge backend and namespace used by this domain. */
38751
- getStorageIsolationKey() {
38752
- return this.#storageIsolationKey;
38753
- }
38754
- getCapabilities() {
38755
- return {
38756
- contractVersion: 4,
38757
- schemaVersion: 1,
38758
- supportsSchemaInspection: false,
38759
- supportsExplicitReset: false
38760
- };
38761
- }
38762
- async inspectSchema() {
38763
- return {
38764
- status: "unavailable",
38765
- schemaVersion: null,
38766
- reason: "This Knowledge storage adapter does not support schema inspection."
38767
- };
38768
- }
38769
- async dangerouslyReset() {
38770
- throw new Error("This Knowledge storage adapter does not support an explicit Knowledge-only reset.");
38771
- }
38772
- /**
38773
- * Scope declarations the store supplies itself, such as the scopes a hosted store's importers write
38774
- * to, with their access rules. Knowledge merges them under its config's, reusing the answer for a
38775
- * short window, so a declaration the store adds, removes or changes (revoking access included)
38776
- * applies within it; a key the config declares keeps the config's declaration. None by default.
38777
- *
38778
- * @experimental
38779
- */
38780
- async getScopeDeclarations() {
38781
- return {};
38782
- }
38783
- materializeScope(_input) {
38784
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("materializeScope"));
38785
- }
38786
- getScopesByAddress(_input) {
38787
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("getScopesByAddress"));
38788
- }
38789
- listScopeDeclarations() {
38790
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listScopeDeclarations"));
38791
- }
38792
- renameScopeDeclaration(_input) {
38793
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("renameScopeDeclaration"));
38794
- }
38795
- listChildScopes(_input) {
38796
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listChildScopes"));
38797
- }
38798
- countChildScopes(_input) {
38799
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("countChildScopes"));
38800
- }
38801
- getPage(_input) {
38802
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPage"));
38803
- }
38804
- getPages(_input) {
38805
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPages"));
38806
- }
38807
- getPageByPath(_input) {
38808
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPageByPath"));
38809
- }
38810
- findPagesByName(_input) {
38811
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("findPagesByName"));
38812
- }
38813
- listChildPages(_input) {
38814
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listChildPages"));
38815
- }
38816
- listPages(_input) {
38817
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPages"));
38818
- }
38819
- createPage(_input) {
38820
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("createPage"));
38821
- }
38822
- updatePage(_input) {
38823
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("updatePage"));
38824
- }
38825
- movePage(_input) {
38826
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("movePage"));
38827
- }
38828
- mergePages(_input) {
38829
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("mergePages"));
38830
- }
38831
- deletePage(_input) {
38832
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("deletePage"));
38833
- }
38834
- getNote(_input) {
38835
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("getNote"));
38836
- }
38837
- countChildPages(_input) {
38838
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("countChildPages"));
38839
- }
38840
- replacePageBodyLinks(_input) {
38841
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("replacePageBodyLinks"));
38842
- }
38843
- listPageBodyLinkSources(_input) {
38844
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageBodyLinkSources"));
38845
- }
38846
- countPageLinks(_input) {
38847
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("countPageLinks"));
38848
- }
38849
- listPageLinks(_input) {
38850
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageLinks"));
38851
- }
38852
- countNotes(_input) {
38853
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("countNotes"));
38854
- }
38855
- listNotes(_input) {
38856
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listNotes"));
38857
- }
38858
- listNotesMentioning(_input) {
38859
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listNotesMentioning"));
38860
- }
38861
- addNote(_input) {
38862
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("addNote"));
38863
- }
38864
- restampNote(_input) {
38865
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("restampNote"));
38866
- }
38867
- removeNote(_input) {
38868
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("removeNote"));
38869
- }
38870
- restoreNote(_input) {
38871
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("restoreNote"));
38872
- }
38873
- searchPages(_input) {
38874
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("searchPages"));
38875
- }
38876
- listPageActivity(_input) {
38877
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageActivity"));
38878
- }
38879
- addPinAudience(_input) {
38880
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("addPinAudience"));
38881
- }
38882
- removePinAudience(_input) {
38883
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("removePinAudience"));
38884
- }
38885
- listPins(_input) {
38886
- return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPins"));
38887
- }
38888
- };
38889
38647
  const KNOWLEDGE_TABLE_NAMES = [
38890
38648
  "mastra_knowledge_nodes",
38891
38649
  "mastra_knowledge_records",
@@ -38921,6 +38679,20 @@ const KNOWLEDGE_PAGES_TABLE_NAMES = [
38921
38679
  new Set([...KNOWLEDGE_TABLE_NAMES, ...RETIRED_KNOWLEDGE_TABLE_NAMES].filter((name) => !KNOWLEDGE_PAGES_TABLE_NAMES.includes(name)));
38922
38680
  KNOWLEDGE_TABLE_NAMES.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
38923
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
+ /**
38924
38696
  * Keyword-search words: the query split on whitespace, lowercased, deduplicated, keeping the first
38925
38697
  * {@link KNOWLEDGE_SEARCH_MAX_WORDS}. A hit needs at least one of them (as a case-insensitive
38926
38698
  * substring); an empty list means the search returns nothing.
@@ -39187,6 +38959,667 @@ function knowledgePositionBetween(before, after) {
39187
38959
  if (before !== void 0 && after !== void 0 && before >= after) throw new Error(`Invalid position range: ${before} >= ${after}`);
39188
38960
  return after === void 0 ? positionAfter(before ?? "") : positionMidpoint(before ?? "", after);
39189
38961
  }
38962
+ // src/storage/domains/knowledge/base.ts
38963
+ /** @experimental Knowledge APIs are experimental and may change without notice. */
38964
+ const KNOWLEDGE_STORAGE_CONTRACT_VERSION = 4;
38965
+ /** @experimental Knowledge APIs are experimental and may change without notice. */
38966
+ const KNOWLEDGE_STORAGE_SCHEMA_VERSION = 4;
38967
+ /**
38968
+ * Classifies an adapter-provided, read-only schema snapshot. Adapters own the physical probe; this
38969
+ * helper owns version negotiation and never mutates the snapshot or backing store.
38970
+ *
38971
+ * @experimental Knowledge APIs are experimental and may change without notice.
38972
+ */
38973
+ function inspectKnowledgeSchema(snapshot) {
38974
+ if (!snapshot.available) return {
38975
+ status: "unavailable",
38976
+ schemaVersion: null,
38977
+ reason: snapshot.reason ?? "The Knowledge storage adapter is unavailable."
38978
+ };
38979
+ if (snapshot.tableNames.length === 0) return {
38980
+ status: "uninitialized",
38981
+ schemaVersion: null
38982
+ };
38983
+ if (snapshot.schemaVersion === 4) return {
38984
+ status: "compatible",
38985
+ schemaVersion: 4
38986
+ };
38987
+ return {
38988
+ status: "incompatible-reset-required",
38989
+ schemaVersion: snapshot.schemaVersion ?? null,
38990
+ reason: snapshot.reason ?? `Existing experimental Knowledge tables are not compatible with schema version 4.`
38991
+ };
38992
+ }
38993
+ /** @experimental Knowledge APIs are experimental and may change without notice. */
38994
+ var KnowledgeConflictError = class extends Error {
38995
+ constructor(id) {
38996
+ super(`Knowledge record version conflict: ${id}`);
38997
+ this.name = "KnowledgeConflictError";
38998
+ }
38999
+ };
39000
+ var KnowledgeNotFoundError$1 = class extends Error {
39001
+ constructor(type, id) {
39002
+ super(`Knowledge ${type} not found: ${id}`);
39003
+ this.name = "KnowledgeNotFoundError";
39004
+ }
39005
+ };
39006
+ var KnowledgeSchemaResetRequiredError = class extends Error {
39007
+ inspection;
39008
+ constructor(inspection) {
39009
+ super(`Knowledge schema reset required: ${inspection.reason}. Existing Knowledge data is not migrated. To replace it, call \`await storage.stores?.knowledge?.dangerouslyReset()\`, which deletes every Knowledge row and nothing else.`);
39010
+ this.name = "KnowledgeSchemaResetRequiredError";
39011
+ this.inspection = inspection;
39012
+ }
39013
+ };
39014
+ var KnowledgeUnsupportedCapabilityError = class extends Error {
39015
+ constructor(capability) {
39016
+ super(`This Knowledge storage adapter does not expose ${capability}.`);
39017
+ this.name = "KnowledgeUnsupportedCapabilityError";
39018
+ }
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
+ };
39028
+ function assertKnowledgeSchemaCompatible(inspection) {
39029
+ if (inspection.status === "compatible" || inspection.status === "uninitialized") return;
39030
+ if (inspection.status === "incompatible-reset-required") throw new KnowledgeSchemaResetRequiredError(inspection);
39031
+ throw new Error(`Knowledge schema inspection unavailable: ${inspection.reason}`);
39032
+ }
39033
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
39034
+ let lastUlidTime = -1;
39035
+ let lastUlidRandom = 0n;
39036
+ function parseKnowledgeWikilinks(text) {
39037
+ const names = [];
39038
+ const seen = /* @__PURE__ */ new Set();
39039
+ let contentStart = -1;
39040
+ for (let index = 0; index < text.length - 1; index++) {
39041
+ const pair = text.slice(index, index + 2);
39042
+ if (pair === "[[") {
39043
+ contentStart = index + 2;
39044
+ index++;
39045
+ continue;
39046
+ }
39047
+ if (pair !== "]]" || contentStart < 0) continue;
39048
+ const name = text.slice(contentStart, index).trim();
39049
+ const key = name.toLocaleLowerCase();
39050
+ if (name && !seen.has(key)) {
39051
+ seen.add(key);
39052
+ names.push(name);
39053
+ }
39054
+ contentStart = -1;
39055
+ index++;
39056
+ }
39057
+ return names;
39058
+ }
39059
+ function encodeCrockford(value, length) {
39060
+ let encoded = "";
39061
+ for (let index = 0; index < length; index++) {
39062
+ encoded = CROCKFORD[Number(value & 31n)] + encoded;
39063
+ value >>= 5n;
39064
+ }
39065
+ return encoded;
39066
+ }
39067
+ function createKnowledgeUlid(now = Date.now()) {
39068
+ if (now <= lastUlidTime) {
39069
+ now = lastUlidTime;
39070
+ lastUlidRandom = lastUlidRandom + 1n & (1n << 80n) - 1n;
39071
+ } else {
39072
+ lastUlidTime = now;
39073
+ lastUlidRandom = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(10)).reduce((value, byte) => value << 8n | BigInt(byte), 0n);
39074
+ }
39075
+ return `${encodeCrockford(BigInt(now), 10)}${encodeCrockford(lastUlidRandom, 16)}`;
39076
+ }
39077
+ var KnowledgeStorage = class extends require_filesystem_versioned.StorageDomain {
39078
+ #storageIsolationKey;
39079
+ constructor(config = {}) {
39080
+ super({
39081
+ component: "STORAGE",
39082
+ name: "KNOWLEDGE"
39083
+ });
39084
+ this.#storageIsolationKey = config.storageIsolationKey ?? this;
39085
+ }
39086
+ /** Identifies the physical Knowledge backend and namespace used by this domain. */
39087
+ getStorageIsolationKey() {
39088
+ return this.#storageIsolationKey;
39089
+ }
39090
+ getCapabilities() {
39091
+ return {
39092
+ contractVersion: 4,
39093
+ schemaVersion: 1,
39094
+ supportsSchemaInspection: false,
39095
+ supportsExplicitReset: false
39096
+ };
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() {}
39162
+ async inspectSchema() {
39163
+ return {
39164
+ status: "unavailable",
39165
+ schemaVersion: null,
39166
+ reason: "This Knowledge storage adapter does not support schema inspection."
39167
+ };
39168
+ }
39169
+ async dangerouslyReset() {
39170
+ throw new Error("This Knowledge storage adapter does not support an explicit Knowledge-only reset.");
39171
+ }
39172
+ /**
39173
+ * Scope declarations the store supplies itself, such as the scopes a hosted store's importers write
39174
+ * to, with their access rules. Knowledge merges them under its config's, reusing the answer for a
39175
+ * short window, so a declaration the store adds, removes or changes (revoking access included)
39176
+ * applies within it; a key the config declares keeps the config's declaration. None by default.
39177
+ *
39178
+ * @experimental
39179
+ */
39180
+ async getScopeDeclarations() {
39181
+ return {};
39182
+ }
39183
+ materializeScope(_input) {
39184
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("materializeScope"));
39185
+ }
39186
+ getScopesByAddress(_input) {
39187
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("getScopesByAddress"));
39188
+ }
39189
+ listScopeDeclarations() {
39190
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listScopeDeclarations"));
39191
+ }
39192
+ renameScopeDeclaration(_input) {
39193
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("renameScopeDeclaration"));
39194
+ }
39195
+ listChildScopes(_input) {
39196
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listChildScopes"));
39197
+ }
39198
+ countChildScopes(_input) {
39199
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("countChildScopes"));
39200
+ }
39201
+ getPage(_input) {
39202
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPage"));
39203
+ }
39204
+ getPages(_input) {
39205
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPages"));
39206
+ }
39207
+ getPageByPath(_input) {
39208
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("getPageByPath"));
39209
+ }
39210
+ findPagesByName(_input) {
39211
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("findPagesByName"));
39212
+ }
39213
+ listChildPages(_input) {
39214
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listChildPages"));
39215
+ }
39216
+ listPages(_input) {
39217
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPages"));
39218
+ }
39219
+ createPage(_input) {
39220
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("createPage"));
39221
+ }
39222
+ updatePage(_input) {
39223
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("updatePage"));
39224
+ }
39225
+ movePage(_input) {
39226
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("movePage"));
39227
+ }
39228
+ mergePages(_input) {
39229
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("mergePages"));
39230
+ }
39231
+ deletePage(_input) {
39232
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("deletePage"));
39233
+ }
39234
+ getNote(_input) {
39235
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("getNote"));
39236
+ }
39237
+ countChildPages(_input) {
39238
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("countChildPages"));
39239
+ }
39240
+ replacePageBodyLinks(_input) {
39241
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("replacePageBodyLinks"));
39242
+ }
39243
+ listPageBodyLinkSources(_input) {
39244
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageBodyLinkSources"));
39245
+ }
39246
+ countPageLinks(_input) {
39247
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("countPageLinks"));
39248
+ }
39249
+ listPageLinks(_input) {
39250
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageLinks"));
39251
+ }
39252
+ countNotes(_input) {
39253
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("countNotes"));
39254
+ }
39255
+ listNotes(_input) {
39256
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listNotes"));
39257
+ }
39258
+ listNotesMentioning(_input) {
39259
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listNotesMentioning"));
39260
+ }
39261
+ addNote(_input) {
39262
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("addNote"));
39263
+ }
39264
+ restampNote(_input) {
39265
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("restampNote"));
39266
+ }
39267
+ removeNote(_input) {
39268
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("removeNote"));
39269
+ }
39270
+ restoreNote(_input) {
39271
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("restoreNote"));
39272
+ }
39273
+ searchPages(_input) {
39274
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("searchPages"));
39275
+ }
39276
+ listPageActivity(_input) {
39277
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPageActivity"));
39278
+ }
39279
+ addPinAudience(_input) {
39280
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("addPinAudience"));
39281
+ }
39282
+ removePinAudience(_input) {
39283
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("removePinAudience"));
39284
+ }
39285
+ listPins(_input) {
39286
+ return Promise.reject(new KnowledgeUnsupportedCapabilityError("listPins"));
39287
+ }
39288
+ };
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
+ }
39298
+ };
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";
39308
+ }
39309
+ };
39310
+ /** @experimental */
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();
39319
+ }
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);
39337
+ /**
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.
39341
+ */
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;
39349
+ }
39350
+ return a.length === b.length ? 0 : a.length < b.length ? -1 : 1;
39351
+ };
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;
39356
+ }
39357
+ /**
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}.
39360
+ */
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
+ };
39391
+ }
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
+ };
39402
+ }
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
+ };
39190
39623
  // src/storage/domains/knowledge/pages-inmemory.ts
39191
39624
  const DEFAULT_SEARCH_LIMIT = 20;
39192
39625
  function pageSize(limit) {
@@ -39195,8 +39628,9 @@ function pageSize(limit) {
39195
39628
  return Math.min(limit, 100);
39196
39629
  }
39197
39630
  function paginate(items, cursor, limit) {
39631
+ if (cursor !== void 0 && !/^(0|[1-9]\d*)$/.test(cursor)) throw new KnowledgeInvalidCursorError(cursor);
39198
39632
  const start = cursor === void 0 ? 0 : Number(cursor);
39199
- if (!Number.isInteger(start) || start < 0) throw new RangeError(`Invalid Knowledge cursor: ${cursor}`);
39633
+ if (!Number.isSafeInteger(start)) throw new KnowledgeInvalidCursorError(String(cursor));
39200
39634
  const size = pageSize(limit);
39201
39635
  return {
39202
39636
  items: items.slice(start, start + size),
@@ -39211,12 +39645,6 @@ const oldestFirst = (a, b) => newestFirst(b, a);
39211
39645
  const clone$1 = (value) => structuredClone(value);
39212
39646
  const PIN_KINDS = ["page", "list"];
39213
39647
  const pinKey = (pageId, kind) => `${kind}:${pageId}`;
39214
- /**
39215
- * In-memory schema-4 page store: the reference implementation of {@link KnowledgePageStore} that the
39216
- * shared contract suite checks every adapter against.
39217
- *
39218
- * @experimental
39219
- */
39220
39648
  var InMemoryKnowledgePageStore = class {
39221
39649
  #pages = /* @__PURE__ */ new Map();
39222
39650
  #notes = /* @__PURE__ */ new Map();
@@ -39224,6 +39652,25 @@ var InMemoryKnowledgePageStore = class {
39224
39652
  #activity = [];
39225
39653
  #bodyLinks = /* @__PURE__ */ new Map();
39226
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
+ }
39227
39674
  /** Drops every page, note, pin, body link and event. */
39228
39675
  clear() {
39229
39676
  this.#pages.clear();
@@ -39924,6 +40371,10 @@ var InMemoryKnowledgePageStore = class {
39924
40371
  // src/storage/domains/knowledge/inmemory.ts
39925
40372
  var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
39926
40373
  #pageStore = new InMemoryKnowledgePageStore();
40374
+ #importers = new InMemoryKnowledgeImportersStorage();
40375
+ get importers() {
40376
+ return this.#importers;
40377
+ }
39927
40378
  materializeScope(input) {
39928
40379
  return this.#pageStore.materializeScope(input);
39929
40380
  }
@@ -40029,9 +40480,41 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40029
40480
  listPins(input) {
40030
40481
  return this.#pageStore.listPins(input);
40031
40482
  }
40483
+ #transactionTail = Promise.resolve();
40032
40484
  constructor(_config) {
40033
40485
  super();
40034
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
+ }
40035
40518
  getCapabilities() {
40036
40519
  return {
40037
40520
  contractVersion: 4,
@@ -40039,6 +40522,7 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40039
40522
  supportsSchemaInspection: true,
40040
40523
  supportsExplicitReset: true,
40041
40524
  supportsPinKinds: true,
40525
+ supportsTransactions: true,
40042
40526
  supportsActivityDateRange: true
40043
40527
  };
40044
40528
  }
@@ -40050,6 +40534,7 @@ var InMemoryKnowledgeStorage = class extends KnowledgeStorage {
40050
40534
  }
40051
40535
  async dangerouslyReset() {
40052
40536
  await this.dangerouslyClearAll();
40537
+ this.#importers.clearOnReset();
40053
40538
  }
40054
40539
  async dangerouslyClearAll() {
40055
40540
  this.#pageStore.clear();
@@ -45186,7 +45671,14 @@ var MessageHistory = class {
45186
45671
  const persistenceMessageList = messageList.cloneForPersistence();
45187
45672
  const newInput = persistenceMessageList.get.input.db();
45188
45673
  const newOutput = persistenceMessageList.get.response.db();
45189
- 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
+ ]);
45190
45682
  if (messagesToSave.length === 0) return messageList;
45191
45683
  this.memorySpan(observabilityContext)?.update({ attributes: { messageCount: messagesToSave.length } });
45192
45684
  await this.persistMessages({
@@ -51082,14 +51574,16 @@ async function storedAttachmentBytes(fs, dir, root = true) {
51082
51574
  return total;
51083
51575
  }
51084
51576
  // src/knowledge/instructions.ts
51085
- 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
+ }
51086
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.`;
51087
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.`;
51088
51582
  function buildKnowledgeInstructions(groups, option) {
51089
51583
  if (option === false) return "";
51090
51584
  if (typeof option === "string") return option;
51091
51585
  const parts = {
51092
- read: groups.read ? KNOWLEDGE_READ_INSTRUCTIONS : "",
51586
+ read: groups.read ? readInstructions(groups.write) : "",
51093
51587
  write: groups.write ? KNOWLEDGE_WRITE_INSTRUCTIONS : "",
51094
51588
  pins: groups.pins ? KNOWLEDGE_PINS_INSTRUCTIONS : ""
51095
51589
  };
@@ -51875,6 +52369,17 @@ async function knowledgeSubtree(storage, root) {
51875
52369
  */
51876
52370
  const MAX_KNOWLEDGE_LINK_REFRESH_NAMESAKES = 99;
51877
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
+ /**
51878
52383
  * Re-resolves the pages whose body links one of `pages` or names a ref one of them answers to now,
51879
52384
  * after they were created, renamed, moved, merged or deleted, in page id order up to
51880
52385
  * {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES}. With `withDescendants`, the pages' subtrees count too
@@ -51904,7 +52409,7 @@ async function refreshKnowledgeLinksTo(storage, pages, options = {}) {
51904
52409
  refs: [...refs],
51905
52410
  toPageIds: [...targets]
51906
52411
  })).sort();
51907
- 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`);
51908
52413
  if (!sources.length) {
51909
52414
  if (crowded.length) throw crowdedError();
51910
52415
  return;
@@ -51927,10 +52432,7 @@ async function refreshKnowledgeLinksTo(storage, pages, options = {}) {
51927
52432
  done++;
51928
52433
  }
51929
52434
  const left = sources.length - done;
51930
- if (left > 0) {
51931
- const names = pages.map((page) => `"${page.name}"`).join(", ");
51932
- throw new Error(`${left} more pages link to ${names}; their links were left as they were`);
51933
- }
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`);
51934
52436
  if (crowded.length) throw crowdedError();
51935
52437
  }
51936
52438
  /**
@@ -61134,12 +61636,13 @@ async function removeKnowledgePage(host, input) {
61134
61636
  await host.runtime.checkDeclarations();
61135
61637
  const storage = await host.getStorage();
61136
61638
  const [scope] = await storage.getScopesByAddress([input.scope]);
61137
- if (!scope) return null;
61138
- const page = await storage.getPageByPath({
61639
+ const page = scope ? await storage.getPageByPath({
61139
61640
  scopeId: scope.id,
61140
61641
  path: keys,
61141
61642
  read: "all"
61142
- });
61643
+ }) : null;
61644
+ const expected = input.expected;
61645
+ if (expected && (page?.id !== expected.id || page.version !== expected.version)) throw new KnowledgeConflictError(expected.id);
61143
61646
  if (!page) return null;
61144
61647
  const template = await host.runtime.templatePageRef(page);
61145
61648
  if (template) throw new Error(`"${template}" is declared in config; change the scope's pages to remove it.`);
@@ -61151,6 +61654,7 @@ async function removeKnowledgePage(host, input) {
61151
61654
  deletedBy: input.author ?? "host"
61152
61655
  });
61153
61656
  } catch (error) {
61657
+ if (expected && error?.name === "KnowledgeNotFoundError") throw new KnowledgeConflictError(expected.id);
61154
61658
  if (error?.name === "KnowledgePageHasChildrenError") throw new Error(`"${input.scope}#${input.path}" has child pages; remove them first.`);
61155
61659
  throw error;
61156
61660
  }
@@ -61851,7 +62355,7 @@ function bodyView(body, input) {
61851
62355
  const headings = knowledgeBodyOutline(body);
61852
62356
  const skeleton = headings.length ? knowledgeBodySkeleton(lines, headings.map((heading) => heading.line), input.maxTokens) : void 0;
61853
62357
  if (skeleton !== void 0) {
61854
- 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." : ""}`);
61855
62359
  return {
61856
62360
  lines: skeleton,
61857
62361
  lineCount: lines.count
@@ -61881,10 +62385,10 @@ function bodyView(body, input) {
61881
62385
  ...outline.length ? { outline } : {}
61882
62386
  };
61883
62387
  }
61884
- function readTool(host) {
62388
+ function readTool(host, canEdit) {
61885
62389
  return require_tool.createTool({
61886
62390
  id: "knowledge_read",
61887
- 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." : ""),
61888
62392
  inputSchema: {
61889
62393
  type: "object",
61890
62394
  properties: {
@@ -61981,7 +62485,8 @@ function readTool(host) {
61981
62485
  context: matchContext,
61982
62486
  from,
61983
62487
  more,
61984
- maxTokens: maxTokensOf(host)
62488
+ maxTokens: maxTokensOf(host),
62489
+ canEdit
61985
62490
  });
61986
62491
  return {
61987
62492
  page: {
@@ -62084,7 +62589,8 @@ function readTool(host) {
62084
62589
  const view = bodyView(page.body ?? "", {
62085
62590
  context: matchContext,
62086
62591
  more,
62087
- maxTokens: maxTokensOf(host)
62592
+ maxTokens: maxTokensOf(host),
62593
+ canEdit
62088
62594
  });
62089
62595
  const noteList = await noteSummaries(run, notes.notes, mentionCache);
62090
62596
  const mentionList = (await noteSummaries(run, mentioning.notes, mentionCache)).map((note, i) => ({
@@ -62365,11 +62871,12 @@ const NUMBERED_LINE = /^\s*\d+\u2502/;
62365
62871
  * Without one, a body longer than one read returns is refused: the writer can only have seen part
62366
62872
  * of it, and writing that part back would drop the rest.
62367
62873
  */
62368
- function writtenBody(args, page, maxTokens) {
62874
+ function writtenBody(args, page, maxTokens, canRead) {
62875
+ const read = canRead ? "knowledge_read" : "read";
62369
62876
  const stored = page.body ?? "";
62370
62877
  if (args.body !== void 0) {
62371
62878
  const written = args.body.split("\n").filter((line) => line.trim());
62372
- 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.`);
62373
62880
  }
62374
62881
  if (args.range) {
62375
62882
  if (args.body === void 0) throw new Error("range needs body: the text that replaces those lines.");
@@ -62378,18 +62885,18 @@ function writtenBody(args, page, maxTokens) {
62378
62885
  const lines = new KnowledgeBodyLines(stored);
62379
62886
  let start = lines.startOffset(args.range.start);
62380
62887
  let end = lines.endOffset(args.range.end);
62381
- if (start > end) throw new Error(`The range starts after it ends. Pass the range a knowledge_read returned.`);
62382
- 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.`);
62383
62890
  if (args.range.start.col === void 0 && args.range.end.col === void 0 && args.body === "") {
62384
62891
  if (end < stored.length) end++;
62385
62892
  else if (start > 0) start--;
62386
62893
  }
62387
62894
  return stored.slice(0, start) + args.body + stored.slice(end);
62388
62895
  }
62389
- 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."));
62390
62897
  return args.body;
62391
62898
  }
62392
- function pageTool(host) {
62899
+ function pageTool(host, canRead) {
62393
62900
  return require_tool.createTool({
62394
62901
  id: "knowledge_page",
62395
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.",
@@ -62444,7 +62951,7 @@ function pageTool(host) {
62444
62951
  },
62445
62952
  range: {
62446
62953
  type: "object",
62447
- 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.`,
62448
62955
  properties: {
62449
62956
  start: linePositionSchema,
62450
62957
  end: linePositionSchema
@@ -62481,7 +62988,7 @@ function pageTool(host) {
62481
62988
  expectedVersion: args.expectedVersion ?? page.version,
62482
62989
  name: args.name,
62483
62990
  description: args.description,
62484
- body: writtenBody(args, page, maxTokensOf(host)),
62991
+ body: writtenBody(args, page, maxTokensOf(host), canRead),
62485
62992
  provenance
62486
62993
  });
62487
62994
  await embed(host, (index) => index.indexPage(updated), pageEmbedFailed(storage, updated));
@@ -62681,10 +63188,10 @@ function noteTool(host) {
62681
63188
  }
62682
63189
  });
62683
63190
  }
62684
- function pinTool(host, onChange) {
63191
+ function pinTool(host, canRead, onChange) {
62685
63192
  return require_tool.createTool({
62686
63193
  id: "knowledge_pin",
62687
- 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.`,
62688
63195
  inputSchema: {
62689
63196
  type: "object",
62690
63197
  properties: {
@@ -62989,14 +63496,14 @@ function buildKnowledgePageTools(host, groups, onPinChange) {
62989
63496
  if (groups.read) {
62990
63497
  tools.knowledge_list = listTool(host);
62991
63498
  tools.knowledge_search = searchTool(host);
62992
- tools.knowledge_read = readTool(host);
63499
+ tools.knowledge_read = readTool(host, groups.write);
62993
63500
  tools.knowledge_activity = activityTool(host);
62994
63501
  }
62995
63502
  if (groups.write) {
62996
- tools.knowledge_page = pageTool(host);
63503
+ tools.knowledge_page = pageTool(host, groups.read);
62997
63504
  tools.knowledge_note = noteTool(host);
62998
63505
  }
62999
- if (groups.pins) tools.knowledge_pin = pinTool(host, onPinChange);
63506
+ if (groups.pins) tools.knowledge_pin = pinTool(host, groups.read, onPinChange);
63000
63507
  return tools;
63001
63508
  }
63002
63509
  // src/knowledge/pinned.ts
@@ -63004,6 +63511,8 @@ const PINNED_KNOWLEDGE_STATE_ID = "knowledge";
63004
63511
  const PINNED_SNAPSHOT_TAG = "pinned-knowledge";
63005
63512
  const PINNED_DELTA_TAG = "pinned-knowledge-update";
63006
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]";
63007
63516
  /** Entry id of the line listing stored pins that didn't fit the budget. */
63008
63517
  const PIN_OVERFLOW_ID = "overflow";
63009
63518
  function bindConfigPin(entry, params) {
@@ -63044,12 +63553,12 @@ async function resolveListing(run, origin, depth, maxTokens) {
63044
63553
  /**
63045
63554
  * Fills `maxTokens` a level at a time: every depth-1 line that fits, then depth 2, and so on, stopping
63046
63555
  * at the first line that doesn't fit (always at least one). Lines print in tree order, so each child
63047
- * 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.
63048
63557
  */
63049
- function renderListing(listing, ref, maxTokens) {
63558
+ function renderListing(listing, ref, maxTokens, read) {
63050
63559
  const head = `Pages under ${listing.origin.name} (${ref}, depth ${listing.depth}):`;
63051
63560
  if (listing.lines.length === 0) return `${head} none.`;
63052
- 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}"` : ""}`;
63053
63562
  const all = [
63054
63563
  head,
63055
63564
  ...listing.lines.map((line) => line.text),
@@ -63075,12 +63584,13 @@ function renderListing(listing, ref, maxTokens) {
63075
63584
  tail(listing.lines.length - kept.length)
63076
63585
  ].join("\n");
63077
63586
  }
63078
- function render(page, label, maxTokens) {
63587
+ function render(page, label, maxTokens, read) {
63079
63588
  const notes = label.notes === void 0 ? "" : label.notes === 0 ? ", no notes" : label.notes === 1 ? ", 1 note" : `, ${label.notes} notes`;
63080
63589
  const text = `${page.name} (${label.ref}, v${page.version}${notes}): ${page.body.trim()}`;
63081
63590
  if (require_workspace.estimateTokenCount(text) <= maxTokens) return text;
63082
- const room = Math.max(maxTokens - require_workspace.estimateTokenCount(PIN_TRUNCATION_MARKER) - 1, 1);
63083
- 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}`;
63084
63594
  }
63085
63595
  /** The run's principals grouped by `pinnedContextPriority`, highest first. */
63086
63596
  function priorityTiers(compiled, principals) {
@@ -63173,9 +63683,10 @@ async function rankedStoredPins(run, excludePageIds, want) {
63173
63683
  total
63174
63684
  };
63175
63685
  }
63176
- function overflowLine(names, more) {
63686
+ function overflowLine(names, more, read) {
63177
63687
  const listed = names.join(", ");
63178
- 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}`;
63179
63690
  }
63180
63691
  /**
63181
63692
  * The pinned pages a run receives, rendered: config pins first (always delivered; an equal share each
@@ -63184,7 +63695,8 @@ function overflowLine(names, more) {
63184
63695
  * the rest. The line counts against the token budget. Only pages the run can read and that have a body
63185
63696
  * are delivered. A run costs a fixed handful of store calls however many pins exist.
63186
63697
  */
63187
- 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) {
63188
63700
  const configPinned = await configPins(run, budget.maxTokens);
63189
63701
  const configured = configPinned.pages.filter((page) => page.body?.trim());
63190
63702
  const listings = configPinned.listings;
@@ -63222,11 +63734,11 @@ async function knowledgeDeliveredPins(run, budget) {
63222
63734
  const renderConfig = (room) => {
63223
63735
  for (const page of configured) entries.push({
63224
63736
  id: page.id,
63225
- text: render(page, labelOf(page), room)
63737
+ text: render(page, labelOf(page), room, read)
63226
63738
  });
63227
63739
  for (const listing of listings) entries.push({
63228
63740
  id: `${PIN_LIST_ID_PREFIX}${listing.origin.id}`,
63229
- text: renderListing(listing, listingRef(listing), room)
63741
+ text: renderListing(listing, listingRef(listing), room, read)
63230
63742
  });
63231
63743
  };
63232
63744
  renderConfig(Number.POSITIVE_INFINITY);
@@ -63248,10 +63760,10 @@ async function knowledgeDeliveredPins(run, budget) {
63248
63760
  }
63249
63761
  const entry = listing ? {
63250
63762
  id: `${PIN_LIST_ID_PREFIX}${page.id}`,
63251
- text: renderListing(listing, listingRef(listing), remaining)
63763
+ text: renderListing(listing, listingRef(listing), remaining, read)
63252
63764
  } : {
63253
63765
  id: page.id,
63254
- text: render(page, labelOf(page), remaining)
63766
+ text: render(page, labelOf(page), remaining, read)
63255
63767
  };
63256
63768
  used += require_workspace.estimateTokenCount(entry.text);
63257
63769
  delivered.push({
@@ -63259,7 +63771,7 @@ async function knowledgeDeliveredPins(run, budget) {
63259
63771
  pin
63260
63772
  });
63261
63773
  }
63262
- 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);
63263
63775
  while (total > delivered.length && delivered.length > 0 && used + require_workspace.estimateTokenCount(line()) > budget.maxTokens) {
63264
63776
  const dropped = delivered.pop();
63265
63777
  used -= require_workspace.estimateTokenCount(dropped.entry.text);
@@ -63386,12 +63898,17 @@ var PinnedStateProcessor = class {
63386
63898
  constructor(deps) {
63387
63899
  this.deps = deps;
63388
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
+ }
63389
63906
  processInput(args) {
63390
63907
  return {
63391
63908
  messages: args.messages,
63392
63909
  systemMessages: [...args.systemMessages, {
63393
63910
  role: "system",
63394
- 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()}`
63395
63912
  }]
63396
63913
  };
63397
63914
  }
@@ -71444,6 +71961,44 @@ function toLiveStructuredOutputSchema(schema, nullToUndefined) {
71444
71961
  const standard = (0, _mastra_schema_compat_schema.toStandardSchema)(schema);
71445
71962
  return nullToUndefined ? (0, _mastra_schema_compat.wrapSchemaWithNullTransform)(standard) : standard;
71446
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
+ }
71447
72002
  // src/agent/save-queue/index.ts
71448
72003
  var SaveQueueManager = class SaveQueueManager {
71449
72004
  logger;
@@ -71699,6 +72254,32 @@ var DurableProcessorRebuildError = class extends Error {
71699
72254
  this.cause = cause;
71700
72255
  }
71701
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
+ }
71702
72283
  async function rebuildProcessorPipeline(options) {
71703
72284
  const { agent, agentId, requestContext, emptyErrorProcessorOverride, processorStates, logger } = options;
71704
72285
  try {
@@ -71742,6 +72323,22 @@ function assertToolsetToolsAvailable(tools, toolsetToolNames, agentId, runId) {
71742
72323
  });
71743
72324
  }
71744
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
+ /**
71745
72342
  * Resolve all runtime dependencies needed for durable step execution.
71746
72343
  *
71747
72344
  * This function reconstructs the non-serializable state needed to execute
@@ -71775,11 +72372,13 @@ async function resolveRuntimeDependencies(options) {
71775
72372
  let processorStates = globalEntry?.processorStates;
71776
72373
  let rehydratedFromMastra = false;
71777
72374
  let rebuiltAgent;
72375
+ let backgroundTasks;
71778
72376
  if (hasHydratedEntry) logger?.debug?.(`[DurableAgent:${agentId}] Using model and tools from global registry for run ${runId}`);
71779
72377
  else if (mastra) try {
71780
- const agent = mastra.getAgentById(agentId);
72378
+ const agent = await resolveRunAgent(mastra, agentId, runId, input.agentVersionId);
71781
72379
  rebuiltAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
71782
72380
  const resolveRequestContext = restoreRequestContext$1(input.requestContextEntries, options.requestContext);
72381
+ backgroundTasks = resolveBackgroundTasks(mastra, agent, input.options);
71783
72382
  tools = await agent.getToolsForExecution({
71784
72383
  runId,
71785
72384
  threadId: input.state.threadId,
@@ -71787,7 +72386,9 @@ async function resolveRuntimeDependencies(options) {
71787
72386
  requestContext: resolveRequestContext,
71788
72387
  memoryConfig: input.state.memoryConfig,
71789
72388
  autoResumeSuspendedTools: input.options?.autoResumeSuspendedTools,
71790
- clientTools: input.options?.clientTools
72389
+ clientTools: input.options?.clientTools,
72390
+ backgroundTaskEnabled: Boolean(backgroundTasks.backgroundTaskManager),
72391
+ backgroundTaskPolicy: input.options?.backgroundTaskPolicy
71791
72392
  });
71792
72393
  assertToolsetToolsAvailable(tools, input.options?.toolsetToolNames, agentId, runId);
71793
72394
  model = await agent.getModel?.({ requestContext: resolveRequestContext }) ?? resolveModel(input.modelConfig, mastra);
@@ -71816,7 +72417,7 @@ async function resolveRuntimeDependencies(options) {
71816
72417
  processorStates = rebuiltProcessors.processorStates;
71817
72418
  rehydratedFromMastra = true;
71818
72419
  } catch (error) {
71819
- if (error instanceof DurableProcessorRebuildError) throw error;
72420
+ if (error instanceof DurableProcessorRebuildError || error instanceof DurableAgentNotFoundError) throw error;
71820
72421
  if ((input.options?.toolsetToolNames?.length ?? 0) > 0) throw error;
71821
72422
  logger?.debug?.(`[DurableAgent:${agentId}] Failed to get agent from Mastra: ${error}`);
71822
72423
  model = resolveModel(input.modelConfig, mastra);
@@ -71841,7 +72442,8 @@ async function resolveRuntimeDependencies(options) {
71841
72442
  outputProcessors,
71842
72443
  errorProcessors,
71843
72444
  processorStates,
71844
- agent: rebuiltAgent
72445
+ agent: rebuiltAgent,
72446
+ ...backgroundTasks
71845
72447
  };
71846
72448
  if (globalEntry) Object.assign(globalEntry, rebuilt);
71847
72449
  else setRunRegistryEntry(runId, rebuilt, mastra);
@@ -71893,10 +72495,11 @@ async function rebuildRunToolsFromMastra(options) {
71893
72495
  if (!mastra) return void 0;
71894
72496
  let agentResolved = false;
71895
72497
  try {
71896
- const agent = mastra.getAgentById(agentId);
72498
+ const agent = await resolveRunAgent(mastra, agentId, runId, options.agentVersionId);
71897
72499
  agentResolved = true;
71898
72500
  const processorAgent = isDurableAgentLike(agent) && agent.agent !== agent ? agent.agent : agent;
71899
72501
  const resolveRequestContext = restoreRequestContext$1(requestContextEntries, requestContext);
72502
+ const backgroundTasks = resolveBackgroundTasks(mastra, agent, execOptions);
71900
72503
  const tools = await agent.getToolsForExecution({
71901
72504
  runId,
71902
72505
  threadId: state.threadId,
@@ -71904,7 +72507,9 @@ async function rebuildRunToolsFromMastra(options) {
71904
72507
  requestContext: resolveRequestContext,
71905
72508
  memoryConfig: state.memoryConfig,
71906
72509
  autoResumeSuspendedTools: execOptions?.autoResumeSuspendedTools,
71907
- clientTools: execOptions?.clientTools
72510
+ clientTools: execOptions?.clientTools,
72511
+ backgroundTaskEnabled: Boolean(backgroundTasks.backgroundTaskManager),
72512
+ backgroundTaskPolicy: execOptions?.backgroundTaskPolicy
71908
72513
  });
71909
72514
  if (!isHydratedRegistryEntry(getRunRegistryEntry(runId, mastra))) assertToolsetToolsAvailable(tools, execOptions?.toolsetToolNames, agentId, runId);
71910
72515
  const memory = await agent.getMemory?.({ requestContext: resolveRequestContext });
@@ -71931,6 +72536,7 @@ async function rebuildRunToolsFromMastra(options) {
71931
72536
  memory,
71932
72537
  saveQueueManager,
71933
72538
  agent: processorAgent,
72539
+ ...backgroundTasks,
71934
72540
  ...rebuiltProcessors,
71935
72541
  ...options.rehydrateProcessors ? { requestContext: resolveRequestContext } : {}
71936
72542
  };
@@ -71949,6 +72555,8 @@ async function rebuildRunToolsFromMastra(options) {
71949
72555
  existing.errorProcessors ??= rebuiltProcessors.errorProcessors;
71950
72556
  existing.processorStates ??= rebuiltProcessors.processorStates;
71951
72557
  existing.agent ??= processorAgent;
72558
+ existing.backgroundTaskManager ??= backgroundTasks.backgroundTaskManager;
72559
+ existing.backgroundTasksConfig ??= backgroundTasks.backgroundTasksConfig;
71952
72560
  } else {
71953
72561
  existing = patch;
71954
72562
  setRunRegistryEntry(runId, existing, mastra);
@@ -72481,6 +73089,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72481
73089
  outputResultChunks.push(data);
72482
73090
  } };
72483
73091
  const outputTextBeforeProcessing = resolveOutputText(messageList);
73092
+ let rewrittenStepTexts;
72484
73093
  if (registryEntry?.outputProcessors?.length) try {
72485
73094
  let agent = registryEntry.agent;
72486
73095
  if (!agent && mastra) try {
@@ -72489,7 +73098,7 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72489
73098
  } catch {
72490
73099
  agent = void 0;
72491
73100
  }
72492
- await new require_stream.ProcessorRunner({
73101
+ const runner = new require_stream.ProcessorRunner({
72493
73102
  inputProcessors: registryEntry.inputProcessors ?? [],
72494
73103
  outputProcessors: registryEntry.outputProcessors,
72495
73104
  errorProcessors: registryEntry.errorProcessors ?? [],
@@ -72497,7 +73106,38 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72497
73106
  agentName: initData.agentName ?? initData.agentId,
72498
73107
  agent,
72499
73108
  processorStates: registryEntry.processorStates
72500
- }).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
+ }
72501
73141
  } catch (error) {
72502
73142
  if (error instanceof require_stream.TripWire) {
72503
73143
  await undoSavedResponseMessages({
@@ -72531,6 +73171,11 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72531
73171
  }
72532
73172
  const outputText = resolveOutputText(messageList);
72533
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
+ };
72534
73179
  const saveQueueManager = registryEntry?.saveQueueManager ?? rebuiltSaveQueueManager;
72535
73180
  const memory = registryEntry?.memory ?? rebuiltMemory;
72536
73181
  const authorizeMemory = durableState?.threadId && durableState.resourceId ? (permission) => authorizeDurableMemory(getDurableMemoryAuthorizationChecks(registryEntry), {
@@ -72612,6 +73257,8 @@ async function runDurableFinishSideEffects({ runId, initData, messageListState,
72612
73257
  messageListState: messageList.serialize(),
72613
73258
  outputText,
72614
73259
  outputTextChanged,
73260
+ finishMessages,
73261
+ rewrittenStepTexts,
72615
73262
  titleGeneration,
72616
73263
  titleForStream,
72617
73264
  structuredOutputChunks,
@@ -74509,6 +75156,7 @@ var DurableChunkPublishError$1 = class extends Error {
74509
75156
  const durableLLMInputSchema = zod.z.object({
74510
75157
  runId: zod.z.string(),
74511
75158
  agentId: zod.z.string(),
75159
+ agentVersionId: zod.z.string().optional(),
74512
75160
  agentName: zod.z.string().optional(),
74513
75161
  messageListState: zod.z.any(),
74514
75162
  initialUntaggedSystemMessages: zod.z.array(zod.z.any()).optional(),
@@ -74677,7 +75325,7 @@ function createDurableLLMExecutionStep(_options) {
74677
75325
  const registry = getRunRegistryEntry(runId, mastra);
74678
75326
  if (registry) registry.tracingTermination = termination;
74679
75327
  };
74680
- const emitFatalErrorBail = async (fatalError, modelId, signalPreempted = false) => {
75328
+ const emitFatalErrorBail = async (fatalError, modelId, { signalPreempted = false, modelRejectedBeforeStream = false } = {}) => {
74681
75329
  ownership?.throwIfLost();
74682
75330
  getRunRegistryEntry(runId, mastra)?.runScope?.set(LOCAL_MODEL_REQUEST_KEY, request);
74683
75331
  const usage = {
@@ -74703,7 +75351,8 @@ function createDurableLLMExecutionStep(_options) {
74703
75351
  payload: {
74704
75352
  stepResult: {
74705
75353
  reason: "error",
74706
- isContinued: false
75354
+ isContinued: false,
75355
+ ...modelRejectedBeforeStream && !require_stream.isMastraTimeoutError(fatalError) ? { warnings: [] } : {}
74707
75356
  },
74708
75357
  output: { usage },
74709
75358
  metadata: {}
@@ -74730,7 +75379,7 @@ function createDurableLLMExecutionStep(_options) {
74730
75379
  ownership?.throwIfLost();
74731
75380
  if (executionAbortSignalEarly?.aborted) {
74732
75381
  const earlyTimeout = resolveTotalTimeoutAbort(executionAbortSignalEarly);
74733
- 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 });
74734
75383
  return {
74735
75384
  ...await storeStepTranscript(),
74736
75385
  text: "",
@@ -74790,6 +75439,7 @@ function createDurableLLMExecutionStep(_options) {
74790
75439
  }];
74791
75440
  if (modelList.length === 0) throw new Error("No enabled models available for execution");
74792
75441
  let lastError;
75442
+ let modelRejectedBeforeStream = false;
74793
75443
  let skipUnavailableAttachments = false;
74794
75444
  const maxProcessorRetries = resolveMaxProcessorRetries({
74795
75445
  maxProcessorRetries: typedInput.options?.maxProcessorRetries,
@@ -74842,7 +75492,7 @@ function createDurableLLMExecutionStep(_options) {
74842
75492
  payload: { id }
74843
75493
  }, true);
74844
75494
  const totalTimeout = resolveTotalTimeoutAbort(executionAbortSignalEarly, error instanceof Error ? error : void 0);
74845
- if (totalTimeout) return emitFatalErrorBail(totalTimeout, modelId, true);
75495
+ if (totalTimeout) return emitFatalErrorBail(totalTimeout, modelId, { signalPreempted: true });
74846
75496
  return {
74847
75497
  ...await storeStepTranscript(),
74848
75498
  text: "",
@@ -74892,6 +75542,7 @@ function createDurableLLMExecutionStep(_options) {
74892
75542
  const modelEntry = modelList[modelIndex];
74893
75543
  const maxRetries = hasModelList || (typedInput.options?.agentMaxRetriesConfigured ?? false) ? modelEntry.maxRetries || 0 : typedInput.options?.modelSettings?.maxRetries ?? modelEntry.maxRetries ?? 0;
74894
75544
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
75545
+ let modelRequestRejected = false;
74895
75546
  ownership?.throwIfLost();
74896
75547
  request = {};
74897
75548
  const attemptMessageId = currentMessageId;
@@ -75530,6 +76181,9 @@ function createDurableLLMExecutionStep(_options) {
75530
76181
  includeRawChunks: execOptions.includeRawChunks,
75531
76182
  methodType: "stream",
75532
76183
  structuredOutput,
76184
+ onRequestFailed: () => {
76185
+ modelRequestRejected = true;
76186
+ },
75533
76187
  onResult: ({ warnings: w, request: r, rawResponse: rr }) => {
75534
76188
  warnings = w || [];
75535
76189
  request = r || {};
@@ -76078,6 +76732,7 @@ function createDurableLLMExecutionStep(_options) {
76078
76732
  };
76079
76733
  }
76080
76734
  lastError = errorObj;
76735
+ modelRejectedBeforeStream = modelRequestRejected;
76081
76736
  const registryEntryInner = getRunRegistryEntry(runId, mastra);
76082
76737
  const canRetryErrorInner = maxProcessorRetries !== void 0 && processorRetryCount < maxProcessorRetries;
76083
76738
  if (registryEntryInner?.errorProcessors?.length) try {
@@ -76156,6 +76811,7 @@ function createDurableLLMExecutionStep(_options) {
76156
76811
  };
76157
76812
  }
76158
76813
  lastError = streamErrorObj;
76814
+ modelRejectedBeforeStream = modelRequestRejected;
76159
76815
  if (attempt < maxRetries) continue;
76160
76816
  break;
76161
76817
  }
@@ -76378,6 +77034,7 @@ function createDurableLLMExecutionStep(_options) {
76378
77034
  if (interruption.signal.aborted) return finishInterruptedRequest(error, modelEntry.config.modelId);
76379
77035
  if (error instanceof require_stream.TripWire) throw error;
76380
77036
  lastError = error instanceof Error ? error : new Error(String(error));
77037
+ modelRejectedBeforeStream = modelRequestRejected;
76381
77038
  const selectedOuterAbortSignal = getRunRegistryEntry(runId, mastra)?.abortSignal ?? abortSignal;
76382
77039
  const outerAbortSignal = ownership?.composeSignal(selectedOuterAbortSignal) ?? selectedOuterAbortSignal;
76383
77040
  const totalTimeout = resolveTotalTimeoutAbort(outerAbortSignal, lastError);
@@ -76477,7 +77134,7 @@ function createDurableLLMExecutionStep(_options) {
76477
77134
  }
76478
77135
  const fatalError = lastError ?? /* @__PURE__ */ new Error("Exhausted all fallback models and reached the maximum number of retries.");
76479
77136
  terminalAttemptContext?.recordTerminalError(fatalError);
76480
- return emitFatalErrorBail(fatalError, modelList.at(-1)?.config.modelId ?? "unknown");
77137
+ return emitFatalErrorBail(fatalError, modelList.at(-1)?.config.modelId ?? "unknown", { modelRejectedBeforeStream });
76481
77138
  })
76482
77139
  });
76483
77140
  }
@@ -77702,6 +78359,7 @@ function createDurableToolCallStep() {
77702
78359
  mastra,
77703
78360
  runId,
77704
78361
  agentId: initData.agentId,
78362
+ agentVersionId: initData.agentVersionId,
77705
78363
  state,
77706
78364
  options: agentOptions,
77707
78365
  requestContextEntries: initData.requestContextEntries,
@@ -77721,8 +78379,9 @@ function createDurableToolCallStep() {
77721
78379
  if (!tool && !hasAuthoritativeToolSnapshot) tool = Object.values(rebuiltTools).find((t) => t && typeof t === "object" && "id" in t && t.id === toolName);
77722
78380
  }
77723
78381
  }
77724
- if (!tool && !hasAuthoritativeToolSnapshot) tool = resolveTool$1(toolName, mastra);
77725
- 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) {
77726
78385
  mastraTools = mastra.listTools?.();
77727
78386
  if (mastraTools) {
77728
78387
  tool = findProviderToolByName(mastraTools, toolName);
@@ -79423,7 +80082,9 @@ function createDurableLLMMappingStep() {
79423
80082
  mastra,
79424
80083
  runId: _runId,
79425
80084
  agentId: _agentId,
80085
+ agentVersionId: getInitData()?.agentVersionId,
79426
80086
  state,
80087
+ options: (getInitData?.())?.options,
79427
80088
  requestContext
79428
80089
  });
79429
80090
  saveQueueManager = rebuilt?.saveQueueManager;
@@ -79872,7 +80533,10 @@ const durableAgenticInputSchema = zod.z.object({
79872
80533
  * Schema for the iteration state that flows through the dowhile loop.
79873
80534
  * Extends base schema with model list for fallback support.
79874
80535
  */
79875
- 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
+ });
79876
80540
  /**
79877
80541
  * Whether a reader that attaches mid-run can read the run's earlier events. Steps publish on the
79878
80542
  * engine's bus, but `observe()` reads through the agent's own stream bus, which has no replay
@@ -79881,7 +80545,8 @@ const iterationStateSchema = baseIterationStateSchema.extend({ modelList: zod.z.
79881
80545
  function runTopicReplays(rt) {
79882
80546
  const topic = AGENT_STREAM_TOPIC(rt.runId);
79883
80547
  if (!rt.pubsub?.__replaysTopic(topic)) return false;
79884
- 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;
79885
80550
  }
79886
80551
  function liveOrRebuiltAgentSpan(agentSpanData, reg, observability) {
79887
80552
  if (!agentSpanData) return void 0;
@@ -80122,6 +80787,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80122
80787
  return params.bail({
80123
80788
  ...update,
80124
80789
  ...await storeAccumulatedSteps(params, accumulatedSteps),
80790
+ agentVersionId: initData.agentVersionId,
80125
80791
  modelList: initData.modelList
80126
80792
  });
80127
80793
  }
@@ -80152,6 +80818,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80152
80818
  return {
80153
80819
  runId: state.runId,
80154
80820
  agentId: state.agentId,
80821
+ agentVersionId: state.agentVersionId,
80155
80822
  agentName: state.agentName,
80156
80823
  messageListState: state.messageListState,
80157
80824
  initialUntaggedSystemMessages: state.initialUntaggedSystemMessages,
@@ -80212,6 +80879,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80212
80879
  return {
80213
80880
  ...baseUpdate,
80214
80881
  ...await storeAccumulatedSteps(params, accumulatedSteps),
80882
+ agentVersionId: initData.agentVersionId,
80215
80883
  modelList: initData.modelList
80216
80884
  };
80217
80885
  }, { id: "update-iteration-state" }).then(isTaskCompleteStep).then(goalStep).commit();
@@ -80504,8 +81172,21 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80504
81172
  steps
80505
81173
  }
80506
81174
  });
80507
- const textRewritten = !!lastStep && finishResult.outputTextChanged;
80508
- 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) {
80509
81190
  lastStep.text = finishResult.outputText;
80510
81191
  steps[steps.length - 1] = {
80511
81192
  ...steps[steps.length - 1],
@@ -80560,7 +81241,7 @@ var DurableAgenticLoopBuilder = class extends BaseAgenticLoopBuilder {
80560
81241
  if (pubsub) await emitFinishEvent(pubsub, state.runId, {
80561
81242
  output: finalOutput.output,
80562
81243
  stepResult: finalOutput.stepResult,
80563
- messages: finishMessages,
81244
+ messages: finishResult.finishMessages ?? finishMessages,
80564
81245
  ...textRewritten && { textRewritten },
80565
81246
  ...stopCause && { stopCause }
80566
81247
  });
@@ -81065,6 +81746,11 @@ var DefaultAgentExecutionEngine = class {
81065
81746
  };
81066
81747
  getWorkflow(options) {
81067
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
+ }
81068
81754
  this.#workflow = this.createWorkflow(options);
81069
81755
  this.warnOnRiskyPersistencePolicy(options.shouldPersistSnapshot, options.guardrailLogger);
81070
81756
  if (this.mastra) {
@@ -81808,7 +82494,7 @@ async function prepareForDurableExecution(options) {
81808
82494
  });
81809
82495
  let tripwireData;
81810
82496
  if (inputProcessors.length > 0) try {
81811
- const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-Dvy_0o14.cjs")).then((n) => n.runner_exports);
82497
+ const { ProcessorRunner } = await Promise.resolve().then(() => require("./stream-0kdqBOOn.cjs")).then((n) => n.runner_exports);
81812
82498
  await new ProcessorRunner({
81813
82499
  inputProcessors,
81814
82500
  outputProcessors,
@@ -81847,7 +82533,7 @@ async function prepareForDurableExecution(options) {
81847
82533
  throw inputProcessorError;
81848
82534
  }
81849
82535
  }
81850
- let requestContextEntriesSnapshot = snapshotRequestContextEntries(requestContext);
82536
+ let requestContextEntriesSnapshot = snapshotRequestContextEntries(requestContext, options.onRequestContextEntryOmitted);
81851
82537
  if (!Array.isArray(requestContextEntriesSnapshot?.["mastra__scopes"])) requestContextEntriesSnapshot = {
81852
82538
  ...requestContextEntriesSnapshot,
81853
82539
  [require_request_context.MASTRA_SCOPES_KEY]: []
@@ -83728,11 +84414,7 @@ var Agent = class Agent extends require_base.MastraBase {
83728
84414
  }
83729
84415
  const durable = config.durable;
83730
84416
  if (durable && typeof durable === "object") {
83731
- const legacyKeys = [
83732
- "maxSteps",
83733
- "id",
83734
- "name"
83735
- ].filter((key) => Object.hasOwn(durable, key));
84417
+ const legacyKeys = ["id", "name"].filter((key) => Object.hasOwn(durable, key));
83736
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.`);
83737
84419
  }
83738
84420
  this.#scopes = config.scopes;
@@ -84230,7 +84912,7 @@ var Agent = class Agent extends require_base.MastraBase {
84230
84912
  #warnInheritedExecutionOptions(options) {
84231
84913
  if (!this.#executionEnginePolicy.inherited) return;
84232
84914
  if (options.eagerToolExecution === true) this.#warnExecutionPolicy("eager", "Mastra-inherited execution engine policy does not support eagerToolExecution.");
84233
- 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.");
84234
84916
  }
84235
84917
  #beginExecutionPolicy() {
84236
84918
  this.#executionEnginePolicy.freeze();
@@ -84562,7 +85244,8 @@ var Agent = class Agent extends require_base.MastraBase {
84562
85244
  }
84563
85245
  processors.push(new PinnedStateProcessor({
84564
85246
  principalsKey: (context) => knowledge.__principalsKey(context),
84565
- readPins: (context) => knowledge.__deliveredPins(context)
85247
+ readPins: (context) => knowledge.__deliveredPins(context),
85248
+ ...knowledge.__toolGroups
84566
85249
  }));
84567
85250
  }
84568
85251
  return processors;
@@ -89911,6 +90594,17 @@ var Agent = class Agent extends require_base.MastraBase {
89911
90594
  return agentThreadStreamRuntime.listActiveThreadRuns(this.getPubSub());
89912
90595
  }
89913
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
+ /**
89914
90608
  * Lists suspended agent runs from workflow snapshot storage — runs waiting on
89915
90609
  * a tool-call approval (`requireApproval` / `requireToolApproval`) or on a
89916
90610
  * tool that called `suspend()`.
@@ -91259,6 +91953,7 @@ var Agent = class Agent extends require_base.MastraBase {
91259
91953
  - always produce a title, even when the transcript is only a greeting or trivial exchange
91260
91954
  - ensure it is not more than 80 characters long
91261
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
91262
91957
  - do not use quotes or colons
91263
91958
  - the entire text you return will be used as the title`;
91264
91959
  if (!instructions) return DEFAULT_TITLE_INSTRUCTIONS;
@@ -91285,10 +91980,13 @@ var Agent = class Agent extends require_base.MastraBase {
91285
91980
  return this.#executionEnginePolicy.engine === "evented" ? "evented" : "default";
91286
91981
  }
91287
91982
  getWorkflow() {
91983
+ const durable = this.durable;
91984
+ const config = typeof durable === "object" ? durable : void 0;
91288
91985
  return this.executionEngine.getWorkflow({
91986
+ maxSteps: config?.maxSteps,
91289
91987
  workflowEngine: this.workflowEngine,
91290
- storesRunsInJournal: false,
91291
- shouldPersistSnapshot: typeof this.durable === "object" ? this.durable.shouldPersistSnapshot : void 0,
91988
+ storesRunsInJournal: config?.storageVersion === 2,
91989
+ shouldPersistSnapshot: config?.shouldPersistSnapshot,
91292
91990
  logger: this.logger,
91293
91991
  guardrailLogger: this.guardrailLogger
91294
91992
  });
@@ -92273,8 +92971,8 @@ var Agent = class Agent extends require_base.MastraBase {
92273
92971
  async #resolveDurableRunOptions(options, snapshot) {
92274
92972
  if (options?.[RESOLVED_EXECUTION_OPTIONS]) return options;
92275
92973
  const defaultOptions = await this.getDefaultOptions({ requestContext: options?.requestContext });
92276
- this.#warnInheritedExecutionOptions(defaultOptions);
92277
92974
  const resolvedOptions = require_utils$1.deepMerge(withDefaultToolCallConcurrencyLimit(defaultOptions ?? {}, options), options ?? {});
92975
+ this.#warnInheritedExecutionOptions(resolvedOptions);
92278
92976
  if (options?.actor !== void 0) resolvedOptions.actor = options.actor;
92279
92977
  const scopedOptions = await this.#applyScopes(resolvedOptions, {
92280
92978
  callScopes: options?.scopes,
@@ -92570,6 +93268,7 @@ var Agent = class Agent extends require_base.MastraBase {
92570
93268
  optionsAreResolved: true,
92571
93269
  resolvedDefaultOptions: options?.[RESOLVED_DEFAULT_OPTIONS],
92572
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,
92573
93272
  mastra: this.#mastra,
92574
93273
  methodType,
92575
93274
  durableAgentId: this.id,
@@ -95856,44 +96555,6 @@ function resolveRegisteredClassifier(mastra, classifierId, scorerId) {
95856
96555
  throw new Error(`Classifier '${classifierId}' not found for scorer '${scorerId}'. Register it with Mastra classifiers or pass the classifier instance directly.`, { cause: error });
95857
96556
  }
95858
96557
  }
95859
- // src/mastra/resolve-agent.ts
95860
- /**
95861
- * Resolve an agent by id the same way server handlers do: in-memory registry
95862
- * first, then the editor for stored agents.
95863
- *
95864
- * Stored (editor) agents aren't registered on the Mastra instance until
95865
- * they've been hydrated once in the current process, so a registry miss does
95866
- * not mean the agent is gone — especially on a cold start. Editor hydration
95867
- * via `getById` also re-registers the agent, so subsequent lookups take the
95868
- * fast registry path.
95869
- *
95870
- * Every internal call site that needs "does this agent exist / give it to
95871
- * me" semantics should go through this helper so the fallback (and the
95872
- * confirmed-miss vs. transient-error distinction) can't drift between call
95873
- * sites.
95874
- */
95875
- async function resolveAgentById(mastra, agentId) {
95876
- try {
95877
- return {
95878
- status: "found",
95879
- agent: mastra.getAgentById(agentId)
95880
- };
95881
- } catch {}
95882
- const editor = mastra.getEditor?.();
95883
- if (!editor) return { status: "missing" };
95884
- try {
95885
- const agent = await editor.agent.getById(agentId);
95886
- return agent ? {
95887
- status: "found",
95888
- agent
95889
- } : { status: "missing" };
95890
- } catch (error) {
95891
- return {
95892
- status: "error",
95893
- error
95894
- };
95895
- }
95896
- }
95897
96558
  // src/mastra/hooks.ts
95898
96559
  function toScorerTargetEntityType(entityType) {
95899
96560
  switch (entityType) {
@@ -102709,6 +103370,12 @@ var AgentThreadStreamRuntime = class {
102709
103370
  type: "run-suspended",
102710
103371
  runId,
102711
103372
  streamId
103373
+ } : hasDurableExecution(record.agent) ? {
103374
+ type: "run-completed",
103375
+ runId,
103376
+ streamId,
103377
+ persisted: false,
103378
+ status: "interrupted"
102712
103379
  } : {
102713
103380
  type: "run-completed",
102714
103381
  runId,
@@ -103244,14 +103911,20 @@ var AgentThreadStreamRuntime = class {
103244
103911
  if (!answersTo(runId)) return;
103245
103912
  const queues = data.preRun ? state.preRunSignalsByThread : state.pendingSignalsByThread;
103246
103913
  if ([state.preRunSignalsByThread.get(key), state.pendingSignalsByThread.get(key)].some((queue) => queue?.some((signal) => signal.id === data.signal.id))) return;
103247
- const queue = queues.get(key) ?? [];
103248
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) ?? [];
103249
103921
  queue.push(signal);
103250
103922
  queues.set(key, queue);
103251
103923
  subscription.admittedSignalIds.add(data.signal.id);
103252
103924
  this.#publishPendingUserMessage(pubsub, key, runId, signal, "pending");
103253
103925
  this.#notifyPendingSignals(state, key, signal);
103254
- } 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") {
103255
103928
  const { chunk } = data;
103256
103929
  if (chunk.type === "data-user-message-pending" && chunk.data.metadata?.status === "pending") this.#settleForwardedIdleSignal(state, key, chunk.data.id, chunk.runId);
103257
103930
  } else if (data?.type === "signals-cancelled") {
@@ -103304,7 +103977,7 @@ var AgentThreadStreamRuntime = class {
103304
103977
  const onEvent = (event, ack) => {
103305
103978
  const type = event.data?.type;
103306
103979
  const awaitingForwards = state.forwardedIdleSignalsByThread.has(key);
103307
- 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?.();
103308
103981
  subscription.references++;
103309
103982
  const handled = tail.then(() => handleEvent(event));
103310
103983
  tail = handled.catch(() => {});
@@ -103381,6 +104054,17 @@ var AgentThreadStreamRuntime = class {
103381
104054
  }
103382
104055
  for (const key of state.threadControlSubscriptions.keys()) this.#releaseUnusedThreadControlSubscription(state, key);
103383
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
+ }
103384
104068
  #threadKey(resourceId, threadId) {
103385
104069
  return agentThreadStreamKey(resourceId, threadId);
103386
104070
  }
@@ -104277,7 +104961,7 @@ var AgentThreadStreamRuntime = class {
104277
104961
  const topic = this.#threadTopic(key);
104278
104962
  await resolvedPubSub.publish(topic, {
104279
104963
  type: event.type,
104280
- runId: "runId" in event ? event.runId : key,
104964
+ runId: ("runId" in event ? event.runId : void 0) ?? key,
104281
104965
  data: event
104282
104966
  });
104283
104967
  }
@@ -104884,6 +105568,14 @@ var AgentThreadStreamRuntime = class {
104884
105568
  hasThreadRun(runId, pubsub) {
104885
105569
  return this.#getState(pubsub).threadRunsById.has(runId);
104886
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
+ }
104887
105579
  /** Whether the run's original stream is still live and carries its resumed segments. */
104888
105580
  hasRunContinuation(runId, pubsub) {
104889
105581
  return this.#getState(pubsub).threadRunsById.get(runId)?.continuation?.canContinue() === true;
@@ -105116,6 +105808,7 @@ var AgentThreadStreamRuntime = class {
105116
105808
  const chunk = this.#pendingUserMessageChunk(runId, signal, status);
105117
105809
  if (chunk) this.#publish(pubsub, key, {
105118
105810
  type: "user-message-presentation",
105811
+ runId,
105119
105812
  chunk
105120
105813
  });
105121
105814
  }
@@ -106233,6 +106926,7 @@ var AgentThreadStreamRuntime = class {
106233
106926
  const statuses = [];
106234
106927
  const settledRunIds = /* @__PURE__ */ new Map();
106235
106928
  const reportedSuspensions = /* @__PURE__ */ new Set();
106929
+ const reportedInterruptions = /* @__PURE__ */ new Set();
106236
106930
  const presentations = [];
106237
106931
  const presentedSignalIds = /* @__PURE__ */ new Set();
106238
106932
  const settledSignalIds = /* @__PURE__ */ new Set();
@@ -106254,6 +106948,9 @@ var AgentThreadStreamRuntime = class {
106254
106948
  if (status === "suspended") {
106255
106949
  if (reportedSuspensions.has(streamId)) return;
106256
106950
  reportedSuspensions.add(streamId);
106951
+ } else if (status === "interrupted") {
106952
+ if (reportedInterruptions.has(streamId)) return;
106953
+ reportedInterruptions.add(streamId);
106257
106954
  } else settledRunIds.set(runId, streamId);
106258
106955
  if (!options.withRunStatus) return;
106259
106956
  statuses.push({
@@ -106738,7 +107435,7 @@ var AgentThreadStreamRuntime = class {
106738
107435
  if (data.type !== "run-suspended") parkedPromptRunIds.delete(data.runId);
106739
107436
  if (data.type === "run-completed") await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId);
106740
107437
  if (data.type !== "run-suspended" || !suspendedRunEnded) {
106741
- 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";
106742
107439
  enqueueStatus(data.runId, eventStreamId, status);
106743
107440
  }
106744
107441
  wake();
@@ -107224,6 +107921,7 @@ var AgentThreadStreamRuntime = class {
107224
107921
  activeRecord ??= state.threadRunsById.get(runId);
107225
107922
  if (activeRecord) key ??= this.#threadKey(activeRecord.resourceId, activeRecord.threadId);
107226
107923
  }
107924
+ this.#assertRunTargetOwner(state, target);
107227
107925
  const resourceId = target.resourceId ?? activeRecord?.resourceId;
107228
107926
  const threadId = target.threadId ?? activeRecord?.threadId;
107229
107927
  if (!resourceId || !threadId) throw new Error("resourceId and threadId are required to queue a message");
@@ -107383,6 +108081,7 @@ var AgentThreadStreamRuntime = class {
107383
108081
  activeRecord ??= state.threadRunsById.get(runId);
107384
108082
  if (activeRecord) key ??= this.#threadKey(activeRecord.resourceId, activeRecord.threadId);
107385
108083
  }
108084
+ this.#assertRunTargetOwner(state, target);
107386
108085
  const resourceId = target.resourceId ?? activeRecord?.resourceId;
107387
108086
  const threadId = target.threadId ?? activeRecord?.threadId;
107388
108087
  if (!resourceId || !threadId) throw new Error("No active agent run found for signal target");
@@ -108656,6 +109355,36 @@ Object.defineProperty(exports, "KnowledgeDeclarationError", {
108656
109355
  return KnowledgeDeclarationError;
108657
109356
  }
108658
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
+ });
108659
109388
  Object.defineProperty(exports, "KnowledgeMoveTooLargeError", {
108660
109389
  enumerable: true,
108661
109390
  get: function() {
@@ -108710,6 +109439,12 @@ Object.defineProperty(exports, "KnowledgeStorage", {
108710
109439
  return KnowledgeStorage;
108711
109440
  }
108712
109441
  });
109442
+ Object.defineProperty(exports, "KnowledgeTransactionDeadlineError", {
109443
+ enumerable: true,
109444
+ get: function() {
109445
+ return KnowledgeTransactionDeadlineError;
109446
+ }
109447
+ });
108713
109448
  Object.defineProperty(exports, "KnowledgeUnsupportedCapabilityError", {
108714
109449
  enumerable: true,
108715
109450
  get: function() {
@@ -110384,6 +111119,12 @@ Object.defineProperty(exports, "groupLinkedToolMessages", {
110384
111119
  return groupLinkedToolMessages;
110385
111120
  }
110386
111121
  });
111122
+ Object.defineProperty(exports, "hasDurableExecution", {
111123
+ enumerable: true,
111124
+ get: function() {
111125
+ return hasDurableExecution;
111126
+ }
111127
+ });
110387
111128
  Object.defineProperty(exports, "hasErrorCode", {
110388
111129
  enumerable: true,
110389
111130
  get: function() {
@@ -110606,6 +111347,12 @@ Object.defineProperty(exports, "knowledgeSemanticIdempotencyKey", {
110606
111347
  return knowledgeSemanticIdempotencyKey;
110607
111348
  }
110608
111349
  });
111350
+ Object.defineProperty(exports, "knowledgeSubtree", {
111351
+ enumerable: true,
111352
+ get: function() {
111353
+ return knowledgeSubtree;
111354
+ }
111355
+ });
110609
111356
  Object.defineProperty(exports, "knowledgeVisibleScopeKeys", {
110610
111357
  enumerable: true,
110611
111358
  get: function() {
@@ -111242,6 +111989,12 @@ Object.defineProperty(exports, "summarizeNotifications", {
111242
111989
  return summarizeNotifications;
111243
111990
  }
111244
111991
  });
111992
+ Object.defineProperty(exports, "syncKnowledgePageBodyLinks", {
111993
+ enumerable: true,
111994
+ get: function() {
111995
+ return syncKnowledgePageBodyLinks;
111996
+ }
111997
+ });
111245
111998
  Object.defineProperty(exports, "takeRunScorerInstances", {
111246
111999
  enumerable: true,
111247
112000
  get: function() {