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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (509) hide show
  1. package/dist/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +363 -0
  2. package/dist/a2a/index.cjs +1 -1
  3. package/dist/a2a/index.js +1 -1
  4. package/dist/agent/agent.d.ts +72 -1
  5. package/dist/agent/agent.types.d.ts +30 -2
  6. package/dist/agent/durable/create-evented-agent.d.ts +6 -0
  7. package/dist/agent/durable/durable-agent.d.ts +1 -15
  8. package/dist/agent/durable/index.cjs +7 -26
  9. package/dist/agent/durable/index.js +7 -26
  10. package/dist/agent/durable/preparation.d.ts +2 -0
  11. package/dist/agent/durable/utils/resolve-runtime.d.ts +9 -0
  12. package/dist/agent/durable/workflows/durable-loop-builder.d.ts +4 -0
  13. package/dist/agent/durable/workflows/finalize-run.d.ts +3 -1
  14. package/dist/agent/durable/workflows/steps/llm-execution.d.ts +1 -0
  15. package/dist/agent/index.cjs +3 -3
  16. package/dist/agent/index.js +3 -3
  17. package/dist/agent/message-list/index.cjs +1 -1
  18. package/dist/agent/message-list/index.js +1 -1
  19. package/dist/agent/message-list/message-list.d.ts +11 -0
  20. package/dist/agent/message-list/utils/provider-compat.d.ts +1 -0
  21. package/dist/agent/request-context-snapshot.d.ts +1 -1
  22. package/dist/agent/streams/types.d.ts +10 -0
  23. package/dist/agent/thread-stream-runtime.d.ts +5 -0
  24. package/dist/agent/types.d.ts +25 -0
  25. package/dist/agent-builder/ee/index.cjs +1 -1
  26. package/dist/agent-builder/ee/index.js +1 -1
  27. package/dist/agent-controller/index.cjs +1 -1
  28. package/dist/agent-controller/index.js +1 -1
  29. package/dist/{agent-controller-K5vHtqfO.cjs → agent-controller-CrQ9OF80.cjs} +8 -8
  30. package/dist/{agent-controller-Cf3_IuY8.js → agent-controller-SSlKzE6A.js} +8 -8
  31. package/dist/background-tasks/index.cjs +1 -1
  32. package/dist/background-tasks/index.js +1 -1
  33. package/dist/{background-tasks-DqnQMfuf.cjs → background-tasks-BDrYBis-.cjs} +5 -3
  34. package/dist/{background-tasks-BgpX1P_s.js → background-tasks-BnJfNLFo.js} +5 -3
  35. package/dist/browser/index.cjs +2 -2
  36. package/dist/browser/index.js +2 -2
  37. package/dist/{builder-x295GDL6.js → builder-Cl-0BWkh.js} +2 -2
  38. package/dist/{builder-D8Osghdo.cjs → builder-Cw8u3pPl.cjs} +2 -2
  39. package/dist/capabilities/302ai.json +192 -192
  40. package/dist/capabilities/abliteratedllm.json +34 -34
  41. package/dist/capabilities/abliteration-ai.json +11 -11
  42. package/dist/capabilities/above.json +17 -17
  43. package/dist/capabilities/adaption.json +12 -12
  44. package/dist/capabilities/adzuki.json +30 -30
  45. package/dist/capabilities/agentrouter.json +10 -10
  46. package/dist/capabilities/agnes.json +4 -4
  47. package/dist/capabilities/ai-router.json +9 -9
  48. package/dist/capabilities/aiand.json +19 -11
  49. package/dist/capabilities/aigrow.json +11 -11
  50. package/dist/capabilities/aimlapi.json +146 -149
  51. package/dist/capabilities/aipg.json +2 -2
  52. package/dist/capabilities/aixy.json +14 -14
  53. package/dist/capabilities/aki-io.json +11 -11
  54. package/dist/capabilities/alibaba-cn.json +128 -109
  55. package/dist/capabilities/alibaba-coding-plan-cn.json +7 -19
  56. package/dist/capabilities/alibaba-coding-plan.json +7 -19
  57. package/dist/capabilities/alibaba-token-plan-cn.json +49 -67
  58. package/dist/capabilities/alibaba-token-plan.json +51 -69
  59. package/dist/capabilities/alibaba.json +71 -118
  60. package/dist/capabilities/ambient.json +14 -14
  61. package/dist/capabilities/amd.json +11 -11
  62. package/dist/capabilities/anthropic.json +48 -48
  63. package/dist/capabilities/anyapi.json +18 -18
  64. package/dist/capabilities/apiko.json +2 -2
  65. package/dist/capabilities/arcee.json +10 -10
  66. package/dist/capabilities/augure.json +6 -6
  67. package/dist/capabilities/auriko.json +20 -20
  68. package/dist/capabilities/bailing.json +5 -5
  69. package/dist/capabilities/baseten.json +46 -16
  70. package/dist/capabilities/bee.json +5 -5
  71. package/dist/capabilities/berget.json +4 -4
  72. package/dist/capabilities/bothub.json +16 -16
  73. package/dist/capabilities/boundless.json +36 -36
  74. package/dist/capabilities/bumo.json +40 -40
  75. package/dist/capabilities/byteplus.json +32 -32
  76. package/dist/capabilities/cerebras.json +4 -4
  77. package/dist/capabilities/cheapaimodel.json +5 -5
  78. package/dist/capabilities/cheapest-token.json +24 -24
  79. package/dist/capabilities/chutes.json +9 -9
  80. package/dist/capabilities/cline-pass.json +37 -37
  81. package/dist/capabilities/cloudcode.json +4 -4
  82. package/dist/capabilities/cloudflare-workers-ai.json +24 -24
  83. package/dist/capabilities/commandcode.json +152 -152
  84. package/dist/capabilities/concentrate.json +290 -266
  85. package/dist/capabilities/cortecs.json +105 -105
  86. package/dist/capabilities/crossmodel.json +160 -160
  87. package/dist/capabilities/crusoe.json +10 -10
  88. package/dist/capabilities/daoxe.json +7 -7
  89. package/dist/capabilities/databricks.json +318 -62
  90. package/dist/capabilities/deepinfra.json +73 -129
  91. package/dist/capabilities/deepseek.json +2 -2
  92. package/dist/capabilities/digitalocean.json +114 -114
  93. package/dist/capabilities/dothoosh.json +28 -28
  94. package/dist/capabilities/doubleword.json +24 -24
  95. package/dist/capabilities/edenai.json +458 -458
  96. package/dist/capabilities/empiriolabs.json +166 -166
  97. package/dist/capabilities/engy.json +20 -20
  98. package/dist/capabilities/evroc.json +8 -8
  99. package/dist/capabilities/ezkielyna.json +8 -8
  100. package/dist/capabilities/fastrouter.json +85 -85
  101. package/dist/capabilities/fireworks-ai.json +107 -44
  102. package/dist/capabilities/freemodel.json +23 -23
  103. package/dist/capabilities/friendli.json +9 -9
  104. package/dist/capabilities/frogbot.json +94 -94
  105. package/dist/capabilities/gisoo.json +16 -16
  106. package/dist/capabilities/gmicloud.json +17 -17
  107. package/dist/capabilities/google.json +57 -57
  108. package/dist/capabilities/graphn.json +10 -10
  109. package/dist/capabilities/greenpt.json +36 -36
  110. package/dist/capabilities/groq.json +2 -2
  111. package/dist/capabilities/helicone.json +68 -68
  112. package/dist/capabilities/hopper.json +2 -2
  113. package/dist/capabilities/hostinger-router.json +12 -12
  114. package/dist/capabilities/hpc-ai.json +13 -13
  115. package/dist/capabilities/huawei-maas.json +17 -17
  116. package/dist/capabilities/hubris.json +30 -30
  117. package/dist/capabilities/huggingface.json +193 -37
  118. package/dist/capabilities/hyper.json +23 -23
  119. package/dist/capabilities/impossibl.json +140 -140
  120. package/dist/capabilities/inception.json +2 -2
  121. package/dist/capabilities/inceptron.json +4 -4
  122. package/dist/capabilities/inco.json +3 -3
  123. package/dist/capabilities/infer.json +15 -15
  124. package/dist/capabilities/inferall.json +10 -10
  125. package/dist/capabilities/inference-coop.json +9 -9
  126. package/dist/capabilities/inferenceapis.json +9 -9
  127. package/dist/capabilities/inferris.json +3 -3
  128. package/dist/capabilities/infersia.json +2 -2
  129. package/dist/capabilities/inferx.json +3 -3
  130. package/dist/capabilities/infomaniak.json +4 -4
  131. package/dist/capabilities/io-net.json +2 -2
  132. package/dist/capabilities/isoquant.json +4 -4
  133. package/dist/capabilities/iteracompute.json +60 -60
  134. package/dist/capabilities/jad-ai.json +3 -3
  135. package/dist/capabilities/jalapeno.json +12 -12
  136. package/dist/capabilities/jiekou.json +63 -63
  137. package/dist/capabilities/jzstoken.json +50 -50
  138. package/dist/capabilities/keln.json +14 -21
  139. package/dist/capabilities/kenari.json +123 -120
  140. package/dist/capabilities/kilo.json +622 -647
  141. package/dist/capabilities/kimi-code-plan-cn.json +5 -5
  142. package/dist/capabilities/kimi-code-plan-global.json +5 -5
  143. package/dist/capabilities/kitani.json +6 -6
  144. package/dist/capabilities/klavo.json +18 -18
  145. package/dist/capabilities/korouter.json +29 -29
  146. package/dist/capabilities/kunavo.json +10 -10
  147. package/dist/capabilities/liquid.json +11 -11
  148. package/dist/capabilities/lithosai.json +2 -2
  149. package/dist/capabilities/llmgateway-providers.json +932 -905
  150. package/dist/capabilities/llmgateway.json +336 -336
  151. package/dist/capabilities/llmtr.json +22 -22
  152. package/dist/capabilities/logits.json +2 -2
  153. package/dist/capabilities/longcat.json +2 -7
  154. package/dist/capabilities/lowrouter.json +54 -54
  155. package/dist/capabilities/lyceum.json +12 -12
  156. package/dist/capabilities/melious.json +13 -13
  157. package/dist/capabilities/merge-gateway.json +260 -260
  158. package/dist/capabilities/meta.json +7 -7
  159. package/dist/capabilities/mistral.json +20 -20
  160. package/dist/capabilities/mixlayer.json +4 -4
  161. package/dist/capabilities/modal.json +10 -10
  162. package/dist/capabilities/model-oracle-ai.json +25 -25
  163. package/dist/capabilities/modelis.json +20 -20
  164. package/dist/capabilities/modular.json +6 -6
  165. package/dist/capabilities/moneo.json +16 -16
  166. package/dist/capabilities/moonshotai-cn.json +7 -7
  167. package/dist/capabilities/moonshotai.json +7 -7
  168. package/dist/capabilities/morph.json +11 -11
  169. package/dist/capabilities/munito-eu.json +6 -6
  170. package/dist/capabilities/munito.json +6 -6
  171. package/dist/capabilities/nan.json +27 -27
  172. package/dist/capabilities/nano-gpt.json +578 -578
  173. package/dist/capabilities/nearai.json +84 -84
  174. package/dist/capabilities/nebius.json +37 -28
  175. package/dist/capabilities/neon.json +126 -126
  176. package/dist/capabilities/neuralwatt.json +41 -41
  177. package/dist/capabilities/nokeep.json +4 -4
  178. package/dist/capabilities/novita-ai.json +154 -154
  179. package/dist/capabilities/nvidia.json +35 -35
  180. package/dist/capabilities/oathbreaker.json +2 -2
  181. package/dist/capabilities/obscurify.json +32 -32
  182. package/dist/capabilities/oci.json +7 -7
  183. package/dist/capabilities/ofox.json +357 -357
  184. package/dist/capabilities/ollama-cloud.json +56 -56
  185. package/dist/capabilities/openai.json +51 -51
  186. package/dist/capabilities/opencode-go.json +85 -84
  187. package/dist/capabilities/openrouter.json +542 -567
  188. package/dist/capabilities/opper.json +30 -24
  189. package/dist/capabilities/orcarouter.json +236 -236
  190. package/dist/capabilities/outerlabs.json +32 -32
  191. package/dist/capabilities/ovhcloud.json +7 -7
  192. package/dist/capabilities/pareto.json +6 -6
  193. package/dist/capabilities/pendra.json +4 -4
  194. package/dist/capabilities/perplexity-agent.json +61 -61
  195. package/dist/capabilities/phala.json +34 -34
  196. package/dist/capabilities/pioneer.json +30 -30
  197. package/dist/capabilities/poe.json +136 -136
  198. package/dist/capabilities/powerspring.json +13 -13
  199. package/dist/capabilities/primalabs.json +10 -10
  200. package/dist/capabilities/prime.json +124 -107
  201. package/dist/capabilities/privatemode-ai.json +14 -14
  202. package/dist/capabilities/proxystacks.json +6 -6
  203. package/dist/capabilities/qiniu-ai.json +16 -16
  204. package/dist/capabilities/refuseless.json +6 -6
  205. package/dist/capabilities/regolo-ai.json +6 -6
  206. package/dist/capabilities/requesty.json +172 -172
  207. package/dist/capabilities/ruapi.json +17 -17
  208. package/dist/capabilities/runcrate.json +5 -5
  209. package/dist/capabilities/runinfra.json +13 -13
  210. package/dist/capabilities/sakana.json +6 -6
  211. package/dist/capabilities/sambanova.json +9 -9
  212. package/dist/capabilities/sandbase.json +27 -27
  213. package/dist/capabilities/sarvam.json +12 -12
  214. package/dist/capabilities/scaleway.json +14 -14
  215. package/dist/capabilities/scnet-token-plan.json +9 -9
  216. package/dist/capabilities/scx-ai.json +26 -26
  217. package/dist/capabilities/sensenova.json +12 -12
  218. package/dist/capabilities/siliconflow-cn.json +49 -49
  219. package/dist/capabilities/siliconflow.json +46 -46
  220. package/dist/capabilities/snowflake-cortex.json +20 -20
  221. package/dist/capabilities/sokkan.json +7 -7
  222. package/dist/capabilities/sparrowcodes.json +25 -25
  223. package/dist/capabilities/standardcompute.json +102 -102
  224. package/dist/capabilities/steadyrouter.json +40 -40
  225. package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
  226. package/dist/capabilities/stepfun-ai.json +15 -8
  227. package/dist/capabilities/stepfun-step-plan.json +15 -8
  228. package/dist/capabilities/stepfun.json +15 -8
  229. package/dist/capabilities/stepping-stone.json +16 -16
  230. package/dist/capabilities/synthetic.json +13 -13
  231. package/dist/capabilities/synthorai.json +19 -19
  232. package/dist/capabilities/teamorouter.json +24 -24
  233. package/dist/capabilities/teapot-router.json +13 -13
  234. package/dist/capabilities/tencent-coding-plan.json +1 -23
  235. package/dist/capabilities/tencent-token-plan.json +60 -23
  236. package/dist/capabilities/tencent-tokenhub.json +182 -7
  237. package/dist/capabilities/tensorx.json +50 -50
  238. package/dist/capabilities/tenstorrent.json +6 -6
  239. package/dist/capabilities/the-grid-ai.json +28 -28
  240. package/dist/capabilities/thinkingmachines.json +72 -55
  241. package/dist/capabilities/tinfoil.json +13 -13
  242. package/dist/capabilities/toapis.json +2 -2
  243. package/dist/capabilities/togetherai.json +54 -83
  244. package/dist/capabilities/tokengo.json +25 -25
  245. package/dist/capabilities/tokenify.json +9 -9
  246. package/dist/capabilities/trustedrouter.json +4 -4
  247. package/dist/capabilities/trustedtokens.json +17 -17
  248. package/dist/capabilities/umans-ai-coding-plan.json +13 -13
  249. package/dist/capabilities/umans-ai.json +10 -10
  250. package/dist/capabilities/unrestricted.json +6 -6
  251. package/dist/capabilities/uplinkswitch.json +21 -21
  252. package/dist/capabilities/upstage.json +4 -4
  253. package/dist/capabilities/vancine.json +23 -23
  254. package/dist/capabilities/vercel.json +540 -527
  255. package/dist/capabilities/vivgrid.json +80 -80
  256. package/dist/capabilities/volcengine-coding-plan.json +24 -54
  257. package/dist/capabilities/volcengine.json +55 -60
  258. package/dist/capabilities/vultr.json +24 -24
  259. package/dist/capabilities/wafer.ai.json +19 -19
  260. package/dist/capabilities/wallaby.json +5 -5
  261. package/dist/capabilities/wally.json +11 -11
  262. package/dist/capabilities/wandb.json +21 -21
  263. package/dist/capabilities/watt.json +24 -24
  264. package/dist/capabilities/xai.json +7 -7
  265. package/dist/capabilities/xiaomi-token-plan-ams.json +2 -12
  266. package/dist/capabilities/xiaomi-token-plan-cn.json +2 -12
  267. package/dist/capabilities/xiaomi-token-plan-sgp.json +2 -12
  268. package/dist/capabilities/xiaomi.json +3 -25
  269. package/dist/capabilities/xpersona.json +13 -13
  270. package/dist/capabilities/xxapi.json +31 -31
  271. package/dist/capabilities/zai-coding-plan.json +18 -18
  272. package/dist/capabilities/zai.json +49 -26
  273. package/dist/capabilities/zenifra.json +26 -26
  274. package/dist/capabilities/zenmux.json +205 -205
  275. package/dist/capabilities/zerogpu.json +11 -11
  276. package/dist/capabilities/zhipuai-coding-plan.json +6 -6
  277. package/dist/capabilities/zhipuai.json +39 -24
  278. package/dist/capabilities/zro.json +6 -6
  279. package/dist/channels/index.cjs +2 -2
  280. package/dist/channels/index.js +2 -2
  281. package/dist/{channels-Dx4jiXeK.js → channels-Cz1y3W6u.js} +1 -1
  282. package/dist/{channels-q6qnuRNV.cjs → channels-DQg4v_gm.cjs} +1 -1
  283. package/dist/coding-agent/index.cjs +2 -2
  284. package/dist/coding-agent/index.js +2 -2
  285. package/dist/datasets/dataset.d.ts +13 -6
  286. package/dist/datasets/experiment/durable.d.ts +16 -0
  287. package/dist/datasets/experiment/index.d.ts +2 -1
  288. package/dist/datasets/experiment/item.d.ts +26 -4
  289. package/dist/datasets/experiment/retries.d.ts +18 -0
  290. package/dist/datasets/experiment/types.d.ts +18 -0
  291. package/dist/datasets/experiment/workflow-id.d.ts +7 -0
  292. package/dist/datasets/experiment/workflow.d.ts +74 -0
  293. package/dist/datasets/index.cjs +3 -2
  294. package/dist/datasets/index.d.ts +2 -1
  295. package/dist/datasets/index.js +3 -3
  296. package/dist/docs/SKILL.md +4 -3
  297. package/dist/docs/assets/SOURCE_MAP.json +928 -903
  298. package/dist/docs/references/docs-deployment-workers.md +1 -1
  299. package/dist/docs/references/docs-evals-experiments.md +29 -1
  300. package/dist/docs/references/docs-harness-background-tasks.md +4 -1
  301. package/dist/docs/references/docs-harness-durable-agents.md +9 -5
  302. package/dist/docs/references/docs-knowledge-agents-and-tools.md +1 -0
  303. package/dist/docs/references/docs-knowledge-importers.md +195 -0
  304. package/dist/docs/references/docs-knowledge-load-your-content.md +2 -2
  305. package/dist/docs/references/docs-knowledge-overview.md +1 -1
  306. package/dist/docs/references/docs-mastra-platform-observability-overview.md +1 -1
  307. package/dist/docs/references/docs-sandbox-filesystem.md +1 -1
  308. package/dist/docs/references/docs-server-pubsub.md +51 -8
  309. package/dist/docs/references/docs-signals-running-across-processes.md +2 -0
  310. package/dist/docs/references/docs-signals-thread-streams.md +1 -1
  311. package/dist/docs/references/docs-studio-auth.md +54 -7
  312. package/dist/docs/references/docs-workflows-overview.md +1 -1
  313. package/dist/docs/references/docs-workflows-scheduled-workflows.md +1 -1
  314. package/dist/docs/references/integrations-auth-clerk.md +48 -4
  315. package/dist/docs/references/integrations-channels-slack.md +4 -2
  316. package/dist/docs/references/integrations.md +6 -0
  317. package/dist/docs/references/reference-agents-agent.md +3 -1
  318. package/dist/docs/references/reference-agents-channels.md +116 -27
  319. package/dist/docs/references/reference-agents-durable-agent.md +12 -4
  320. package/dist/docs/references/reference-auth-clerk.md +21 -1
  321. package/dist/docs/references/reference-datasets-runExperimentItem.md +13 -1
  322. package/dist/docs/references/reference-datasets-startExperimentAsync.md +3 -1
  323. package/dist/docs/references/reference-editor-mastra-editor.md +3 -1
  324. package/dist/docs/references/reference-knowledge-knowledge-class.md +13 -6
  325. package/dist/docs/references/reference-knowledge-knowledge-tools.md +43 -20
  326. package/dist/docs/references/reference-memory-observational-memory.md +2 -2
  327. package/dist/docs/references/reference-processors-moderation-processor.md +2 -2
  328. package/dist/docs/references/reference-pubsub-base.md +5 -1
  329. package/dist/docs/references/reference-pubsub-event-emitter.md +2 -0
  330. package/dist/docs/references/reference-pubsub-redis-streams.md +1 -1
  331. package/dist/docs/references/reference-pubsub-unix-socket-pubsub.md +2 -0
  332. package/dist/docs/references/reference-streaming-ChunkType.md +3 -3
  333. package/dist/docs/references/reference-workers-overview.md +1 -1
  334. package/dist/docs/references/reference-workflows-run-methods-start.md +23 -0
  335. package/dist/docs/references/reference-workflows-run-methods-timeTravel.md +4 -0
  336. package/dist/docs/references/reference-workflows-run.md +1 -1
  337. package/dist/docs/references/reference-workspace-local-sandbox.md +2 -0
  338. package/dist/error/index.cjs +1 -1
  339. package/dist/error/index.js +1 -1
  340. package/dist/{error-C9d_24w-.js → error-BLwEXqOK.js} +2 -2
  341. package/dist/{error-BRQf2ku0.cjs → error-BdEvO8za.cjs} +2 -2
  342. package/dist/evals/index.cjs +1 -1
  343. package/dist/evals/index.js +1 -1
  344. package/dist/evals/scoreTraces/index.cjs +1 -1
  345. package/dist/evals/scoreTraces/index.js +1 -1
  346. package/dist/events/caching-pubsub.d.ts +1 -0
  347. package/dist/events/event-emitter/index.d.ts +12 -5
  348. package/dist/events/index.cjs +15 -1
  349. package/dist/events/index.js +15 -1
  350. package/dist/events/pubsub.d.ts +29 -0
  351. package/dist/events/reach.d.ts +11 -0
  352. package/dist/events/unix-socket-pubsub.d.ts +14 -0
  353. package/dist/features/index.cjs +1 -0
  354. package/dist/features/index.js +1 -0
  355. package/dist/{filesystem-B5X-5G0x.js → filesystem-B8ad6kAW.js} +1 -1
  356. package/dist/{filesystem-BDSpwBke.cjs → filesystem-BB5YWXH-.cjs} +1 -1
  357. package/dist/{filesystem-DzM9pcQ8.js → filesystem-BDHUxbHn.js} +1 -1
  358. package/dist/{filesystem-B0AZrbj8.cjs → filesystem-BP5yz5LG.cjs} +1 -1
  359. package/dist/{filesystem-BsdkC311.js → filesystem-B_afSgYk.js} +1 -1
  360. package/dist/{filesystem-C-cyJfi1.cjs → filesystem-BaOJOc-V.cjs} +1 -1
  361. package/dist/{filesystem-B3s0WRud.js → filesystem-BhYgU8qg.js} +1 -1
  362. package/dist/{filesystem-DzfqVTO_.js → filesystem-CLBVmR5j.js} +1 -1
  363. package/dist/{filesystem-CEbD_77-.cjs → filesystem-Cgxc2a_-.cjs} +1 -1
  364. package/dist/{filesystem-Cv79mHRk.js → filesystem-ClBOBoDc.js} +1 -1
  365. package/dist/{filesystem-DsCQiBl2.cjs → filesystem-DVVecqZt.cjs} +1 -1
  366. package/dist/{filesystem-CUAgLugE.cjs → filesystem-Fpsu7e24.cjs} +1 -1
  367. package/dist/{filesystem-versioned-Bijb_p9l.js → filesystem-versioned-BL1ojJLo.js} +1 -1
  368. package/dist/{filesystem-versioned-DZGyPbNC.cjs → filesystem-versioned-BavRtYWJ.cjs} +1 -1
  369. package/dist/harness/index.cjs +1 -1
  370. package/dist/harness/index.js +1 -1
  371. package/dist/index.cjs +1 -1
  372. package/dist/index.js +1 -1
  373. package/dist/knowledge/config.d.ts +10 -0
  374. package/dist/knowledge/host-writes.d.ts +10 -0
  375. package/dist/knowledge/importers/conformance.d.ts +25 -0
  376. package/dist/knowledge/importers/define.d.ts +204 -0
  377. package/dist/knowledge/importers/host.d.ts +143 -0
  378. package/dist/knowledge/importers/index.d.ts +12 -0
  379. package/dist/knowledge/importers/local-host.d.ts +106 -0
  380. package/dist/knowledge/importers/manifest.d.ts +25 -0
  381. package/dist/knowledge/importers/runner.d.ts +61 -0
  382. package/dist/knowledge/importers/sink.d.ts +105 -0
  383. package/dist/knowledge/importers/types.d.ts +144 -0
  384. package/dist/knowledge/index.cjs +2715 -8
  385. package/dist/knowledge/index.d.ts +54 -4
  386. package/dist/knowledge/index.js +2692 -9
  387. package/dist/knowledge/instructions.d.ts +1 -1
  388. package/dist/knowledge/links.d.ts +8 -0
  389. package/dist/knowledge/pinned-state-processor.d.ts +5 -0
  390. package/dist/knowledge/pinned.d.ts +4 -1
  391. package/dist/knowledge/scope-runtime.d.ts +10 -0
  392. package/dist/llm/index.cjs +3 -3
  393. package/dist/llm/index.js +3 -3
  394. package/dist/llm/model/provider-types.generated.d.ts +7812 -7831
  395. package/dist/llm/model/shared.types.d.ts +31 -0
  396. package/dist/{llm-CsQuqKPc.cjs → llm-8Av3mSjD.cjs} +2 -2
  397. package/dist/{llm-DnXK3Pmw.js → llm-B5A5cwJr.js} +2 -2
  398. package/dist/loop/index.cjs +2 -2
  399. package/dist/loop/index.js +2 -2
  400. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +2 -2
  401. package/dist/{manager-BsghM-UL.js → manager-DfWQCJUK.js} +460 -94
  402. package/dist/{manager-DwFnIrI6.cjs → manager-sv35JY-z.cjs} +476 -92
  403. package/dist/mastra/index.cjs +1 -1
  404. package/dist/mastra/index.d.ts +13 -0
  405. package/dist/mastra/index.js +1 -1
  406. package/dist/mastra/resolve-agent.d.ts +3 -1
  407. package/dist/{mastra-B8i1UDZs.js → mastra-CigBrT7X.js} +32 -23
  408. package/dist/{mastra-Cn5NC6Es.cjs → mastra-D4hvfuxX.cjs} +34 -25
  409. package/dist/memory/index.cjs +3 -3
  410. package/dist/memory/index.js +3 -3
  411. package/dist/{message-list-DPXPXvin.cjs → message-list-Cj0Sq_JP.cjs} +63 -8
  412. package/dist/{message-list-DEuRl82K.js → message-list-KRbg-TnI.js} +63 -8
  413. package/dist/{model-CNPfry_X.cjs → model-BK93CMtl.cjs} +1 -1
  414. package/dist/{model-CsOcWMUt.js → model-CYtXw861.js} +1 -1
  415. package/dist/{netlify-C-83Fxus.cjs → netlify-BAnn3ouY.cjs} +1 -1
  416. package/dist/{netlify-C-OpNSGp.js → netlify-CuI1ZrwR.js} +1 -1
  417. package/dist/notifications/index.cjs +1 -1
  418. package/dist/notifications/index.js +1 -1
  419. package/dist/{output-helpers-JL-HeCbT.cjs → output-helpers-1Zu4Vt9C.cjs} +68 -25
  420. package/dist/{output-helpers-D4II19No.js → output-helpers-CedRCE17.js} +69 -26
  421. package/dist/processor-provider/index.cjs +1 -1
  422. package/dist/processor-provider/index.js +1 -1
  423. package/dist/processors/abort-signal-scope.d.ts +6 -0
  424. package/dist/processors/index.cjs +2 -2
  425. package/dist/processors/index.js +2 -2
  426. package/dist/{provider-registry-9O-H9osy.cjs → provider-registry-BwuI_IpT.cjs} +21690 -21811
  427. package/dist/{provider-registry-RZ8EgSe8.js → provider-registry-CmQLzLF_.js} +21690 -21811
  428. package/dist/provider-registry.json +22113 -22215
  429. package/dist/{registry-generator-e8sltJls.js → registry-generator-C17V4WfG.js} +1 -1
  430. package/dist/{registry-generator-DxCX-FiO.cjs → registry-generator-C_0ae7Ce.cjs} +1 -1
  431. package/dist/{rehydrate-B-wrAN7C.cjs → rehydrate-CDQ4dOYj.cjs} +2 -2
  432. package/dist/{rehydrate-D3fPgJwp.js → rehydrate-PnaVawGX.js} +2 -2
  433. package/dist/relevance/index.cjs +2 -2
  434. package/dist/relevance/index.js +2 -2
  435. package/dist/{run-registry-5_LQBGn_.cjs → run-registry-BmckDVBk.cjs} +1698 -497
  436. package/dist/{run-registry-DC03XLeZ.js → run-registry-BwEcwYlU.js} +1614 -467
  437. package/dist/{source-DDwx-87N.cjs → source-BVOi8Xhp.cjs} +1 -1
  438. package/dist/{source-Did_2XQc.js → source-fNa6u1kH.js} +1 -1
  439. package/dist/storage/domains/agents/index.cjs +1 -1
  440. package/dist/storage/domains/agents/index.js +1 -1
  441. package/dist/storage/domains/knowledge/base.d.ts +72 -0
  442. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +146 -0
  443. package/dist/storage/domains/knowledge/importers.d.ts +287 -0
  444. package/dist/storage/domains/knowledge/index.d.ts +1 -0
  445. package/dist/storage/domains/knowledge/inmemory.d.ts +12 -0
  446. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +12 -1
  447. package/dist/storage/domains/knowledge/pages.d.ts +25 -7
  448. package/dist/storage/domains/mcp-clients/index.cjs +1 -1
  449. package/dist/storage/domains/mcp-clients/index.js +1 -1
  450. package/dist/storage/domains/mcp-servers/index.cjs +1 -1
  451. package/dist/storage/domains/mcp-servers/index.js +1 -1
  452. package/dist/storage/domains/prompt-blocks/index.cjs +1 -1
  453. package/dist/storage/domains/prompt-blocks/index.js +1 -1
  454. package/dist/storage/domains/scorer-definitions/index.cjs +1 -1
  455. package/dist/storage/domains/scorer-definitions/index.js +1 -1
  456. package/dist/storage/domains/skills/index.cjs +1 -1
  457. package/dist/storage/domains/skills/index.js +1 -1
  458. package/dist/storage/domains/workspaces/index.cjs +1 -1
  459. package/dist/storage/domains/workspaces/index.js +1 -1
  460. package/dist/storage/index.cjs +15 -10
  461. package/dist/storage/index.js +11 -11
  462. package/dist/stream/base/output.d.ts +59 -15
  463. package/dist/stream/index.cjs +2 -2
  464. package/dist/stream/index.js +2 -2
  465. package/dist/stream/types.d.ts +24 -2
  466. package/dist/{stream-4aNIw_TQ.cjs → stream-0kdqBOOn.cjs} +64 -9
  467. package/dist/{stream-CJUm6EAH.js → stream-D1y9GzoD.js} +29 -10
  468. package/dist/test-utils/llm-mock.cjs +1 -1
  469. package/dist/test-utils/llm-mock.js +1 -1
  470. package/dist/tool-loop-agent/index.cjs +1 -1
  471. package/dist/tool-loop-agent/index.js +1 -1
  472. package/dist/{tool-loop-agent-FEEwHfmg.js → tool-loop-agent-BdjWGVIb.js} +4 -4
  473. package/dist/{tool-loop-agent-Dn0QCB9n.cjs → tool-loop-agent-kWaZAT6Q.cjs} +4 -4
  474. package/dist/tools/types.d.ts +27 -1
  475. package/dist/{utils-DY01hxVd.cjs → utils-BKUCaZ12.cjs} +1 -1
  476. package/dist/{utils-Bd_y1_a-.js → utils-GHY3hmLx.js} +1 -1
  477. package/dist/utils.cjs +1 -1
  478. package/dist/utils.js +1 -1
  479. package/dist/{validate-CX0yQo_q.js → validate-CB-q-R2F.js} +1 -1
  480. package/dist/{validate-CuB_1Zd3.cjs → validate-De92squ7.cjs} +1 -1
  481. package/dist/vector/index.cjs +2 -2
  482. package/dist/vector/index.js +2 -2
  483. package/dist/worker/index.cjs +1 -1
  484. package/dist/worker/index.js +1 -1
  485. package/dist/{worker-CbaSmip-.cjs → worker-BbWPQuPR.cjs} +2 -2
  486. package/dist/{worker-B80xkcKG.js → worker-C3u_xzY2.js} +2 -2
  487. package/dist/{worker-GsGIxPMa.cjs → worker-CAKvQj9_.cjs} +2 -2
  488. package/dist/{worker-DSEfMPmq.js → worker-Kwm8EKcj.js} +2 -2
  489. package/dist/{workflow-CnBPXTpv.cjs → workflow-CSjXeNcR.cjs} +4 -4
  490. package/dist/{workflow-CZHY_C85.js → workflow-CVmI1Sw-.js} +4 -4
  491. package/dist/workflows/builder/index.cjs +1 -1
  492. package/dist/workflows/builder/index.js +1 -1
  493. package/dist/workflows/evented/index.cjs +1 -1
  494. package/dist/workflows/evented/index.js +1 -1
  495. package/dist/workflows/evented/setup-warning.d.ts +18 -0
  496. package/dist/workflows/evented/workflow-event-processor/run-status.d.ts +37 -0
  497. package/dist/workflows/evented/workflow.d.ts +10 -0
  498. package/dist/workflows/index.cjs +4 -4
  499. package/dist/workflows/index.js +4 -4
  500. package/dist/workflows/workflow.d.ts +6 -1
  501. package/dist/workspace/filesystem/filesystem.d.ts +5 -0
  502. package/dist/workspace/index.cjs +1 -1
  503. package/dist/workspace/index.js +1 -1
  504. package/dist/workspace/sandbox/local-sandbox.d.ts +16 -7
  505. package/dist/workspace/sandbox/native-sandbox/types.d.ts +11 -1
  506. package/dist/{workspace-D7TIleIt.js → workspace-DY2Nxiyi.js} +235 -34
  507. package/dist/{workspace-D2drutNg.cjs → workspace-X2RHJZU9.cjs} +235 -34
  508. package/package.json +7 -7
  509. package/src/llm/model/provider-types.generated.d.ts +7812 -7831
@@ -1,5 +1,7 @@
1
1
  import { t as MastraBase } from "../base-CKLWBhDo.js";
2
- import { $n as assertKnowledgeCeilingRaised, $r as KnowledgeMoveTooLargeError, $t as knowledgeDeliveredPins, Ai as inspectKnowledgeSchema, Ci as KnowledgeConflictError, Cn as decodeKnowledgeScopeId, Di as KnowledgeUnsupportedCapabilityError, Ei as KnowledgeStorage, Oi as assertKnowledgeSchemaCompatible, Oo as augmentWithInit, Qn as MAX_KNOWLEDGE_SCOPE_TAGS, Qr as InMemoryKnowledgeStorage, Qt as PINNED_READ_MEMO_KEY, Si as KNOWLEDGE_STORAGE_SCHEMA_VERSION, Sn as strongerKnowledgeRole, Ti as KnowledgeSchemaResetRequiredError, Tn as buildKnowledgeInstructions, Xn as MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, Zn as MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, _i as knowledgePinDepth, _n as KnowledgeDeclarationError, ai as MAX_KNOWLEDGE_PAGE_BODY_LINKS, an as removeKnowledgeNote, ar as expandKnowledgeScope, bi as parseKnowledgePageRef, bn as knowledgeRunScopes, ci as MAX_KNOWLEDGE_PAGE_LINKS, cn as upsertKnowledgePage, cr as knowledgeSemanticDocumentId, di as MAX_KNOWLEDGE_PIN_LIST_DEPTH, dn as refreshKnowledgeLinksTo, dr as parseKnowledgeNodeCursor, ei as KnowledgePageDepthError, en as buildKnowledgePageTools, er as assertKnowledgeDescriptionWithinBound, fi as assertKnowledgeNoteTextWithinBound, fn as reindexKnowledgeLinks, gi as knowledgePagePath, gn as knowledgeRoleOn, hi as knowledgeLinkRefKey, hn as knowledgeReadScopeFor, ii as MAX_KNOWLEDGE_NOTE_TOKENS, in as moveKnowledgePage, ir as createKnowledgeNodeCursor, ji as parseKnowledgeWikilinks, ki as createKnowledgeUlid, ko as getStorageSource, li as MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, ln as KnowledgeSemanticIndex, lr as knowledgeSemanticIdempotencyKey, mi as canonicalKnowledgeName, mn as knowledgeAccessGrants, ni as KnowledgePageKeyConflictError, nn as knowledgeRunPrincipals, nr as assertKnowledgeScopeWithinCeiling, oi as MAX_KNOWLEDGE_PAGE_DEPTH, on as removeKnowledgePage, or as isKnowledgeScopeVisible, pi as assertKnowledgePageDescriptionWithinBound, pn as updateKnowledgeLinks, ri as MAX_KNOWLEDGE_MOVE_PAGES, rn as addKnowledgeNote, rr as canonicalizeKnowledgeScope, si as MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, sn as updateKnowledgeNote, sr as knowledgeScopeKey, ti as KnowledgePageHasChildrenError, tn as KnowledgeRun, tr as assertKnowledgeRecordTextWithinBound, ui as MAX_KNOWLEDGE_PAGE_LIST_LIMIT, ur as knowledgeVisibleScopeKeys, vi as knowledgePositionBetween, vn as compileKnowledgeScopes, wi as KnowledgeNotFoundError, wn as encodeKnowledgeScopeId, xi as KNOWLEDGE_STORAGE_CONTRACT_VERSION, xn as knowledgeScopeAddress, yi as knowledgeScopeReadable, yn as knowledgeMemoryScopes } from "../run-registry-DC03XLeZ.js";
2
+ import { $n as MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, $t as knowledgeDeliveredPins, Ai as assertKnowledgeNoteTextWithinBound, Ci as MAX_KNOWLEDGE_PAGE_BODY_LINKS, Cn as knowledgeRunScopes, Di as MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, Dn as encodeKnowledgeScopeId, Ei as MAX_KNOWLEDGE_PAGE_LINKS, En as decodeKnowledgeScopeId, Fi as knowledgePinDepth, Ii as knowledgePositionBetween, Io as augmentWithInit, Li as knowledgeScopeReadable, Lo as getStorageSource, Mi as canonicalKnowledgeName, Ni as knowledgeLinkRefKey, Oi as MAX_KNOWLEDGE_PAGE_LIST_LIMIT, On as buildKnowledgeInstructions, Pi as knowledgePagePath, Qt as PINNED_READ_MEMO_KEY, Ri as parseKnowledgePageRef, Si as MAX_KNOWLEDGE_NOTE_TOKENS, Sn as knowledgeMemoryScopes, Ti as MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, Tn as strongerKnowledgeRole, _i as KnowledgeMoveTooLargeError, _n as knowledgeAccessGrants, ai as KNOWLEDGE_STORAGE_CONTRACT_VERSION, an as removeKnowledgeNote, ar as assertKnowledgeScopeWithinCeiling, bi as KnowledgePageKeyConflictError, bn as KnowledgeDeclarationError, ci as KnowledgeNotFoundError, cn as upsertKnowledgePage, cr as expandKnowledgeScope, di as KnowledgeTransactionDeadlineError, dn as KnowledgeLinkRefreshIncompleteError, dr as knowledgeSemanticDocumentId, en as buildKnowledgePageTools, er as MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, fi as KnowledgeUnsupportedCapabilityError, fn as knowledgeSubtree, fr as knowledgeSemanticIdempotencyKey, gi as parseKnowledgeWikilinks, gn as updateKnowledgeLinks, hi as inspectKnowledgeSchema, hn as syncKnowledgePageBodyLinks, ii as KnowledgeImportersStorage, in as moveKnowledgePage, ir as assertKnowledgeRecordTextWithinBound, ji as assertKnowledgePageDescriptionWithinBound, ki as MAX_KNOWLEDGE_PIN_LIST_DEPTH, li as KnowledgeSchemaResetRequiredError, ln as KnowledgeSemanticIndex, lr as isKnowledgeScopeVisible, mi as createKnowledgeUlid, mn as reindexKnowledgeLinks, mr as parseKnowledgeNodeCursor, ni as KnowledgeImporterBindingConflictError, nn as knowledgeRunPrincipals, nr as assertKnowledgeCeilingRaised, oi as KNOWLEDGE_STORAGE_SCHEMA_VERSION, on as removeKnowledgePage, or as canonicalizeKnowledgeScope, pi as assertKnowledgeSchemaCompatible, pn as refreshKnowledgeLinksTo, pr as knowledgeVisibleScopeKeys, ri as KnowledgeImporterRunStateError, rn as addKnowledgeNote, rr as assertKnowledgeDescriptionWithinBound, si as KnowledgeConflictError, sn as updateKnowledgeNote, sr as createKnowledgeNodeCursor, ti as InMemoryKnowledgeStorage, tn as KnowledgeRun, tr as MAX_KNOWLEDGE_SCOPE_TAGS, ui as KnowledgeStorage, ur as knowledgeScopeKey, vi as KnowledgePageDepthError, vn as knowledgeReadScopeFor, wi as MAX_KNOWLEDGE_PAGE_DEPTH, wn as knowledgeScopeAddress, xi as MAX_KNOWLEDGE_MOVE_PAGES, xn as compileKnowledgeScopes, yi as KnowledgePageHasChildrenError, yn as knowledgeRoleOn, zi as KnowledgeInvalidCursorError } from "../run-registry-BwEcwYlU.js";
3
+ import { standardSchemaToJSONSchema, toStandardSchema } from "../schema/index.js";
4
+ import { i as createStandardSchemaIssuesError } from "../tool-Z3bykc1m.js";
3
5
  import { randomUUID } from "crypto";
4
6
  // src/knowledge/changes.ts
5
7
  const page = (op) => (result) => {
@@ -110,6 +112,2595 @@ function emitKnowledgeChanges(storage, emit, listening, onError) {
110
112
  };
111
113
  } });
112
114
  }
115
+ // src/knowledge/importers/host.ts
116
+ /** A host refused a flush or a finish (409 over HTTP). Retrying the same request won't help. @experimental */
117
+ var KnowledgeImporterHostConflictError = class extends Error {
118
+ code;
119
+ status = 409;
120
+ constructor(code, message) {
121
+ super(message);
122
+ this.code = code;
123
+ this.name = "KnowledgeImporterHostConflictError";
124
+ }
125
+ };
126
+ const KNOWLEDGE_IMPORTER_ERROR_CODES = [
127
+ "source_auth_failed",
128
+ "source_unreachable",
129
+ "source_rate_limited",
130
+ "source_bad_response",
131
+ "source_not_found",
132
+ "settings_invalid",
133
+ "credential_missing",
134
+ "importer_missing_from_deploy",
135
+ "importer_error",
136
+ "stopped",
137
+ "lease_expired",
138
+ "deadline_exceeded"
139
+ ];
140
+ /**
141
+ * The finish request as a host stores and compares it: missing optional fields become null.
142
+ * Throws a TypeError for a request no host should accept.
143
+ */
144
+ function normalizeKnowledgeImporterFinish(request) {
145
+ const { outcome, backlog, lastSeq, error } = request;
146
+ if (outcome !== "succeeded" && outcome !== "failed" && outcome !== "canceled") throw new TypeError(`Unknown importer run outcome "${String(outcome)}".`);
147
+ if (typeof backlog !== "boolean") throw new TypeError("Importer finish needs backlog: true or false.");
148
+ if (backlog && outcome !== "succeeded") throw new TypeError("Only a succeeded importer run can report backlog.");
149
+ if (!Number.isSafeInteger(lastSeq) || lastSeq < 0) throw new TypeError("Importer finish needs lastSeq >= 0.");
150
+ const hasError = error !== void 0 && error !== null;
151
+ if (outcome === "failed" !== hasError) throw new TypeError("A failed importer run needs an error code, and only a failed run has one.");
152
+ if (!hasError) return {
153
+ outcome,
154
+ backlog,
155
+ lastSeq,
156
+ error: null
157
+ };
158
+ if (!isPlainObject$1(error)) throw new TypeError("Importer finish error must be an object.");
159
+ const unknownErrorKeys = Object.keys(error).filter((key) => ![
160
+ "code",
161
+ "retryable",
162
+ "httpStatus"
163
+ ].includes(key));
164
+ if (unknownErrorKeys.length) throw new TypeError(`Importer finish error has unknown field "${unknownErrorKeys[0]}".`);
165
+ if (!KNOWLEDGE_IMPORTER_ERROR_CODES.includes(error.code)) throw new TypeError(`Unknown importer error code "${String(error.code)}".`);
166
+ if (error.retryable !== void 0 && typeof error.retryable !== "boolean") throw new TypeError("Importer error retryable must be a boolean.");
167
+ const { httpStatus } = error;
168
+ if (httpStatus !== void 0 && (!Number.isInteger(httpStatus) || httpStatus < 100 || httpStatus > 599)) throw new TypeError("Importer error httpStatus must be an HTTP status code.");
169
+ return {
170
+ outcome,
171
+ backlog,
172
+ lastSeq,
173
+ error: {
174
+ code: error.code,
175
+ retryable: error.retryable ?? null,
176
+ httpStatus: httpStatus ?? null
177
+ }
178
+ };
179
+ }
180
+ /**
181
+ * RFC 8785 (JCS) canonical JSON: object members sorted by UTF-16 code units, no whitespace, numbers
182
+ * and strings as ECMAScript serializes them. Members whose value is undefined are left out, as
183
+ * JSON.stringify leaves them out of what goes over the wire; array holes and undefined items are
184
+ * null, as JSON.stringify writes them. Strings with a lone UTF-16 surrogate are refused (RFC 8785
185
+ * §3.2.2.2).
186
+ */
187
+ function canonicalJson(value) {
188
+ if (value === null) return "null";
189
+ switch (typeof value) {
190
+ case "boolean": return value ? "true" : "false";
191
+ case "number":
192
+ if (!Number.isFinite(value)) throw new TypeError("Canonical JSON has no NaN or Infinity.");
193
+ return JSON.stringify(value);
194
+ case "string": return JSON.stringify(wellFormed(value));
195
+ case "object": {
196
+ if (Array.isArray(value)) {
197
+ const items = [];
198
+ for (let index = 0; index < value.length; index++) {
199
+ const item = value[index];
200
+ items.push(item === void 0 ? "null" : canonicalJson(item));
201
+ }
202
+ return `[${items.join(",")}]`;
203
+ }
204
+ const record = value;
205
+ return `{${Object.keys(record).filter((key) => record[key] !== void 0).sort().map((key) => `${JSON.stringify(wellFormed(key))}:${canonicalJson(record[key])}`).join(",")}}`;
206
+ }
207
+ default: throw new TypeError(`Canonical JSON can't hold a ${typeof value}.`);
208
+ }
209
+ }
210
+ /**
211
+ * A flush's digest: lowercase hex SHA-256 of the canonical JSON of `{ ops, state }`, with an absent
212
+ * `state` as null. Runners send it; hosts recompute it from the body they received. The body is
213
+ * checked with `parseKnowledgeImporterFlushBody` first, so only payloads that survive a JSON round
214
+ * trip unchanged get a digest.
215
+ */
216
+ async function knowledgeImporterFlushDigest(flush) {
217
+ const { ops, state } = parseKnowledgeImporterFlushBody(flush);
218
+ const bytes = new TextEncoder().encode(canonicalJson({
219
+ ops,
220
+ state: state ?? null
221
+ }));
222
+ const hash = await globalThis.crypto.subtle.digest("SHA-256", bytes);
223
+ return Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("");
224
+ }
225
+ function isPlainObject$1(value) {
226
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
227
+ const proto = Object.getPrototypeOf(value);
228
+ return proto === Object.prototype || proto === null;
229
+ }
230
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
231
+ function wellFormed(value) {
232
+ if (LONE_SURROGATE.test(value)) throw new TypeError("Canonical JSON refuses strings with a lone UTF-16 surrogate.");
233
+ return value;
234
+ }
235
+ const DECLARATION_FIELDS = {
236
+ sourceId: {
237
+ kind: "nonEmpty",
238
+ required: true
239
+ },
240
+ kind: { kind: "string" },
241
+ title: {
242
+ kind: "string",
243
+ required: true
244
+ },
245
+ parent: { kind: "nullableString" },
246
+ fallbackParent: { kind: "nonEmpty" }
247
+ };
248
+ const ITEM_FIELDS = {
249
+ ...DECLARATION_FIELDS,
250
+ description: { kind: "string" },
251
+ body: {
252
+ kind: "string",
253
+ required: true
254
+ },
255
+ links: { kind: "links" },
256
+ aliases: { kind: "aliases" }
257
+ };
258
+ function checkString(value, where, nonEmpty = false) {
259
+ if (typeof value !== "string") throw new TypeError(`${where} must be a string.`);
260
+ if (nonEmpty && !value) throw new TypeError(`${where} must not be empty.`);
261
+ return wellFormed(value);
262
+ }
263
+ function checkDenseArray(value, where) {
264
+ if (!Array.isArray(value)) throw new TypeError(`${where} must be an array.`);
265
+ for (let index = 0; index < value.length; index++) if (!(index in value)) throw new TypeError(`${where}[${index}] is empty.`);
266
+ return value;
267
+ }
268
+ function checkFields(value, fields, where) {
269
+ if (!isPlainObject$1(value)) throw new TypeError(`${where} must be an object.`);
270
+ const out = Object.create(null);
271
+ for (const key of Object.keys(value)) if (!Object.hasOwn(fields, key)) throw new TypeError(`${where} has unknown field "${key}".`);
272
+ for (const [key, { kind, required }] of Object.entries(fields)) {
273
+ const field = value[key];
274
+ const at = `${where}.${key}`;
275
+ if (field === void 0) {
276
+ if (required) throw new TypeError(`${at} is required.`);
277
+ continue;
278
+ }
279
+ switch (kind) {
280
+ case "string":
281
+ out[key] = checkString(field, at);
282
+ break;
283
+ case "nonEmpty":
284
+ out[key] = checkString(field, at, true);
285
+ break;
286
+ case "nullableString":
287
+ out[key] = field === null ? null : checkString(field, at, true);
288
+ break;
289
+ case "aliases":
290
+ out[key] = checkDenseArray(field, at).map((alias, index) => checkString(alias, `${at}[${index}]`, true));
291
+ break;
292
+ case "links": out[key] = checkDenseArray(field, at).map((link, index) => checkFields(link, {
293
+ sourceId: {
294
+ kind: "nonEmpty",
295
+ required: true
296
+ },
297
+ rel: { kind: "string" }
298
+ }, `${at}[${index}]`));
299
+ }
300
+ }
301
+ return { ...out };
302
+ }
303
+ /**
304
+ * Checks a flush body the way every host and runner must before hashing or applying it: known ops
305
+ * and fields only, strings where strings belong, no array holes, no lone surrogates, string-only
306
+ * state. Returns a copy with undefined optional fields left out, so what passes hashes the same
307
+ * before and after a JSON round trip. Throws a TypeError otherwise.
308
+ *
309
+ * @experimental
310
+ */
311
+ function parseKnowledgeImporterFlushBody(body) {
312
+ const ops = checkDenseArray(body.ops, "ops").map((op, index) => {
313
+ const where = `ops[${index}]`;
314
+ if (!isPlainObject$1(op)) throw new TypeError(`${where} must be an object.`);
315
+ switch (op.op) {
316
+ case "upsert":
317
+ case "declare": {
318
+ const extra = Object.keys(op).find((key) => key !== "op" && key !== "item");
319
+ if (extra) throw new TypeError(`${where} has unknown field "${extra}".`);
320
+ const fields = op.op === "upsert" ? ITEM_FIELDS : DECLARATION_FIELDS;
321
+ return {
322
+ op: op.op,
323
+ item: checkFields(op.item, fields, `${where}.item`)
324
+ };
325
+ }
326
+ case "remove": {
327
+ const extra = Object.keys(op).find((key) => key !== "op" && key !== "sourceId");
328
+ if (extra) throw new TypeError(`${where} has unknown field "${extra}".`);
329
+ return {
330
+ op: "remove",
331
+ sourceId: checkString(op.sourceId, `${where}.sourceId`, true)
332
+ };
333
+ }
334
+ default: throw new TypeError(`${where}.op must be "upsert", "declare" or "remove".`);
335
+ }
336
+ });
337
+ if (body.state === void 0 || body.state === null) return { ops };
338
+ if (!isPlainObject$1(body.state)) throw new TypeError("state must be an object of strings.");
339
+ return {
340
+ ops,
341
+ state: Object.fromEntries(Object.entries(body.state).map(([key, value]) => [wellFormed(key), checkString(value, `state.${key}`)]))
342
+ };
343
+ }
344
+ // src/knowledge/importers/manifest.ts
345
+ /** The settings schema of an importer with no settings: an empty object. */
346
+ const EMPTY_KNOWLEDGE_IMPORTER_SETTINGS_SCHEMA = {
347
+ type: "object",
348
+ properties: {},
349
+ additionalProperties: false
350
+ };
351
+ /** Every `$ref` in a schema, so a manifest can refuse ones that point outside the schema. */
352
+ function jsonSchemaRefs(schema, refs = []) {
353
+ if (Array.isArray(schema)) for (const item of schema) jsonSchemaRefs(item, refs);
354
+ else if (schema && typeof schema === "object") for (const [key, value] of Object.entries(schema)) if (key === "$ref" && typeof value === "string") refs.push(value);
355
+ else jsonSchemaRefs(value, refs);
356
+ return refs;
357
+ }
358
+ // src/knowledge/importers/define.ts
359
+ /**
360
+ * The base every importer extends through {@link KnowledgeImporter}. An instance is one binding;
361
+ * `import` is called once per pass of a run.
362
+ *
363
+ * @experimental
364
+ */
365
+ var KnowledgeImporterBase = class {
366
+ /** What the instance was constructed with, as the host sees a binding. */
367
+ binding;
368
+ constructor(binding) {
369
+ const definition = new.target.definition;
370
+ if (!definition) throw new KnowledgeImporterDefinitionError("Importer classes extend KnowledgeImporter({ ... }).");
371
+ const input = binding;
372
+ if (typeof input?.id !== "string" || !input.id.trim()) throw new KnowledgeImporterDefinitionError(`A "${definition.id}" importer binding needs an id.`);
373
+ if (typeof input.target !== "string" || !input.target.trim()) throw new KnowledgeImporterDefinitionError(`Importer binding "${input.id}" needs a target ("<scope>#<path>").`);
374
+ this.binding = Object.freeze({
375
+ id: input.id,
376
+ importer: definition.id,
377
+ target: input.target,
378
+ settings: input.settings ?? {},
379
+ credentials: { ...definition.checkCredentials(input.credentials) }
380
+ });
381
+ }
382
+ };
383
+ /** A definition, a registry or a binding's settings or credentials are invalid. @experimental */
384
+ var KnowledgeImporterDefinitionError = class extends Error {
385
+ constructor(message) {
386
+ super(message);
387
+ this.name = "KnowledgeImporterDefinitionError";
388
+ }
389
+ };
390
+ /** A binding's settings don't match the importer's schema (run error code `settings_invalid`). @experimental */
391
+ var KnowledgeImporterSettingsError = class extends KnowledgeImporterDefinitionError {
392
+ errors;
393
+ constructor(message, errors) {
394
+ super(message);
395
+ this.errors = errors;
396
+ this.name = "KnowledgeImporterSettingsError";
397
+ }
398
+ };
399
+ /** A binding is missing a credential or supplies an undeclared one (run error code `credential_missing`). @experimental */
400
+ var KnowledgeImporterCredentialsError = class extends KnowledgeImporterDefinitionError {
401
+ constructor(message) {
402
+ super(message);
403
+ this.name = "KnowledgeImporterCredentialsError";
404
+ }
405
+ };
406
+ /** The source answered with an error status. The runner maps the status to the run's error code. @experimental */
407
+ var KnowledgeImporterSourceError = class extends Error {
408
+ status;
409
+ constructor(message, status) {
410
+ super(message);
411
+ this.status = status;
412
+ this.name = "KnowledgeImporterSourceError";
413
+ }
414
+ };
415
+ /**
416
+ * The host failed, not the source: a fetch proxy or relay, or a remote host's flush, heartbeat or
417
+ * finish. Never a sign an item is gone. `status` is the HTTP status when there was a response;
418
+ * absent for a network error. @experimental
419
+ */
420
+ var KnowledgeImporterHostError = class extends Error {
421
+ status;
422
+ constructor(message, status) {
423
+ super(message);
424
+ this.status = status;
425
+ this.name = "KnowledgeImporterHostError";
426
+ }
427
+ };
428
+ const IMPORTER_ID = /^[a-z][a-z0-9_-]{0,63}$/;
429
+ const SLOT_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
430
+ function checkIconUrl(id, iconUrl) {
431
+ if (/^data:image\//.test(iconUrl)) return;
432
+ let protocol;
433
+ try {
434
+ protocol = new URL(iconUrl).protocol;
435
+ } catch {
436
+ protocol = "";
437
+ }
438
+ if (protocol !== "https:" && protocol !== "http:") throw new KnowledgeImporterDefinitionError(`Importer "${id}" iconUrl must be an http(s) URL or a data:image/ URI.`);
439
+ }
440
+ /**
441
+ * The base class of an importer: code that reads a source and writes it into Knowledge as items.
442
+ * The class declares what it is (id, label, settings schema, credential slots); each instance is
443
+ * one binding (where it writes, with which settings and credentials).
444
+ *
445
+ * ```ts
446
+ * class HelpSpotImporter extends KnowledgeImporter({
447
+ * id: 'helpspot',
448
+ * label: 'HelpSpot',
449
+ * settings: z.object({ baseUrl: z.url() }),
450
+ * credentials: { apiKey: { description: 'HelpSpot API token' } },
451
+ * }) {
452
+ * async import(ctx) {
453
+ * // read ctx.state.get('cursor'), ctx.items.upsert(...), ctx.state.set('cursor', ...)
454
+ * }
455
+ * }
456
+ *
457
+ * new HelpSpotImporter({ id: 'support', target: 'docs#support', settings: { baseUrl }, credentials: { apiKey } });
458
+ * ```
459
+ *
460
+ * Invalid declarations throw `KnowledgeImporterDefinitionError` here, not at the first run.
461
+ *
462
+ * @experimental
463
+ */
464
+ function KnowledgeImporter(input) {
465
+ const definition = defineImporter(input);
466
+ class Importer extends KnowledgeImporterBase {
467
+ static id = definition.id;
468
+ static definition = definition;
469
+ static toManifest() {
470
+ return definition.toManifest();
471
+ }
472
+ }
473
+ return Importer;
474
+ }
475
+ function defineImporter(input) {
476
+ const { id, label, description, iconUrl } = input ?? {};
477
+ if (typeof id !== "string" || !IMPORTER_ID.test(id)) throw new KnowledgeImporterDefinitionError(`Importer id "${String(id)}" must be 1-64 lowercase letters, digits, "-" or "_", starting with a letter.`);
478
+ if (typeof label !== "string" || !label.trim()) throw new KnowledgeImporterDefinitionError(`Importer "${id}" needs a label.`);
479
+ if (iconUrl !== void 0) checkIconUrl(id, iconUrl);
480
+ const credentials = {};
481
+ for (const [slot, declared] of Object.entries(input.credentials ?? {})) {
482
+ if (!SLOT_NAME.test(slot)) throw new KnowledgeImporterDefinitionError(`Importer "${id}" credential slot "${slot}" must be letters, digits and "_", starting with a letter.`);
483
+ if (!declared || typeof declared.description !== "string" || !declared.description.trim()) throw new KnowledgeImporterDefinitionError(`Importer "${id}" credential slot "${slot}" needs a description.`);
484
+ credentials[slot] = Object.freeze({
485
+ description: declared.description,
486
+ secret: declared.secret ?? true
487
+ });
488
+ }
489
+ Object.freeze(credentials);
490
+ let settingsSchema;
491
+ let settingsJsonSchema = EMPTY_KNOWLEDGE_IMPORTER_SETTINGS_SCHEMA;
492
+ if (input.settings !== void 0) {
493
+ try {
494
+ settingsSchema = toStandardSchema(input.settings);
495
+ settingsJsonSchema = standardSchemaToJSONSchema(settingsSchema, {
496
+ io: "input",
497
+ target: "draft-07"
498
+ });
499
+ } catch (error) {
500
+ throw new KnowledgeImporterDefinitionError(`Importer "${id}" settings schema can't be turned into JSON Schema: ${error instanceof Error ? error.message : String(error)}`);
501
+ }
502
+ const outside = jsonSchemaRefs(settingsJsonSchema).find((ref) => !ref.startsWith("#"));
503
+ if (outside) throw new KnowledgeImporterDefinitionError(`Importer "${id}" settings schema refers outside itself ($ref "${outside}").`);
504
+ }
505
+ const manifest = {
506
+ id,
507
+ label,
508
+ ...description !== void 0 && { description },
509
+ ...iconUrl !== void 0 && { iconUrl },
510
+ settingsSchema: settingsJsonSchema,
511
+ credentials: Object.fromEntries(Object.entries(credentials).map(([slot, declared]) => [slot, { ...declared }]))
512
+ };
513
+ return Object.freeze({
514
+ id,
515
+ label,
516
+ description,
517
+ iconUrl,
518
+ credentials,
519
+ async parseSettings(value) {
520
+ if (!settingsSchema) {
521
+ if (!(value === void 0 || isPlainObject(value) && Object.keys(value).length === 0)) throw new KnowledgeImporterSettingsError(`Importer "${id}" takes no settings.`, [{
522
+ path: [],
523
+ message: "Importer takes no settings"
524
+ }]);
525
+ return {};
526
+ }
527
+ const result = await settingsSchema["~standard"].validate(value);
528
+ if (result.issues) {
529
+ const issues = createStandardSchemaIssuesError(result.issues);
530
+ throw new KnowledgeImporterSettingsError(`Settings for importer "${id}" are invalid:\n${issues.message}`, issues.errors);
531
+ }
532
+ return result.value;
533
+ },
534
+ checkCredentials(values) {
535
+ const supplied = values ?? {};
536
+ const unknown = Object.keys(supplied).filter((slot) => !Object.hasOwn(credentials, slot));
537
+ if (unknown.length) throw new KnowledgeImporterCredentialsError(`Importer "${id}" has no credential slot ${unknown.map((slot) => `"${slot}"`).join(", ")}.`);
538
+ const missing = Object.keys(credentials).filter((slot) => {
539
+ const value = supplied[slot];
540
+ return typeof value !== "string" || value.length === 0;
541
+ });
542
+ if (missing.length) throw new KnowledgeImporterCredentialsError(`Importer "${id}" is missing credential ${missing.map((slot) => `"${slot}"`).join(", ")}.`);
543
+ return Object.freeze({ ...supplied });
544
+ },
545
+ toManifest: () => structuredClone(manifest)
546
+ });
547
+ }
548
+ function isPlainObject(value) {
549
+ return typeof value === "object" && value !== null && !Array.isArray(value);
550
+ }
551
+ /**
552
+ * Indexes importer classes by id, refusing two different classes with the same id. A host uses it
553
+ * to construct the instance a stored binding names.
554
+ *
555
+ * @experimental
556
+ */
557
+ function knowledgeImporterRegistry(importers) {
558
+ const registry = /* @__PURE__ */ new Map();
559
+ for (const importer of importers) {
560
+ const known = registry.get(importer.id);
561
+ if (known && known !== importer) throw new KnowledgeImporterDefinitionError(`Two importer classes have the id "${importer.id}".`);
562
+ registry.set(importer.id, importer);
563
+ }
564
+ return registry;
565
+ }
566
+ // src/knowledge/importers/runner.ts
567
+ /** Waits `ms`, or until `cut` settles; the timer is cleared either way. */
568
+ async function sleep(ms, cut) {
569
+ let timer;
570
+ try {
571
+ await Promise.race([new Promise((resolve) => timer = setTimeout(resolve, ms)), ...cut ? [cut] : []]);
572
+ } finally {
573
+ clearTimeout(timer);
574
+ }
575
+ }
576
+ /** `promise`, or `onTimeout()` thrown after `ms`. */
577
+ async function within(promise, ms, onTimeout) {
578
+ let timer;
579
+ try {
580
+ return await Promise.race([promise, new Promise((_, reject) => timer = setTimeout(() => reject(onTimeout()), ms))]);
581
+ } finally {
582
+ clearTimeout(timer);
583
+ }
584
+ }
585
+ /** Refusals kept on a run receipt. */
586
+ const MAX_RECEIPT_REFUSALS = 100;
587
+ const isRetryable = (error) => error instanceof KnowledgeImporterHostError && (error.status === void 0 || error.status >= 500);
588
+ /** The run ended for a reason that decides its outcome; buffered ops after it are dropped. */
589
+ var RunStop = class extends Error {
590
+ reason;
591
+ constructor(reason) {
592
+ super(`importer run ${reason}`);
593
+ this.reason = reason;
594
+ }
595
+ };
596
+ function sourceError(error) {
597
+ const { status } = error;
598
+ const httpStatus = Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
599
+ if (status === 401 || status === 403) return {
600
+ code: "source_auth_failed",
601
+ retryable: false,
602
+ httpStatus
603
+ };
604
+ if (status === 404) return {
605
+ code: "source_not_found",
606
+ retryable: false,
607
+ httpStatus
608
+ };
609
+ if (status === 429) return {
610
+ code: "source_rate_limited",
611
+ retryable: true,
612
+ httpStatus
613
+ };
614
+ if (status >= 500) return {
615
+ code: "source_unreachable",
616
+ retryable: true,
617
+ httpStatus
618
+ };
619
+ return {
620
+ code: "source_bad_response",
621
+ retryable: false,
622
+ httpStatus
623
+ };
624
+ }
625
+ /**
626
+ * Runs one import: starts a run on the host, calls the importer's `import` in passes, sends its items
627
+ * in numbered flushes, and records how the run ended. Every write goes through `host`; the runner
628
+ * never touches storage. Failures end the run with a fixed code; no exception text leaves the app.
629
+ *
630
+ * @experimental
631
+ */
632
+ async function runKnowledgeImport(options) {
633
+ const { host, budgetMs = 15e5, graceMs = 18e4, maxPasses = 200, bufferSize = 200, heartbeatMs = 3e4, maxRetries = 8, hostCallTimeoutMs = 6e4, retryDelayMs = (attempt) => Math.min(250 * 2 ** attempt, 1e4) } = options;
634
+ const started = await within(host.startRun(options.bindingId, options.start), hostCallTimeoutMs, () => new KnowledgeImporterHostError("host call timed out"));
635
+ if (started.status === "skipped") return started;
636
+ const { runId, generation } = started;
637
+ const startedAt = Date.now();
638
+ let lastSeq = started.lastSeq;
639
+ /** A flush sent but never acknowledged: it may have committed. */
640
+ let unsettledSeq;
641
+ let state = { ...started.state };
642
+ let buffer = [];
643
+ let stop;
644
+ let hostFailure;
645
+ const controller = new AbortController();
646
+ let deadlineHit;
647
+ /** Settles at the hard deadline; never otherwise. */
648
+ const deadlinePassed = new Promise((resolve) => deadlineHit = resolve);
649
+ let wake;
650
+ /** Settles when the run stops for any reason, so nothing waits on an import or a backoff past it. */
651
+ const stopped = new Promise((resolve) => wake = resolve);
652
+ const halt = (reason) => {
653
+ if (reason === "stopped") deadlineHit();
654
+ stop ??= new RunStop(reason);
655
+ controller.abort(stop);
656
+ wake();
657
+ };
658
+ /**
659
+ * Sends with resends after a retryable failure. A call that takes longer than `hostCallTimeoutMs`
660
+ * counts as a lost ack. Once the run has stopped, a mutation (a flush) is not resent: its
661
+ * outcome stays unknown and the finish settles it. The finish itself is still resent.
662
+ */
663
+ async function withRetries(send, kind) {
664
+ for (let attempt = 0;; attempt++) try {
665
+ return await within(send(), hostCallTimeoutMs, () => new KnowledgeImporterHostError("host call timed out"));
666
+ } catch (error) {
667
+ if (!isRetryable(error) || attempt >= maxRetries) throw error;
668
+ if (kind === "mutation" && stop) throw error;
669
+ await sleep(retryDelayMs(attempt), kind === "mutation" ? stopped : void 0);
670
+ if (kind === "mutation" && stop) throw error;
671
+ }
672
+ }
673
+ /**
674
+ * The last receipt said the host has settle work left. Unknown until a receipt arrives: settle
675
+ * work can be left from an earlier run, so a run that flushes nothing still sends one empty flush.
676
+ */
677
+ let pending;
678
+ const refused = [];
679
+ let flushing = Promise.resolve();
680
+ /** `settle` sends an empty flush, which only runs the host's next settle slice. */
681
+ function flush(staged, settle = false) {
682
+ const ops = buffer;
683
+ buffer = [];
684
+ const next = flushing.then(async () => {
685
+ if (stop) throw stop;
686
+ if (ops.length === 0 && !staged && !settle) return;
687
+ const body = {
688
+ ops,
689
+ ...staged ? { state: staged } : {}
690
+ };
691
+ const seq = lastSeq + 1;
692
+ const digest = await knowledgeImporterFlushDigest(body);
693
+ if (stop) throw stop;
694
+ const request = {
695
+ runId,
696
+ generation,
697
+ seq,
698
+ digest,
699
+ ...body
700
+ };
701
+ unsettledSeq = seq;
702
+ try {
703
+ const receipt = await withRetries(() => host.flush(request), "mutation");
704
+ pending = receipt.pending === true;
705
+ refused.push(...receipt.refused.slice(0, MAX_RECEIPT_REFUSALS - refused.length));
706
+ } catch (error) {
707
+ if (!isRetryable(error)) unsettledSeq = void 0;
708
+ hostFailure = {
709
+ code: "importer_error",
710
+ retryable: isRetryable(error)
711
+ };
712
+ halt("host");
713
+ throw stop;
714
+ }
715
+ unsettledSeq = void 0;
716
+ lastSeq = seq;
717
+ if (staged) state = {
718
+ ...state,
719
+ ...staged
720
+ };
721
+ });
722
+ flushing = next.catch(() => {});
723
+ return next;
724
+ }
725
+ const push = async (op) => {
726
+ if (stop) throw stop;
727
+ buffer.push(op);
728
+ if (buffer.length >= bufferSize) await flush();
729
+ };
730
+ const finish = async (request) => {
731
+ const result = await finishRun(host, {
732
+ runId,
733
+ generation,
734
+ ...request
735
+ }, lastSeq, unsettledSeq, (send) => withRetries(send, "finish"));
736
+ return "outcome" in result ? {
737
+ ...result,
738
+ refused
739
+ } : result;
740
+ };
741
+ const binding = started.binding;
742
+ const configured = binding && options.importers.find((entry) => entry instanceof KnowledgeImporterBase && entry.binding.id === binding.id && entry.binding.importer === binding.importer);
743
+ const importerClass = binding && (configured ? configured.constructor : options.importers.find((entry) => typeof entry === "function" && entry.id === binding.importer));
744
+ if (!binding || !importerClass) return finish({
745
+ outcome: "failed",
746
+ backlog: false,
747
+ error: { code: "importer_missing_from_deploy" }
748
+ });
749
+ let importer;
750
+ let settings;
751
+ let credentials;
752
+ try {
753
+ importer = configured ?? new importerClass(binding);
754
+ settings = await importerClass.definition.parseSettings(binding.settings ?? {});
755
+ credentials = importerClass.definition.checkCredentials(binding.credentials ?? {});
756
+ } catch (error) {
757
+ if (error instanceof KnowledgeImporterSettingsError) return finish({
758
+ outcome: "failed",
759
+ backlog: false,
760
+ error: { code: "settings_invalid" }
761
+ });
762
+ if (error instanceof KnowledgeImporterCredentialsError) return finish({
763
+ outcome: "failed",
764
+ backlog: false,
765
+ error: { code: "credential_missing" }
766
+ });
767
+ await finish({
768
+ outcome: "failed",
769
+ backlog: false,
770
+ error: { code: "importer_error" }
771
+ }).catch(() => {});
772
+ throw error;
773
+ }
774
+ let backlog = false;
775
+ const fetchImpl = options.fetch ?? globalThis.fetch;
776
+ const ctx = {
777
+ signal: controller.signal,
778
+ binding: {
779
+ id: binding.id,
780
+ target: binding.target
781
+ },
782
+ settings,
783
+ credentials,
784
+ fetch: (input, init) => fetchImpl(input, {
785
+ ...init,
786
+ signal: init?.signal ? AbortSignal.any([controller.signal, init.signal]) : controller.signal
787
+ }),
788
+ state: {
789
+ get: async (key) => state[key],
790
+ set: async (key, value) => {
791
+ if (stop) throw stop;
792
+ await flush({ [key]: value });
793
+ }
794
+ },
795
+ items: {
796
+ upsert: (item) => push({
797
+ op: "upsert",
798
+ item
799
+ }),
800
+ declare: (item) => push({
801
+ op: "declare",
802
+ item
803
+ }),
804
+ remove: (sourceId) => push({
805
+ op: "remove",
806
+ sourceId
807
+ })
808
+ },
809
+ reportBacklog: () => {
810
+ backlog = true;
811
+ }
812
+ };
813
+ let beating = false;
814
+ const heartbeat = setInterval(() => {
815
+ if (beating) return;
816
+ beating = true;
817
+ host.heartbeat(runId, generation).then(({ cancel }) => cancel && halt("canceled"), () => {}).finally(() => beating = false);
818
+ }, heartbeatMs);
819
+ const hardStop = setTimeout(() => halt("stopped"), budgetMs + graceMs);
820
+ let failure;
821
+ try {
822
+ for (let pass = 0; pass < maxPasses; pass++) {
823
+ backlog = false;
824
+ try {
825
+ await Promise.race([importer.import(ctx), stopped]);
826
+ if (!stop) await Promise.race([flush(), stopped]);
827
+ } catch (error) {
828
+ if (stop) break;
829
+ if (error instanceof KnowledgeImporterSourceError) failure = sourceError(error);
830
+ else if (error instanceof KnowledgeImporterHostError) failure = {
831
+ code: "importer_error",
832
+ retryable: true
833
+ };
834
+ else failure = { code: "importer_error" };
835
+ break;
836
+ }
837
+ if (stop || !backlog || Date.now() - startedAt >= budgetMs) break;
838
+ }
839
+ while (!stop && !failure && pending !== false && Date.now() - startedAt < budgetMs) try {
840
+ await Promise.race([flush(void 0, true), stopped]);
841
+ } catch {
842
+ break;
843
+ }
844
+ } finally {
845
+ clearInterval(heartbeat);
846
+ }
847
+ if (!stop || stop.reason !== "stopped") await Promise.race([flushing, deadlinePassed]);
848
+ clearTimeout(hardStop);
849
+ if (stop?.reason === "canceled") return finish({
850
+ outcome: "canceled",
851
+ backlog: false
852
+ });
853
+ if (stop?.reason === "stopped") return finish({
854
+ outcome: "failed",
855
+ backlog: false,
856
+ error: { code: "stopped" }
857
+ });
858
+ const error = stop?.reason === "host" ? hostFailure : failure;
859
+ if (error) return finish({
860
+ outcome: "failed",
861
+ backlog: false,
862
+ error
863
+ });
864
+ return finish({
865
+ outcome: "succeeded",
866
+ backlog
867
+ });
868
+ }
869
+ /**
870
+ * Records the end. A flush whose ack was lost may have committed, so the finish names the seq the
871
+ * host says it holds: the known seq, or the unsettled one when the host refuses the known one. The
872
+ * same request is resent after a lost ack; a host that stays unreachable leaves the run open for
873
+ * its liveness check, and the runner returns `unfinished`.
874
+ */
875
+ async function finishRun(host, request, lastSeq, unsettledSeq, withRetries) {
876
+ const candidates = unsettledSeq === void 0 ? [lastSeq] : [lastSeq, unsettledSeq];
877
+ for (const seq of candidates) try {
878
+ return await withRetries(() => host.finishRun({
879
+ ...request,
880
+ lastSeq: seq
881
+ }));
882
+ } catch (error) {
883
+ if (error instanceof KnowledgeImporterHostConflictError && error.code === "seq_mismatch") continue;
884
+ if (isRetryable(error)) return {
885
+ status: "unfinished",
886
+ runId: request.runId,
887
+ lastSeq: seq
888
+ };
889
+ throw error;
890
+ }
891
+ return {
892
+ status: "unfinished",
893
+ runId: request.runId,
894
+ lastSeq
895
+ };
896
+ }
897
+ // src/knowledge/importers/sink.ts
898
+ /**
899
+ * Applies one flush's ops to pages and the node map, on a transaction view. Pages are found by id
900
+ * through the node map: the binding tracks its anchor (the folder at its target) and the pages its
901
+ * nodes point at. A page already at a new item's path is taken over by that item's node, whoever
902
+ * wrote it, and kept as a stub rather than deleted when the item is removed.
903
+ *
904
+ * @internal
905
+ */
906
+ /** The body a page keeps when its item is gone at the source but pages are still nested under it. */
907
+ const REMOVED_PARENT_BODY = "Removed from the source. Kept because pages are still nested under it.";
908
+ const REMOVED_BODIES = /* @__PURE__ */ new Set([
909
+ REMOVED_PARENT_BODY,
910
+ "Removed from the source. Kept because another importer writes under it.",
911
+ "Removed from the source. Kept because the page was here before the import."
912
+ ]);
913
+ /** Heads the note that keeps the body a page had before an importer took it over. */
914
+ const ORIGINAL_BODY_NOTE = "The body this page had before an importer took it over:\n\n";
915
+ /** Every heading a kept-body note has been written with, newest first; removal recognizes them all. */
916
+ const ORIGINAL_BODY_NOTE_HEADINGS = [ORIGINAL_BODY_NOTE, "Written by hand before an importer took over this page:\n\n"];
917
+ /**
918
+ * Kept-body notes on a page have ids starting with this. Each takeover writes a new one and removes
919
+ * the earlier, so removal finds the body from the latest takeover. Notes written before takeovers
920
+ * had their own id used the prefix alone.
921
+ */
922
+ const originalBodyNotePrefix = (pageId) => `knowledge-import-original:${pageId}`;
923
+ /**
924
+ * Host state key another binding's flush sets, to a fresh value, when it queues link repairs on
925
+ * this binding's pages. Those pages may sort before this binding's saved settle cursor, so its next
926
+ * slice starts the pass over when the value differs from {@link KNOWLEDGE_IMPORT_SETTLE_SEEN_KEY}.
927
+ * The binding's own flushes never write this key, so a flush that read the state earlier can't undo it.
928
+ */
929
+ const KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY = "mastra:settle:restart";
930
+ /** The {@link KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY} value the binding's settling last started over for. */
931
+ const KNOWLEDGE_IMPORT_SETTLE_SEEN_KEY = "mastra:settle:seen";
932
+ /** An unresolved link as the node map lists it, with its label. */
933
+ const encodeLink = (link) => JSON.stringify([link.sourceId, link.rel]);
934
+ const LINKS_HEADING = "Links:";
935
+ /**
936
+ * The links section for these lines, or null for none. Lines are sorted, so a body written in one
937
+ * flush and one completed by a later settle match.
938
+ */
939
+ const linkSection = (lines) => {
940
+ const sorted = [...new Set(lines)].sort();
941
+ return sorted.length ? `${LINKS_HEADING}\n${sorted.join("\n")}` : null;
942
+ };
943
+ const withSection = (text, section) => section === null ? text : text ? `${text}\n\n${section}` : section;
944
+ /**
945
+ * The source's own text in a body the sink wrote with `section` at its end, byte for byte; null when
946
+ * the body no longer ends with that section, because someone edited the page since.
947
+ */
948
+ const ownText = (body, section) => {
949
+ if (section === null) return body;
950
+ if (body === section) return "";
951
+ return body.endsWith(`\n\n${section}`) ? body.slice(0, body.length - section.length - 2) : null;
952
+ };
953
+ /** A per-item refusal: its savepoint rolls back and the flush goes on. */
954
+ var KnowledgeImportRefusalError = class extends Error {
955
+ reason;
956
+ constructor(reason) {
957
+ super(`Knowledge import op refused: ${reason}`);
958
+ this.reason = reason;
959
+ this.name = "KnowledgeImportRefusalError";
960
+ }
961
+ };
962
+ /** Splits `<scope>#<path>`; throws on a target the sink can't own. */
963
+ function parseKnowledgeImportTarget(target) {
964
+ const hash = target.indexOf("#");
965
+ const scope = hash < 0 ? "" : target.slice(0, hash);
966
+ const path = hash < 0 ? [] : target.slice(hash + 1).split("/");
967
+ if (!scope || path.length === 0 || path.some((key) => !key || /[#%]/.test(key))) throw new TypeError(`Importer target "${target}" must be <scope>#<path> with non-empty keys.`);
968
+ return {
969
+ scope,
970
+ path
971
+ };
972
+ }
973
+ /**
974
+ * A reversible page key for a source ID: `/`, `#`, `%`, `:` and `~` become `~` and two hex digits,
975
+ * and an empty ID is `~`. As Platform's sink, so imported paths match.
976
+ */
977
+ function knowledgeImportKey(sourceId) {
978
+ if (!sourceId) return "~";
979
+ return sourceId.replace(/[/#%:~]/g, (char) => `~${char.charCodeAt(0).toString(16).toUpperCase()}`);
980
+ }
981
+ const live = (page) => !!page && !page.deletedAt && !page.mergedInto;
982
+ /** Core errors that mean "this op can't land here", by name: an adapter may carry its own core copy. */
983
+ function refusalFor(error) {
984
+ if (error instanceof KnowledgeImportRefusalError) return error.reason;
985
+ switch (error?.name) {
986
+ case "KnowledgePageKeyConflictError": return "occupied";
987
+ case "KnowledgeMoveTooLargeError":
988
+ case "KnowledgeConflictError":
989
+ case "KnowledgeNotFoundError":
990
+ case "KnowledgePageHasChildrenError": return "conflict";
991
+ case "KnowledgePageDepthError": return "invalid";
992
+ default: return;
993
+ }
994
+ }
995
+ /**
996
+ * Link-index work for a page the flush just wrote. Unlike host writes, a failure isn't logged and
997
+ * skipped: it rolls the whole flush back (no pages, nodes or receipt), and the runner resends it.
998
+ * Only a store without a link index, and a refresh that landed but stopped at its cap (more than 100
999
+ * linking pages, or more than 99 pages sharing a name), are let through: resending would stop at
1000
+ * the same cap every time.
1001
+ */
1002
+ async function syncLinks(work) {
1003
+ try {
1004
+ await work();
1005
+ } catch (error) {
1006
+ if (error instanceof KnowledgeUnsupportedCapabilityError || error instanceof KnowledgeLinkRefreshIncompleteError) return;
1007
+ throw error;
1008
+ }
1009
+ }
1010
+ /** The ops as the sink applies them: the last op per sourceId, upserts parent-first, then removes. */
1011
+ function order(ops) {
1012
+ const last = /* @__PURE__ */ new Map();
1013
+ for (const op of ops) {
1014
+ const id = op.op === "remove" ? op.sourceId : op.item.sourceId;
1015
+ const before = last.get(id);
1016
+ if (op.op === "declare" && before?.op === "upsert") {
1017
+ last.delete(id);
1018
+ last.set(id, {
1019
+ op: "upsert",
1020
+ item: {
1021
+ ...before.item,
1022
+ ...op.item
1023
+ }
1024
+ });
1025
+ continue;
1026
+ }
1027
+ last.delete(id);
1028
+ last.set(id, op);
1029
+ }
1030
+ const writes = [...last.values()].filter((op) => op.op !== "remove");
1031
+ const removes = [...last.values()].filter((op) => op.op === "remove");
1032
+ const pending = new Map(writes.map((op) => [op.item.sourceId, op]));
1033
+ const sorted = [];
1034
+ const visit = (op, seen) => {
1035
+ if (!pending.has(op.item.sourceId) || seen.has(op.item.sourceId)) return;
1036
+ seen.add(op.item.sourceId);
1037
+ for (const dep of [op.item.parent, op.item.fallbackParent]) {
1038
+ const parent = dep ? pending.get(dep) : void 0;
1039
+ if (parent) visit(parent, seen);
1040
+ }
1041
+ pending.delete(op.item.sourceId);
1042
+ sorted.push(op);
1043
+ };
1044
+ for (const op of writes) visit(op, /* @__PURE__ */ new Set());
1045
+ return [...sorted, ...removes];
1046
+ }
1047
+ async function applyKnowledgeImportFlush(input) {
1048
+ const { storage, importers, binding, scope, provenance } = input;
1049
+ const target = parseKnowledgeImportTarget(binding.target);
1050
+ const result = {
1051
+ counts: {
1052
+ created: 0,
1053
+ updated: 0,
1054
+ unchanged: 0,
1055
+ moved: 0,
1056
+ removed: 0,
1057
+ stubbed: 0
1058
+ },
1059
+ refused: [],
1060
+ changes: [],
1061
+ embeds: [],
1062
+ applied: false
1063
+ };
1064
+ const ops = order(input.ops);
1065
+ if (ops.length === 0 && !(input.settle && binding.anchorPageId)) {
1066
+ if (input.settle) result.settle = {
1067
+ pending: false,
1068
+ cursor: null,
1069
+ settled: 0,
1070
+ fromStart: false
1071
+ };
1072
+ return result;
1073
+ }
1074
+ const keyPath = async (page) => {
1075
+ const keys = [];
1076
+ const ids = [];
1077
+ let at = page;
1078
+ while (at && !at.isScope) {
1079
+ if (!live(at) || at.key === void 0) return null;
1080
+ keys.unshift(at.key);
1081
+ ids.unshift(at.id);
1082
+ at = at.parentId ? await storage.getPage({
1083
+ id: at.parentId,
1084
+ read: "all"
1085
+ }) : null;
1086
+ }
1087
+ return at?.id === scope.id ? {
1088
+ keys,
1089
+ ids
1090
+ } : null;
1091
+ };
1092
+ const sameKeys = (a, b) => a.length === b.length && a.every((key, i) => key === b[i]);
1093
+ /**
1094
+ * Marks another binding's pages that link to `targets` for repair, and has its next settle slice
1095
+ * start the pass over: they may sort before its saved cursor.
1096
+ */
1097
+ const queueRepairs = async (bindingId, targets) => {
1098
+ await importers.markLinkingNodesUnsettled(bindingId, targets);
1099
+ if (bindingId !== binding.id) await importers.setState(bindingId, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: randomUUID() });
1100
+ };
1101
+ /**
1102
+ * Stops another binding tracking a page as its item, so this one can take it over: its node is
1103
+ * dropped and that binding's links to it are marked for repair. Says whether it was an item. A
1104
+ * page that is another binding's folder stays its folder: folders are shared, so taking one over
1105
+ * never stops that binding writing or removing under it.
1106
+ */
1107
+ const release = async (pageId) => {
1108
+ const node = await importers.getNodeByPage(pageId);
1109
+ if (!node) return false;
1110
+ await queueRepairs(node.bindingId, [node.sourceId]);
1111
+ await importers.deleteNode(node.bindingId, node.sourceId);
1112
+ return true;
1113
+ };
1114
+ const anchor = await (async () => {
1115
+ if (binding.anchorPageId) {
1116
+ const page = await storage.getPage({
1117
+ id: binding.anchorPageId,
1118
+ read: "all"
1119
+ });
1120
+ const path = live(page) ? await keyPath(page) : null;
1121
+ if (page && path) {
1122
+ await storage.lockPages(path.ids);
1123
+ const fresh = await storage.getPage({
1124
+ id: page.id,
1125
+ read: "all"
1126
+ });
1127
+ const freshPath = live(fresh) ? await keyPath(fresh) : null;
1128
+ if (fresh && freshPath) return {
1129
+ page: fresh,
1130
+ keys: freshPath.keys
1131
+ };
1132
+ }
1133
+ if (!await importers.setBindingAnchor({
1134
+ bindingId: binding.id,
1135
+ expected: binding.anchorPageId,
1136
+ pageId: null
1137
+ })) throw new KnowledgeImportRefusalError("conflict");
1138
+ }
1139
+ if (ops.every((op) => op.op === "remove")) return null;
1140
+ return storage.transaction(async (tx) => {
1141
+ const chain = async () => {
1142
+ const pages = [];
1143
+ for (let depth = 1; depth <= target.path.length; depth++) {
1144
+ const page = await tx.getPageByPath({
1145
+ scopeId: scope.id,
1146
+ path: target.path.slice(0, depth),
1147
+ read: "all"
1148
+ });
1149
+ if (!page) break;
1150
+ pages.push(page);
1151
+ }
1152
+ return pages;
1153
+ };
1154
+ for (let round = 0; round < 3; round++) {
1155
+ const before = await chain();
1156
+ await tx.lockPages([scope.id, ...before.map((page) => page.id)]);
1157
+ const locked = await chain();
1158
+ if (locked.length !== before.length || locked.some((page, i) => page.id !== before[i].id)) continue;
1159
+ let parent = locked.at(-1) ?? scope;
1160
+ if (locked.length === target.path.length) {
1161
+ const own = await importers.getNodeByPage(parent.id);
1162
+ if (own?.bindingId === binding.id) await importers.deleteNode(binding.id, own.sourceId);
1163
+ }
1164
+ for (let depth = locked.length + 1; depth <= target.path.length; depth++) {
1165
+ const key = target.path[depth - 1];
1166
+ parent = await tx.createPage({
1167
+ parentId: parent.id,
1168
+ key,
1169
+ name: key,
1170
+ provenance
1171
+ });
1172
+ result.embeds.push({
1173
+ kind: "index",
1174
+ pageId: parent.id
1175
+ });
1176
+ }
1177
+ if (!await importers.setBindingAnchor({
1178
+ bindingId: binding.id,
1179
+ expected: null,
1180
+ pageId: parent.id
1181
+ })) throw new KnowledgeImportRefusalError("conflict");
1182
+ result.applied = true;
1183
+ return {
1184
+ page: parent,
1185
+ keys: target.path
1186
+ };
1187
+ }
1188
+ throw new KnowledgeImportRefusalError("conflict");
1189
+ });
1190
+ })().catch((error) => {
1191
+ const reason = refusalFor(error);
1192
+ if (!reason) throw error;
1193
+ return reason;
1194
+ });
1195
+ if (typeof anchor === "string") {
1196
+ for (const op of ops) result.refused.push({
1197
+ sourceId: op.op === "remove" ? op.sourceId : op.item.sourceId,
1198
+ reason: anchor
1199
+ });
1200
+ return result;
1201
+ }
1202
+ const anchorPath = anchor?.keys ?? [];
1203
+ /**
1204
+ * A page this binding owns, checked after locking: live, in the target's scope, mapped back to the
1205
+ * node. A person may have moved it out of the anchor, under anyone's pages: it is still the
1206
+ * binding's and is updated where they put it (`outside`).
1207
+ */
1208
+ const owned = async (pageId, sourceId) => {
1209
+ const read = async () => {
1210
+ const page = await storage.getPage({
1211
+ id: pageId,
1212
+ read: "all"
1213
+ });
1214
+ const path = live(page) ? await keyPath(page) : null;
1215
+ return page && path ? {
1216
+ page,
1217
+ path
1218
+ } : null;
1219
+ };
1220
+ const before = await read();
1221
+ if (!before) throw new KnowledgeImportRefusalError("conflict");
1222
+ await storage.lockPages(before.path.ids);
1223
+ const after = await read();
1224
+ if (!after) throw new KnowledgeImportRefusalError("conflict");
1225
+ const outside = !anchor || !(sameKeys(after.path.keys.slice(0, anchorPath.length), anchorPath) && after.path.ids.includes(anchor.page.id));
1226
+ if (after.page.id !== anchor?.page.id) {
1227
+ const node = await importers.getNodeByPage(after.page.id);
1228
+ if (!node || node.bindingId !== binding.id || sourceId !== void 0 && node.sourceId !== sourceId) throw new KnowledgeImportRefusalError("conflict");
1229
+ }
1230
+ return {
1231
+ page: after.page,
1232
+ keys: after.path.keys,
1233
+ outside
1234
+ };
1235
+ };
1236
+ const nodeOf = async (sourceId) => sourceId ? importers.getNode(binding.id, sourceId) : null;
1237
+ const gone = async (node) => {
1238
+ const page = await storage.getPage({
1239
+ id: node.pageId,
1240
+ read: "all"
1241
+ });
1242
+ return !page || !!page.deletedAt && !page.mergedInto || live(page) && page.scopeId !== scope.id;
1243
+ };
1244
+ /**
1245
+ * Drops the node of a page that is gone, so its item is written again as new. Pages that linked to
1246
+ * it still name its old path: this binding's linking items are marked unsettled so a settle slice
1247
+ * renders their links section from wherever the item lands, and Knowledge's own link index is
1248
+ * refreshed for the old page's refs. Keep that refresh: the sink's own removal does the same, and
1249
+ * a page deleted without going through `removePage` would otherwise leave stale index rows.
1250
+ */
1251
+ /** A page's live kept-body notes, oldest first. */
1252
+ const keptBodyNotes = async (pageId) => {
1253
+ const prefix = originalBodyNotePrefix(pageId);
1254
+ const kept = [];
1255
+ let cursor;
1256
+ do {
1257
+ const out = await storage.listNotes({
1258
+ pageId,
1259
+ read: "all",
1260
+ ...cursor ? { cursor } : {}
1261
+ });
1262
+ kept.push(...out.notes.filter((note) => note.id === prefix || note.id.startsWith(`${prefix}:`)));
1263
+ cursor = out.nextCursor;
1264
+ } while (cursor);
1265
+ return kept;
1266
+ };
1267
+ /**
1268
+ * Saves the body a page has as it is taken over, in place of any earlier takeover's. An empty body
1269
+ * keeps no note, so a removal stubs the page rather than bringing back a body a person cleared.
1270
+ */
1271
+ const keepBody = async (pageId, body) => {
1272
+ for (const earlier of await keptBodyNotes(pageId)) await storage.removeNote({
1273
+ id: earlier.id,
1274
+ deletedBy: provenance.author,
1275
+ provenance
1276
+ });
1277
+ if (!body) return;
1278
+ await storage.addNote({
1279
+ id: `${originalBodyNotePrefix(pageId)}:${randomUUID()}`,
1280
+ pageId,
1281
+ text: ORIGINAL_BODY_NOTE + body,
1282
+ stampScopeIds: [scope.id],
1283
+ mentions: [],
1284
+ provenance
1285
+ });
1286
+ };
1287
+ const forget = async (node) => {
1288
+ const old = await storage.getPage({
1289
+ id: node.pageId,
1290
+ read: "all"
1291
+ });
1292
+ await importers.markLinkingNodesUnsettled(binding.id, [node.sourceId]);
1293
+ await importers.deleteNode(binding.id, node.sourceId);
1294
+ if (old) await syncLinks(() => refreshKnowledgeLinksTo(storage, [old]));
1295
+ };
1296
+ const liveNodeOf = async (sourceId) => {
1297
+ const node = await nodeOf(sourceId);
1298
+ return node && !await gone(node) ? node : null;
1299
+ };
1300
+ const ref = (keys) => `${target.scope}#${keys.join("/")}`;
1301
+ const linkLine = async (link) => {
1302
+ const node = await importers.getNode(binding.id, link.sourceId);
1303
+ const page = node ? await storage.getPage({
1304
+ id: node.pageId,
1305
+ read: "all"
1306
+ }) : null;
1307
+ const path = live(page) ? await keyPath(page) : null;
1308
+ return path ? `- ${link.rel ? `${link.rel}: ` : ""}[[${ref(path.keys)}]]` : null;
1309
+ };
1310
+ const renderLinks = async (links) => {
1311
+ const lines = [];
1312
+ const unresolved = [];
1313
+ for (const link of links) {
1314
+ const line = await linkLine(link);
1315
+ if (line) lines.push(line);
1316
+ else unresolved.push(encodeLink(link));
1317
+ }
1318
+ return {
1319
+ section: linkSection(lines),
1320
+ unresolved
1321
+ };
1322
+ };
1323
+ const renderBody = async (item) => {
1324
+ const links = (item.links ?? []).map((link) => ({
1325
+ sourceId: link.sourceId,
1326
+ rel: link.rel ?? null
1327
+ }));
1328
+ const { section, unresolved } = await renderLinks(links);
1329
+ return {
1330
+ body: withSection(item.body.trim(), section),
1331
+ links,
1332
+ section,
1333
+ unresolved
1334
+ };
1335
+ };
1336
+ /**
1337
+ * Writes a node's links section again from where its targets are now. Only the section the sink
1338
+ * wrote is replaced; the source's text before it stays byte for byte. A page edited past that
1339
+ * section is left as it is, with nothing left waiting, until the source sends it again.
1340
+ */
1341
+ const relink = async (node, current) => {
1342
+ const text = ownText(current.body ?? "", node.linkSection);
1343
+ if (text === null) return {
1344
+ page: current,
1345
+ changed: false,
1346
+ section: node.linkSection,
1347
+ unresolved: []
1348
+ };
1349
+ const { section, unresolved } = await renderLinks(node.links);
1350
+ const body = withSection(text, section);
1351
+ if (body === (current.body ?? "")) return {
1352
+ page: current,
1353
+ changed: false,
1354
+ section,
1355
+ unresolved
1356
+ };
1357
+ const page = await storage.updatePage({
1358
+ id: current.id,
1359
+ expectedVersion: current.version,
1360
+ body,
1361
+ provenance
1362
+ });
1363
+ await syncLinks(() => syncKnowledgePageBodyLinks(storage, page));
1364
+ return {
1365
+ page,
1366
+ changed: true,
1367
+ section,
1368
+ unresolved
1369
+ };
1370
+ };
1371
+ const misplacedAt = async (node, page, outside) => {
1372
+ if (!node.parentSourceId || outside) return false;
1373
+ const parent = await nodeOf(node.parentSourceId);
1374
+ return !parent || page.parentId !== parent.pageId;
1375
+ };
1376
+ /**
1377
+ * Moves an owned page, `self`'s, under `parentId`, then rewrites the links sections of this
1378
+ * binding's pages that link to it or to an imported page in its subtree. Generated links are
1379
+ * paths, so without this a linking page that isn't sent again would keep pointing at where they
1380
+ * were. Other bindings' pages can move with the subtree too: their linking pages are marked
1381
+ * unsettled, one statement per binding, and each binding's next settle slice rewrites them. Of
1382
+ * this binding's, all are marked unsettled in one statement; up to
1383
+ * {@link MAX_KNOWLEDGE_LINK_REFRESH_SOURCES} are rewritten here and the rest by the settle slices
1384
+ * that follow. `self` is left to the caller, which writes its body anyway. Returns the moved page
1385
+ * and the pages it rewrote; the caller counts them once its op lands.
1386
+ */
1387
+ let deferredLinkers = false;
1388
+ const moveOwned = async (self, page, parent) => {
1389
+ const targets = [];
1390
+ const othersTargets = /* @__PURE__ */ new Map();
1391
+ await storage.lockSubtree(page.id);
1392
+ for (const p of await knowledgeSubtree(storage, page)) {
1393
+ const node = await importers.getNodeByPage(p.id);
1394
+ if (!node) continue;
1395
+ if (node.bindingId === binding.id) targets.push(node.sourceId);
1396
+ else othersTargets.set(node.bindingId, [...othersTargets.get(node.bindingId) ?? [], node.sourceId]);
1397
+ }
1398
+ const moved = await storage.movePage({
1399
+ id: page.id,
1400
+ expectedVersion: page.version,
1401
+ parentId: parent.page.id,
1402
+ provenance
1403
+ });
1404
+ const keys = [...parent.keys, moved.key];
1405
+ const relinked = [];
1406
+ for (const [other, theirs] of othersTargets) await queueRepairs(other, theirs);
1407
+ await importers.markLinkingNodesUnsettled(binding.id, targets);
1408
+ const linking = await importers.listLinkingNodes(binding.id, targets, { limit: 101 });
1409
+ if (linking.next || linking.items.filter((id) => id !== self).length > 100) deferredLinkers = true;
1410
+ for (const sourceId of linking.items.filter((id) => id !== self).slice(0, 100)) {
1411
+ const node = await importers.getNode(binding.id, sourceId);
1412
+ if (!node) continue;
1413
+ let current;
1414
+ try {
1415
+ current = await owned(node.pageId, sourceId);
1416
+ } catch (error) {
1417
+ if (!refusalFor(error)) throw error;
1418
+ deferredLinkers = true;
1419
+ continue;
1420
+ }
1421
+ const out = await relink(node, current.page);
1422
+ await importers.saveNode({
1423
+ ...node,
1424
+ linkSection: out.section,
1425
+ unresolvedLinks: out.unresolved,
1426
+ unsettled: await misplacedAt(node, out.page, current.outside) || out.unresolved.length > 0
1427
+ });
1428
+ if (out.changed) relinked.push({
1429
+ sourceId,
1430
+ page: out.page,
1431
+ keys: current.keys
1432
+ });
1433
+ }
1434
+ return {
1435
+ page: moved,
1436
+ keys,
1437
+ relinked
1438
+ };
1439
+ };
1440
+ const recordRelinked = (relinked, embeds) => {
1441
+ for (const { sourceId, page, keys } of relinked) {
1442
+ result.applied = true;
1443
+ result.counts.updated++;
1444
+ embeds.push({
1445
+ kind: "index",
1446
+ pageId: page.id
1447
+ });
1448
+ result.changes.push({
1449
+ sourceId,
1450
+ pageId: page.id,
1451
+ change: "updated",
1452
+ title: page.name,
1453
+ path: ref(keys)
1454
+ });
1455
+ }
1456
+ };
1457
+ const write = async (item, hasBody) => {
1458
+ let existing = await importers.getNode(binding.id, item.sourceId);
1459
+ if (existing && await gone(existing)) {
1460
+ await forget(existing);
1461
+ existing = null;
1462
+ }
1463
+ const sourceParent = await liveNodeOf(item.parent);
1464
+ const misplaced = !!item.parent && !sourceParent;
1465
+ const parentNode = sourceParent ?? await liveNodeOf(item.fallbackParent);
1466
+ const destination = parentNode ? await owned(parentNode.pageId, parentNode.sourceId) : anchor;
1467
+ if (existing && destination.page.id === existing.pageId) throw new KnowledgeImportRefusalError("invalid");
1468
+ let rendered = hasBody ? await renderBody(item) : void 0;
1469
+ let fields = {
1470
+ name: item.title,
1471
+ ...item.description !== void 0 ? { description: item.description } : {},
1472
+ ...rendered ? { body: rendered.body } : {}
1473
+ };
1474
+ const key = knowledgeImportKey(item.sourceId);
1475
+ let page;
1476
+ let change;
1477
+ let moved = false;
1478
+ let renamed = false;
1479
+ let relinked = [];
1480
+ let rewrote = false;
1481
+ let adopted = existing?.adopted ?? false;
1482
+ const held = existing ? null : await storage.getPageByPath({
1483
+ scopeId: scope.id,
1484
+ path: [...destination.keys, key],
1485
+ read: "all"
1486
+ });
1487
+ if (held) {
1488
+ await storage.lockPages([held.id]);
1489
+ const fresh = await storage.getPage({
1490
+ id: held.id,
1491
+ read: "all"
1492
+ });
1493
+ if (!live(fresh) || fresh.parentId !== destination.page.id || fresh.key !== key) throw new KnowledgeImportRefusalError("occupied");
1494
+ const imported = await release(fresh.id);
1495
+ renamed = fields.name !== fresh.name;
1496
+ if (!imported) await keepBody(fresh.id, fresh.body ?? "");
1497
+ page = await storage.updatePage({
1498
+ id: fresh.id,
1499
+ expectedVersion: fresh.version,
1500
+ ...fields,
1501
+ provenance
1502
+ });
1503
+ change = "updated";
1504
+ adopted = true;
1505
+ } else if (!existing) {
1506
+ page = await storage.createPage({
1507
+ parentId: destination.page.id,
1508
+ key,
1509
+ ...fields,
1510
+ body: fields.body ?? "",
1511
+ provenance
1512
+ });
1513
+ change = "created";
1514
+ } else {
1515
+ const current = await owned(existing.pageId, item.sourceId);
1516
+ page = current.page;
1517
+ if (existing.stub && existing.adopted && !REMOVED_BODIES.has(page.body ?? "")) await keepBody(page.id, page.body ?? "");
1518
+ if (!current.outside && page.parentId !== destination.page.id) {
1519
+ if (destination.keys.length > current.keys.length && sameKeys(destination.keys.slice(0, current.keys.length), current.keys)) throw new KnowledgeImportRefusalError("invalid");
1520
+ ({page, relinked} = await moveOwned(item.sourceId, page, destination));
1521
+ moved = true;
1522
+ if (hasBody) {
1523
+ rendered = await renderBody(item);
1524
+ fields = {
1525
+ ...fields,
1526
+ body: rendered.body
1527
+ };
1528
+ }
1529
+ }
1530
+ if (!hasBody) {
1531
+ const out = await relink(existing, page);
1532
+ page = out.page;
1533
+ rewrote = out.changed;
1534
+ rendered = {
1535
+ links: existing.links,
1536
+ section: out.section,
1537
+ unresolved: out.unresolved
1538
+ };
1539
+ }
1540
+ const same = fields.name === page.name && (fields.description === void 0 || fields.description === (page.description ?? "")) && (fields.body === void 0 || fields.body === (page.body ?? ""));
1541
+ if (!same) {
1542
+ renamed = fields.name !== page.name;
1543
+ page = await storage.updatePage({
1544
+ id: page.id,
1545
+ expectedVersion: page.version,
1546
+ ...fields,
1547
+ provenance
1548
+ });
1549
+ }
1550
+ change = !same || rewrote ? "updated" : moved ? "moved" : "unchanged";
1551
+ }
1552
+ await importers.saveNode({
1553
+ bindingId: binding.id,
1554
+ sourceId: item.sourceId,
1555
+ pageId: page.id,
1556
+ kind: item.kind ?? existing?.kind ?? null,
1557
+ parentSourceId: item.parent ?? null,
1558
+ aliases: item.aliases ?? existing?.aliases ?? [],
1559
+ unresolvedLinks: rendered ? rendered.unresolved : existing?.unresolvedLinks ?? [],
1560
+ links: rendered ? rendered.links : existing?.links ?? [],
1561
+ linkSection: rendered ? rendered.section : existing?.linkSection ?? null,
1562
+ stub: false,
1563
+ adopted,
1564
+ unsettled: misplaced || (rendered ? rendered.unresolved : existing?.unresolvedLinks ?? []).length > 0
1565
+ });
1566
+ if (change !== "unchanged" || existing?.stub) await syncLinks(async () => {
1567
+ await syncKnowledgePageBodyLinks(storage, page);
1568
+ if (change === "created" || renamed || moved) await refreshKnowledgeLinksTo(storage, [page], { withDescendants: moved });
1569
+ });
1570
+ return {
1571
+ page,
1572
+ change,
1573
+ moved,
1574
+ relinked
1575
+ };
1576
+ };
1577
+ const depth = /* @__PURE__ */ new Map();
1578
+ for (const op of ops) {
1579
+ if (op.op !== "remove") continue;
1580
+ const node = await importers.getNode(binding.id, op.sourceId);
1581
+ const page = node ? await storage.getPage({
1582
+ id: node.pageId,
1583
+ read: "all"
1584
+ }) : null;
1585
+ const path = live(page) ? await keyPath(page) : null;
1586
+ depth.set(op.sourceId, path?.keys.length ?? 0);
1587
+ }
1588
+ const writes = ops.filter((op) => op.op !== "remove");
1589
+ const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
1590
+ for (const op of [...writes, ...removes]) {
1591
+ const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
1592
+ const embeds = [];
1593
+ try {
1594
+ await storage.transaction(async () => {
1595
+ if (op.op === "remove") {
1596
+ const node = await importers.getNode(binding.id, sourceId);
1597
+ if (!node) return;
1598
+ if (await gone(node)) {
1599
+ await forget(node);
1600
+ result.applied = true;
1601
+ return;
1602
+ }
1603
+ const current = await owned(node.pageId, sourceId);
1604
+ await storage.lockSubtree(current.page.id);
1605
+ const children = (await storage.countChildPages({
1606
+ parentIds: [current.page.id],
1607
+ read: "all"
1608
+ }))[current.page.id] ?? 0;
1609
+ const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
1610
+ if (children > 0 || node.adopted || folder) {
1611
+ if (node.stub) return;
1612
+ const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
1613
+ const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
1614
+ const original = heading ? note.text.slice(heading.length) : note?.text;
1615
+ const page = await storage.updatePage({
1616
+ id: current.page.id,
1617
+ expectedVersion: current.page.version,
1618
+ body: original || (children > 0 ? "Removed from the source. Kept because pages are still nested under it." : folder ? "Removed from the source. Kept because another importer writes under it." : "Removed from the source. Kept because the page was here before the import."),
1619
+ provenance
1620
+ });
1621
+ await importers.saveNode({
1622
+ ...node,
1623
+ stub: true
1624
+ });
1625
+ await syncLinks(() => syncKnowledgePageBodyLinks(storage, page));
1626
+ embeds.push({
1627
+ kind: "index",
1628
+ pageId: page.id
1629
+ });
1630
+ result.counts.stubbed++;
1631
+ result.changes.push({
1632
+ sourceId,
1633
+ pageId: page.id,
1634
+ change: "stubbed",
1635
+ title: page.name,
1636
+ path: ref(current.keys)
1637
+ });
1638
+ } else {
1639
+ const deleted = await storage.deletePage({
1640
+ id: current.page.id,
1641
+ expectedVersion: current.page.version,
1642
+ deletedBy: provenance.author
1643
+ });
1644
+ await importers.deleteNode(binding.id, sourceId);
1645
+ if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
1646
+ await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
1647
+ await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: randomUUID() });
1648
+ deferredLinkers = true;
1649
+ }
1650
+ await syncLinks(async () => {
1651
+ await syncKnowledgePageBodyLinks(storage, deleted);
1652
+ await refreshKnowledgeLinksTo(storage, [deleted]);
1653
+ });
1654
+ embeds.push({
1655
+ kind: "remove",
1656
+ pageId: deleted.id
1657
+ });
1658
+ result.counts.removed++;
1659
+ result.changes.push({
1660
+ sourceId,
1661
+ pageId: null,
1662
+ change: "removed",
1663
+ title: deleted.name,
1664
+ path: ref(current.keys)
1665
+ });
1666
+ }
1667
+ result.applied = true;
1668
+ return;
1669
+ }
1670
+ const { page, change, moved, relinked } = await write(op.item, op.op === "upsert");
1671
+ recordRelinked(relinked, embeds);
1672
+ if (change === "unchanged") {
1673
+ result.counts.unchanged++;
1674
+ return;
1675
+ }
1676
+ result.applied = true;
1677
+ if (change !== "moved") embeds.push({
1678
+ kind: "index",
1679
+ pageId: page.id
1680
+ });
1681
+ if (change === "created") result.counts.created++;
1682
+ else if (change === "updated") result.counts.updated++;
1683
+ if (moved) result.counts.moved++;
1684
+ const path = await keyPath(page);
1685
+ result.changes.push({
1686
+ sourceId,
1687
+ pageId: page.id,
1688
+ change,
1689
+ title: page.name,
1690
+ path: path ? ref(path.keys) : ""
1691
+ });
1692
+ });
1693
+ result.embeds.push(...embeds);
1694
+ } catch (error) {
1695
+ const reason = refusalFor(error);
1696
+ if (!reason) throw error;
1697
+ result.refused.push({
1698
+ sourceId,
1699
+ reason
1700
+ });
1701
+ }
1702
+ }
1703
+ if (input.settle) {
1704
+ if (anchor) {
1705
+ input.settle.onStart?.();
1706
+ result.settle = await settle(input.settle);
1707
+ } else result.settle = {
1708
+ pending: false,
1709
+ cursor: null,
1710
+ settled: 0,
1711
+ fromStart: false
1712
+ };
1713
+ }
1714
+ return result;
1715
+ /**
1716
+ * One settle slice (O3 §C, §C′): visits the binding's unsettled nodes after `budget.after`, each
1717
+ * in its own savepoint, moving a page under a source parent that has arrived since and writing
1718
+ * links whose targets now resolve. Stops at the candidate, move or time cap and leaves the rest
1719
+ * for the next slice. A node it can't settle (refused, or still waiting) is skipped and stays
1720
+ * unsettled; the pass ends when it reaches the last unsettled node.
1721
+ */
1722
+ async function settle(budget) {
1723
+ let after = budget.after ?? void 0;
1724
+ const fromStart = after === void 0;
1725
+ let examined = 0;
1726
+ let moves = 0;
1727
+ let settled = 0;
1728
+ for (;;) {
1729
+ const page = await importers.listNodes(binding.id, {
1730
+ unsettled: true,
1731
+ ...after !== void 0 ? { after } : {},
1732
+ limit: Math.max(1, budget.candidates - examined)
1733
+ });
1734
+ for (const node of page.items) {
1735
+ if (examined >= budget.candidates || moves >= budget.moves || Date.now() >= budget.until) return {
1736
+ pending: true,
1737
+ cursor: resumeAt(),
1738
+ settled,
1739
+ fromStart
1740
+ };
1741
+ examined++;
1742
+ after = node.sourceId;
1743
+ const embeds = [];
1744
+ try {
1745
+ const outcome = await storage.transaction(() => settleNode(node.sourceId, embeds, moves < budget.moves));
1746
+ if (outcome.moved) moves++;
1747
+ if (outcome.moved || outcome.relinked) settled++;
1748
+ result.embeds.push(...embeds);
1749
+ } catch (error) {
1750
+ if (!refusalFor(error)) throw error;
1751
+ }
1752
+ }
1753
+ if (!page.next) {
1754
+ if (deferredLinkers) {
1755
+ if ((await importers.listNodes(binding.id, {
1756
+ unsettled: true,
1757
+ limit: 1
1758
+ })).items.length > 0) return {
1759
+ pending: true,
1760
+ cursor: null,
1761
+ settled,
1762
+ fromStart
1763
+ };
1764
+ }
1765
+ return {
1766
+ pending: false,
1767
+ cursor: null,
1768
+ settled,
1769
+ fromStart
1770
+ };
1771
+ }
1772
+ if (examined >= budget.candidates) return {
1773
+ pending: true,
1774
+ cursor: resumeAt(),
1775
+ settled,
1776
+ fromStart
1777
+ };
1778
+ }
1779
+ function resumeAt() {
1780
+ return deferredLinkers ? null : after ?? null;
1781
+ }
1782
+ }
1783
+ async function settleNode(sourceId, embeds, canMove) {
1784
+ const node = await importers.getNode(binding.id, sourceId);
1785
+ if (!node?.unsettled) return {
1786
+ moved: false,
1787
+ relinked: false
1788
+ };
1789
+ const current = await owned(node.pageId, sourceId);
1790
+ let { page, keys } = current;
1791
+ let moved = false;
1792
+ let relinked = false;
1793
+ const parent = current.outside ? null : await nodeOf(node.parentSourceId);
1794
+ let misplaced = !current.outside && !!node.parentSourceId && !parent;
1795
+ if (parent && canMove) {
1796
+ const destination = await owned(parent.pageId, parent.sourceId);
1797
+ if (page.parentId !== destination.page.id) {
1798
+ if (destination.keys.length > keys.length && sameKeys(destination.keys.slice(0, keys.length), keys)) throw new KnowledgeImportRefusalError("invalid");
1799
+ let rewrote;
1800
+ ({page, keys, relinked: rewrote} = await moveOwned(sourceId, page, destination));
1801
+ recordRelinked(rewrote, embeds);
1802
+ moved = true;
1803
+ await syncLinks(() => refreshKnowledgeLinksTo(storage, [page], { withDescendants: true }));
1804
+ }
1805
+ } else if (parent) misplaced = true;
1806
+ const out = await relink(node, page);
1807
+ page = out.page;
1808
+ if (out.changed) {
1809
+ relinked = true;
1810
+ embeds.push({
1811
+ kind: "index",
1812
+ pageId: page.id
1813
+ });
1814
+ }
1815
+ await importers.saveNode({
1816
+ ...node,
1817
+ linkSection: out.section,
1818
+ unresolvedLinks: out.unresolved,
1819
+ unsettled: misplaced || out.unresolved.length > 0
1820
+ });
1821
+ if (moved || relinked) {
1822
+ result.applied = true;
1823
+ if (moved) result.counts.moved++;
1824
+ if (relinked) result.counts.updated++;
1825
+ result.changes.push({
1826
+ sourceId,
1827
+ pageId: page.id,
1828
+ change: relinked ? "updated" : "moved",
1829
+ title: page.name,
1830
+ path: ref(keys)
1831
+ });
1832
+ }
1833
+ return {
1834
+ moved,
1835
+ relinked
1836
+ };
1837
+ }
1838
+ }
1839
+ // src/knowledge/importers/conformance.ts
1840
+ /**
1841
+ * The protocol every {@link KnowledgeImporterHost} keeps, as framework-free cases: run each one as a
1842
+ * test (`for (const c of importerHostConformance(factory)) it(c.name, c.run)`). A case throws when
1843
+ * the host breaks the protocol. It checks only what the runner relies on (sequencing, digests,
1844
+ * replay, generations, finish, heartbeat, state), not where pages land.
1845
+ * @experimental
1846
+ */
1847
+ function importerHostConformance(factory) {
1848
+ return [
1849
+ ["starts a run at seq 0 with empty state, and skips a second start while it runs", async (t) => {
1850
+ const run = await t.start();
1851
+ check(run.lastSeq === 0, `a first run starts at lastSeq 0, got ${run.lastSeq}`);
1852
+ check(Object.keys(run.state).length === 0, "a first run starts with empty state");
1853
+ const second = await t.host.startRun(t.bindingId);
1854
+ check(second.status === "skipped", `a second start while a run is going is skipped, got ${second.status}`);
1855
+ }],
1856
+ ["applies flushes in seq order and returns a receipt for each", async (t) => {
1857
+ const run = await t.start();
1858
+ const first = await t.flush(run, 1, [upsert("a")]);
1859
+ check(first.seq === 1, `the receipt names its seq, got ${first.seq}`);
1860
+ check(first.created === 1, `one new item is one created page, got ${first.created}`);
1861
+ check((await t.flush(run, 2, [])).seq === 2, "an empty flush is a valid next seq");
1862
+ }],
1863
+ ["replays a committed seq to the same receipt and refuses other content for it", async (t) => {
1864
+ const run = await t.start();
1865
+ const ops = [upsert("a")];
1866
+ const first = await t.flush(run, 1, ops);
1867
+ check(same(first, await t.flush(run, 1, ops)), "resending a committed flush returns its stored receipt");
1868
+ await refused(() => t.flush(run, 1, [upsert("b")]), 409, "digest_mismatch");
1869
+ const digest = await knowledgeImporterFlushDigest({ ops });
1870
+ await refused(() => t.host.flush({
1871
+ runId: run.runId,
1872
+ generation: run.generation,
1873
+ seq: 1,
1874
+ digest,
1875
+ ops: [upsert("b")]
1876
+ }), 409, "digest_mismatch");
1877
+ check(same(first, await t.flush(run, 1, ops)), "an exact replay still returns the stored receipt");
1878
+ check((await t.flush(run, 2, [])).seq === 2, "the replay did not advance the seq");
1879
+ }],
1880
+ ["refuses a seq gap", async (t) => {
1881
+ const run = await t.start();
1882
+ await refused(() => t.flush(run, 2, [upsert("a")]), 409, "seq_mismatch");
1883
+ await t.flush(run, 1, [upsert("a")]);
1884
+ }],
1885
+ ["recomputes the digest and refuses one that does not match the content", async (t) => {
1886
+ const run = await t.start();
1887
+ const digest = await knowledgeImporterFlushDigest({ ops: [upsert("a")] });
1888
+ await refused(() => t.host.flush({
1889
+ runId: run.runId,
1890
+ generation: run.generation,
1891
+ seq: 1,
1892
+ digest,
1893
+ ops: [upsert("b")]
1894
+ }), 409, "digest_mismatch");
1895
+ }],
1896
+ ["refuses a flush or finish from another generation", async (t) => {
1897
+ const run = await t.start();
1898
+ const stale = {
1899
+ ...run,
1900
+ generation: run.generation + 1
1901
+ };
1902
+ await refused(() => t.flush(stale, 1, [upsert("a")]), 409, "stale_generation");
1903
+ await refused(() => t.finish(stale, { lastSeq: 0 }), 409, "stale_generation");
1904
+ await toldToStop(() => t.host.heartbeat(run.runId, run.generation + 1), "stale_generation");
1905
+ }],
1906
+ ["refuses a malformed flush without applying it", async (t) => {
1907
+ const run = await t.start();
1908
+ const ops = [{
1909
+ op: "upsert",
1910
+ item: { sourceId: "a" }
1911
+ }];
1912
+ await refused(() => t.host.flush({
1913
+ runId: run.runId,
1914
+ generation: run.generation,
1915
+ seq: 1,
1916
+ digest: "0".repeat(64),
1917
+ ops
1918
+ }), 400);
1919
+ await t.flush(run, 1, [upsert("a")]);
1920
+ }],
1921
+ ["keeps a running run alive on heartbeat", async (t) => {
1922
+ const run = await t.start();
1923
+ check((await t.host.heartbeat(run.runId, run.generation)).cancel === false, "a live run is not told to cancel");
1924
+ }],
1925
+ ["finishes at the committed seq, sums counts from receipts, and replays the finish exactly", async (t) => {
1926
+ const run = await t.start();
1927
+ await t.flush(run, 1, [upsert("a"), upsert("b")]);
1928
+ await refused(() => t.finish(run, { lastSeq: 2 }), 409, "seq_mismatch");
1929
+ const receipt = await t.finish(run, { lastSeq: 1 });
1930
+ check(receipt.outcome === "succeeded" && receipt.lastSeq === 1, "the receipt records the finish");
1931
+ check(receipt.counts.created === 2, `counts come from flush receipts, got ${receipt.counts.created}`);
1932
+ check(receipt.chain === false, "a run with no backlog and no settle work does not chain");
1933
+ check(same(receipt, await t.finish(run, { lastSeq: 1 })), "an identical finish replays its receipt");
1934
+ await refused(() => t.finish(run, {
1935
+ lastSeq: 1,
1936
+ backlog: true
1937
+ }), 409, "finish_mismatch");
1938
+ await refused(() => t.finish(run, {
1939
+ lastSeq: 1,
1940
+ outcome: "canceled"
1941
+ }), 409, "finish_mismatch");
1942
+ }],
1943
+ ["chains a succeeded run that reports backlog", async (t) => {
1944
+ const run = await t.start();
1945
+ const receipt = await t.finish(run, {
1946
+ lastSeq: 0,
1947
+ backlog: true
1948
+ });
1949
+ check(receipt.backlog === true && receipt.chain === true, "backlog is chained");
1950
+ }],
1951
+ ["records a failed run with its fixed error code", async (t) => {
1952
+ const run = await t.start();
1953
+ const receipt = await t.finish(run, {
1954
+ lastSeq: 0,
1955
+ outcome: "failed",
1956
+ error: {
1957
+ code: "source_unreachable",
1958
+ retryable: true,
1959
+ httpStatus: 503
1960
+ }
1961
+ });
1962
+ check(receipt.outcome === "failed", "the outcome is recorded");
1963
+ check(receipt.error?.code === "source_unreachable" && receipt.error.httpStatus === 503, "the error code and status are recorded");
1964
+ check(receipt.chain === false, "a failed run does not chain");
1965
+ }],
1966
+ ["after a finish, refuses new flushes and still replays committed ones", async (t) => {
1967
+ const run = await t.start();
1968
+ const ops = [upsert("a")];
1969
+ const first = await t.flush(run, 1, ops);
1970
+ await t.finish(run, { lastSeq: 1 });
1971
+ check(same(first, await t.flush(run, 1, ops)), "a committed flush still replays after the finish");
1972
+ await refused(() => t.flush(run, 2, []), 409, "run_not_active");
1973
+ await toldToStop(() => t.host.heartbeat(run.runId, run.generation), "run_not_active");
1974
+ }],
1975
+ ["hands the next run the state the last committed flush saved, and lets it start", async (t) => {
1976
+ const run = await t.start();
1977
+ await t.flush(run, 1, [upsert("a")], { cursor: "1" });
1978
+ await t.flush(run, 2, [], {
1979
+ cursor: "2",
1980
+ page: "x"
1981
+ });
1982
+ await t.finish(run, { lastSeq: 2 });
1983
+ const next = await t.start();
1984
+ check(next.runId !== run.runId, "the next run has its own id");
1985
+ check(next.lastSeq === 0, "seq starts over for each run");
1986
+ check(next.state.cursor === "2" && next.state.page === "x", "state is what the last flush saved");
1987
+ }],
1988
+ ["saves no state from a refused flush", async (t) => {
1989
+ const run = await t.start();
1990
+ await t.flush(run, 1, [], { cursor: "1" });
1991
+ await refused(() => t.flush(run, 3, [], { cursor: "3" }), 409, "seq_mismatch");
1992
+ await t.finish(run, { lastSeq: 1 });
1993
+ const next = await t.start();
1994
+ check(next.state.cursor === "1", `a refused flush saves nothing, got cursor ${next.state.cursor}`);
1995
+ }]
1996
+ ].map(([name, body]) => ({
1997
+ name,
1998
+ run: async () => {
1999
+ const fixture = await factory();
2000
+ try {
2001
+ await body(session(fixture));
2002
+ } finally {
2003
+ await fixture.cleanup?.();
2004
+ }
2005
+ }
2006
+ }));
2007
+ }
2008
+ function session({ host, bindingId }) {
2009
+ return {
2010
+ host,
2011
+ bindingId,
2012
+ async start() {
2013
+ const started = await host.startRun(bindingId);
2014
+ check(started.status === "started", `the binding's run starts, got ${started.status}`);
2015
+ return started;
2016
+ },
2017
+ async flush(run, seq, ops, state) {
2018
+ const digest = await knowledgeImporterFlushDigest(state ? {
2019
+ ops,
2020
+ state
2021
+ } : { ops });
2022
+ return host.flush({
2023
+ runId: run.runId,
2024
+ generation: run.generation,
2025
+ seq,
2026
+ digest,
2027
+ ops,
2028
+ ...state ? { state } : {}
2029
+ });
2030
+ },
2031
+ finish(run, request) {
2032
+ return host.finishRun({
2033
+ runId: run.runId,
2034
+ generation: run.generation,
2035
+ outcome: "succeeded",
2036
+ backlog: false,
2037
+ ...request
2038
+ });
2039
+ }
2040
+ };
2041
+ }
2042
+ const upsert = (sourceId) => ({
2043
+ op: "upsert",
2044
+ item: {
2045
+ sourceId,
2046
+ title: sourceId.toUpperCase(),
2047
+ body: `body of ${sourceId}`
2048
+ }
2049
+ });
2050
+ function check(condition, message) {
2051
+ if (!condition) throw new Error(`Importer host conformance: ${message}`);
2052
+ }
2053
+ /** Equal as JSON, key order aside: a host may store receipts in a store that reorders keys. */
2054
+ function same(a, b) {
2055
+ return canonicalJson(JSON.parse(JSON.stringify(a))) === canonicalJson(JSON.parse(JSON.stringify(b)));
2056
+ }
2057
+ /**
2058
+ * A heartbeat for a run the host no longer holds must not keep it going: it answers
2059
+ * `{ cancel: true }`, or (a host that enforces a lease) refuses with a 409 and `code`. The runner
2060
+ * ignores a refused heartbeat; its next flush or finish gets the same refusal.
2061
+ */
2062
+ async function toldToStop(beat, code) {
2063
+ let answer;
2064
+ let error;
2065
+ try {
2066
+ answer = await beat();
2067
+ } catch (e) {
2068
+ error = e;
2069
+ }
2070
+ check(answer ? answer.cancel === true : error?.status === 409 && error.code === code, answer ? "a heartbeat for a run the host no longer holds is told to cancel" : `a refused heartbeat is a 409 ${code}, got ${String(error?.status)} ${String(error?.code)}: ${String(error)}`);
2071
+ }
2072
+ async function refused(call, status, code) {
2073
+ let error;
2074
+ try {
2075
+ await call();
2076
+ } catch (e) {
2077
+ error = e;
2078
+ }
2079
+ check(error, `expected a ${status}${code ? ` ${code}` : ""} refusal, but the call succeeded`);
2080
+ check(error.status === status && (code === void 0 || error.code === code), `expected a ${status}${code ? ` ${code}` : ""} refusal, got ${String(error.status)} ${String(error.code)}: ${String(error)}`);
2081
+ }
2082
+ // src/knowledge/importers/local-host.ts
2083
+ const DEFAULT_FLUSH_BUDGET_MS = 45e3;
2084
+ const DEFAULT_STALE_RUN_AFTER_MS = 3e5;
2085
+ const DEFAULT_SETTLE_BUDGET_MS = 1e4;
2086
+ const SETTLE_CANDIDATES = 200;
2087
+ const SETTLE_MOVES = 50;
2088
+ /** Settle flushes in a row that may time out before a run stops settling (O3 §C″). */
2089
+ const SETTLE_MAX_TIMEOUTS = 3;
2090
+ /**
2091
+ * Host bookkeeping kept beside the importer's own state, under a prefix the importer can't write:
2092
+ * where the settle pass stopped, `<runId>:<n>` settle timeouts in a row for the current run, and
2093
+ * the restart request another binding's flush left (see {@link KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY}).
2094
+ */
2095
+ const RESERVED_STATE_PREFIX = "mastra:";
2096
+ const SETTLE_CURSOR_KEY = "mastra:settle:cursor";
2097
+ const SETTLE_TIMEOUTS_KEY = "mastra:settle:timeouts";
2098
+ const settleTimeouts = (state, runId) => {
2099
+ const value = state[SETTLE_TIMEOUTS_KEY] ?? "";
2100
+ const at = value.lastIndexOf(":");
2101
+ return at > 0 && value.slice(0, at) === runId ? Number(value.slice(at + 1)) || 0 : 0;
2102
+ };
2103
+ const SETTLE_TIMEOUT_RECORD_MS = 5e3;
2104
+ const timedOut = (error) => {
2105
+ const e = error;
2106
+ if (!e) return false;
2107
+ if (e.name === "KnowledgeTransactionDeadlineError" || e.name === "TransactionDeadlineError") return true;
2108
+ if (e.code === "57014" || e.code === "55P03") return true;
2109
+ return e.cause !== void 0 && e.cause !== error && timedOut(e.cause);
2110
+ };
2111
+ /** Re-index rounds after a page changed under its embed; a page rewritten faster than this is left to its own writes' jobs. */
2112
+ const MAX_REINDEX_ROUNDS = 3;
2113
+ /** Unwinds a claimed start's transaction when another run of the binding is going (r352 S4). */
2114
+ var SkippedClaim = class extends Error {
2115
+ runId;
2116
+ constructor(runId) {
2117
+ super("Another run of the binding is going.");
2118
+ this.runId = runId;
2119
+ }
2120
+ };
2121
+ /**
2122
+ * Unwinds a transaction that holds the writer guard shared but found `firstWriteAt` unset where it
2123
+ * must mark it: marking under a shared lock can deadlock against another holder, so the work is
2124
+ * redone holding it exclusively (O2 lock preselection).
2125
+ */
2126
+ var NeedsExclusiveGuard = class extends Error {
2127
+ constructor() {
2128
+ super("The first write must be marked under the exclusive writer guard.");
2129
+ }
2130
+ };
2131
+ /**
2132
+ * Unwinds a flush whose transaction deadline runs past where its run stops being live (r352 S1):
2133
+ * it is redone with `cutoff` as its deadline.
2134
+ */
2135
+ var LeaseCutoff = class extends Error {
2136
+ cutoff;
2137
+ constructor(cutoff) {
2138
+ super("The flush transaction outlives its run lease.");
2139
+ this.cutoff = cutoff;
2140
+ }
2141
+ };
2142
+ /** Attempts to bound a flush by its run's lease before it is refused as retryable. */
2143
+ const MAX_LEASE_BOUND_ATTEMPTS = 3;
2144
+ /**
2145
+ * Taken off a redone flush's cutoff, so that a slower read of the store's clock on the next
2146
+ * attempt, which maps it earlier, doesn't unwind it again.
2147
+ */
2148
+ const LEASE_CUTOFF_MARGIN_MS = 250;
2149
+ /**
2150
+ * The local time (epoch ms) by which the store's clock reaches `end`. The local clock is read
2151
+ * before the store's, so the round trip only moves the result earlier, never later.
2152
+ */
2153
+ async function localTimeOf(importers, end) {
2154
+ return Date.now() + (end - (await importers.now()).getTime());
2155
+ }
2156
+ /** Carries `admit`'s own error out of the start transaction it rolled back. */
2157
+ var AdmitRefusal = class extends Error {
2158
+ refusal;
2159
+ constructor(refusal) {
2160
+ super("The claim was refused.");
2161
+ this.refusal = refusal;
2162
+ }
2163
+ };
2164
+ const conflict = (code, message) => new KnowledgeImporterHostConflictError(code, message);
2165
+ /** O2 run-state refusals as the host contract names them. */
2166
+ function runStateConflict(error) {
2167
+ switch (error.reason) {
2168
+ case "seq": return conflict("seq_mismatch", "The flush seq is not the committed seq + 1.");
2169
+ case "generation":
2170
+ case "stale_guard": return conflict("stale_generation", "The run belongs to an older writer generation.");
2171
+ default: return conflict("run_not_active", "The run is not running.");
2172
+ }
2173
+ }
2174
+ /** Failures a resend can get past: lock and serialization aborts, deadlines, lost connections. */
2175
+ function transient(error) {
2176
+ const e = error;
2177
+ return e?.name === "KnowledgeTransactionDeadlineError" || e?.name === "TransactionRolledBackError" || [
2178
+ "40001",
2179
+ "40P01",
2180
+ "55P03",
2181
+ "57014",
2182
+ "08006",
2183
+ "08003",
2184
+ "SQLITE_BUSY",
2185
+ "ECONNRESET"
2186
+ ].includes(e?.code ?? "");
2187
+ }
2188
+ function hostError(error) {
2189
+ if (error instanceof KnowledgeImporterHostConflictError || error instanceof KnowledgeImporterHostError) return error;
2190
+ if (error instanceof KnowledgeImporterRunStateError) return runStateConflict(error);
2191
+ const failure = new KnowledgeImporterHostError("The importer host could not apply the request; nothing was applied.", transient(error) ? 503 : 422);
2192
+ failure.cause = error;
2193
+ return failure;
2194
+ }
2195
+ const receiptCounts = (counts) => ({
2196
+ created: counts.created ?? 0,
2197
+ updated: counts.updated ?? 0,
2198
+ unchanged: counts.unchanged ?? 0,
2199
+ moved: counts.moved ?? 0,
2200
+ removed: counts.removed ?? 0,
2201
+ stubbed: counts.stubbed ?? 0,
2202
+ refused: counts.refused ?? 0
2203
+ });
2204
+ const runReceipt = (run) => {
2205
+ const { chain, by: _by, canceled, ...finish } = run.finish;
2206
+ const reported = canceled ? {
2207
+ outcome: "canceled",
2208
+ backlog: false,
2209
+ error: null
2210
+ } : {};
2211
+ return {
2212
+ runId: run.id,
2213
+ ...finish,
2214
+ ...reported,
2215
+ counts: receiptCounts(run.counts),
2216
+ chain: chain ?? false
2217
+ };
2218
+ };
2219
+ /** The app's normalized request a stored finish replays against. */
2220
+ const replayIdentity = (finish) => {
2221
+ const { chain: _chain, by: _by, canceled: _canceled, ...rest } = finish;
2222
+ return rest;
2223
+ };
2224
+ /** The finish a host records for a run it ended (r352 S2/S3). */
2225
+ const hostFinish = (run, code) => {
2226
+ const canceled = run.cancelRequestedAt !== null;
2227
+ return {
2228
+ ...normalizeKnowledgeImporterFinish({
2229
+ runId: run.id,
2230
+ generation: run.generation,
2231
+ outcome: canceled ? "canceled" : "failed",
2232
+ backlog: false,
2233
+ lastSeq: run.lastSeq,
2234
+ ...canceled ? {} : { error: {
2235
+ code,
2236
+ retryable: true
2237
+ } }
2238
+ }),
2239
+ chain: false,
2240
+ by: "host"
2241
+ };
2242
+ };
2243
+ /**
2244
+ * A {@link KnowledgeImporterHost} over the app's own Knowledge storage: each flush is one storage
2245
+ * transaction holding its page writes, node map, state, run changes and receipt. Embeds run after
2246
+ * commit; a failed embed is a warning and never fails the flush.
2247
+ *
2248
+ * @internal Reached through `Knowledge`; the writer is Knowledge's own.
2249
+ */
2250
+ function createLocalKnowledgeImporterHost(writer, options) {
2251
+ const author = options.author ?? ((binding) => `importer:${binding.id}`);
2252
+ const leaseMs = options.leaseMs;
2253
+ /** The clock leases are judged by: the store's under `leaseMs`, else this process's. */
2254
+ const clock = async (importers) => leaseMs !== void 0 ? importers.now() : /* @__PURE__ */ new Date();
2255
+ /** Why a running run is no longer live at `now`, or null while it is. */
2256
+ const lapsed = (run, now, after = leaseMs) => {
2257
+ if (run.deadlineAt && run.deadlineAt.getTime() <= now.getTime()) return "deadline_exceeded";
2258
+ if (after !== void 0 && now.getTime() >= (run.heartbeatAt ?? run.startedAt).getTime() + after) return "lease_expired";
2259
+ return null;
2260
+ };
2261
+ /** Store time (epoch ms) at which a running run stops being live under `leaseMs`. */
2262
+ const liveUntil = (run) => Math.min((run.heartbeatAt ?? run.startedAt).getTime() + (leaseMs ?? Infinity), run.deadlineAt?.getTime() ?? Infinity);
2263
+ const listBindings = async () => typeof options.bindings === "function" ? await options.bindings() : options.bindings;
2264
+ const storageAndImporters = async () => {
2265
+ const storage = await writer.getStorage();
2266
+ const importers = storage.importers;
2267
+ if (!importers || !storage.getCapabilities().supportsTransactions) throw new KnowledgeImporterHostError("This Knowledge storage adapter does not support importers.", 501);
2268
+ return {
2269
+ storage,
2270
+ importers
2271
+ };
2272
+ };
2273
+ const bindingFor = async (bindingId) => {
2274
+ const binding = (await listBindings()).find((b) => b.id === bindingId);
2275
+ if (!binding) throw new KnowledgeImporterHostError(`No importer binding "${bindingId}".`, 404);
2276
+ return binding;
2277
+ };
2278
+ const runEmbeds = async (storage, jobs) => {
2279
+ const semantic = writer.semantic;
2280
+ if (!semantic) return;
2281
+ for (const job of jobs) try {
2282
+ if (job.kind === "remove") {
2283
+ await semantic.removePage(job.pageId);
2284
+ continue;
2285
+ }
2286
+ let indexed = 0;
2287
+ for (let round = 0; round < MAX_REINDEX_ROUNDS; round++) {
2288
+ const page = await storage.getPage({
2289
+ id: job.pageId,
2290
+ read: "all"
2291
+ });
2292
+ if (!page || page.deletedAt || page.version <= indexed) break;
2293
+ await semantic.indexPage(page);
2294
+ indexed = page.version;
2295
+ }
2296
+ } catch (error) {
2297
+ writer.warn(`Knowledge importer: indexing page ${job.pageId} failed after commit: ${String(error)}`);
2298
+ }
2299
+ };
2300
+ /**
2301
+ * Ends the binding's running run when its runner is gone (O3 §D): past its deadline, or no
2302
+ * heartbeat within `staleRunAfterMs`. Called under the writer guard and registration lock; the run row is
2303
+ * locked and rechecked so a heartbeat that commits first keeps it alive. Its runner's later
2304
+ * flushes and finish are refused as `run_not_active`; exact replays still return receipts.
2305
+ */
2306
+ const staleAfter = leaseMs ?? options.staleRunAfterMs ?? DEFAULT_STALE_RUN_AFTER_MS;
2307
+ /** Ends `run` if it isn't live; the caller holds the guard and the run's lock. */
2308
+ const expireLocked = async (importers, run) => {
2309
+ const why = lapsed(run, await clock(importers), staleAfter);
2310
+ if (!why) return false;
2311
+ const finish = hostFinish(run, leaseMs !== void 0 ? why : "stopped");
2312
+ await importers.abandonRun({
2313
+ runId: run.id,
2314
+ finish,
2315
+ status: finish.outcome === "canceled" ? "canceled" : "failed"
2316
+ });
2317
+ return true;
2318
+ };
2319
+ const reclaimStaleRuns = async (importers, bindingId) => {
2320
+ for (const candidate of await importers.listRuns(bindingId)) {
2321
+ if (candidate.status !== "running") continue;
2322
+ const run = await importers.lockRun(candidate.id);
2323
+ if (!run || run.status !== "running") continue;
2324
+ await expireLocked(importers, run);
2325
+ }
2326
+ };
2327
+ /**
2328
+ * Counts a settle flush that timed out, outside its rolled-back transaction. Best effort, and
2329
+ * only for a run still live by the same checks a flush passes: same generation, not canceled, not
2330
+ * past its lease or deadline. Under a lease the write is also bounded by where the locked run
2331
+ * stops being live, so a timeout caused by the lease ending never writes after it.
2332
+ */
2333
+ const countSettleTimeout = async (runId, generation) => {
2334
+ try {
2335
+ const { storage } = await storageAndImporters();
2336
+ const fenced = leaseMs !== void 0 && storage.getCapabilities().enforcesTransactionDeadline === true;
2337
+ let deadlineAt = Date.now() + SETTLE_TIMEOUT_RECORD_MS;
2338
+ for (let attempt = 1; attempt <= MAX_LEASE_BOUND_ATTEMPTS; attempt++) try {
2339
+ await storage.transaction(async (tx) => {
2340
+ const importers = tx.importers;
2341
+ const guard = await importers.lockWriterGuard("share");
2342
+ const run = await importers.lockRun(runId);
2343
+ if (!run || run.status !== "running" || run.cancelRequestedAt) return;
2344
+ if (run.generation !== generation || guard.generation !== generation) return;
2345
+ if (lapsed(run, await clock(importers))) return;
2346
+ if (fenced) {
2347
+ const cutoff = await localTimeOf(importers, liveUntil(run));
2348
+ if (cutoff < deadlineAt) throw new LeaseCutoff(cutoff);
2349
+ }
2350
+ const n = settleTimeouts(await importers.getState(run.bindingId), runId) + 1;
2351
+ await importers.setState(run.bindingId, { [SETTLE_TIMEOUTS_KEY]: `${runId}:${n}` });
2352
+ }, { deadlineAt });
2353
+ return;
2354
+ } catch (error) {
2355
+ if (!(error instanceof LeaseCutoff)) throw error;
2356
+ deadlineAt = error.cutoff - LEASE_CUTOFF_MARGIN_MS;
2357
+ if (deadlineAt <= Date.now()) return;
2358
+ }
2359
+ } catch (error) {
2360
+ writer.warn(`Knowledge importer: recording a settle timeout for run ${runId} failed: ${String(error)}`);
2361
+ }
2362
+ };
2363
+ return {
2364
+ async startRun(bindingId, start) {
2365
+ const binding = await bindingFor(bindingId);
2366
+ const runId = start?.runId ?? randomUUID();
2367
+ const claimed = start?.admit !== void 0 || start?.generation !== void 0;
2368
+ try {
2369
+ const { scope } = parseKnowledgeImportTarget(binding.target);
2370
+ const { storage, importers: rootImporters } = await storageAndImporters();
2371
+ let exclusive = !(await rootImporters.readWriterGuard()).firstWriteAt;
2372
+ await writer.runtime.resolve();
2373
+ const attempt = () => storage.transaction(async (tx) => {
2374
+ const importers = tx.importers;
2375
+ const guard = await importers.lockWriterGuard(exclusive ? "update" : "share");
2376
+ if (claimed && (guard.activePath !== "new" || start?.generation !== void 0 && guard.generation !== start.generation)) throw conflict("stale_generation", "The claim belongs to another writer generation or write path.");
2377
+ await importers.registerBinding({
2378
+ id: binding.id,
2379
+ importer: binding.importer,
2380
+ target: binding.target
2381
+ });
2382
+ await reclaimStaleRuns(importers, binding.id);
2383
+ if (start?.admit) try {
2384
+ await start.admit(tx);
2385
+ } catch (error) {
2386
+ throw new AdmitRefusal(error);
2387
+ }
2388
+ const { wrote } = await writer.runtime.materializeScopeIn(tx, scope, { author: author(binding) });
2389
+ if (wrote && !guard.firstWriteAt) {
2390
+ if (!exclusive) throw new NeedsExclusiveGuard();
2391
+ await importers.markFirstWrite();
2392
+ }
2393
+ const run = await importers.startRun({
2394
+ bindingId: binding.id,
2395
+ runId,
2396
+ generation: guard.generation,
2397
+ ...start?.fireKey !== void 0 ? { fireKey: start.fireKey } : {},
2398
+ ...start?.deadline !== void 0 ? { deadlineAt: new Date(start.deadline) } : {}
2399
+ });
2400
+ if (run.status !== "started" && start?.admit) throw new SkippedClaim(run.run.id);
2401
+ const saved = run.status === "started" ? await importers.getState(binding.id) : {};
2402
+ return {
2403
+ run,
2404
+ state: Object.fromEntries(Object.entries(saved).filter(([key]) => !key.startsWith(RESERVED_STATE_PREFIX)))
2405
+ };
2406
+ });
2407
+ let result;
2408
+ try {
2409
+ result = await attempt();
2410
+ } catch (error) {
2411
+ if (!(error instanceof NeedsExclusiveGuard)) throw error;
2412
+ exclusive = true;
2413
+ result = await attempt();
2414
+ }
2415
+ if (result.run.status !== "started") return {
2416
+ status: "skipped",
2417
+ runId: result.run.run.id
2418
+ };
2419
+ return {
2420
+ status: "started",
2421
+ runId: result.run.run.id,
2422
+ generation: result.run.run.generation,
2423
+ state: result.state,
2424
+ lastSeq: result.run.run.lastSeq,
2425
+ binding
2426
+ };
2427
+ } catch (error) {
2428
+ if (error instanceof SkippedClaim) return {
2429
+ status: "skipped",
2430
+ runId: error.runId
2431
+ };
2432
+ if (error?.name === "KnowledgeImporterBindingConflictError") throw new KnowledgeImporterHostError(`Importer binding "${binding.id}" was recorded with another importer or target.`, 409);
2433
+ if (error instanceof TypeError) throw new KnowledgeImporterHostError(error.message, 400);
2434
+ if (error instanceof AdmitRefusal) throw error.refusal;
2435
+ throw hostError(error);
2436
+ }
2437
+ },
2438
+ async flush(flush) {
2439
+ let body;
2440
+ try {
2441
+ body = parseKnowledgeImporterFlushBody(flush);
2442
+ } catch (error) {
2443
+ throw new KnowledgeImporterHostError(`Malformed flush: ${error.message}`, 400);
2444
+ }
2445
+ const reserved = Object.keys(body.state ?? {}).find((key) => key.startsWith(RESERVED_STATE_PREFIX));
2446
+ if (reserved !== void 0) throw new KnowledgeImporterHostError(`Malformed flush: state key "${reserved}" is reserved for the host.`, 400);
2447
+ const digest = await knowledgeImporterFlushDigest(body);
2448
+ if (digest !== flush.digest) throw conflict("digest_mismatch", "The digest does not match the flush content.");
2449
+ const { storage, importers: rootImporters } = await storageAndImporters();
2450
+ const budgetAt = Date.now() + (options.flushBudgetMs ?? DEFAULT_FLUSH_BUDGET_MS);
2451
+ const replayed = await storage.transaction((tx) => tx.importers.getFlush(flush.runId, flush.generation, flush.seq), { deadlineAt: budgetAt }).catch((error) => {
2452
+ throw hostError(error);
2453
+ });
2454
+ if (replayed) {
2455
+ if (replayed.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
2456
+ return replayed.receipt;
2457
+ }
2458
+ const [peek, peekRun] = await Promise.all([rootImporters.readWriterGuard(), rootImporters.getRun(flush.runId)]).catch((error) => {
2459
+ throw hostError(error);
2460
+ });
2461
+ if (leaseMs === void 0 && peekRun?.deadlineAt && peekRun.deadlineAt.getTime() <= Date.now()) throw conflict("run_not_active", "The run is past its deadline.");
2462
+ const resolvedAuthor = peekRun ? await bindingFor(peekRun.bindingId).then((binding) => ({ author: author(binding) })).catch((error) => ({ error })) : { error: conflict("run_not_active", "The run is not running.") };
2463
+ let deadlineAt = Math.min(budgetAt, peekRun?.deadlineAt?.getTime() ?? Infinity);
2464
+ const fenced = leaseMs !== void 0 && storage.getCapabilities().enforcesTransactionDeadline === true;
2465
+ if (fenced && peekRun) {
2466
+ const cutoff = await localTimeOf(rootImporters, liveUntil(peekRun)).catch((error) => {
2467
+ throw hostError(error);
2468
+ });
2469
+ if (cutoff > Date.now()) deadlineAt = Math.min(deadlineAt, cutoff);
2470
+ }
2471
+ let embeds = [];
2472
+ let settling = false;
2473
+ try {
2474
+ const write = (deadlineAt) => storage.transaction(async (tx) => {
2475
+ const importers = tx.importers;
2476
+ const guard = await importers.lockWriterGuard(peek.firstWriteAt ? "share" : "update");
2477
+ const run = await importers.lockRun(flush.runId);
2478
+ const stored = await importers.getFlush(flush.runId, flush.generation, flush.seq);
2479
+ if (stored) {
2480
+ if (stored.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
2481
+ return stored.receipt;
2482
+ }
2483
+ if (!run || run.status !== "running") throw conflict("run_not_active", "The run is not running.");
2484
+ if (run.generation !== flush.generation || guard.generation !== flush.generation) throw conflict("stale_generation", "The run belongs to an older writer generation.");
2485
+ if (run.cancelRequestedAt) throw conflict("run_not_active", "The run was canceled.");
2486
+ if (lapsed(run, await clock(importers))) throw conflict("run_not_active", "The run is past its lease or deadline.");
2487
+ if (fenced) {
2488
+ const cutoff = await localTimeOf(importers, liveUntil(run));
2489
+ if (cutoff < deadlineAt) throw new LeaseCutoff(cutoff);
2490
+ }
2491
+ if (flush.seq !== run.lastSeq + 1) throw conflict("seq_mismatch", "The flush seq is not the committed seq + 1.");
2492
+ if ("error" in resolvedAuthor) throw resolvedAuthor.error;
2493
+ const binding = await importers.getBinding(run.bindingId);
2494
+ if (!binding) throw conflict("run_not_active", "The run has no binding.");
2495
+ const [scope] = await tx.getScopesByAddress([parseKnowledgeImportTarget(binding.target).scope]);
2496
+ if (!scope) throw new KnowledgeImporterHostError("The binding target scope does not exist.", 503);
2497
+ const hostState = await importers.getState(binding.id);
2498
+ const timeouts = settleTimeouts(hostState, run.id);
2499
+ const restart = hostState["mastra:settle:restart"] ?? "";
2500
+ const restarting = restart !== (hostState["mastra:settle:seen"] ?? "");
2501
+ const applied = await applyKnowledgeImportFlush({
2502
+ storage: tx,
2503
+ importers,
2504
+ binding,
2505
+ scope,
2506
+ runId: run.id,
2507
+ ops: body.ops,
2508
+ provenance: { author: resolvedAuthor.author },
2509
+ ...timeouts < SETTLE_MAX_TIMEOUTS ? { settle: {
2510
+ after: restarting ? null : hostState[SETTLE_CURSOR_KEY] || null,
2511
+ candidates: Math.max(1, SETTLE_CANDIDATES >> timeouts),
2512
+ moves: SETTLE_MOVES,
2513
+ until: Math.min(Date.now() + (options.settleBudgetMs ?? DEFAULT_SETTLE_BUDGET_MS), deadlineAt),
2514
+ onStart: () => {
2515
+ settling = true;
2516
+ }
2517
+ } } : {}
2518
+ });
2519
+ const settled = applied.settle;
2520
+ const hostUpdates = {};
2521
+ if (settled && (settled.cursor ?? "") !== (hostState[SETTLE_CURSOR_KEY] ?? "")) hostUpdates[SETTLE_CURSOR_KEY] = settled.cursor ?? "";
2522
+ if (timeouts > 0 && timeouts < SETTLE_MAX_TIMEOUTS) hostUpdates[SETTLE_TIMEOUTS_KEY] = "";
2523
+ if (restarting && settled?.fromStart) hostUpdates[KNOWLEDGE_IMPORT_SETTLE_SEEN_KEY] = restart;
2524
+ const state = {
2525
+ ...body.state,
2526
+ ...hostUpdates
2527
+ };
2528
+ if (Object.keys(state).length) await importers.setState(binding.id, state);
2529
+ for (const change of applied.changes) await importers.recordRunChange({
2530
+ runId: run.id,
2531
+ ...change
2532
+ });
2533
+ const receipt = {
2534
+ seq: flush.seq,
2535
+ ...applied.counts,
2536
+ refused: applied.refused,
2537
+ pending: settled?.pending ?? false
2538
+ };
2539
+ await importers.recordFlush({
2540
+ runId: run.id,
2541
+ generation: flush.generation,
2542
+ seq: flush.seq,
2543
+ digest,
2544
+ receipt,
2545
+ counts: {
2546
+ ...applied.counts,
2547
+ refused: applied.refused.length,
2548
+ settled: settled?.settled ?? 0
2549
+ }
2550
+ });
2551
+ if (applied.applied && !guard.firstWriteAt) await importers.markFirstWrite();
2552
+ embeds = applied.embeds;
2553
+ return receipt;
2554
+ }, { deadlineAt });
2555
+ let receipt;
2556
+ for (let attempt = 1; receipt === void 0; attempt++) try {
2557
+ receipt = await write(deadlineAt);
2558
+ } catch (error) {
2559
+ if (!(error instanceof LeaseCutoff)) throw error;
2560
+ if (attempt >= MAX_LEASE_BOUND_ATTEMPTS) throw new KnowledgeImporterHostError("The flush could not be bounded by its run lease; resend it.", 503);
2561
+ deadlineAt = Math.min(budgetAt, error.cutoff - LEASE_CUTOFF_MARGIN_MS);
2562
+ }
2563
+ await runEmbeds(storage, embeds);
2564
+ return receipt;
2565
+ } catch (error) {
2566
+ if (settling && timedOut(error)) await countSettleTimeout(flush.runId, flush.generation);
2567
+ throw hostError(error);
2568
+ }
2569
+ },
2570
+ async heartbeat(runId, generation) {
2571
+ try {
2572
+ const { storage, importers } = await storageAndImporters();
2573
+ if (leaseMs === void 0) {
2574
+ const run = await importers.heartbeat(runId);
2575
+ return { cancel: !run || run.generation !== generation || run.cancelRequestedAt !== null };
2576
+ }
2577
+ return await storage.transaction(async (tx) => {
2578
+ const locked = tx.importers;
2579
+ const guard = await locked.lockWriterGuard("share");
2580
+ const run = await locked.lockRun(runId);
2581
+ if (!run || run.status !== "running") throw conflict("run_not_active", "The run is not running.");
2582
+ if (run.generation !== generation || guard.generation !== generation) throw conflict("stale_generation", "The run belongs to an older writer generation.");
2583
+ if (lapsed(run, await clock(locked))) throw conflict("run_not_active", "The run is past its lease or deadline.");
2584
+ if (run.cancelRequestedAt) return { cancel: true };
2585
+ await locked.heartbeat(runId);
2586
+ return { cancel: false };
2587
+ });
2588
+ } catch (error) {
2589
+ throw hostError(error);
2590
+ }
2591
+ },
2592
+ async requestCancel(runId) {
2593
+ const { storage } = await storageAndImporters();
2594
+ try {
2595
+ return await storage.transaction(async (tx) => {
2596
+ const importers = tx.importers;
2597
+ await importers.lockWriterGuard("share");
2598
+ const run = await importers.lockRun(runId);
2599
+ if (!run) return null;
2600
+ if (run.status !== "running") return { status: run.status };
2601
+ await importers.requestCancel(runId);
2602
+ return { status: run.status };
2603
+ });
2604
+ } catch (error) {
2605
+ throw hostError(error);
2606
+ }
2607
+ },
2608
+ async retireBinding(bindingId) {
2609
+ const { storage } = await storageAndImporters();
2610
+ try {
2611
+ await storage.transaction(async (tx) => {
2612
+ await tx.importers.lockWriterGuard("share");
2613
+ await tx.importers.retireBinding(bindingId);
2614
+ });
2615
+ } catch (error) {
2616
+ throw hostError(error);
2617
+ }
2618
+ },
2619
+ async expireRuns() {
2620
+ const { storage, importers: root } = await storageAndImporters();
2621
+ const expired = [];
2622
+ try {
2623
+ const candidates = [];
2624
+ for (const stored of await root.listBindings()) for (const run of await root.listRuns(stored.id)) if (run.status === "running") candidates.push(run.id);
2625
+ for (const runId of candidates) if (await storage.transaction(async (tx) => {
2626
+ const importers = tx.importers;
2627
+ await importers.lockWriterGuard("share");
2628
+ const run = await importers.lockRun(runId);
2629
+ return !!run && run.status === "running" && await expireLocked(importers, run);
2630
+ })) expired.push(runId);
2631
+ return { expired };
2632
+ } catch (error) {
2633
+ throw hostError(error);
2634
+ }
2635
+ },
2636
+ async readRun(runId) {
2637
+ const { importers } = await storageAndImporters();
2638
+ const run = await importers.getRun(runId);
2639
+ if (!run) return null;
2640
+ return {
2641
+ status: run.status,
2642
+ receipt: run.status === "running" || !run.finish ? null : runReceipt(run)
2643
+ };
2644
+ },
2645
+ async finishRun(request) {
2646
+ let normalized;
2647
+ try {
2648
+ normalized = normalizeKnowledgeImporterFinish(request);
2649
+ } catch (error) {
2650
+ throw new KnowledgeImporterHostError(`Malformed finish: ${error.message}`, 400);
2651
+ }
2652
+ const { storage } = await storageAndImporters();
2653
+ try {
2654
+ return await storage.transaction(async (tx) => {
2655
+ const importers = tx.importers;
2656
+ const guard = await importers.lockWriterGuard("share");
2657
+ const run = await importers.lockRun(request.runId);
2658
+ if (!run) throw conflict("run_not_active", "No such run.");
2659
+ if (run.finish !== null) {
2660
+ if (run.finish.by === "host") throw conflict("run_not_active", "The host ended the run.");
2661
+ if (run.generation === request.generation && canonicalJson(replayIdentity(run.finish)) === canonicalJson(normalized)) return runReceipt(run);
2662
+ throw conflict("finish_mismatch", "The run already finished differently.");
2663
+ }
2664
+ if (run.status !== "running") throw conflict("run_not_active", "The run is not running.");
2665
+ if (run.generation !== request.generation || guard.generation !== request.generation) throw conflict("stale_generation", "The run belongs to an older writer generation.");
2666
+ if (leaseMs !== void 0 && lapsed(run, await clock(importers))) throw conflict("run_not_active", "The run is past its lease or deadline.");
2667
+ if (run.lastSeq !== request.lastSeq) throw conflict("seq_mismatch", "lastSeq is not the committed seq.");
2668
+ if (run.cancelRequestedAt) {
2669
+ const canceled = await importers.finishRun({
2670
+ runId: run.id,
2671
+ generation: request.generation,
2672
+ lastSeq: request.lastSeq,
2673
+ status: "canceled",
2674
+ finish: {
2675
+ ...normalized,
2676
+ chain: false,
2677
+ canceled: true
2678
+ }
2679
+ });
2680
+ return runReceipt(canceled);
2681
+ }
2682
+ const pending = ((run.lastSeq > 0 ? await importers.getFlush(run.id, run.generation, run.lastSeq) : null)?.receipt)?.pending === true;
2683
+ const binding = await importers.getBinding(run.bindingId);
2684
+ const gaveUp = !!binding && settleTimeouts(await importers.getState(binding.id), run.id) >= SETTLE_MAX_TIMEOUTS;
2685
+ const chain = normalized.backlog || normalized.outcome === "succeeded" && pending && !gaveUp && (run.counts.settled ?? 0) > 0;
2686
+ const finished = await importers.finishRun({
2687
+ runId: run.id,
2688
+ generation: request.generation,
2689
+ lastSeq: request.lastSeq,
2690
+ status: normalized.outcome,
2691
+ finish: {
2692
+ ...normalized,
2693
+ chain
2694
+ }
2695
+ });
2696
+ return runReceipt(finished);
2697
+ });
2698
+ } catch (error) {
2699
+ throw hostError(error);
2700
+ }
2701
+ }
2702
+ };
2703
+ }
113
2704
  // src/knowledge/reembed.ts
114
2705
  const DEFAULT_LIMIT = 50;
115
2706
  const MAX_LIMIT = 500;
@@ -623,6 +3214,23 @@ var KnowledgeScopeRuntime = class {
623
3214
  return this.#materialize(address, principals, provenance, [], { held: this.#held(principals) });
624
3215
  }
625
3216
  /**
3217
+ * {@link materializeScope} through `storage`, a transaction view, so the scope's rows commit or
3218
+ * roll back with the caller's transaction. Declarations must already be resolved
3219
+ * ({@link resolve}): nothing here reads the runtime's own storage, so a one-connection pool
3220
+ * can't deadlock against the open transaction. `wrote` is false only when no row can have changed.
3221
+ */
3222
+ async materializeScopeIn(storage, address, provenance) {
3223
+ const run = {
3224
+ held: this.#held([]),
3225
+ storage,
3226
+ wrote: false
3227
+ };
3228
+ return {
3229
+ scope: await this.#materialize(address, [], provenance, [], run),
3230
+ wrote: run.wrote === true
3231
+ };
3232
+ }
3233
+ /**
626
3234
  * {@link materializeScope} for each address in turn (a write-run start's principals), reading
627
3235
  * scopes from one lookup. `#materialize` skips the store call for a scope that exists, needs no new
628
3236
  * `belongsTo` link, has its child scopes and declares no template pages; warnings fire as before.
@@ -676,7 +3284,7 @@ var KnowledgeScopeRuntime = class {
676
3284
  const match = this.compiled.match(address);
677
3285
  if (!match) throw new KnowledgeDeclarationError(`Knowledge scope "${address}" does not match a declared scope type.`);
678
3286
  if (ancestors.includes(address)) throw new KnowledgeDeclarationError(`Knowledge scope placement cycle at "${address}".`);
679
- const storage = await this.getStorage();
3287
+ const storage = run.storage ?? await this.getStorage();
680
3288
  const known = run.known;
681
3289
  const lookUp = async (scope) => known?.looked.has(scope) || known?.byAddress.has(scope) ? known.byAddress.get(scope) : (await storage.getScopesByAddress([scope]))[0];
682
3290
  if (match.compiled.child) {
@@ -709,6 +3317,7 @@ var KnowledgeScopeRuntime = class {
709
3317
  }
710
3318
  const declaration = match.compiled.declaration;
711
3319
  if (known && existing && parentId === existing.parentId && !declaration.pages?.length && match.compiled.children.every((child) => known.byAddress.has(`${address}/${child.child.name}`))) return existing;
3320
+ const templateCount = declaration.pages?.length ?? 0;
712
3321
  const result = await storage.materializeScope({
713
3322
  address,
714
3323
  declaration: match.declaration,
@@ -725,6 +3334,7 @@ var KnowledgeScopeRuntime = class {
725
3334
  provenance
726
3335
  });
727
3336
  this.#assertCurrent(result.scope);
3337
+ if (!existing || result.created || templateCount > 0 || match.compiled.children.length > 0 || result.scope.parentId !== existing.parentId) run.wrote = true;
728
3338
  if (result.created) await updateKnowledgeLinks(this.warn, () => refreshKnowledgeLinksTo(storage, [result.scope], { withDescendants: true }));
729
3339
  if (result.parentConflict) this.warn(`Knowledge scope "${address}" was already linked by another run; keeping its persisted parent.`);
730
3340
  if (run.known) {
@@ -1284,6 +3894,8 @@ async function readKnowledgePageLinks(store, input) {
1284
3894
  };
1285
3895
  }
1286
3896
  // src/knowledge/index.ts
3897
+ /** Reads a Knowledge's host writer for {@link createKnowledgeImporterHost}; set in the class's static block. */
3898
+ let hostWriterOf;
1287
3899
  function resolvePins(pins) {
1288
3900
  if (!pins) return false;
1289
3901
  const options = pins === true ? {} : pins;
@@ -1306,6 +3918,7 @@ var Knowledge = class extends MastraBase {
1306
3918
  #tools;
1307
3919
  #pins;
1308
3920
  #instructions;
3921
+ #importers;
1309
3922
  #semantic;
1310
3923
  #listeners = /* @__PURE__ */ new Set();
1311
3924
  /** Config pins are never dropped, so a scope with more of them than the budget holds is a setup mistake. */
@@ -1339,6 +3952,15 @@ var Knowledge = class extends MastraBase {
1339
3952
  if (maxTokens !== void 0 && (!Number.isInteger(maxTokens) || maxTokens < 100)) throw new Error(`Knowledge \`tools.read.maxTokens\` must be a whole number of at least 100; got ${maxTokens}.`);
1340
3953
  this.#pins = resolvePins(config.pinnedContext);
1341
3954
  this.#instructions = config.instructions;
3955
+ if (config.importers) {
3956
+ knowledgeImporterRegistry(config.importers.map((importer) => importer.constructor));
3957
+ const ids = /* @__PURE__ */ new Set();
3958
+ for (const importer of config.importers) {
3959
+ if (ids.has(importer.binding.id)) throw new KnowledgeImporterDefinitionError(`Two importers have the binding id "${importer.binding.id}".`);
3960
+ ids.add(importer.binding.id);
3961
+ }
3962
+ }
3963
+ this.#importers = config.importers;
1342
3964
  if (Boolean(config.vector) !== Boolean(config.embedder)) throw new Error("Knowledge semantic search needs both `vector` and `embedder`; pass both or neither.");
1343
3965
  if (config.vector && config.embedder) this.#semantic = new KnowledgeSemanticIndex(config.vector, config.embedder, config.embedderOptions);
1344
3966
  this.#runtime = new KnowledgeScopeRuntime(config.scopes, () => this.getStorage(), (message) => this.logger.warn(message));
@@ -1373,10 +3995,22 @@ var Knowledge = class extends MastraBase {
1373
3995
  return this.#runtime.explainAccess(runScopes, target);
1374
3996
  }
1375
3997
  /**
3998
+ * Reads the store's scope declarations into the ones {@link scopeGrants}, {@link scopeDeclaration}
3999
+ * and {@link scopeLabel} use, reusing a read from the last 30 seconds. Call it before those when
4000
+ * nothing else async ran first, e.g. at the start of a browsing request. Checks nothing and grants
4001
+ * nothing.
4002
+ *
4003
+ * @experimental
4004
+ */
4005
+ async resolveScopeDeclarations() {
4006
+ await this.#runtime.resolve();
4007
+ }
4008
+ /**
1376
4009
  * Who the declared rules give a role on one scope: each principal scope address (bound for this
1377
4010
  * scope's params) with its strongest role, `self` rules left out. `parentAddress` is the
1378
4011
  * address of the scope page's tree parent, needed for rules that bind through `belongsTo`. Reads the
1379
- * declarations as last resolved, not storage. For browsing UIs that draw access between scopes.
4012
+ * declarations as last resolved, not storage (see {@link Knowledge.resolveScopeDeclarations}). For
4013
+ * browsing UIs that draw access between scopes.
1380
4014
  *
1381
4015
  * @experimental
1382
4016
  */
@@ -1448,7 +4082,8 @@ var Knowledge = class extends MastraBase {
1448
4082
  * Deletes the page at `scope#path`; `null` when there is none. Refuses a page with child pages
1449
4083
  * and a page declared in config. Host-only, like {@link Knowledge.upsertPage}. Not retried: a
1450
4084
  * concurrent write to the same page between the read and the delete throws, so remove from one
1451
- * sync worker or retry the call.
4085
+ * sync worker or retry the call. Pass `expected` to delete only the page you read, at the version
4086
+ * you read: anything else at the path throws `KnowledgeConflictError` and nothing is deleted.
1452
4087
  *
1453
4088
  * @experimental
1454
4089
  */
@@ -1497,6 +4132,30 @@ var Knowledge = class extends MastraBase {
1497
4132
  removeNote(input) {
1498
4133
  return removeKnowledgeNote(this.#hostWriter(), input);
1499
4134
  }
4135
+ /**
4136
+ * The app's importers: `host` applies flushes to this Knowledge's storage, and `run` runs one
4137
+ * binding's importer through it. Undefined without `importers` in the config. Host-only, like
4138
+ * {@link Knowledge.upsertPage}: never expose `run` without admin-level auth.
4139
+ *
4140
+ * @experimental
4141
+ */
4142
+ get importers() {
4143
+ const importers = this.#importers;
4144
+ if (!importers) return void 0;
4145
+ const host = createKnowledgeImporterHost(this, { bindings: importers.map((importer) => importer.binding) });
4146
+ return {
4147
+ host,
4148
+ run: (bindingId, options) => runKnowledgeImport({
4149
+ ...options,
4150
+ importers,
4151
+ host,
4152
+ bindingId
4153
+ })
4154
+ };
4155
+ }
4156
+ static {
4157
+ hostWriterOf = (knowledge) => knowledge.#hostWriter();
4158
+ }
1500
4159
  #hostWriter() {
1501
4160
  return {
1502
4161
  runtime: this.#runtime,
@@ -1539,6 +4198,14 @@ var Knowledge = class extends MastraBase {
1539
4198
  get pinnedContextEnabled() {
1540
4199
  return this.#pins !== false;
1541
4200
  }
4201
+ /** Which tool groups `createTools()` and `getInstructions()` include by default. @internal */
4202
+ get __toolGroups() {
4203
+ const { read, write } = this.#groups();
4204
+ return {
4205
+ read,
4206
+ write
4207
+ };
4208
+ }
1542
4209
  /** The run's principals as a stable key; throws when the run has none or holds an undeclared scope. @internal */
1543
4210
  __principalsKey(context) {
1544
4211
  return knowledgeRunPrincipals(this.#runtime, context).sort().join("\n");
@@ -1546,14 +4213,15 @@ var Knowledge = class extends MastraBase {
1546
4213
  /**
1547
4214
  * The pinned pages a host-run caller with these principals receives, rendered as an agent run
1548
4215
  * receives them: only pages they can read, within this instance's pin budget. For hosts that serve
1549
- * Knowledge outside an agent run, alongside {@link Knowledge.createTools} with `principals`.
4216
+ * Knowledge outside an agent run, alongside {@link Knowledge.createTools} with `principals`. Pass the
4217
+ * same `read` as that `createTools` call, so entries name read tools only when the caller has them.
1550
4218
  */
1551
4219
  async getPinnedContext(options) {
1552
4220
  const principals = this.#hostPrincipals(options.principals);
1553
4221
  const budget = this.#pins || resolvePins(true);
1554
4222
  if (!budget) return [];
1555
4223
  const run = await KnowledgeRun.start(this.#runtime, await this.getStorage(), void 0, { principals });
1556
- return knowledgeDeliveredPins(run, budget);
4224
+ return knowledgeDeliveredPins(run, budget, this.#groups({ read: options.read }).read);
1557
4225
  }
1558
4226
  #hostPrincipals(principals) {
1559
4227
  const unique = [...new Set(principals)];
@@ -1565,7 +4233,7 @@ var Knowledge = class extends MastraBase {
1565
4233
  const budget = this.#pins || resolvePins(true);
1566
4234
  if (!budget) return [];
1567
4235
  const run = await KnowledgeRun.start(this.#runtime, await this.getStorage(), context);
1568
- return knowledgeDeliveredPins(run, budget);
4236
+ return knowledgeDeliveredPins(run, budget, this.#groups().read);
1569
4237
  }
1570
4238
  /** @internal */
1571
4239
  __registerMastra(_mastra) {}
@@ -1636,7 +4304,8 @@ var Knowledge = class extends MastraBase {
1636
4304
  /**
1637
4305
  * The declaration a scope page was created from, by its `declaration` key (template children
1638
4306
  * included, e.g. `account:$orgId:$accountId/internal`), for display. Access rules are left out;
1639
- * use `explainAccess` for those. `undefined` for an unknown key.
4307
+ * use `explainAccess` for those. `undefined` for an unknown key. Reads the declarations as last
4308
+ * resolved, not storage; see {@link Knowledge.resolveScopeDeclarations}.
1640
4309
  */
1641
4310
  scopeDeclaration(key) {
1642
4311
  const compiled = this.#runtime.compiled.declarations.get(key);
@@ -1660,6 +4329,7 @@ var Knowledge = class extends MastraBase {
1660
4329
  * declaration's `$params` filled in from the address's decoded values: `'$orgId policy'` on
1661
4330
  * `policy:$orgId` gives `'acme policy'` for `policy:acme`. A concrete address's own `displayLabel`
1662
4331
  * wins over its pattern's. `undefined` when the address matches no declaration or has no label.
4332
+ * Reads the declarations as last resolved, like {@link Knowledge.scopeDeclaration}.
1663
4333
  */
1664
4334
  scopeLabel(address) {
1665
4335
  const match = this.#runtime.compiled.match(address);
@@ -1668,4 +4338,17 @@ var Knowledge = class extends MastraBase {
1668
4338
  return label.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, (token, name) => Object.hasOwn(match.params, name) ? match.params[name] : token);
1669
4339
  }
1670
4340
  };
1671
- export { DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS, InMemoryKnowledgeStorage, KNOWLEDGE_STORAGE_CONTRACT_VERSION, KNOWLEDGE_STORAGE_SCHEMA_VERSION, Knowledge, KnowledgeConflictError, KnowledgeDeclarationError, KnowledgeMoveTooLargeError, KnowledgeNotFoundError, KnowledgePageDepthError, KnowledgePageHasChildrenError, KnowledgePageKeyConflictError, KnowledgeSchemaResetRequiredError, KnowledgeStorage, KnowledgeUnsupportedCapabilityError, MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS, MAX_KNOWLEDGE_LINK_COUNT_PAGES, MAX_KNOWLEDGE_MOVE_PAGES, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, MAX_KNOWLEDGE_NOTE_TOKENS, MAX_KNOWLEDGE_PAGE_BODY_LINKS, MAX_KNOWLEDGE_PAGE_DEPTH, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, MAX_KNOWLEDGE_PAGE_LINKS, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, MAX_KNOWLEDGE_PAGE_LIST_LIMIT, MAX_KNOWLEDGE_PIN_LIST_DEPTH, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, MAX_KNOWLEDGE_SCOPE_TAGS, assertKnowledgeCeilingRaised, assertKnowledgeDescriptionWithinBound, assertKnowledgeNoteTextWithinBound, assertKnowledgePageDescriptionWithinBound, assertKnowledgeRecordTextWithinBound, assertKnowledgeSchemaCompatible, assertKnowledgeScopeWithinCeiling, canonicalKnowledgeName, canonicalizeKnowledgeScope, createKnowledgeNodeCursor, createKnowledgeUlid, decodeKnowledgeScopeId, encodeKnowledgeScopeId, expandKnowledgeScope, inspectKnowledgeSchema, isKnowledgeScopeVisible, knowledgeLinkRefKey, knowledgeMemoryScopes, knowledgePagePath, knowledgePinDepth, knowledgePositionBetween, knowledgeScopeAddress, knowledgeScopeKey, knowledgeScopeReadable, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, knowledgeVisibleScopeKeys, listKnowledgeTreeChildren, parseKnowledgeNodeCursor, parseKnowledgePageRef, parseKnowledgeWikilinks, readKnowledgePage, readKnowledgePageActivity, readKnowledgePageGraph, readKnowledgePageLinkCounts, readKnowledgePageLinks, readKnowledgeScopeGrants, searchKnowledgeExplorerPages };
4341
+ /**
4342
+ * An importer host over this Knowledge's storage, for a host that applies flushes for bindings it
4343
+ * keeps itself and runs no importer code (a service that importers in other processes flush to).
4344
+ * Pass `bindings` as a function to read them at each run start. An app that runs its own importers
4345
+ * uses `new Knowledge({ importers: [...] })` and `knowledge.importers` instead.
4346
+ *
4347
+ * Host-only, like {@link Knowledge.upsertPage}: never expose it without admin-level auth.
4348
+ *
4349
+ * @experimental
4350
+ */
4351
+ function createKnowledgeImporterHost(knowledge, options) {
4352
+ return createLocalKnowledgeImporterHost(hostWriterOf(knowledge), options);
4353
+ }
4354
+ export { DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS, InMemoryKnowledgeStorage, KNOWLEDGE_IMPORTER_ERROR_CODES, REMOVED_PARENT_BODY as KNOWLEDGE_IMPORT_REMOVED_PARENT_BODY, KNOWLEDGE_STORAGE_CONTRACT_VERSION, KNOWLEDGE_STORAGE_SCHEMA_VERSION, Knowledge, KnowledgeConflictError, KnowledgeDeclarationError, KnowledgeImporter, KnowledgeImporterBase, KnowledgeImporterBindingConflictError, KnowledgeImporterCredentialsError, KnowledgeImporterDefinitionError, KnowledgeImporterHostConflictError, KnowledgeImporterHostError, KnowledgeImporterRunStateError, KnowledgeImporterSettingsError, KnowledgeImporterSourceError, KnowledgeImportersStorage, KnowledgeInvalidCursorError, KnowledgeMoveTooLargeError, KnowledgeNotFoundError, KnowledgePageDepthError, KnowledgePageHasChildrenError, KnowledgePageKeyConflictError, KnowledgeSchemaResetRequiredError, KnowledgeStorage, KnowledgeTransactionDeadlineError, KnowledgeUnsupportedCapabilityError, MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS, MAX_KNOWLEDGE_LINK_COUNT_PAGES, MAX_KNOWLEDGE_MOVE_PAGES, MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, MAX_KNOWLEDGE_NOTE_TOKENS, MAX_KNOWLEDGE_PAGE_BODY_LINKS, MAX_KNOWLEDGE_PAGE_DEPTH, MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, MAX_KNOWLEDGE_PAGE_LINKS, MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, MAX_KNOWLEDGE_PAGE_LIST_LIMIT, MAX_KNOWLEDGE_PIN_LIST_DEPTH, MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, MAX_KNOWLEDGE_SCOPE_TAGS, assertKnowledgeCeilingRaised, assertKnowledgeDescriptionWithinBound, assertKnowledgeNoteTextWithinBound, assertKnowledgePageDescriptionWithinBound, assertKnowledgeRecordTextWithinBound, assertKnowledgeSchemaCompatible, assertKnowledgeScopeWithinCeiling, canonicalJson, canonicalKnowledgeName, canonicalizeKnowledgeScope, createKnowledgeImporterHost, createKnowledgeNodeCursor, createKnowledgeUlid, decodeKnowledgeScopeId, encodeKnowledgeScopeId, expandKnowledgeScope, importerHostConformance, inspectKnowledgeSchema, isKnowledgeScopeVisible, knowledgeImportKey, knowledgeImporterFlushDigest, knowledgeImporterRegistry, knowledgeLinkRefKey, knowledgeMemoryScopes, knowledgePagePath, knowledgePinDepth, knowledgePositionBetween, knowledgeScopeAddress, knowledgeScopeKey, knowledgeScopeReadable, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, knowledgeVisibleScopeKeys, listKnowledgeTreeChildren, normalizeKnowledgeImporterFinish, parseKnowledgeImporterFlushBody, parseKnowledgeNodeCursor, parseKnowledgePageRef, parseKnowledgeWikilinks, readKnowledgePage, readKnowledgePageActivity, readKnowledgePageGraph, readKnowledgePageLinkCounts, readKnowledgePageLinks, readKnowledgeScopeGrants, runKnowledgeImport, searchKnowledgeExplorerPages };