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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (494) hide show
  1. package/dist/_types/@ai-sdk_openai@4.0.106/dist/index.d.ts +2034 -0
  2. package/dist/_types/@ai-sdk_openai@4.0.106/package.json +1 -0
  3. package/dist/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +49 -0
  4. package/dist/a2a/index.cjs +1 -1
  5. package/dist/a2a/index.js +1 -1
  6. package/dist/agent/agent.d.ts +3 -1
  7. package/dist/agent/durable/index.cjs +1 -1
  8. package/dist/agent/durable/index.js +1 -1
  9. package/dist/agent/durable/run-message-refs.d.ts +3 -2
  10. package/dist/agent/index.cjs +5 -4
  11. package/dist/agent/index.d.ts +2 -0
  12. package/dist/agent/index.js +5 -5
  13. package/dist/agent/merge-persona.d.ts +15 -0
  14. package/dist/agent/message-list/adapters/AIV5Adapter.d.ts +15 -1
  15. package/dist/agent/message-list/index.cjs +2 -2
  16. package/dist/agent/message-list/index.js +2 -2
  17. package/dist/agent/message-list/state/types.d.ts +5 -1
  18. package/dist/agent/message-list/types.d.ts +1 -1
  19. package/dist/agent/message-list/utils/provider-compat.d.ts +9 -1
  20. package/dist/agent-builder/ee/index.cjs +1 -1
  21. package/dist/agent-builder/ee/index.js +1 -1
  22. package/dist/agent-controller/agent-controller.d.ts +6 -0
  23. package/dist/agent-controller/index.cjs +2 -2
  24. package/dist/agent-controller/index.js +2 -2
  25. package/dist/agent-controller/session.d.ts +11 -1
  26. package/dist/agent-controller/worker-run-binding.d.ts +15 -0
  27. package/dist/{agent-controller-C1bK0CXm.js → agent-controller-BrRzZy4-.js} +66 -15
  28. package/dist/{agent-controller-BTIxiD1u.cjs → agent-controller-DKI-d-np.cjs} +66 -15
  29. package/dist/background-tasks/index.cjs +2 -1
  30. package/dist/background-tasks/index.d.ts +1 -1
  31. package/dist/background-tasks/index.js +1 -1
  32. package/dist/background-tasks/resolve-config.d.ts +30 -1
  33. package/dist/background-tasks/system-prompt.d.ts +8 -2
  34. package/dist/background-tasks/types.d.ts +47 -1
  35. package/dist/{background-tasks-BbVsBghi.js → background-tasks-CDP3Pgeu.js} +156 -33
  36. package/dist/{background-tasks-CVl6e0Jo.cjs → background-tasks-CDgdfRmB.cjs} +167 -32
  37. package/dist/browser/index.cjs +2 -2
  38. package/dist/browser/index.js +2 -2
  39. package/dist/{builder-BRJPSTig.cjs → builder-Bs4CtyqT.cjs} +2 -2
  40. package/dist/{builder-C8XzrtBQ.js → builder-DuT0Iqb5.js} +2 -2
  41. package/dist/capabilities/302ai.json +199 -199
  42. package/dist/capabilities/abliteratedllm.json +43 -34
  43. package/dist/capabilities/abliteration-ai.json +7 -7
  44. package/dist/capabilities/above.json +19 -19
  45. package/dist/capabilities/adaption.json +15 -15
  46. package/dist/capabilities/adzuki.json +27 -27
  47. package/dist/capabilities/agentrouter.json +13 -13
  48. package/dist/capabilities/agnes.json +3 -3
  49. package/dist/capabilities/ai-router.json +6 -6
  50. package/dist/capabilities/aiand.json +21 -21
  51. package/dist/capabilities/aigrow.json +12 -12
  52. package/dist/capabilities/aimlapi.json +143 -146
  53. package/dist/capabilities/aipg.json +2 -2
  54. package/dist/capabilities/aixy.json +22 -22
  55. package/dist/capabilities/aki-io.json +16 -16
  56. package/dist/capabilities/alibaba-cn.json +108 -102
  57. package/dist/capabilities/alibaba-coding-plan-cn.json +5 -5
  58. package/dist/capabilities/alibaba-coding-plan.json +5 -5
  59. package/dist/capabilities/alibaba-token-plan-cn.json +52 -52
  60. package/dist/capabilities/alibaba-token-plan.json +53 -53
  61. package/dist/capabilities/alibaba.json +98 -64
  62. package/dist/capabilities/ambient.json +17 -10
  63. package/dist/capabilities/amd.json +9 -9
  64. package/dist/capabilities/anthropic.json +45 -45
  65. package/dist/capabilities/anyapi.json +47 -47
  66. package/dist/capabilities/apiko.json +2 -2
  67. package/dist/capabilities/arcee.json +11 -11
  68. package/dist/capabilities/augure.json +6 -6
  69. package/dist/capabilities/auriko.json +20 -20
  70. package/dist/capabilities/bailing.json +4 -4
  71. package/dist/capabilities/baseten.json +33 -33
  72. package/dist/capabilities/bee.json +5 -5
  73. package/dist/capabilities/berget.json +20 -7
  74. package/dist/capabilities/bothub.json +14 -14
  75. package/dist/capabilities/boundless.json +37 -37
  76. package/dist/capabilities/bumo.json +42 -42
  77. package/dist/capabilities/byteplus.json +28 -28
  78. package/dist/capabilities/cerebras.json +4 -4
  79. package/dist/capabilities/cheapaimodel.json +7 -7
  80. package/dist/capabilities/cheapest-token.json +30 -30
  81. package/dist/capabilities/chutes.json +4 -4
  82. package/dist/capabilities/clarifai.json +2 -2
  83. package/dist/capabilities/claudinio.json +10 -1
  84. package/dist/capabilities/cline-pass.json +42 -42
  85. package/dist/capabilities/cloudcode.json +9 -16
  86. package/dist/capabilities/cloudferro-sherlock.json +4 -4
  87. package/dist/capabilities/cloudflare-workers-ai.json +14 -14
  88. package/dist/capabilities/commandcode.json +140 -140
  89. package/dist/capabilities/concentrate.json +289 -298
  90. package/dist/capabilities/cortecs.json +105 -105
  91. package/dist/capabilities/crossmodel.json +197 -197
  92. package/dist/capabilities/crusoe.json +38 -9
  93. package/dist/capabilities/daoxe.json +8 -8
  94. package/dist/capabilities/databricks.json +125 -125
  95. package/dist/capabilities/deepinfra.json +109 -94
  96. package/dist/capabilities/deepseek.json +4 -4
  97. package/dist/capabilities/digitalocean.json +112 -112
  98. package/dist/capabilities/dothoosh.json +34 -34
  99. package/dist/capabilities/doubleword.json +24 -24
  100. package/dist/capabilities/edenai.json +280 -292
  101. package/dist/capabilities/empiriolabs.json +168 -168
  102. package/dist/capabilities/engy.json +21 -21
  103. package/dist/capabilities/entrim.json +8 -8
  104. package/dist/capabilities/evroc.json +12 -12
  105. package/dist/capabilities/ezkielyna.json +8 -8
  106. package/dist/capabilities/fastrouter.json +87 -87
  107. package/dist/capabilities/fireworks-ai.json +130 -69
  108. package/dist/capabilities/fortytwo.json +9 -3
  109. package/dist/capabilities/freemodel.json +14 -14
  110. package/dist/capabilities/friendli.json +2 -2
  111. package/dist/capabilities/frogbot.json +96 -96
  112. package/dist/capabilities/gisoo.json +17 -17
  113. package/dist/capabilities/gmicloud.json +24 -24
  114. package/dist/capabilities/google.json +54 -54
  115. package/dist/capabilities/graphn.json +16 -16
  116. package/dist/capabilities/greenpt.json +35 -35
  117. package/dist/capabilities/groq.json +2 -2
  118. package/dist/capabilities/helicone.json +94 -94
  119. package/dist/capabilities/hetzner.json +35 -3
  120. package/dist/capabilities/hostinger-router.json +14 -14
  121. package/dist/capabilities/hpc-ai.json +11 -11
  122. package/dist/capabilities/huawei-maas.json +14 -14
  123. package/dist/capabilities/hubris.json +30 -30
  124. package/dist/capabilities/huggingface.json +113 -155
  125. package/dist/capabilities/humain.json +2 -2
  126. package/dist/capabilities/hyper.json +25 -33
  127. package/dist/capabilities/impossibl.json +155 -155
  128. package/dist/capabilities/inception.json +2 -2
  129. package/dist/capabilities/inceptron.json +8 -8
  130. package/dist/capabilities/inco.json +5 -5
  131. package/dist/capabilities/infer.json +20 -20
  132. package/dist/capabilities/inferall.json +14 -14
  133. package/dist/capabilities/inference-coop.json +9 -9
  134. package/dist/capabilities/inferenceapis.json +20 -20
  135. package/dist/capabilities/inferris.json +4 -4
  136. package/dist/capabilities/infersia.json +11 -11
  137. package/dist/capabilities/infomaniak.json +4 -4
  138. package/dist/capabilities/io-net.json +4 -4
  139. package/dist/capabilities/isoquant.json +4 -4
  140. package/dist/capabilities/iteracompute.json +59 -59
  141. package/dist/capabilities/jad-ai.json +3 -3
  142. package/dist/capabilities/jalapeno.json +10 -10
  143. package/dist/capabilities/jiekou.json +60 -60
  144. package/dist/capabilities/joingonka.json +4 -4
  145. package/dist/capabilities/jzstoken.json +58 -59
  146. package/dist/capabilities/keln.json +18 -18
  147. package/dist/capabilities/kenari.json +119 -127
  148. package/dist/capabilities/kilo.json +609 -613
  149. package/dist/capabilities/kimi-code-plan-cn.json +5 -5
  150. package/dist/capabilities/kimi-code-plan-global.json +5 -5
  151. package/dist/capabilities/kitani.json +6 -6
  152. package/dist/capabilities/klavo.json +20 -20
  153. package/dist/capabilities/korouter.json +32 -32
  154. package/dist/capabilities/kunavo.json +8 -8
  155. package/dist/capabilities/liquid.json +12 -12
  156. package/dist/capabilities/lithosai.json +2 -2
  157. package/dist/capabilities/llmgateway-providers.json +947 -878
  158. package/dist/capabilities/llmgateway.json +336 -335
  159. package/dist/capabilities/llmtr.json +26 -26
  160. package/dist/capabilities/logits.json +2 -2
  161. package/dist/capabilities/longcat.json +2 -2
  162. package/dist/capabilities/lowrouter.json +65 -65
  163. package/dist/capabilities/lyceum.json +19 -11
  164. package/dist/capabilities/melious.json +14 -14
  165. package/dist/capabilities/merge-gateway.json +264 -263
  166. package/dist/capabilities/meta.json +13 -13
  167. package/dist/capabilities/minimax-cn-coding-plan.json +2 -2
  168. package/dist/capabilities/minimax-cn.json +5 -5
  169. package/dist/capabilities/minimax-coding-plan.json +2 -2
  170. package/dist/capabilities/minimax.json +5 -5
  171. package/dist/capabilities/mistral.json +21 -21
  172. package/dist/capabilities/mixlayer.json +3 -3
  173. package/dist/capabilities/modal.json +10 -10
  174. package/dist/capabilities/model-oracle-ai.json +26 -26
  175. package/dist/capabilities/modelis.json +17 -17
  176. package/dist/capabilities/modelscope.json +2 -2
  177. package/dist/capabilities/modular.json +30 -8
  178. package/dist/capabilities/moneo.json +12 -12
  179. package/dist/capabilities/moonshotai-cn.json +2 -2
  180. package/dist/capabilities/moonshotai.json +2 -2
  181. package/dist/capabilities/morph.json +17 -17
  182. package/dist/capabilities/munito-eu.json +6 -6
  183. package/dist/capabilities/munito.json +6 -6
  184. package/dist/capabilities/nan.json +29 -29
  185. package/dist/capabilities/nano-gpt.json +606 -593
  186. package/dist/capabilities/nearai.json +112 -112
  187. package/dist/capabilities/nebius.json +30 -30
  188. package/dist/capabilities/neon.json +136 -136
  189. package/dist/capabilities/neuralwatt.json +43 -43
  190. package/dist/capabilities/nokeep.json +4 -4
  191. package/dist/capabilities/novita-ai.json +136 -136
  192. package/dist/capabilities/nvidia.json +52 -35
  193. package/dist/capabilities/oathbreaker.json +24 -1
  194. package/dist/capabilities/obscurify.json +29 -29
  195. package/dist/capabilities/oci.json +7 -7
  196. package/dist/capabilities/ofox.json +315 -315
  197. package/dist/capabilities/ollama-cloud.json +53 -53
  198. package/dist/capabilities/openai.json +53 -53
  199. package/dist/capabilities/opencode-go.json +88 -88
  200. package/dist/capabilities/openreason.json +5 -5
  201. package/dist/capabilities/openrouter.json +528 -519
  202. package/dist/capabilities/opper.json +29 -29
  203. package/dist/capabilities/orcarouter.json +214 -214
  204. package/dist/capabilities/outerlabs.json +33 -33
  205. package/dist/capabilities/ovhcloud.json +20 -20
  206. package/dist/capabilities/pareto.json +6 -6
  207. package/dist/capabilities/pendra.json +4 -4
  208. package/dist/capabilities/perplexity-agent.json +55 -55
  209. package/dist/capabilities/perplexity.json +2 -2
  210. package/dist/capabilities/phala.json +26 -26
  211. package/dist/capabilities/pioneer.json +31 -31
  212. package/dist/capabilities/poe.json +136 -136
  213. package/dist/capabilities/poolside.json +2 -2
  214. package/dist/capabilities/powerspring.json +12 -12
  215. package/dist/capabilities/primalabs.json +9 -9
  216. package/dist/capabilities/prime.json +121 -111
  217. package/dist/capabilities/privatemode-ai.json +5 -5
  218. package/dist/capabilities/proxystacks.json +7 -7
  219. package/dist/capabilities/qiniu-ai.json +16 -16
  220. package/dist/capabilities/refuseless.json +9 -9
  221. package/dist/capabilities/regolo-ai.json +11 -11
  222. package/dist/capabilities/requesty.json +451 -177
  223. package/dist/capabilities/ruapi.json +35 -19
  224. package/dist/capabilities/runcrate.json +13 -13
  225. package/dist/capabilities/runinfra.json +18 -18
  226. package/dist/capabilities/sakana.json +7 -7
  227. package/dist/capabilities/sambanova.json +6 -6
  228. package/dist/capabilities/sandbase.json +25 -25
  229. package/dist/capabilities/sarvam.json +7 -7
  230. package/dist/capabilities/scaleway.json +19 -19
  231. package/dist/capabilities/scnet-token-plan.json +10 -10
  232. package/dist/capabilities/scx-ai.json +30 -30
  233. package/dist/capabilities/sensenova.json +12 -12
  234. package/dist/capabilities/siliconflow-cn.json +60 -60
  235. package/dist/capabilities/siliconflow.json +62 -62
  236. package/dist/capabilities/snowflake-cortex.json +21 -21
  237. package/dist/capabilities/sokkan.json +7 -7
  238. package/dist/capabilities/sparrowcodes.json +19 -19
  239. package/dist/capabilities/standardcompute.json +106 -106
  240. package/dist/capabilities/steadyrouter.json +37 -37
  241. package/dist/capabilities/stepfun-ai-step-plan.json +6 -6
  242. package/dist/capabilities/stepfun-ai.json +6 -6
  243. package/dist/capabilities/stepfun-step-plan.json +6 -6
  244. package/dist/capabilities/stepfun.json +6 -6
  245. package/dist/capabilities/stepping-stone.json +17 -17
  246. package/dist/capabilities/superbot-gg.json +4 -4
  247. package/dist/capabilities/synthetic.json +13 -13
  248. package/dist/capabilities/synthorai.json +24 -24
  249. package/dist/capabilities/teamorouter.json +23 -23
  250. package/dist/capabilities/teapot-router.json +11 -11
  251. package/dist/capabilities/tencent-token-plan-intl.json +126 -0
  252. package/dist/capabilities/tencent-token-plan.json +44 -44
  253. package/dist/capabilities/tencent-tokenhub.json +58 -43
  254. package/dist/capabilities/tensorx.json +40 -40
  255. package/dist/capabilities/tenstorrent.json +8 -8
  256. package/dist/capabilities/the-grid-ai.json +35 -35
  257. package/dist/capabilities/thinkingmachines.json +76 -76
  258. package/dist/capabilities/tinfoil.json +13 -13
  259. package/dist/capabilities/toapis.json +3 -3
  260. package/dist/capabilities/togetherai.json +54 -54
  261. package/dist/capabilities/tokengo.json +25 -25
  262. package/dist/capabilities/tokenify.json +9 -9
  263. package/dist/capabilities/tokenwatt.json +10 -2
  264. package/dist/capabilities/trustedrouter.json +7 -7
  265. package/dist/capabilities/trustedtokens.json +18 -18
  266. package/dist/capabilities/umans-ai-coding-plan.json +13 -13
  267. package/dist/capabilities/umans-ai.json +14 -14
  268. package/dist/capabilities/uncensuredai.json +5 -5
  269. package/dist/capabilities/unrestricted.json +8 -8
  270. package/dist/capabilities/uplinkswitch.json +22 -22
  271. package/dist/capabilities/upstage.json +6 -6
  272. package/dist/capabilities/vancine.json +23 -23
  273. package/dist/capabilities/vercel.json +543 -540
  274. package/dist/capabilities/vivgrid.json +88 -79
  275. package/dist/capabilities/volcengine-coding-plan.json +26 -26
  276. package/dist/capabilities/volcengine.json +26 -25
  277. package/dist/capabilities/vultr.json +32 -32
  278. package/dist/capabilities/wafer.ai.json +16 -16
  279. package/dist/capabilities/wallaby.json +2 -2
  280. package/dist/capabilities/wally.json +11 -11
  281. package/dist/capabilities/wandb.json +17 -17
  282. package/dist/capabilities/watt.json +25 -25
  283. package/dist/capabilities/xai.json +6 -6
  284. package/dist/capabilities/xiaomi.json +2 -2
  285. package/dist/capabilities/xpersona.json +13 -13
  286. package/dist/capabilities/xxapi.json +26 -26
  287. package/dist/capabilities/zai-coding-plan.json +15 -15
  288. package/dist/capabilities/zai.json +32 -32
  289. package/dist/capabilities/zenifra.json +26 -26
  290. package/dist/capabilities/zenmux.json +208 -208
  291. package/dist/capabilities/zerogpu.json +13 -13
  292. package/dist/capabilities/zhipuai-coding-plan.json +4 -4
  293. package/dist/capabilities/zhipuai.json +31 -31
  294. package/dist/capabilities/zro.json +7 -7
  295. package/dist/channels/agent-channels.d.ts +22 -0
  296. package/dist/channels/index.cjs +2 -2
  297. package/dist/channels/index.js +2 -2
  298. package/dist/channels/output-processor.d.ts +12 -0
  299. package/dist/channels/state-adapter.d.ts +3 -1
  300. package/dist/channels/stream-helpers.d.ts +17 -0
  301. package/dist/{channels-Cl-pRrWB.cjs → channels-Bkd_v8M1.cjs} +1 -1
  302. package/dist/{channels-DegTNzaq.js → channels-CkRMEIQ6.js} +1 -1
  303. package/dist/coding-agent/index.cjs +2 -2
  304. package/dist/coding-agent/index.js +2 -2
  305. package/dist/{constants-B9ZDvXZ4.cjs → constants-Bou0hEgY.cjs} +4 -0
  306. package/dist/{constants-BmdTvEYN.js → constants-CFWgIaqA.js} +4 -0
  307. package/dist/datasets/experiment/scorer.d.ts +16 -5
  308. package/dist/datasets/index.cjs +2 -2
  309. package/dist/datasets/index.js +2 -2
  310. package/dist/docs/SKILL.md +2 -1
  311. package/dist/docs/assets/SOURCE_MAP.json +1070 -1055
  312. package/dist/docs/references/docs-agents-code-mode.md +36 -0
  313. package/dist/docs/references/docs-agents-networks.md +1 -1
  314. package/dist/docs/references/docs-agents-tools.md +6 -0
  315. package/dist/docs/references/docs-auth-simple-auth.md +8 -8
  316. package/dist/docs/references/docs-browser.md +3 -1
  317. package/dist/docs/references/docs-evals-custom-scorers.md +1 -1
  318. package/dist/docs/references/docs-harness-background-tasks.md +38 -0
  319. package/dist/docs/references/docs-knowledge-agents-and-tools.md +2 -0
  320. package/dist/docs/references/docs-mastra-platform-observability-overview.md +3 -189
  321. package/dist/docs/references/docs-memory-message-history.md +25 -0
  322. package/dist/docs/references/docs-sandbox-lsp.md +5 -6
  323. package/dist/docs/references/docs-sandbox-overview.md +20 -0
  324. package/dist/docs/references/docs-sandbox-skills.md +2 -0
  325. package/dist/docs/references/docs-signals-sending-signals.md +1 -1
  326. package/dist/docs/references/integrations.md +1 -0
  327. package/dist/docs/references/reference-agent-controller-session.md +30 -2
  328. package/dist/docs/references/reference-agents-generate.md +1 -1
  329. package/dist/docs/references/reference-agents-network.md +1 -1
  330. package/dist/docs/references/reference-configuration.md +8 -8
  331. package/dist/docs/references/reference-core-getWorkspaceById.md +37 -0
  332. package/dist/docs/references/reference-evals-create-scorer.md +5 -5
  333. package/dist/docs/references/reference-evals-run-evals.md +1 -1
  334. package/dist/docs/references/reference-knowledge-knowledge-tools.md +3 -3
  335. package/dist/docs/references/reference-manual-install.md +1 -1
  336. package/dist/docs/references/reference-memory-observational-memory.md +8 -0
  337. package/dist/docs/references/reference-observability-tracing-interfaces.md +10 -6
  338. package/dist/docs/references/reference-processors-processor-interface.md +3 -2
  339. package/dist/docs/references/reference-processors-system-prompt-scrubber.md +1 -1
  340. package/dist/docs/references/reference-processors-tool-search-processor.md +3 -3
  341. package/dist/docs/references/reference-pubsub-base.md +5 -3
  342. package/dist/docs/references/reference-pubsub-caching-pubsub.md +3 -1
  343. package/dist/docs/references/reference-storage-overview.md +1 -1
  344. package/dist/docs/references/reference-storage-retention.md +20 -20
  345. package/dist/docs/references/reference-tools-create-code-mode.md +22 -0
  346. package/dist/docs/references/reference-tools-vector-query-tool.md +8 -0
  347. package/dist/docs/references/reference-voice-overview.md +11 -26
  348. package/dist/docs/references/reference-voice-speech-to-speech.md +1 -1
  349. package/dist/docs/references/reference-voice-voice.listen.md +1 -0
  350. package/dist/docs/references/reference-voice-voice.speak.md +1 -3
  351. package/dist/docs/references/reference-workspace-factory-sandbox.md +6 -6
  352. package/dist/docs/references/reference-workspace-sandbox.md +14 -0
  353. package/dist/docs/references/reference.md +1 -0
  354. package/dist/evals/index.cjs +2 -2
  355. package/dist/evals/index.js +2 -2
  356. package/dist/evals/scoreTraces/index.cjs +2 -2
  357. package/dist/evals/scoreTraces/index.js +2 -2
  358. package/dist/events/index.cjs +1 -1
  359. package/dist/events/index.js +1 -1
  360. package/dist/harness/index.cjs +2 -2
  361. package/dist/harness/index.js +2 -2
  362. package/dist/index.cjs +1 -1
  363. package/dist/index.js +1 -1
  364. package/dist/knowledge/agent-scopes.d.ts +17 -0
  365. package/dist/knowledge/declarations.d.ts +2 -0
  366. package/dist/knowledge/held-scopes-state-processor.d.ts +50 -0
  367. package/dist/knowledge/importers/host.d.ts +7 -1
  368. package/dist/knowledge/importers/overlay.d.ts +138 -0
  369. package/dist/knowledge/importers/runner.d.ts +12 -0
  370. package/dist/knowledge/importers/sink.d.ts +6 -0
  371. package/dist/knowledge/importers/types.d.ts +9 -0
  372. package/dist/knowledge/index.cjs +1611 -167
  373. package/dist/knowledge/index.d.ts +12 -2
  374. package/dist/knowledge/index.js +1610 -168
  375. package/dist/knowledge/links.d.ts +27 -0
  376. package/dist/knowledge/page-tools.d.ts +23 -0
  377. package/dist/knowledge/pinned-state-processor.d.ts +2 -2
  378. package/dist/knowledge/run.d.ts +5 -0
  379. package/dist/knowledge/scope-runtime.d.ts +6 -0
  380. package/dist/llm/index.cjs +3 -3
  381. package/dist/llm/index.js +3 -3
  382. package/dist/llm/model/base.types.d.ts +3 -1
  383. package/dist/llm/model/mastra-gateway-provider-tools.d.ts +9 -6
  384. package/dist/llm/model/model.d.ts +1 -1
  385. package/dist/llm/model/model.loop.d.ts +1 -1
  386. package/dist/llm/model/model.loop.types.d.ts +3 -1
  387. package/dist/llm/model/provider-options.d.ts +4 -3
  388. package/dist/llm/model/provider-types.generated.d.ts +8161 -8082
  389. package/dist/{llm-BKxlS9Kk.cjs → llm-DAw2eouV.cjs} +38 -78
  390. package/dist/{llm-CMkzIFAk.js → llm-DFT5EKp4.js} +38 -78
  391. package/dist/loop/index.cjs +2 -2
  392. package/dist/loop/index.js +2 -2
  393. package/dist/{manager-C-eQXmRq.js → manager-DiDnvKLM.js} +106 -35
  394. package/dist/{manager-CasaT35Q.cjs → manager-hxzEe4U5.cjs} +106 -35
  395. package/dist/mastra/index.cjs +1 -1
  396. package/dist/mastra/index.js +1 -1
  397. package/dist/{mastra-C7Tj4U8c.cjs → mastra-1diaq68N.cjs} +17 -17
  398. package/dist/{mastra-5EEmN3Ok.js → mastra-BPaPxG5t.js} +17 -17
  399. package/dist/memory/index.cjs +3 -3
  400. package/dist/memory/index.js +3 -3
  401. package/dist/{message-list-wI71UGxk.js → message-list-BGm1DCiG.js} +230 -129
  402. package/dist/{message-list-DfN9mWeN.cjs → message-list-vR3uLAHL.cjs} +230 -129
  403. package/dist/{model-DCLUL-8a.js → model-CUBZjm0T.js} +4 -3
  404. package/dist/{model-9HA-W0tg.cjs → model-DSMHJM3c.cjs} +4 -3
  405. package/dist/{netlify-Cq3H-A9I.cjs → netlify-C21T9ozJ.cjs} +41364 -30461
  406. package/dist/{netlify-DaWURNSU.js → netlify-D1BKjns0.js} +41361 -30464
  407. package/dist/notifications/index.cjs +1 -1
  408. package/dist/notifications/index.js +1 -1
  409. package/dist/observability/types/tracing.d.ts +1 -1
  410. package/dist/processor-provider/index.cjs +1 -1
  411. package/dist/processor-provider/index.js +1 -1
  412. package/dist/processors/index.cjs +2 -2
  413. package/dist/processors/index.js +2 -2
  414. package/dist/processors/processors/tool-search.d.ts +2 -2
  415. package/dist/processors/runner.d.ts +12 -0
  416. package/dist/{provider-registry-DWixjFX7.js → provider-registry-BAlFFX5o.js} +21911 -21671
  417. package/dist/{provider-registry-a649fS5r.cjs → provider-registry-ChojUVJa.cjs} +21910 -21670
  418. package/dist/provider-registry.json +21947 -21767
  419. package/dist/{registry-generator-BYJC7p8M.js → registry-generator-BbWSH6W4.js} +1 -1
  420. package/dist/{registry-generator-BuKC7UKd.cjs → registry-generator-CAUL9Hek.cjs} +1 -1
  421. package/dist/{rehydrate-DR2_WAz2.cjs → rehydrate-0xSq47n9.cjs} +2 -2
  422. package/dist/{rehydrate-DPhmASM6.js → rehydrate-CzUnNFU6.js} +2 -2
  423. package/dist/relevance/index.cjs +2 -2
  424. package/dist/relevance/index.js +2 -2
  425. package/dist/{run-registry-oUNF6szW.cjs → run-registry-CrTsH9iL.cjs} +1158 -125
  426. package/dist/{run-registry-D3X7XvUL.js → run-registry-DJT02z_9.js} +1092 -125
  427. package/dist/storage/constants.cjs +1 -1
  428. package/dist/storage/constants.js +1 -1
  429. package/dist/storage/domains/knowledge/base.d.ts +101 -1
  430. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +10 -0
  431. package/dist/storage/domains/knowledge/importers.d.ts +39 -0
  432. package/dist/storage/domains/knowledge/inmemory.d.ts +8 -0
  433. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +35 -1
  434. package/dist/storage/domains/knowledge/pages.d.ts +74 -0
  435. package/dist/storage/index.cjs +3 -3
  436. package/dist/storage/index.js +3 -3
  437. package/dist/storage/types.d.ts +14 -0
  438. package/dist/stream/index.cjs +2 -2
  439. package/dist/stream/index.js +2 -2
  440. package/dist/{stream-DoZ6F41o.js → stream-CG9OooRx.js} +37 -14
  441. package/dist/{stream-DQC1vpvl.cjs → stream-CMKRczs4.cjs} +37 -14
  442. package/dist/test-utils/llm-mock.cjs +1 -1
  443. package/dist/test-utils/llm-mock.js +1 -1
  444. package/dist/{to-prompt-B9eZo2U5.cjs → to-prompt-CG-LyaBY.cjs} +9 -0
  445. package/dist/{to-prompt-BsDtVXrf.js → to-prompt-CMlVGYxC.js} +9 -0
  446. package/dist/tool-loop-agent/index.cjs +1 -1
  447. package/dist/tool-loop-agent/index.js +1 -1
  448. package/dist/{tool-loop-agent-Cy4NDOMS.cjs → tool-loop-agent-14o3Z1qo.cjs} +4 -4
  449. package/dist/{tool-loop-agent-C9YkvDRd.js → tool-loop-agent-Bi6z_q7o.js} +4 -4
  450. package/dist/tools/code-mode/index.d.ts +2 -0
  451. package/dist/tools/code-mode/log-collector.d.ts +49 -0
  452. package/dist/tools/code-mode/types.d.ts +71 -0
  453. package/dist/tools/index.cjs +3 -1
  454. package/dist/tools/index.js +2 -2
  455. package/dist/{tools-CGF5Ik6j.cjs → tools-BEYxowf0.cjs} +429 -61
  456. package/dist/{tools-CDfyMpzN.js → tools-tPy2FwMI.js} +418 -62
  457. package/dist/{utils-Bs2IYyOb.cjs → utils-DkvbP8EA.cjs} +7 -6
  458. package/dist/{utils-9JyiKu5r.js → utils-Fag7YDBU.js} +7 -6
  459. package/dist/utils.cjs +1 -1
  460. package/dist/utils.js +1 -1
  461. package/dist/{validate-BE3mVxVy.cjs → validate-Bhrlve2E.cjs} +1 -1
  462. package/dist/{validate-8j0phWFV.js → validate-DLER0nlQ.js} +1 -1
  463. package/dist/vector/index.cjs +2 -2
  464. package/dist/vector/index.js +2 -2
  465. package/dist/worker/index.cjs +1 -1
  466. package/dist/worker/index.js +1 -1
  467. package/dist/worker/workers/orchestration-worker.d.ts +1 -0
  468. package/dist/{worker-DwdgU6E9.cjs → worker-0gczpztM.cjs} +2 -2
  469. package/dist/{worker-BiK1kfMa.cjs → worker-BwJyrFQN.cjs} +10 -4
  470. package/dist/{worker-BfWFqSH2.js → worker-D-em3hyS.js} +5 -5
  471. package/dist/{worker-DIRdEwih.js → worker-leYV1Y91.js} +2 -2
  472. package/dist/{workflow-CxQMcTbT.cjs → workflow-DWdcEcxw.cjs} +3 -3
  473. package/dist/{workflow-ni-keg2i.js → workflow-FikHVwog.js} +3 -3
  474. package/dist/workflows/builder/index.cjs +1 -1
  475. package/dist/workflows/builder/index.js +1 -1
  476. package/dist/workflows/evented/index.cjs +1 -1
  477. package/dist/workflows/evented/index.js +1 -1
  478. package/dist/workflows/index.cjs +4 -4
  479. package/dist/workflows/index.js +4 -4
  480. package/dist/workflows/step.d.ts +2 -0
  481. package/dist/workflows/workflow.d.ts +2 -0
  482. package/dist/workspace/index.cjs +3 -1
  483. package/dist/workspace/index.d.ts +1 -1
  484. package/dist/workspace/index.js +2 -2
  485. package/dist/workspace/lsp/manager.d.ts +19 -4
  486. package/dist/workspace/sandbox/mastra-sandbox.d.ts +17 -0
  487. package/dist/workspace/sandbox/teardown-context.d.ts +74 -0
  488. package/dist/workspace/tools/index.d.ts +1 -0
  489. package/dist/workspace/tools/media.d.ts +20 -1
  490. package/dist/workspace/tools/recreate-sandbox.d.ts +24 -0
  491. package/dist/{workspace-X2RHJZU9.cjs → workspace-C8Zo5_qK.cjs} +387 -109
  492. package/dist/{workspace-DY2Nxiyi.js → workspace-DOAil8mG.js} +376 -110
  493. package/package.json +6 -6
  494. package/src/llm/model/provider-types.generated.d.ts +8161 -8082
@@ -1,5 +1,5 @@
1
1
  import { t as MastraBase } from "../base-CKLWBhDo.js";
2
- import { $t as knowledgeDeliveredPins, Ai as MAX_KNOWLEDGE_PAGE_BODY_LINKS, Bi as knowledgeLinkRefKey, Ci as parseKnowledgeWikilinks, Cn as knowledgeRunScopes, Di as KnowledgePageKeyConflictError, Dn as encodeKnowledgeScopeId, Ei as KnowledgePageHasChildrenError, En as decodeKnowledgeScopeId, Fi as MAX_KNOWLEDGE_PAGE_LIST_LIMIT, Gi as parseKnowledgePageRef, Hi as knowledgePinDepth, Ii as MAX_KNOWLEDGE_PIN_LIST_DEPTH, Ki as KnowledgeInvalidCursorError, Li as assertKnowledgeNoteTextWithinBound, Mi as MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, Ni as MAX_KNOWLEDGE_PAGE_LINKS, Oi as MAX_KNOWLEDGE_MOVE_PAGES, On as buildKnowledgeInstructions, Pi as MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, Qt as PINNED_READ_MEMO_KEY, Ri as assertKnowledgePageDescriptionWithinBound, Si as inspectKnowledgeSchema, Sn as knowledgeMemoryScopes, Ti as KnowledgePageDepthError, Tn as strongerKnowledgeRole, Ui as knowledgePositionBetween, Uo as augmentWithInit, Vi as knowledgePagePath, Wi as knowledgeScopeReadable, Wo as getStorageSource, _i as KnowledgeStorage, _n as knowledgeAccessGrants, _r as knowledgeScopeKey, an as removeKnowledgeNote, bi as assertKnowledgeSchemaCompatible, bn as KnowledgeDeclarationError, br as knowledgeVisibleScopeKeys, ci as InMemoryKnowledgeStorage, cn as upsertKnowledgePage, cr as MAX_KNOWLEDGE_SCOPE_TAGS, di as KnowledgeImportersStorage, dn as KnowledgeLinkRefreshIncompleteError, dr as assertKnowledgeRecordTextWithinBound, en as buildKnowledgePageTools, fi as KNOWLEDGE_STORAGE_CONTRACT_VERSION, fn as knowledgeSubtree, fr as assertKnowledgeScopeWithinCeiling, gi as KnowledgeSchemaResetRequiredError, gn as updateKnowledgeLinks, gr as isKnowledgeScopeVisible, hi as KnowledgeNotFoundError, hn as syncKnowledgePageBodyLinks, hr as expandKnowledgeScope, in as moveKnowledgePage, ji as MAX_KNOWLEDGE_PAGE_DEPTH, ki as MAX_KNOWLEDGE_NOTE_TOKENS, li as KnowledgeImporterBindingConflictError, ln as KnowledgeSemanticIndex, lr as assertKnowledgeCeilingRaised, mi as KnowledgeConflictError, mn as reindexKnowledgeLinks, mr as createKnowledgeNodeCursor, nn as knowledgeRunPrincipals, on as removeKnowledgePage, or as MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, pi as KNOWLEDGE_STORAGE_SCHEMA_VERSION, pn as refreshKnowledgeLinksTo, pr as canonicalizeKnowledgeScope, rn as addKnowledgeNote, sn as updateKnowledgeNote, sr as MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, tn as KnowledgeRun, ui as KnowledgeImporterRunStateError, ur as assertKnowledgeDescriptionWithinBound, vi as KnowledgeTransactionDeadlineError, vn as knowledgeReadScopeFor, vr as knowledgeSemanticDocumentId, wi as KnowledgeMoveTooLargeError, wn as knowledgeScopeAddress, xi as createKnowledgeUlid, xn as compileKnowledgeScopes, xr as parseKnowledgeNodeCursor, yi as KnowledgeUnsupportedCapabilityError, yn as knowledgeRoleOn, yr as knowledgeSemanticIdempotencyKey, zi as canonicalKnowledgeName } from "../run-registry-D3X7XvUL.js";
2
+ import { $i as parseKnowledgePageRef, $o as getStorageSource, $t as PINNED_READ_MEMO_KEY, Ai as inspectKnowledgeSchema, An as knowledgeMemoryScopes, Bi as MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, Ci as KnowledgeNotFoundError, Cn as syncKnowledgePageBodyLinks, Cr as expandKnowledgeScope, Di as KnowledgeUnsupportedCapabilityError, Dn as knowledgeRoleOn, Dr as knowledgeSemanticIdempotencyKey, Ei as KnowledgeTransactionDeadlineError, En as knowledgeReadScopeFor, Er as knowledgeSemanticDocumentId, Fi as KnowledgePageKeyConflictError, Fn as encodeKnowledgeScopeId, Gi as assertKnowledgeNoteTextWithinBound, Hi as MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, Ii as MAX_KNOWLEDGE_MOVE_PAGES, In as buildKnowledgeInstructions, Ji as knowledgeLinkRefKey, Ki as assertKnowledgePageDescriptionWithinBound, Li as MAX_KNOWLEDGE_NOTE_TOKENS, Mi as KnowledgeMoveTooLargeError, Mn as knowledgeScopeAddress, Ni as KnowledgePageDepthError, Nn as strongerKnowledgeRole, Oi as assertKnowledgeSchemaCompatible, On as KnowledgeDeclarationError, Or as knowledgeVisibleScopeKeys, Pi as KnowledgePageHasChildrenError, Pn as decodeKnowledgeScopeId, Qi as knowledgeScopeReadable, Qo as augmentWithInit, Ri as MAX_KNOWLEDGE_PAGE_BODY_LINKS, Si as KnowledgeConflictError, Sn as repairKnowledgeLinks, Sr as createKnowledgeNodeCursor, Ti as KnowledgeStorage, Tn as knowledgeAccessGrants, Tr as knowledgeScopeKey, Ui as MAX_KNOWLEDGE_PAGE_LIST_LIMIT, Vi as MAX_KNOWLEDGE_PAGE_LINKS, Wi as MAX_KNOWLEDGE_PIN_LIST_DEPTH, Xi as knowledgePinDepth, Yi as knowledgePagePath, Zi as knowledgePositionBetween, _i as KnowledgeImporterBindingConflictError, _n as KnowledgeLinkRepairUnsupportedError, _r as assertKnowledgeCeilingRaised, an as knowledgeRunPrincipals, bi as KNOWLEDGE_STORAGE_CONTRACT_VERSION, bn as refreshKnowledgeLinksTo, br as assertKnowledgeScopeWithinCeiling, cn as addKnowledgeNote, dn as removeKnowledgePage, ea as KnowledgeInvalidCursorError, en as knowledgeDeliveredPins, fn as updateKnowledgeNote, gi as InMemoryKnowledgeStorage, gn as KnowledgeLinkRefreshIncompleteError, gr as MAX_KNOWLEDGE_SCOPE_TAGS, hr as MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, in as KnowledgeRunScopesError, ji as parseKnowledgeWikilinks, jn as knowledgeRunScopes, ki as createKnowledgeUlid, kn as compileKnowledgeScopes, kr as parseKnowledgeNodeCursor, ln as moveKnowledgePage, mn as KnowledgeSemanticIndex, mr as MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, nn as heldScopes, on as knowledgeAgentScopes, pn as upsertKnowledgePage, qi as canonicalKnowledgeName, rn as KnowledgeRun, sn as knowledgePersonaScopes, ta as knowledgePageKeyProblem, tn as buildKnowledgePageTools, un as removeKnowledgeNote, vi as KnowledgeImporterRunStateError, vn as canRepairKnowledgeLinksInBatch, vr as assertKnowledgeDescriptionWithinBound, wi as KnowledgeSchemaResetRequiredError, wn as updateKnowledgeLinks, wr as isKnowledgeScopeVisible, xi as KNOWLEDGE_STORAGE_SCHEMA_VERSION, xn as reindexKnowledgeLinks, xr as canonicalizeKnowledgeScope, yi as KnowledgeImportersStorage, yn as knowledgeSubtree, yr as assertKnowledgeRecordTextWithinBound, zi as MAX_KNOWLEDGE_PAGE_DEPTH } from "../run-registry-DJT02z_9.js";
3
3
  import { standardSchemaToJSONSchema, toStandardSchema } from "../schema/index.js";
4
4
  import { i as createStandardSchemaIssuesError } from "../tool-Z3bykc1m.js";
5
5
  import { randomUUID } from "crypto";
@@ -22,6 +22,39 @@ const note = (op) => (result) => {
22
22
  noteId: id
23
23
  };
24
24
  };
25
+ /** The event each single write would emit for `write`, so a batch emits what its single writes would. */
26
+ function describePageWrite(write) {
27
+ switch (write.op) {
28
+ case "create":
29
+ case "update":
30
+ case "delete": return {
31
+ kind: "page",
32
+ op: write.op,
33
+ pageId: write.id,
34
+ scopeId: write.scopeId
35
+ };
36
+ case "move": return {
37
+ kind: "page",
38
+ op: "move",
39
+ pageId: write.id,
40
+ scopeId: write.scopeId,
41
+ fromScopeId: write.fromScopeId
42
+ };
43
+ case "add-note": return {
44
+ kind: "note",
45
+ op: "add",
46
+ pageId: write.pageId,
47
+ noteId: write.id
48
+ };
49
+ case "remove-note": return {
50
+ kind: "note",
51
+ op: "remove",
52
+ pageId: write.pageId,
53
+ noteId: write.id
54
+ };
55
+ case "replace-links": return null;
56
+ }
57
+ }
25
58
  /** The page-store writes that emit, and the event each one's result maps to. */
26
59
  const WRITES = {
27
60
  materializeScope: (result) => {
@@ -57,6 +90,7 @@ const WRITES = {
57
90
  fromScopeId
58
91
  };
59
92
  },
93
+ applyPageWrites: (_result, input) => input.writes.map(describePageWrite).filter((change) => change !== null),
60
94
  addNote: note("add"),
61
95
  restampNote: note("restamp"),
62
96
  removeNote: note("remove"),
@@ -142,9 +176,15 @@ function emitKnowledgeChanges(storage, emit, listening, onError, chain) {
142
176
  }
143
177
  const result = await value.call(target, input, ...rest);
144
178
  if (!listening()) return result;
179
+ let changes = [];
145
180
  try {
146
181
  const change = describe(result, input, fromScopeId);
147
- if (change) report(change);
182
+ changes = Array.isArray(change) ? change : change ? [change] : [];
183
+ } catch (error) {
184
+ onError(error);
185
+ }
186
+ for (const one of changes) try {
187
+ report(one);
148
188
  } catch (error) {
149
189
  onError(error);
150
190
  }
@@ -173,6 +213,7 @@ const KNOWLEDGE_IMPORTER_ERROR_CODES = [
173
213
  "credential_missing",
174
214
  "importer_missing_from_deploy",
175
215
  "importer_error",
216
+ "flush_too_large",
176
217
  "stopped",
177
218
  "lease_expired",
178
219
  "deadline_exceeded"
@@ -670,17 +711,22 @@ function sourceError(error) {
670
711
  * @experimental
671
712
  */
672
713
  async function runKnowledgeImport(options) {
673
- const { host, budgetMs = 15e5, graceMs = 18e4, maxPasses = 200, bufferSize = 200, flushAfterMs = 3e4, heartbeatMs = 3e4, maxRetries = 8, hostCallTimeoutMs = 6e4, retryDelayMs = (attempt) => Math.min(250 * 2 ** attempt, 1e4) } = options;
714
+ const { host, budgetMs = 15e5, graceMs = 18e4, maxPasses = 200, bufferSize = 200, maxFlushBytes: ownMaxFlushBytes = Infinity, flushAfterMs = 3e4, heartbeatMs = 3e4, maxRetries = 8, hostCallTimeoutMs = 6e4, retryDelayMs = (attempt) => Math.min(250 * 2 ** attempt, 1e4) } = options;
674
715
  if (!Number.isFinite(flushAfterMs) || flushAfterMs <= 0 || flushAfterMs > 2 ** 31 - 1) throw new TypeError(`flushAfterMs must be a positive number of milliseconds up to 2147483647, got ${flushAfterMs}`);
716
+ if (ownMaxFlushBytes !== Infinity && !(Number.isInteger(ownMaxFlushBytes) && ownMaxFlushBytes > 0)) throw new TypeError(`maxFlushBytes must be a positive whole number of bytes, got ${ownMaxFlushBytes}`);
675
717
  const started = await within(host.startRun(options.bindingId, options.start), hostCallTimeoutMs, () => new KnowledgeImporterHostError("host call timed out"));
676
718
  if (started.status === "skipped") return started;
677
719
  const { runId, generation } = started;
720
+ const hostMaxFlushBytes = started.maxFlushBytes;
721
+ const maxFlushBytes = typeof hostMaxFlushBytes === "number" && Number.isInteger(hostMaxFlushBytes) && hostMaxFlushBytes > 0 ? Math.min(ownMaxFlushBytes, hostMaxFlushBytes) : ownMaxFlushBytes;
678
722
  const startedAt = Date.now();
679
723
  let lastSeq = started.lastSeq;
680
724
  /** A flush sent but never acknowledged: it may have committed. */
681
725
  let unsettledSeq;
682
726
  let state = { ...started.state };
683
727
  let buffer = [];
728
+ /** Encoded bytes of the ops in `buffer`, without the commas between them. */
729
+ let bufferBytes = 0;
684
730
  let stop;
685
731
  /** Armed while the buffer holds ops; sends them once the oldest has waited `flushAfterMs`. */
686
732
  let flushTimer;
@@ -731,6 +777,7 @@ async function runKnowledgeImport(options) {
731
777
  disarm();
732
778
  const ops = buffer;
733
779
  buffer = [];
780
+ bufferBytes = 0;
734
781
  const next = flushing.then(async () => {
735
782
  if (stop) throw stop;
736
783
  if (ops.length === 0 && !staged && !settle) return;
@@ -755,6 +802,11 @@ async function runKnowledgeImport(options) {
755
802
  digest,
756
803
  ...body
757
804
  };
805
+ if (maxFlushBytes !== Infinity && encodedBytes(request) > maxFlushBytes) {
806
+ flushFailure = { code: "flush_too_large" };
807
+ halt("flush");
808
+ throw stop;
809
+ }
758
810
  unsettledSeq = seq;
759
811
  try {
760
812
  const receipt = await withRetries(() => host.flush(request), "mutation");
@@ -779,14 +831,70 @@ async function runKnowledgeImport(options) {
779
831
  flushing = next.catch(() => {});
780
832
  return next;
781
833
  }
782
- const push = async (op) => {
834
+ /** The request around the ops, at the longest `seq` it can have; `ops` empty, no `state`. */
835
+ const envelopeBytes = encodedBytes({
836
+ runId,
837
+ generation,
838
+ seq: Number.MAX_SAFE_INTEGER,
839
+ digest: "0".repeat(64),
840
+ ops: []
841
+ });
842
+ /**
843
+ * The envelope at the shortest `seq` the next request can have. A request's `seq` is only known
844
+ * when it is sent, so splitting plans for the longest; refusing what can never fit uses the
845
+ * shortest, and the request as sent is measured again before it goes.
846
+ */
847
+ const shortestEnvelopeBytes = () => envelopeBytes - String(Number.MAX_SAFE_INTEGER).length + String(lastSeq + 1).length;
848
+ /** Bytes of a request holding the buffer plus `extra` more ops' bytes over `more` ops, and a state. */
849
+ const requestBytes = (extra, more, stateBytes) => {
850
+ const count = buffer.length + more;
851
+ const commas = Math.max(count - 1, 0);
852
+ const state = stateBytes === void 0 ? 0 : 9 + stateBytes;
853
+ return envelopeBytes + bufferBytes + extra + commas + state;
854
+ };
855
+ /**
856
+ * Measures what the importer hands over and returns a copy decoded from that encoding, so a value
857
+ * the importer changes after handing it over can't outgrow its measured size. Anything
858
+ * unencodable or too big ends the run here.
859
+ */
860
+ const measure = (value, alone) => {
861
+ let json;
862
+ let bytes;
863
+ try {
864
+ json = JSON.stringify(value);
865
+ bytes = new TextEncoder().encode(json).byteLength;
866
+ } catch (error) {
867
+ flushFailure = { code: "importer_error" };
868
+ halt("flush");
869
+ throw error;
870
+ }
871
+ if (alone(bytes) > maxFlushBytes) {
872
+ flushFailure = { code: "flush_too_large" };
873
+ halt("flush");
874
+ throw stop;
875
+ }
876
+ return {
877
+ bytes,
878
+ copy: JSON.parse(json)
879
+ };
880
+ };
881
+ const push = async (handed) => {
783
882
  if (stop) throw stop;
883
+ let op = handed;
884
+ let sending;
885
+ if (maxFlushBytes !== Infinity) {
886
+ const { bytes, copy } = measure(handed, (opBytes) => shortestEnvelopeBytes() + opBytes);
887
+ op = copy;
888
+ if (buffer.length > 0 && requestBytes(bytes, 1) > maxFlushBytes) sending = flush();
889
+ bufferBytes += bytes;
890
+ }
784
891
  buffer.push(op);
785
- if (buffer.length >= bufferSize) await flush();
786
- else if (!flushTimer) {
892
+ if (!flushTimer && buffer.length < bufferSize) {
787
893
  flushTimer = setTimeout(() => flush().catch(() => {}), flushAfterMs);
788
894
  flushTimer.unref?.();
789
895
  }
896
+ if (sending) await sending;
897
+ if (buffer.length >= bufferSize) await flush();
790
898
  };
791
899
  const finish = async (request) => {
792
900
  const result = await finishRun(host, {
@@ -850,7 +958,12 @@ async function runKnowledgeImport(options) {
850
958
  get: async (key) => state[key],
851
959
  set: async (key, value) => {
852
960
  if (stop) throw stop;
853
- await flush({ [key]: value });
961
+ const staged = { [key]: value };
962
+ if (maxFlushBytes !== Infinity) {
963
+ const { bytes } = measure(staged, (stateBytes) => shortestEnvelopeBytes() + 9 + stateBytes);
964
+ if (requestBytes(0, 0, bytes) > maxFlushBytes) flush().catch(() => {});
965
+ }
966
+ await flush(staged);
854
967
  }
855
968
  },
856
969
  items: {
@@ -956,6 +1069,892 @@ async function finishRun(host, request, lastSeq, unsettledSeq, withRetries) {
956
1069
  lastSeq
957
1070
  };
958
1071
  }
1072
+ function encodedBytes(value) {
1073
+ return new TextEncoder().encode(JSON.stringify(value)).byteLength;
1074
+ }
1075
+ // src/knowledge/importers/overlay.ts
1076
+ /**
1077
+ * The working copy a batched importer flush decides over (batched-flush plan v3.1 §1). The sink's
1078
+ * rule code runs unchanged against {@link ImportOverlay.storage} and {@link ImportOverlay.importers}:
1079
+ * reads come from rows gathered in a few set-based queries and locked, writes are applied to the
1080
+ * working copy and kept, in call order, for one batched write after every op is decided.
1081
+ *
1082
+ * A read of something not gathered throws {@link KnowledgeImportNotGatheredError} and names it, so
1083
+ * the caller gathers it and decides again. A call the working copy can't model throws
1084
+ * {@link KnowledgeImportBatchUnsupportedError}, and the flush takes the per-op path instead.
1085
+ *
1086
+ * @internal
1087
+ */
1088
+ /** The overlay was asked for a row it wasn't given. The caller gathers it and decides again. */
1089
+ var KnowledgeImportNotGatheredError = class extends Error {
1090
+ constructor(what) {
1091
+ super(`Not gathered for the batched import flush: ${what}`);
1092
+ this.name = "KnowledgeImportNotGatheredError";
1093
+ }
1094
+ };
1095
+ /** The flush needs a call the overlay doesn't model: it falls back to the per-op path. */
1096
+ var KnowledgeImportBatchUnsupportedError = class extends Error {
1097
+ call;
1098
+ constructor(call) {
1099
+ super(`Not supported by the batched import flush: ${call}`);
1100
+ this.call = call;
1101
+ this.name = "KnowledgeImportBatchUnsupportedError";
1102
+ }
1103
+ };
1104
+ const nodeKey = (bindingId, sourceId) => `${bindingId}\u0000${sourceId}`;
1105
+ const pathKey = (scopeId, path) => JSON.stringify([scopeId, ...path]);
1106
+ const childKey = (parentId, key) => `${parentId}\u0000${key}`;
1107
+ const byPosition = (a, b) => a.position < b.position ? -1 : a.position > b.position ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
1108
+ /** UTF-8 byte order, as the stores sort source IDs. */
1109
+ const byteOrder = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
1110
+ const emptyImportOverlayMissing = () => ({
1111
+ pages: /* @__PURE__ */ new Set(),
1112
+ nodes: /* @__PURE__ */ new Set(),
1113
+ nodesByPage: /* @__PURE__ */ new Set(),
1114
+ paths: /* @__PURE__ */ new Map(),
1115
+ notes: /* @__PURE__ */ new Set(),
1116
+ positions: /* @__PURE__ */ new Set(),
1117
+ locks: /* @__PURE__ */ new Set(),
1118
+ subtrees: /* @__PURE__ */ new Set(),
1119
+ linkTargets: /* @__PURE__ */ new Set(),
1120
+ bindings: /* @__PURE__ */ new Set()
1121
+ });
1122
+ const emptyImportOverlayRows = () => ({
1123
+ pages: /* @__PURE__ */ new Map(),
1124
+ nodes: /* @__PURE__ */ new Map(),
1125
+ nodesByPage: /* @__PURE__ */ new Map(),
1126
+ paths: /* @__PURE__ */ new Map(),
1127
+ notes: /* @__PURE__ */ new Map(),
1128
+ positions: /* @__PURE__ */ new Map(),
1129
+ locked: /* @__PURE__ */ new Set(),
1130
+ complete: /* @__PURE__ */ new Set(),
1131
+ tooLarge: /* @__PURE__ */ new Set(),
1132
+ linkTargets: /* @__PURE__ */ new Set(),
1133
+ tooManyLinkers: /* @__PURE__ */ new Set()
1134
+ });
1135
+ /** The binding and targets of a deferred mark, so back-to-back marks for one binding run as one. */
1136
+ const markTargets = /* @__PURE__ */ new WeakMap();
1137
+ const copyRows = (rows) => ({
1138
+ pages: new Map(rows.pages),
1139
+ nodes: new Map(rows.nodes),
1140
+ nodesByPage: new Map(rows.nodesByPage),
1141
+ paths: new Map(rows.paths),
1142
+ notes: new Map(rows.notes),
1143
+ positions: new Map(rows.positions),
1144
+ locked: new Set(rows.locked),
1145
+ complete: new Set(rows.complete),
1146
+ tooLarge: new Set(rows.tooLarge),
1147
+ linkTargets: new Set(rows.linkTargets),
1148
+ tooManyLinkers: new Set(rows.tooManyLinkers),
1149
+ ...rows.bindings ? { bindings: rows.bindings } : {}
1150
+ });
1151
+ const copyState = (state) => ({
1152
+ rows: copyRows(state.rows),
1153
+ writes: [...state.writes],
1154
+ touched: new Set(state.touched),
1155
+ marks: [...state.marks],
1156
+ links: [...state.links],
1157
+ moved: new Set(state.moved),
1158
+ freed: new Set(state.freed),
1159
+ stalePositions: new Set(state.stalePositions)
1160
+ });
1161
+ /** Every method the given implementation lacks throws {@link KnowledgeImportBatchUnsupportedError}. */
1162
+ function only(impl, name) {
1163
+ return new Proxy(impl, { get(target, prop, receiver) {
1164
+ if (prop in target) return Reflect.get(target, prop, receiver);
1165
+ if (typeof prop !== "string" || prop === "then") return void 0;
1166
+ return () => {
1167
+ throw new KnowledgeImportBatchUnsupportedError(`${name}.${prop}`);
1168
+ };
1169
+ } });
1170
+ }
1171
+ var ImportOverlay = class {
1172
+ missing = emptyImportOverlayMissing();
1173
+ #state;
1174
+ storage;
1175
+ importers;
1176
+ constructor(base, now = () => /* @__PURE__ */ new Date()) {
1177
+ this.#state = {
1178
+ rows: copyRows(base),
1179
+ writes: [],
1180
+ touched: /* @__PURE__ */ new Set(),
1181
+ marks: [],
1182
+ links: [],
1183
+ moved: /* @__PURE__ */ new Set(),
1184
+ freed: /* @__PURE__ */ new Set(),
1185
+ stalePositions: /* @__PURE__ */ new Set()
1186
+ };
1187
+ this.storage = this.#storage(now);
1188
+ this.importers = this.#importers();
1189
+ }
1190
+ get writes() {
1191
+ return this.#state.writes;
1192
+ }
1193
+ get marks() {
1194
+ return this.#state.marks;
1195
+ }
1196
+ get links() {
1197
+ return this.#state.links;
1198
+ }
1199
+ /** Link-index work the sink would run now; it runs, in one batch, after the batched write instead. */
1200
+ deferLinks(...work) {
1201
+ this.#state.links.push(...work);
1202
+ }
1203
+ /** The node writes decided: each touched node's last record, or a delete when it ends up gone. */
1204
+ nodeWrites(base) {
1205
+ const deletes = [];
1206
+ const saves = [];
1207
+ for (const key of this.#state.touched) {
1208
+ const node = this.#state.rows.nodes.get(key);
1209
+ if (node) {
1210
+ const { updatedAt: _updatedAt, ...record } = node;
1211
+ saves.push(record);
1212
+ } else if (base.nodes.get(key)) {
1213
+ const [bindingId, sourceId] = key.split("\0");
1214
+ deletes.push({
1215
+ bindingId,
1216
+ sourceId
1217
+ });
1218
+ }
1219
+ }
1220
+ return {
1221
+ deletes,
1222
+ saves
1223
+ };
1224
+ }
1225
+ #page(id) {
1226
+ const { pages } = this.#state.rows;
1227
+ if (!pages.has(id)) {
1228
+ this.missing.pages.add(id);
1229
+ throw new KnowledgeImportNotGatheredError(`page ${id}`);
1230
+ }
1231
+ return pages.get(id);
1232
+ }
1233
+ #livePage(id) {
1234
+ const page = this.#page(id);
1235
+ if (!page || page.deletedAt || page.mergedInto) throw new KnowledgeNotFoundError("page", id);
1236
+ return page;
1237
+ }
1238
+ /** Levels below the home scope, from the working copy's chain. */
1239
+ #depth(page) {
1240
+ let depth = 0;
1241
+ let at = page;
1242
+ while (at && !at.isScope) {
1243
+ depth++;
1244
+ at = at.parentId ? this.#page(at.parentId) : null;
1245
+ }
1246
+ return depth;
1247
+ }
1248
+ /** The page's key path from its scope, or null when the chain doesn't reach one. */
1249
+ #keys(page) {
1250
+ const path = [];
1251
+ let at = page;
1252
+ while (at && !at.isScope) {
1253
+ if (at.key === void 0 || at.deletedAt || at.mergedInto) return null;
1254
+ path.unshift(at.key);
1255
+ at = at.parentId ? this.#page(at.parentId) : null;
1256
+ }
1257
+ return at ? {
1258
+ scopeId: at.id,
1259
+ path
1260
+ } : null;
1261
+ }
1262
+ /**
1263
+ * Live ordinary children by parent, sorted by position: built on first use, dropped on each page
1264
+ * write, and keyed by the pages map, which a rolled-back transaction replaces.
1265
+ */
1266
+ #childIndex;
1267
+ #setPage(id, page) {
1268
+ this.#state.rows.pages.set(id, page);
1269
+ this.#childIndex = void 0;
1270
+ }
1271
+ /** Live ordinary children by position, once gathered. */
1272
+ #children(parentId) {
1273
+ const { pages, complete } = this.#state.rows;
1274
+ if (!complete.has(parentId)) {
1275
+ this.missing.subtrees.add(parentId);
1276
+ throw new KnowledgeImportNotGatheredError(`children of ${parentId}`);
1277
+ }
1278
+ if (this.#childIndex?.pages !== pages) {
1279
+ const byParent = /* @__PURE__ */ new Map();
1280
+ for (const page of pages.values()) {
1281
+ if (!page || !page.parentId || page.isScope || page.deletedAt) continue;
1282
+ const siblings = byParent.get(page.parentId);
1283
+ if (siblings) siblings.push(page);
1284
+ else byParent.set(page.parentId, [page]);
1285
+ }
1286
+ for (const siblings of byParent.values()) siblings.sort(byPosition);
1287
+ this.#childIndex = {
1288
+ pages,
1289
+ byParent
1290
+ };
1291
+ }
1292
+ return [...this.#childIndex.byParent.get(parentId) ?? []];
1293
+ }
1294
+ /** The next position under a parent, as `createPage` and `movePage` would place a page. */
1295
+ #nextPosition(parentId) {
1296
+ const { positions, complete } = this.#state.rows;
1297
+ if (this.#state.stalePositions.has(parentId)) {
1298
+ if (!complete.has(parentId)) throw new KnowledgeImportBatchUnsupportedError("a position under a parent its last child left");
1299
+ return knowledgePositionBetween(this.#children(parentId).at(-1)?.position);
1300
+ }
1301
+ if (!positions.has(parentId)) {
1302
+ this.missing.positions.add(parentId);
1303
+ throw new KnowledgeImportNotGatheredError(`last child position of ${parentId}`);
1304
+ }
1305
+ return knowledgePositionBetween(positions.get(parentId) ?? void 0);
1306
+ }
1307
+ /** A page left `parentId`: its next position is still the gathered one unless it was the last child. */
1308
+ #left(parentId, position) {
1309
+ if (!parentId) return;
1310
+ const last = this.#state.rows.positions.get(parentId);
1311
+ if (last === void 0 || last === position) this.#state.stalePositions.add(parentId);
1312
+ }
1313
+ /** Points the path map at where `pages` are now; `before` holds their old paths. */
1314
+ #repath(pages, before) {
1315
+ const { paths } = this.#state.rows;
1316
+ const ids = new Set(pages.map((page) => page.id));
1317
+ for (const [key, id] of paths) if (id && ids.has(id)) paths.set(key, null);
1318
+ for (const old of before) if (old) paths.set(pathKey(old.scopeId, old.path), null);
1319
+ for (const page of pages) {
1320
+ const keys = this.#rowKeys(page);
1321
+ if (keys) paths.set(pathKey(keys.scopeId, keys.path), page.id);
1322
+ }
1323
+ }
1324
+ /** {@link #keys} on the working copy's current row. */
1325
+ #rowKeys(page) {
1326
+ return this.#keys(this.#state.rows.pages.get(page.id) ?? page);
1327
+ }
1328
+ #node(key) {
1329
+ const { nodes } = this.#state.rows;
1330
+ if (!nodes.has(key)) {
1331
+ this.missing.nodes.add(key);
1332
+ throw new KnowledgeImportNotGatheredError(`node ${key}`);
1333
+ }
1334
+ return nodes.get(key);
1335
+ }
1336
+ #setNode(key, node) {
1337
+ const { nodes, nodesByPage } = this.#state.rows;
1338
+ const before = nodes.get(key);
1339
+ if (before && nodesByPage.get(before.pageId) === key) nodesByPage.set(before.pageId, null);
1340
+ nodes.set(key, node);
1341
+ if (node) nodesByPage.set(node.pageId, key);
1342
+ this.#state.touched.add(key);
1343
+ }
1344
+ #storage(now) {
1345
+ const rows = () => this.#state.rows;
1346
+ const impl = {
1347
+ transaction: async (fn) => {
1348
+ const saved = copyState(this.#state);
1349
+ try {
1350
+ return await fn(this.storage);
1351
+ } catch (error) {
1352
+ this.#state = saved;
1353
+ throw error;
1354
+ }
1355
+ },
1356
+ getPage: async ({ id }) => this.#page(id),
1357
+ getPageParents: async ({ parentId }) => {
1358
+ const parents = [];
1359
+ let id = parentId;
1360
+ while (id && parents.length <= 10) {
1361
+ const page = this.#page(id);
1362
+ if (!page) break;
1363
+ parents.push(page);
1364
+ id = page.parentId;
1365
+ }
1366
+ return parents;
1367
+ },
1368
+ getPageByPath: async ({ scopeId, path }) => {
1369
+ if (path.length === 0) return null;
1370
+ const key = pathKey(scopeId, path);
1371
+ if (!rows().paths.has(key)) {
1372
+ this.missing.paths.set(key, {
1373
+ scopeId,
1374
+ path
1375
+ });
1376
+ throw new KnowledgeImportNotGatheredError(`path ${key}`);
1377
+ }
1378
+ const id = rows().paths.get(key);
1379
+ return id ? this.#page(id) : null;
1380
+ },
1381
+ lockPages: async (ids) => {
1382
+ const unlocked = ids.filter((id) => !rows().locked.has(id));
1383
+ if (unlocked.length) {
1384
+ for (const id of unlocked) this.missing.locks.add(id);
1385
+ throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
1386
+ }
1387
+ },
1388
+ listNotes: async ({ pageId }) => {
1389
+ if (!rows().notes.has(pageId)) {
1390
+ this.missing.notes.add(pageId);
1391
+ throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
1392
+ }
1393
+ return { notes: rows().notes.get(pageId).filter((note) => !note.deletedAt) };
1394
+ },
1395
+ createPage: async (input) => {
1396
+ if (input.id !== void 0 || input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("createPage with id or position");
1397
+ if (!input.name.trim()) throw new Error("Knowledge page name must not be empty");
1398
+ assertKnowledgePageDescriptionWithinBound(input.description || void 0);
1399
+ const parent = this.#livePage(input.parentId);
1400
+ const scopeId = parent.isScope ? parent.id : parent.scopeId;
1401
+ const id = randomUUID();
1402
+ const depth = this.#depth(parent) + 1;
1403
+ if (depth > 10) throw new KnowledgePageDepthError(id);
1404
+ let path = null;
1405
+ if (input.key !== void 0) {
1406
+ const problem = knowledgePageKeyProblem(input.key);
1407
+ if (problem) throw new Error(problem);
1408
+ const parentKeys = parent.isScope ? {
1409
+ scopeId: parent.id,
1410
+ path: []
1411
+ } : this.#keys(parent);
1412
+ if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("createPage under a broken chain");
1413
+ path = [...parentKeys.path, input.key];
1414
+ if (await impl.getPageByPath({
1415
+ scopeId,
1416
+ path,
1417
+ read: "all"
1418
+ })) throw new KnowledgePageKeyConflictError(input.key, parent.id);
1419
+ }
1420
+ if (input.key !== void 0 && this.#state.freed.has(childKey(parent.id, input.key))) throw new KnowledgeImportBatchUnsupportedError("createPage at a key a move left");
1421
+ const position = this.#nextPosition(parent.id);
1422
+ const at = now();
1423
+ const page = {
1424
+ id,
1425
+ scopeId,
1426
+ parentId: parent.id,
1427
+ isScope: false,
1428
+ ...input.key !== void 0 ? { key: input.key } : {},
1429
+ position,
1430
+ name: input.name,
1431
+ ...input.description ? { description: input.description } : {},
1432
+ ...input.body !== void 0 ? { body: input.body } : {},
1433
+ version: 1,
1434
+ createdBy: structuredClone(input.provenance),
1435
+ updatedBy: structuredClone(input.provenance),
1436
+ createdAt: at,
1437
+ updatedAt: at
1438
+ };
1439
+ const state = rows();
1440
+ this.#setPage(id, page);
1441
+ state.positions.set(parent.id, position);
1442
+ state.positions.set(id, null);
1443
+ state.notes.set(id, []);
1444
+ state.nodesByPage.set(id, null);
1445
+ state.locked.add(id);
1446
+ state.complete.add(id);
1447
+ if (path) state.paths.set(pathKey(scopeId, path), id);
1448
+ this.#state.writes.push({
1449
+ op: "create",
1450
+ id,
1451
+ scopeId,
1452
+ parentId: parent.id,
1453
+ ...input.key !== void 0 ? { key: input.key } : {},
1454
+ name: input.name,
1455
+ ...input.description !== void 0 ? { description: input.description } : {},
1456
+ ...input.body !== void 0 ? { body: input.body } : {},
1457
+ position,
1458
+ depth,
1459
+ provenance: input.provenance
1460
+ });
1461
+ return structuredClone(page);
1462
+ },
1463
+ updatePage: async (input) => {
1464
+ const page = this.#livePage(input.id);
1465
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(page.id);
1466
+ if (input.name !== void 0 && !input.name.trim()) throw new Error("Knowledge page name must not be empty");
1467
+ assertKnowledgePageDescriptionWithinBound(input.description || void 0);
1468
+ const next = {
1469
+ ...page,
1470
+ version: page.version + 1,
1471
+ updatedBy: structuredClone(input.provenance)
1472
+ };
1473
+ next.updatedAt = now();
1474
+ if (input.name !== void 0) next.name = input.name;
1475
+ if (input.description !== void 0) {
1476
+ if (input.description) next.description = input.description;
1477
+ else delete next.description;
1478
+ }
1479
+ if (input.body !== void 0) next.body = input.body;
1480
+ this.#setPage(page.id, next);
1481
+ this.#state.writes.push({
1482
+ op: "update",
1483
+ id: page.id,
1484
+ scopeId: page.scopeId,
1485
+ expectedVersion: input.expectedVersion,
1486
+ ...input.name !== void 0 ? { name: input.name } : {},
1487
+ ...input.description !== void 0 ? { description: input.description } : {},
1488
+ ...input.body !== void 0 ? { body: input.body } : {},
1489
+ provenance: input.provenance
1490
+ });
1491
+ return structuredClone(next);
1492
+ },
1493
+ listChildPages: async ({ parentId, read, cursor, limit }) => {
1494
+ if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("listChildPages with a read scope");
1495
+ const children = this.#children(parentId);
1496
+ const start = cursor ? Number(cursor) : 0;
1497
+ const end = limit === void 0 ? children.length : start + limit;
1498
+ return {
1499
+ pages: children.slice(start, end).map((page) => structuredClone(page)),
1500
+ ...end < children.length ? { nextCursor: String(end) } : {}
1501
+ };
1502
+ },
1503
+ countChildPages: async ({ parentIds, read }) => {
1504
+ if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("countChildPages with a read scope");
1505
+ return Object.fromEntries(parentIds.map((id) => [id, this.#children(id).length]));
1506
+ },
1507
+ lockSubtree: async (rootId) => {
1508
+ if (rows().tooLarge.has(rootId)) throw new KnowledgeMoveTooLargeError(rootId, 501);
1509
+ const ids = [];
1510
+ const parents = [rootId];
1511
+ while (parents.length) {
1512
+ for (const child of this.#children(parents.shift())) {
1513
+ ids.push(child.id);
1514
+ parents.push(child.id);
1515
+ }
1516
+ if (ids.length >= 500) throw new KnowledgeMoveTooLargeError(rootId, ids.length + 1);
1517
+ }
1518
+ const unlocked = ids.filter((id) => !rows().locked.has(id));
1519
+ if (unlocked.length) {
1520
+ for (const id of unlocked) this.missing.locks.add(id);
1521
+ throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
1522
+ }
1523
+ return ids;
1524
+ },
1525
+ movePage: async (input) => {
1526
+ if (input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("movePage with a position");
1527
+ const page = this.#livePage(input.id);
1528
+ if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be moved`);
1529
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(page.id);
1530
+ const parent = this.#livePage(input.parentId);
1531
+ const subtree = [];
1532
+ const visit = (at, depth) => {
1533
+ subtree.push({
1534
+ page: at,
1535
+ depth
1536
+ });
1537
+ for (const child of this.#children(at.id)) visit(child, depth + 1);
1538
+ };
1539
+ visit(page, 0);
1540
+ if (subtree.some((entry) => entry.page.id === parent.id)) throw new Error(`Knowledge page ${page.id} can't move under itself or its own subtree`);
1541
+ if (subtree.length > 500) throw new KnowledgeMoveTooLargeError(page.id, subtree.length);
1542
+ const parentDepth = parent.isScope ? 0 : this.#depth(parent);
1543
+ if (parentDepth + 1 + Math.max(...subtree.map((entry) => entry.depth)) > 10) throw new KnowledgePageDepthError(page.id);
1544
+ const scopeId = parent.isScope ? parent.id : parent.scopeId;
1545
+ if (scopeId !== page.scopeId) throw new KnowledgeImportBatchUnsupportedError("movePage across scopes");
1546
+ if (page.key !== void 0) {
1547
+ const parentKeys = parent.isScope ? {
1548
+ scopeId: parent.id,
1549
+ path: []
1550
+ } : this.#keys(parent);
1551
+ if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("movePage under a broken chain");
1552
+ const clash = await impl.getPageByPath({
1553
+ scopeId,
1554
+ path: [...parentKeys.path, page.key],
1555
+ read: "all"
1556
+ });
1557
+ if (clash && clash.id !== page.id) throw new KnowledgePageKeyConflictError(page.key, parent.id);
1558
+ }
1559
+ if (this.#state.moved.has(page.id)) throw new KnowledgeImportBatchUnsupportedError("a second move of a page");
1560
+ const position = this.#nextPosition(parent.id);
1561
+ const before = subtree.map((entry) => this.#keys(entry.page));
1562
+ const at = now();
1563
+ const moved = {
1564
+ ...page,
1565
+ parentId: parent.id,
1566
+ position,
1567
+ version: page.version + 1,
1568
+ updatedBy: structuredClone(input.provenance),
1569
+ updatedAt: at
1570
+ };
1571
+ const state = rows();
1572
+ this.#setPage(page.id, moved);
1573
+ state.positions.set(parent.id, position);
1574
+ this.#left(page.parentId, page.position);
1575
+ if (page.parentId && page.key !== void 0) this.#state.freed.add(childKey(page.parentId, page.key));
1576
+ this.#state.moved.add(page.id);
1577
+ this.#repath(subtree.map((entry) => state.pages.get(entry.page.id)), before);
1578
+ this.#state.writes.push({
1579
+ op: "move",
1580
+ id: page.id,
1581
+ fromScopeId: page.scopeId,
1582
+ expectedVersion: input.expectedVersion,
1583
+ parentId: parent.id,
1584
+ scopeId,
1585
+ depth: parentDepth + 1,
1586
+ position,
1587
+ provenance: input.provenance
1588
+ });
1589
+ return structuredClone(moved);
1590
+ },
1591
+ deletePage: async (input) => {
1592
+ const page = this.#livePage(input.id);
1593
+ if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be deleted`);
1594
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(page.id);
1595
+ if (this.#children(page.id).length) throw new KnowledgePageHasChildrenError(page.id);
1596
+ const at = now();
1597
+ const deleted = {
1598
+ ...page,
1599
+ deletedAt: at,
1600
+ deletedBy: input.deletedBy,
1601
+ version: page.version + 1,
1602
+ updatedAt: at
1603
+ };
1604
+ this.#setPage(page.id, deleted);
1605
+ this.#left(page.parentId, page.position);
1606
+ for (const [key, id] of rows().paths) if (id === page.id) rows().paths.set(key, null);
1607
+ this.#state.writes.push({
1608
+ op: "delete",
1609
+ id: page.id,
1610
+ scopeId: page.scopeId,
1611
+ expectedVersion: input.expectedVersion,
1612
+ deletedBy: input.deletedBy
1613
+ });
1614
+ return structuredClone(deleted);
1615
+ },
1616
+ addNote: async (input) => {
1617
+ const page = this.#livePage(input.pageId);
1618
+ assertKnowledgeNoteTextWithinBound(input.text);
1619
+ if (input.mentions.length) throw new KnowledgeImportBatchUnsupportedError("addNote with mentions");
1620
+ const notes = this.#notesOf(page.id);
1621
+ const id = input.id ?? randomUUID();
1622
+ if (notes.some((note) => note.id === id)) throw new KnowledgeConflictError(id);
1623
+ const at = now();
1624
+ const note = {
1625
+ id,
1626
+ pageId: page.id,
1627
+ text: input.text,
1628
+ ...input.when ? { when: new Date(input.when) } : {},
1629
+ stampScopeIds: [...new Set(input.stampScopeIds)],
1630
+ mentions: [],
1631
+ provenance: structuredClone(input.provenance),
1632
+ version: 1,
1633
+ createdAt: at,
1634
+ updatedAt: at
1635
+ };
1636
+ rows().notes.set(page.id, [...notes, note]);
1637
+ this.#state.writes.push({
1638
+ op: "add-note",
1639
+ id,
1640
+ pageId: page.id,
1641
+ scopeId: page.scopeId,
1642
+ text: input.text,
1643
+ ...input.when ? { when: input.when } : {},
1644
+ stampScopeIds: input.stampScopeIds,
1645
+ mentions: [],
1646
+ provenance: input.provenance
1647
+ });
1648
+ return structuredClone(note);
1649
+ },
1650
+ removeNote: async (input) => {
1651
+ for (const [pageId, notes] of rows().notes) {
1652
+ const note = notes.find((each) => each.id === input.id);
1653
+ if (!note) continue;
1654
+ if (note.deletedAt) throw new KnowledgeNotFoundError("note", input.id);
1655
+ if (this.#state.writes.some((write) => write.op === "add-note" && write.id === input.id)) throw new KnowledgeImportBatchUnsupportedError("removeNote of a note this flush added");
1656
+ const page = this.#livePage(pageId);
1657
+ const at = now();
1658
+ const removed = {
1659
+ ...note,
1660
+ deletedAt: at,
1661
+ deletedBy: input.deletedBy,
1662
+ version: note.version + 1,
1663
+ updatedAt: at
1664
+ };
1665
+ rows().notes.set(pageId, notes.map((each) => each.id === input.id ? removed : each));
1666
+ this.#state.writes.push({
1667
+ op: "remove-note",
1668
+ id: input.id,
1669
+ pageId,
1670
+ scopeId: page.scopeId,
1671
+ deletedBy: input.deletedBy,
1672
+ provenance: input.provenance
1673
+ });
1674
+ return structuredClone(removed);
1675
+ }
1676
+ throw new KnowledgeImportBatchUnsupportedError("removeNote of a note not gathered");
1677
+ }
1678
+ };
1679
+ return only(impl, "storage");
1680
+ }
1681
+ #notesOf(pageId) {
1682
+ const { notes } = this.#state.rows;
1683
+ if (!notes.has(pageId)) {
1684
+ this.missing.notes.add(pageId);
1685
+ throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
1686
+ }
1687
+ return notes.get(pageId);
1688
+ }
1689
+ #importers() {
1690
+ const rows = () => this.#state.rows;
1691
+ return only({
1692
+ getNode: async (bindingId, sourceId) => structuredClone(this.#node(nodeKey(bindingId, sourceId))),
1693
+ getNodes: async (bindingId, sourceIds) => {
1694
+ const nodes = [];
1695
+ const unread = [...new Set(sourceIds)].filter((sourceId) => !rows().nodes.has(nodeKey(bindingId, sourceId)));
1696
+ if (unread.length) {
1697
+ for (const sourceId of unread) this.missing.nodes.add(nodeKey(bindingId, sourceId));
1698
+ throw new KnowledgeImportNotGatheredError(`nodes ${unread.join(", ")}`);
1699
+ }
1700
+ for (const sourceId of new Set(sourceIds)) {
1701
+ const node = rows().nodes.get(nodeKey(bindingId, sourceId));
1702
+ if (node) nodes.push(structuredClone(node));
1703
+ }
1704
+ return nodes;
1705
+ },
1706
+ getNodeByPage: async (pageId) => {
1707
+ if (!rows().nodesByPage.has(pageId)) {
1708
+ this.missing.nodesByPage.add(pageId);
1709
+ throw new KnowledgeImportNotGatheredError(`node of page ${pageId}`);
1710
+ }
1711
+ const key = rows().nodesByPage.get(pageId);
1712
+ return key ? structuredClone(this.#node(key)) : null;
1713
+ },
1714
+ saveNode: async (node) => {
1715
+ const key = nodeKey(node.bindingId, node.sourceId);
1716
+ const mapped = rows().nodesByPage.get(node.pageId);
1717
+ if (mapped === void 0) {
1718
+ this.missing.nodesByPage.add(node.pageId);
1719
+ throw new KnowledgeImportNotGatheredError(`node of page ${node.pageId}`);
1720
+ }
1721
+ if (mapped && mapped !== key) throw new KnowledgeImportBatchUnsupportedError("saveNode onto a mapped page");
1722
+ this.#setNode(key, {
1723
+ ...structuredClone(node),
1724
+ updatedAt: /* @__PURE__ */ new Date()
1725
+ });
1726
+ },
1727
+ deleteNode: async (bindingId, sourceId) => {
1728
+ const key = nodeKey(bindingId, sourceId);
1729
+ this.#node(key);
1730
+ this.#setNode(key, null);
1731
+ },
1732
+ markLinkingNodesUnsettled: async (bindingId, targetSourceIds) => {
1733
+ const targets = new Set(targetSourceIds);
1734
+ for (const [key, node] of rows().nodes) if (node && node.bindingId === bindingId && node.links.some((link) => targets.has(link.sourceId))) rows().nodes.set(key, {
1735
+ ...node,
1736
+ unsettled: true
1737
+ });
1738
+ const marks = this.#state.marks;
1739
+ const last = marks.at(-1);
1740
+ const prior = last && markTargets.get(last);
1741
+ const all = prior?.bindingId === bindingId ? [.../* @__PURE__ */ new Set([...prior.targets, ...targetSourceIds])] : [...targetSourceIds];
1742
+ if (prior?.bindingId === bindingId) marks.pop();
1743
+ const mark = (_, importers) => importers.markLinkingNodesUnsettled(bindingId, all);
1744
+ markTargets.set(mark, {
1745
+ bindingId,
1746
+ targets: all
1747
+ });
1748
+ marks.push(mark);
1749
+ },
1750
+ setState: async (bindingId, state) => {
1751
+ this.#state.marks.push((_, importers) => importers.setState(bindingId, state));
1752
+ },
1753
+ listLinkingNodes: async (bindingId, targetSourceIds, options = {}) => {
1754
+ const keys = [...new Set(targetSourceIds)].map((sourceId) => nodeKey(bindingId, sourceId));
1755
+ if (keys.some((key) => rows().tooManyLinkers.has(key))) throw new KnowledgeImportBatchUnsupportedError("listLinkingNodes past the gathered linking nodes");
1756
+ const unread = keys.filter((key) => !rows().linkTargets.has(key));
1757
+ if (unread.length) {
1758
+ for (const key of unread) this.missing.linkTargets.add(key);
1759
+ throw new KnowledgeImportNotGatheredError(`linking nodes of ${unread.join(", ")}`);
1760
+ }
1761
+ const targets = new Set(targetSourceIds);
1762
+ const ids = [...rows().nodes.values()].filter((node) => !!node && node.bindingId === bindingId && node.links.some((link) => targets.has(link.sourceId))).map((node) => node.sourceId).filter((id) => options.after === void 0 || byteOrder(id, options.after) > 0).sort(byteOrder);
1763
+ const limit = options.limit ?? 500;
1764
+ const items = ids.slice(0, limit);
1765
+ return {
1766
+ items,
1767
+ next: ids.length > limit ? items[items.length - 1] : null
1768
+ };
1769
+ },
1770
+ listBindings: async () => {
1771
+ const { bindings } = rows();
1772
+ if (!bindings) {
1773
+ this.missing.bindings.add("bindings");
1774
+ throw new KnowledgeImportNotGatheredError("bindings");
1775
+ }
1776
+ return structuredClone(bindings);
1777
+ }
1778
+ }, "importers");
1779
+ }
1780
+ };
1781
+ /** True when the stores implement every set-based method the batched flush needs. */
1782
+ function canBatchImportFlush(storage, importers) {
1783
+ return !!(storage.getPageChains && storage.getPagesByPaths && storage.getLastChildPositions && storage.listNotesByPages && storage.getPageSubtrees && storage.applyPageWrites && canRepairKnowledgeLinksInBatch(storage) && importers.getNodes && importers.getNodesByPages && importers.writeNodes);
1784
+ }
1785
+ async function readImportRows(input) {
1786
+ const { storage, importers, bindingId, missing } = input;
1787
+ const rows = emptyImportOverlayRows();
1788
+ const sourceIds = new Set(input.sourceIds);
1789
+ for (const key of missing?.nodes ?? []) {
1790
+ const [binding, sourceId] = key.split("\0");
1791
+ if (binding === bindingId) sourceIds.add(sourceId);
1792
+ }
1793
+ const nodes = sourceIds.size ? await importers.getNodes(bindingId, [...sourceIds]) : [];
1794
+ for (const sourceId of sourceIds) rows.nodes.set(nodeKey(bindingId, sourceId), null);
1795
+ for (const node of nodes) {
1796
+ rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
1797
+ rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
1798
+ }
1799
+ const addChains = async (ids) => {
1800
+ const wanted = [...ids].filter((id) => !rows.pages.has(id));
1801
+ if (!wanted.length) return;
1802
+ const chains = await storage.getPageChains({
1803
+ ids: wanted,
1804
+ read: "all"
1805
+ });
1806
+ for (const id of wanted) {
1807
+ const chain = chains[id] ?? [];
1808
+ if (!chain.length) rows.pages.set(id, null);
1809
+ for (const page of chain) rows.pages.set(page.id, page);
1810
+ const last = chain.at(-1);
1811
+ if (last?.parentId && chain.length <= 10 && !rows.pages.has(last.parentId)) rows.pages.set(last.parentId, null);
1812
+ }
1813
+ };
1814
+ await addChains(/* @__PURE__ */ new Set([
1815
+ ...input.pageIds,
1816
+ ...nodes.map((node) => node.pageId),
1817
+ ...missing?.pages ?? [],
1818
+ ...missing?.locks ?? []
1819
+ ]));
1820
+ const plan = input.plan(rows);
1821
+ const roots = [.../* @__PURE__ */ new Set([...plan.subtrees, ...missing?.subtrees ?? []])].filter((id) => !rows.complete.has(id));
1822
+ const carried = [];
1823
+ if (roots.length) {
1824
+ const subtrees = await storage.getPageSubtrees({
1825
+ rootIds: roots,
1826
+ limit: 499
1827
+ });
1828
+ for (const root of roots) {
1829
+ const pages = subtrees[root];
1830
+ if (!pages) {
1831
+ rows.tooLarge.add(root);
1832
+ continue;
1833
+ }
1834
+ rows.complete.add(root);
1835
+ for (const page of pages) {
1836
+ rows.pages.set(page.id, page);
1837
+ rows.complete.add(page.id);
1838
+ carried.push(page.id);
1839
+ }
1840
+ }
1841
+ const unmapped = carried.filter((id) => !rows.nodesByPage.has(id));
1842
+ if (unmapped.length) {
1843
+ for (const id of unmapped) rows.nodesByPage.set(id, null);
1844
+ for (const node of await importers.getNodesByPages(unmapped)) {
1845
+ const key = nodeKey(node.bindingId, node.sourceId);
1846
+ rows.nodes.set(key, node);
1847
+ rows.nodesByPage.set(node.pageId, key);
1848
+ }
1849
+ }
1850
+ }
1851
+ const targets = new Set(plan.linkTargets);
1852
+ for (const id of carried) {
1853
+ const key = rows.nodesByPage.get(id);
1854
+ const node = key ? rows.nodes.get(key) : null;
1855
+ if (node?.bindingId === bindingId) targets.add(node.sourceId);
1856
+ }
1857
+ for (const key of missing?.linkTargets ?? []) {
1858
+ const [binding, sourceId] = key.split("\0");
1859
+ if (binding === bindingId) targets.add(sourceId);
1860
+ }
1861
+ const wanted = [...targets].filter((sourceId) => !rows.linkTargets.has(nodeKey(bindingId, sourceId)));
1862
+ if (wanted.length) {
1863
+ const linking = await importers.listLinkingNodes(bindingId, wanted, { limit: LINKING_NODES_READ });
1864
+ for (const sourceId of wanted) (linking.next ? rows.tooManyLinkers : rows.linkTargets).add(nodeKey(bindingId, sourceId));
1865
+ const readNodes = async (sourceIds) => {
1866
+ const unread = [...new Set(sourceIds)].filter((sourceId) => !rows.nodes.has(nodeKey(bindingId, sourceId)));
1867
+ if (!unread.length) return [];
1868
+ for (const sourceId of unread) rows.nodes.set(nodeKey(bindingId, sourceId), null);
1869
+ const read = await importers.getNodes(bindingId, unread);
1870
+ for (const node of read) {
1871
+ rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
1872
+ rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
1873
+ }
1874
+ return read;
1875
+ };
1876
+ const linkers = await readNodes(linking.items);
1877
+ const reached = await readNodes(linking.items.map((sourceId) => rows.nodes.get(nodeKey(bindingId, sourceId))).filter((n) => !!n).flatMap((node) => [...node.links.map((link) => link.sourceId), ...node.parentSourceId ? [node.parentSourceId] : []]));
1878
+ await addChains(new Set([...linkers, ...reached].map((node) => node.pageId)));
1879
+ }
1880
+ if (plan.bindings || missing?.bindings.size) rows.bindings ??= await importers.listBindings();
1881
+ const paths = new Map(plan.paths.map((each) => [pathKey(each.scopeId, each.path), each]));
1882
+ for (const [key, each] of missing?.paths ?? []) paths.set(key, each);
1883
+ const byScope = /* @__PURE__ */ new Map();
1884
+ for (const [key, { scopeId, path }] of paths) {
1885
+ if (path.length === 0) continue;
1886
+ byScope.set(scopeId, [...byScope.get(scopeId) ?? [], {
1887
+ key,
1888
+ path
1889
+ }]);
1890
+ }
1891
+ for (const [scopeId, entries] of byScope) {
1892
+ const found = await storage.getPagesByPaths({
1893
+ scopeId,
1894
+ paths: entries.map((each) => each.path),
1895
+ read: "all"
1896
+ });
1897
+ entries.forEach((each, i) => {
1898
+ const page = found[i] ?? null;
1899
+ rows.paths.set(each.key, page?.id ?? null);
1900
+ if (page && !rows.pages.has(page.id)) rows.pages.set(page.id, page);
1901
+ });
1902
+ }
1903
+ const held = [...rows.paths.values()].filter((id) => !!id);
1904
+ await addChains(new Set(held.map((id) => rows.pages.get(id)?.parentId).filter((id) => !!id)));
1905
+ const byPage = [...new Set([...held, ...missing?.nodesByPage ?? []].filter((id) => !rows.nodesByPage.has(id)))];
1906
+ if (byPage.length) {
1907
+ for (const id of byPage) rows.nodesByPage.set(id, null);
1908
+ for (const node of await importers.getNodesByPages(byPage)) {
1909
+ const key = nodeKey(node.bindingId, node.sourceId);
1910
+ rows.nodes.set(key, node);
1911
+ rows.nodesByPage.set(node.pageId, key);
1912
+ }
1913
+ }
1914
+ const notes = [.../* @__PURE__ */ new Set([
1915
+ ...plan.notes,
1916
+ ...held,
1917
+ ...missing?.notes ?? []
1918
+ ])];
1919
+ if (notes.length) {
1920
+ const listed = await storage.listNotesByPages({
1921
+ pageIds: notes,
1922
+ read: "all"
1923
+ });
1924
+ for (const id of notes) rows.notes.set(id, listed[id] ?? []);
1925
+ }
1926
+ const positions = [.../* @__PURE__ */ new Set([...plan.positions, ...missing?.positions ?? []])];
1927
+ if (positions.length) {
1928
+ const last = await storage.getLastChildPositions({ parentIds: positions });
1929
+ for (const id of positions) rows.positions.set(id, last[id] ?? null);
1930
+ }
1931
+ return rows;
1932
+ }
1933
+ /** Most linking nodes one gather reads; past it, a flush that lists them is saved op by op. */
1934
+ const LINKING_NODES_READ = 500;
1935
+ /** Live, non-scope pages among the rows: the ones a decide pass may lock. */
1936
+ const lockable = (rows) => [...rows.pages.values()].filter((page) => !!page && !page.isScope && !page.deletedAt && !page.mergedInto).map((page) => page.id);
1937
+ /**
1938
+ * Reads every row a decide pass needs in a few set-based queries, locks the live pages among them
1939
+ * in one sorted call, and reads again under the lock: what the second read returns can't change
1940
+ * until commit (a new page at an empty path is refused by the unique key when written). Pages the
1941
+ * second read finds that the first didn't are locked too, and read again, up to `rounds` times.
1942
+ */
1943
+ async function gatherImportRows(input) {
1944
+ const locked = new Set(input.locked ?? []);
1945
+ let rows = await readImportRows(input);
1946
+ for (let round = 0; round < (input.rounds ?? 3); round++) {
1947
+ const unlocked = lockable(rows).filter((id) => !locked.has(id));
1948
+ if (!unlocked.length) {
1949
+ rows.locked = locked;
1950
+ return rows;
1951
+ }
1952
+ await input.storage.lockPages(unlocked.sort());
1953
+ for (const id of unlocked) locked.add(id);
1954
+ rows = await readImportRows(input);
1955
+ }
1956
+ return null;
1957
+ }
959
1958
  // src/knowledge/importers/sink.ts
960
1959
  /**
961
1960
  * Applies one flush's ops to pages and the node map, on a transaction view. Pages are found by id
@@ -1012,6 +2011,17 @@ const ownText = (body, section) => {
1012
2011
  if (body === section) return "";
1013
2012
  return body.endsWith(`\n\n${section}`) ? body.slice(0, body.length - section.length - 2) : null;
1014
2013
  };
2014
+ /** Decide passes a batched flush makes before it falls back: each reads what the last one lacked. */
2015
+ const BATCH_DECIDE_PASSES = 4;
2016
+ /** The batched flush can't land this one: its savepoint rolls back and the ops go one by one. */
2017
+ var BatchFallback = class extends Error {
2018
+ reason;
2019
+ constructor(reason) {
2020
+ super(`Batched import flush fell back: ${reason}`);
2021
+ this.reason = reason;
2022
+ this.name = "BatchFallback";
2023
+ }
2024
+ };
1015
2025
  /** A per-item refusal: its savepoint rolls back and the flush goes on. */
1016
2026
  var KnowledgeImportRefusalError = class extends Error {
1017
2027
  reason;
@@ -1107,7 +2117,27 @@ function order(ops) {
1107
2117
  return [...sorted, ...removes];
1108
2118
  }
1109
2119
  async function applyKnowledgeImportFlush(input) {
1110
- const { storage, importers, binding, scope, provenance } = input;
2120
+ const { binding, scope, provenance } = input;
2121
+ let { storage, importers } = input;
2122
+ let overlay = null;
2123
+ /**
2124
+ * Link-index work for a written page: a sync of its body links, then maybe a refresh of the links to
2125
+ * it. Run now, or after the batched write in one repair when deciding over the working copy.
2126
+ */
2127
+ const links = async (sync, refresh) => {
2128
+ if (overlay) {
2129
+ if (sync) overlay.deferLinks({ sync });
2130
+ for (const page of refresh?.pages ?? []) overlay.deferLinks({
2131
+ refresh: page,
2132
+ withDescendants: !!refresh.withDescendants
2133
+ });
2134
+ return;
2135
+ }
2136
+ await syncLinks(async () => {
2137
+ if (sync) await syncKnowledgePageBodyLinks(storage, sync);
2138
+ if (refresh) await refreshKnowledgeLinksTo(storage, refresh.pages, { withDescendants: refresh.withDescendants });
2139
+ });
2140
+ };
1111
2141
  const target = parseKnowledgeImportTarget(binding.target);
1112
2142
  const result = {
1113
2143
  counts: {
@@ -1116,7 +2146,8 @@ async function applyKnowledgeImportFlush(input) {
1116
2146
  unchanged: 0,
1117
2147
  moved: 0,
1118
2148
  removed: 0,
1119
- stubbed: 0
2149
+ stubbed: 0,
2150
+ merged: 0
1120
2151
  },
1121
2152
  refused: [],
1122
2153
  changes: [],
@@ -1136,20 +2167,24 @@ async function applyKnowledgeImportFlush(input) {
1136
2167
  const keyPath = async (page) => {
1137
2168
  const keys = [];
1138
2169
  const ids = [];
1139
- let at = page;
1140
- while (at && !at.isScope) {
2170
+ if (page.isScope) return page.id === scope.id ? {
2171
+ keys,
2172
+ ids
2173
+ } : null;
2174
+ const parents = page.parentId ? await storage.getPageParents({
2175
+ parentId: page.parentId,
2176
+ read: "all"
2177
+ }) : [];
2178
+ for (const at of [page, ...parents]) {
2179
+ if (at.isScope) return at.id === scope.id ? {
2180
+ keys,
2181
+ ids
2182
+ } : null;
1141
2183
  if (!live(at) || at.key === void 0) return null;
1142
2184
  keys.unshift(at.key);
1143
2185
  ids.unshift(at.id);
1144
- at = at.parentId ? await storage.getPage({
1145
- id: at.parentId,
1146
- read: "all"
1147
- }) : null;
1148
2186
  }
1149
- return at?.id === scope.id ? {
1150
- keys,
1151
- ids
1152
- } : null;
2187
+ return null;
1153
2188
  };
1154
2189
  const sameKeys = (a, b) => a.length === b.length && a.every((key, i) => key === b[i]);
1155
2190
  /**
@@ -1296,12 +2331,13 @@ async function applyKnowledgeImportFlush(input) {
1296
2331
  };
1297
2332
  };
1298
2333
  const nodeOf = async (sourceId) => sourceId ? importers.getNode(binding.id, sourceId) : null;
1299
- const gone = async (node) => {
2334
+ const stateOf = async (node) => {
1300
2335
  const page = await storage.getPage({
1301
2336
  id: node.pageId,
1302
2337
  read: "all"
1303
2338
  });
1304
- return !page || !!page.deletedAt && !page.mergedInto || live(page) && page.scopeId !== scope.id;
2339
+ if (page?.mergedInto) return "merged";
2340
+ return !page || !!page.deletedAt || page.scopeId !== scope.id ? "gone" : "live";
1305
2341
  };
1306
2342
  /**
1307
2343
  * Drops the node of a page that is gone, so its item is written again as new. Pages that linked to
@@ -1353,15 +2389,14 @@ async function applyKnowledgeImportFlush(input) {
1353
2389
  });
1354
2390
  await importers.markLinkingNodesUnsettled(binding.id, [node.sourceId]);
1355
2391
  await importers.deleteNode(binding.id, node.sourceId);
1356
- if (old) await syncLinks(() => refreshKnowledgeLinksTo(storage, [old]));
2392
+ if (old) await links(null, { pages: [old] });
1357
2393
  };
1358
2394
  const liveNodeOf = async (sourceId) => {
1359
2395
  const node = await nodeOf(sourceId);
1360
- return node && !await gone(node) ? node : null;
2396
+ return node && await stateOf(node) === "live" ? node : null;
1361
2397
  };
1362
2398
  const ref = (keys) => `${target.scope}#${keys.join("/")}`;
1363
- const linkLine = async (link) => {
1364
- const node = await importers.getNode(binding.id, link.sourceId);
2399
+ const linkLine = async (link, node) => {
1365
2400
  const page = node ? await storage.getPage({
1366
2401
  id: node.pageId,
1367
2402
  read: "all"
@@ -1372,11 +2407,30 @@ async function applyKnowledgeImportFlush(input) {
1372
2407
  const renderLinks = async (links) => {
1373
2408
  const lines = [];
1374
2409
  const unresolved = [];
2410
+ const getNodes = async (sourceIds) => {
2411
+ if (!sourceIds.length) return [];
2412
+ if (importers.getNodes) return importers.getNodes(binding.id, sourceIds);
2413
+ const nodes = [];
2414
+ for (const sourceId of new Set(sourceIds)) {
2415
+ const node = await importers.getNode(binding.id, sourceId);
2416
+ if (node) nodes.push(node);
2417
+ }
2418
+ return nodes;
2419
+ };
2420
+ const read = async (sourceIds) => new Map((await getNodes(sourceIds)).map((node) => [node.sourceId, node]));
2421
+ const before = await read(links.map((link) => link.sourceId));
2422
+ const rendered = [];
1375
2423
  for (const link of links) {
1376
- const line = await linkLine(link);
1377
- if (line) lines.push(line);
1378
- else unresolved.push(encodeLink(link));
2424
+ const node = before.get(link.sourceId);
2425
+ rendered.push({
2426
+ link,
2427
+ line: await linkLine(link, node),
2428
+ pageId: node?.pageId
2429
+ });
1379
2430
  }
2431
+ const after = await read(rendered.filter((each) => each.line).map((each) => each.link.sourceId));
2432
+ for (const { link, line, pageId } of rendered) if (line && after.get(link.sourceId)?.pageId === pageId) lines.push(line);
2433
+ else unresolved.push(encodeLink(link));
1380
2434
  return {
1381
2435
  section: linkSection(lines),
1382
2436
  unresolved
@@ -1422,7 +2476,7 @@ async function applyKnowledgeImportFlush(input) {
1422
2476
  body,
1423
2477
  provenance
1424
2478
  });
1425
- await syncLinks(() => syncKnowledgePageBodyLinks(storage, page));
2479
+ await links(page);
1426
2480
  return {
1427
2481
  page,
1428
2482
  changed: true,
@@ -1518,12 +2572,17 @@ async function applyKnowledgeImportFlush(input) {
1518
2572
  };
1519
2573
  const write = async (item, hasBody) => {
1520
2574
  let existing = await importers.getNode(binding.id, item.sourceId);
1521
- if (existing && await gone(existing)) {
2575
+ const state = existing ? await stateOf(existing) : null;
2576
+ if (state === "merged") return null;
2577
+ if (existing && state === "gone") {
1522
2578
  await forget(existing);
1523
2579
  existing = null;
1524
2580
  }
1525
- const sourceParent = await liveNodeOf(item.parent);
1526
- const misplaced = !!item.parent && !sourceParent;
2581
+ const parentRecord = await nodeOf(item.parent);
2582
+ const parentState = parentRecord ? await stateOf(parentRecord) : null;
2583
+ const sourceParent = parentState === "live" ? parentRecord : null;
2584
+ const parentMerged = parentState === "merged";
2585
+ const misplaced = !!item.parent && !sourceParent && !parentMerged;
1527
2586
  const parentNode = sourceParent ?? await liveNodeOf(item.fallbackParent);
1528
2587
  const destination = parentNode ? await owned(parentNode.pageId, parentNode.sourceId) : anchor;
1529
2588
  if (existing && destination.page.id === existing.pageId) throw new KnowledgeImportRefusalError("invalid");
@@ -1577,7 +2636,7 @@ async function applyKnowledgeImportFlush(input) {
1577
2636
  const current = await owned(existing.pageId, item.sourceId);
1578
2637
  page = current.page;
1579
2638
  if (existing.stub && existing.adopted && !REMOVED_BODIES.has(page.body ?? "")) await keepBody(page.id, page.body ?? "");
1580
- if (!current.outside && page.parentId !== destination.page.id) {
2639
+ if (!current.outside && !parentMerged && page.parentId !== destination.page.id) {
1581
2640
  if (destination.keys.length > current.keys.length && sameKeys(destination.keys.slice(0, current.keys.length), current.keys)) throw new KnowledgeImportRefusalError("invalid");
1582
2641
  ({page, relinked} = await moveOwned(item.sourceId, page, destination));
1583
2642
  moved = true;
@@ -1625,10 +2684,10 @@ async function applyKnowledgeImportFlush(input) {
1625
2684
  adopted,
1626
2685
  unsettled: misplaced || (rendered ? rendered.unresolved : existing?.unresolvedLinks ?? []).length > 0
1627
2686
  });
1628
- if (change !== "unchanged" || existing?.stub) await syncLinks(async () => {
1629
- await syncKnowledgePageBodyLinks(storage, page);
1630
- if (change === "created" || renamed || moved) await refreshKnowledgeLinksTo(storage, [page], { withDescendants: moved });
1631
- });
2687
+ if (change !== "unchanged" || existing?.stub) await links(page, change === "created" || renamed || moved ? {
2688
+ pages: [page],
2689
+ withDescendants: moved
2690
+ } : void 0);
1632
2691
  return {
1633
2692
  page,
1634
2693
  change,
@@ -1636,136 +2695,150 @@ async function applyKnowledgeImportFlush(input) {
1636
2695
  relinked
1637
2696
  };
1638
2697
  };
1639
- const depth = /* @__PURE__ */ new Map();
1640
- for (const op of ops) {
1641
- if (op.op !== "remove") continue;
1642
- const node = await importers.getNode(binding.id, op.sourceId);
1643
- const page = node ? await storage.getPage({
1644
- id: node.pageId,
1645
- read: "all"
1646
- }) : null;
1647
- const path = live(page) ? await keyPath(page) : null;
1648
- depth.set(op.sourceId, path?.keys.length ?? 0);
1649
- }
1650
- const writes = ops.filter((op) => op.op !== "remove");
1651
- const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
1652
- for (const op of [...writes, ...removes]) {
1653
- const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
1654
- const embeds = [];
1655
- try {
1656
- await storage.transaction(async () => {
1657
- if (op.op === "remove") {
1658
- const node = await importers.getNode(binding.id, sourceId);
1659
- if (!node) return;
1660
- if (await gone(node)) {
1661
- await forget(node);
2698
+ const runOps = async () => {
2699
+ const depth = /* @__PURE__ */ new Map();
2700
+ for (const op of ops) {
2701
+ if (op.op !== "remove") continue;
2702
+ const node = await importers.getNode(binding.id, op.sourceId);
2703
+ const page = node ? await storage.getPage({
2704
+ id: node.pageId,
2705
+ read: "all"
2706
+ }) : null;
2707
+ const path = live(page) ? await keyPath(page) : null;
2708
+ depth.set(op.sourceId, path?.keys.length ?? 0);
2709
+ }
2710
+ const writes = ops.filter((op) => op.op !== "remove");
2711
+ const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
2712
+ for (const op of [...writes, ...removes]) {
2713
+ const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
2714
+ const embeds = [];
2715
+ try {
2716
+ await storage.transaction(async () => {
2717
+ if (op.op === "remove") {
2718
+ const node = await importers.getNode(binding.id, sourceId);
2719
+ if (!node) return;
2720
+ const state = await stateOf(node);
2721
+ if (state === "merged") return;
2722
+ if (state === "gone") {
2723
+ await forget(node);
2724
+ result.applied = true;
2725
+ return;
2726
+ }
2727
+ const current = await owned(node.pageId, sourceId);
2728
+ await storage.lockSubtree(current.page.id);
2729
+ const children = (await storage.countChildPages({
2730
+ parentIds: [current.page.id],
2731
+ read: "all"
2732
+ }))[current.page.id] ?? 0;
2733
+ const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
2734
+ if (children > 0 || node.adopted || folder) {
2735
+ if (node.stub) return;
2736
+ const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
2737
+ const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
2738
+ const original = heading ? note.text.slice(heading.length) : note?.text;
2739
+ const page = await storage.updatePage({
2740
+ id: current.page.id,
2741
+ expectedVersion: current.page.version,
2742
+ 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."),
2743
+ provenance
2744
+ });
2745
+ await importers.saveNode({
2746
+ ...node,
2747
+ stub: true
2748
+ });
2749
+ await links(page);
2750
+ embeds.push({
2751
+ kind: "index",
2752
+ pageId: page.id
2753
+ });
2754
+ result.counts.stubbed++;
2755
+ result.changes.push({
2756
+ sourceId,
2757
+ pageId: page.id,
2758
+ change: "stubbed",
2759
+ title: page.name,
2760
+ path: ref(current.keys)
2761
+ });
2762
+ } else {
2763
+ const deleted = await storage.deletePage({
2764
+ id: current.page.id,
2765
+ expectedVersion: current.page.version,
2766
+ deletedBy: provenance.author
2767
+ });
2768
+ await importers.deleteNode(binding.id, sourceId);
2769
+ if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
2770
+ await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
2771
+ await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: randomUUID() });
2772
+ deferredLinkers = true;
2773
+ }
2774
+ await links(deleted, { pages: [deleted] });
2775
+ embeds.push({
2776
+ kind: "remove",
2777
+ pageId: deleted.id
2778
+ });
2779
+ result.counts.removed++;
2780
+ result.changes.push({
2781
+ sourceId,
2782
+ pageId: null,
2783
+ change: "removed",
2784
+ title: deleted.name,
2785
+ path: ref(current.keys)
2786
+ });
2787
+ }
1662
2788
  result.applied = true;
1663
2789
  return;
1664
2790
  }
1665
- const current = await owned(node.pageId, sourceId);
1666
- await storage.lockSubtree(current.page.id);
1667
- const children = (await storage.countChildPages({
1668
- parentIds: [current.page.id],
1669
- read: "all"
1670
- }))[current.page.id] ?? 0;
1671
- const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
1672
- if (children > 0 || node.adopted || folder) {
1673
- if (node.stub) return;
1674
- const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
1675
- const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
1676
- const original = heading ? note.text.slice(heading.length) : note?.text;
1677
- const page = await storage.updatePage({
1678
- id: current.page.id,
1679
- expectedVersion: current.page.version,
1680
- 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."),
1681
- provenance
1682
- });
1683
- await importers.saveNode({
1684
- ...node,
1685
- stub: true
1686
- });
1687
- await syncLinks(() => syncKnowledgePageBodyLinks(storage, page));
1688
- embeds.push({
1689
- kind: "index",
1690
- pageId: page.id
1691
- });
1692
- result.counts.stubbed++;
1693
- result.changes.push({
1694
- sourceId,
1695
- pageId: page.id,
1696
- change: "stubbed",
1697
- title: page.name,
1698
- path: ref(current.keys)
1699
- });
1700
- } else {
1701
- const deleted = await storage.deletePage({
1702
- id: current.page.id,
1703
- expectedVersion: current.page.version,
1704
- deletedBy: provenance.author
1705
- });
1706
- await importers.deleteNode(binding.id, sourceId);
1707
- if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
1708
- await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
1709
- await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: randomUUID() });
1710
- deferredLinkers = true;
1711
- }
1712
- await syncLinks(async () => {
1713
- await syncKnowledgePageBodyLinks(storage, deleted);
1714
- await refreshKnowledgeLinksTo(storage, [deleted]);
1715
- });
1716
- embeds.push({
1717
- kind: "remove",
1718
- pageId: deleted.id
1719
- });
1720
- result.counts.removed++;
1721
- result.changes.push({
1722
- sourceId,
1723
- pageId: null,
1724
- change: "removed",
1725
- title: deleted.name,
1726
- path: ref(current.keys)
1727
- });
2791
+ const written = await write(op.item, op.op === "upsert");
2792
+ if (!written) {
2793
+ result.counts.merged++;
2794
+ return;
2795
+ }
2796
+ const { page, change, moved, relinked } = written;
2797
+ recordRelinked(relinked, embeds);
2798
+ if (change === "unchanged") {
2799
+ result.counts.unchanged++;
2800
+ return;
1728
2801
  }
1729
2802
  result.applied = true;
1730
- return;
1731
- }
1732
- const { page, change, moved, relinked } = await write(op.item, op.op === "upsert");
1733
- recordRelinked(relinked, embeds);
1734
- if (change === "unchanged") {
1735
- result.counts.unchanged++;
1736
- return;
1737
- }
1738
- result.applied = true;
1739
- if (change !== "moved") embeds.push({
1740
- kind: "index",
1741
- pageId: page.id
2803
+ if (change !== "moved") embeds.push({
2804
+ kind: "index",
2805
+ pageId: page.id
2806
+ });
2807
+ if (change === "created") result.counts.created++;
2808
+ else if (change === "updated") result.counts.updated++;
2809
+ if (moved) result.counts.moved++;
2810
+ const path = await keyPath(page);
2811
+ result.changes.push({
2812
+ sourceId,
2813
+ pageId: page.id,
2814
+ change,
2815
+ title: page.name,
2816
+ path: path ? ref(path.keys) : ""
2817
+ });
1742
2818
  });
1743
- if (change === "created") result.counts.created++;
1744
- else if (change === "updated") result.counts.updated++;
1745
- if (moved) result.counts.moved++;
1746
- const path = await keyPath(page);
1747
- result.changes.push({
2819
+ result.embeds.push(...embeds);
2820
+ } catch (error) {
2821
+ const reason = refusalFor(error);
2822
+ if (!reason) throw error;
2823
+ result.refused.push({
1748
2824
  sourceId,
1749
- pageId: page.id,
1750
- change,
1751
- title: page.name,
1752
- path: path ? ref(path.keys) : ""
2825
+ reason
1753
2826
  });
1754
- });
1755
- result.embeds.push(...embeds);
1756
- } catch (error) {
1757
- const reason = refusalFor(error);
1758
- if (!reason) throw error;
1759
- result.refused.push({
1760
- sourceId,
1761
- reason
1762
- });
2827
+ }
2828
+ }
2829
+ };
2830
+ if (!canBatchImportFlush(input.storage, input.importers)) await runOps();
2831
+ else if (ops.length) {
2832
+ const fallback = await applyBatched(anchor?.page ?? null);
2833
+ if (fallback) {
2834
+ result.fallback = fallback;
2835
+ await runOps();
1763
2836
  }
1764
2837
  }
1765
2838
  if (input.settle) {
1766
2839
  if (anchor) {
1767
2840
  input.settle.onStart?.();
1768
- result.settle = await settle(input.settle);
2841
+ result.settle = await settle(input.settle, anchor.page);
1769
2842
  } else result.settle = {
1770
2843
  pending: false,
1771
2844
  cursor: null,
@@ -1775,13 +2848,314 @@ async function applyKnowledgeImportFlush(input) {
1775
2848
  }
1776
2849
  return result;
1777
2850
  /**
2851
+ * Decides every op over a working copy (overlay.ts) and writes what they decided in a few
2852
+ * set-based statements, all in one savepoint (batched-flush plan v3.1). Returns why it fell back,
2853
+ * with the savepoint rolled back and the result as before, or null once the ops landed.
2854
+ */
2855
+ async function applyBatched(folder) {
2856
+ const writeOps = new Map(ops.flatMap((op) => op.op === "remove" ? [] : [[op.item.sourceId, op]]));
2857
+ const removed = ops.flatMap((op) => op.op === "remove" ? [op.sourceId] : []);
2858
+ const sourceIds = new Set(removed);
2859
+ for (const op of writeOps.values()) {
2860
+ sourceIds.add(op.item.sourceId);
2861
+ if (op.item.parent) sourceIds.add(op.item.parent);
2862
+ if (op.item.fallbackParent) sourceIds.add(op.item.fallbackParent);
2863
+ for (const link of ("links" in op.item ? op.item.links : void 0) ?? []) sourceIds.add(link.sourceId);
2864
+ }
2865
+ const plan = (rows) => {
2866
+ const keysOf = (page) => {
2867
+ const keys = [];
2868
+ for (let at = page; at && !at.isScope; at = at.parentId ? rows.pages.get(at.parentId) : null) {
2869
+ if (!live(at) || at.key === void 0) return null;
2870
+ keys.unshift(at.key);
2871
+ if (keys.length > 10) return null;
2872
+ }
2873
+ return keys;
2874
+ };
2875
+ const at = (sourceId, seen) => {
2876
+ if (!sourceId) return null;
2877
+ const node = rows.nodes.get(`${binding.id}\u0000${sourceId}`);
2878
+ const page = node ? rows.pages.get(node.pageId) : null;
2879
+ if (live(page ?? null) && page.scopeId === scope.id) {
2880
+ const keys = keysOf(page);
2881
+ if (keys) return {
2882
+ id: page.id,
2883
+ keys
2884
+ };
2885
+ }
2886
+ const op = writeOps.get(sourceId);
2887
+ if (!op || seen.has(sourceId)) return null;
2888
+ return {
2889
+ id: null,
2890
+ keys: [...destinationOf(op, /* @__PURE__ */ new Set([...seen, sourceId])).keys, knowledgeImportKey(sourceId)]
2891
+ };
2892
+ };
2893
+ const destinationOf = (op, seen) => at(op.item.parent, seen) ?? at(op.item.fallbackParent, seen) ?? {
2894
+ id: folder.id,
2895
+ keys: anchorPath
2896
+ };
2897
+ const out = {
2898
+ paths: [],
2899
+ positions: [],
2900
+ notes: [],
2901
+ subtrees: [],
2902
+ linkTargets: removed,
2903
+ bindings: removed.length > 0
2904
+ };
2905
+ const nodeAt = (sourceId) => rows.nodes.get(`${binding.id}\u0000${sourceId}`);
2906
+ const left = /* @__PURE__ */ new Set();
2907
+ for (const op of writeOps.values()) {
2908
+ const destination = destinationOf(op, /* @__PURE__ */ new Set([op.item.sourceId]));
2909
+ out.paths.push({
2910
+ scopeId: scope.id,
2911
+ path: [...destination.keys, knowledgeImportKey(op.item.sourceId)]
2912
+ });
2913
+ if (destination.id) out.positions.push(destination.id);
2914
+ const page = rows.pages.get(nodeAt(op.item.sourceId)?.pageId ?? "");
2915
+ if (live(page ?? null) && page.parentId !== destination.id) {
2916
+ out.subtrees.push(page.id);
2917
+ if (page.parentId) left.add(page.parentId);
2918
+ }
2919
+ }
2920
+ for (const id of out.positions) if (left.has(id)) out.subtrees.push(id);
2921
+ for (const sourceId of removed) {
2922
+ const node = nodeAt(sourceId);
2923
+ if (!node) continue;
2924
+ out.subtrees.push(node.pageId);
2925
+ if (node.adopted) out.notes.push(node.pageId);
2926
+ }
2927
+ for (const node of rows.nodes.values()) if (node?.stub && node.adopted) out.notes.push(node.pageId);
2928
+ return out;
2929
+ };
2930
+ return batchedOver(folder, sourceIds, plan, runOps);
2931
+ }
2932
+ /**
2933
+ * Runs `decide` over a working copy of the rows `plan` names, then writes what it decided in a few
2934
+ * set-based statements, all in one savepoint. Returns why it fell back, with the savepoint rolled
2935
+ * back and the result as before, or null once the writes landed.
2936
+ */
2937
+ async function batchedOver(folder, sourceIds, plan, decide) {
2938
+ const real = {
2939
+ storage: input.storage,
2940
+ importers: input.importers
2941
+ };
2942
+ const before = structuredClone(result);
2943
+ const deferredBefore = deferredLinkers;
2944
+ const reset = () => {
2945
+ const copy = structuredClone(before);
2946
+ Object.assign(result, copy);
2947
+ deferredLinkers = deferredBefore;
2948
+ };
2949
+ const missing = emptyImportOverlayMissing();
2950
+ let locked = /* @__PURE__ */ new Set();
2951
+ try {
2952
+ return await real.storage.transaction(async () => {
2953
+ for (let pass = 0; pass < BATCH_DECIDE_PASSES; pass++) {
2954
+ const rows = await gatherImportRows({
2955
+ storage: real.storage,
2956
+ importers: real.importers,
2957
+ bindingId: binding.id,
2958
+ sourceIds,
2959
+ pageIds: folder ? [folder.id] : [],
2960
+ plan,
2961
+ missing,
2962
+ locked
2963
+ });
2964
+ if (!rows) throw new BatchFallback("lock-churn");
2965
+ locked = rows.locked;
2966
+ const working = new ImportOverlay(rows);
2967
+ reset();
2968
+ overlay = working;
2969
+ storage = working.storage;
2970
+ importers = working.importers;
2971
+ try {
2972
+ await decide();
2973
+ } catch (error) {
2974
+ if (error instanceof KnowledgeImportNotGatheredError) {
2975
+ for (const [name, set] of Object.entries(working.missing)) {
2976
+ const into = missing[name];
2977
+ if (into instanceof Map) for (const [k, v] of set) into.set(k, v);
2978
+ else for (const k of set) into.add(k);
2979
+ }
2980
+ continue;
2981
+ }
2982
+ if (error instanceof KnowledgeImportBatchUnsupportedError) throw new BatchFallback(error.call);
2983
+ throw error;
2984
+ } finally {
2985
+ overlay = null;
2986
+ storage = real.storage;
2987
+ importers = real.importers;
2988
+ }
2989
+ try {
2990
+ if (working.writes.length) await real.storage.applyPageWrites({ writes: working.writes });
2991
+ } catch (error) {
2992
+ if (!refusalFor(error)) throw error;
2993
+ throw new BatchFallback(`page writes: ${error.name}`);
2994
+ }
2995
+ for (const work of working.marks) await work(real.storage, real.importers);
2996
+ const nodes = working.nodeWrites(rows);
2997
+ try {
2998
+ if (nodes.deletes.length || nodes.saves.length) await real.importers.writeNodes(nodes);
2999
+ } catch (error) {
3000
+ if (!refusalFor(error)) throw error;
3001
+ throw new BatchFallback(`node writes: ${error.name}`);
3002
+ }
3003
+ try {
3004
+ await repairKnowledgeLinks(real.storage, {
3005
+ synced: working.links.flatMap((work) => "sync" in work ? [work.sync] : []),
3006
+ refreshed: working.links.flatMap((work) => "refresh" in work ? [{
3007
+ page: work.refresh,
3008
+ withDescendants: work.withDescendants
3009
+ }] : [])
3010
+ });
3011
+ } catch (error) {
3012
+ if (error instanceof KnowledgeLinkRepairUnsupportedError) throw new BatchFallback(error.reason);
3013
+ if (error instanceof KnowledgeUnsupportedCapabilityError) throw new BatchFallback(`link repair: ${error.name}`);
3014
+ throw error;
3015
+ }
3016
+ return null;
3017
+ }
3018
+ throw new BatchFallback("gather passes");
3019
+ });
3020
+ } catch (error) {
3021
+ if (!(error instanceof BatchFallback)) throw error;
3022
+ reset();
3023
+ return error.reason;
3024
+ }
3025
+ }
3026
+ /**
1778
3027
  * One settle slice (O3 §C, §C′): visits the binding's unsettled nodes after `budget.after`, each
1779
3028
  * in its own savepoint, moving a page under a source parent that has arrived since and writing
1780
3029
  * links whose targets now resolve. Stops at the candidate, move or time cap and leaves the rest
1781
3030
  * for the next slice. A node it can't settle (refused, or still waiting) is skipped and stays
1782
3031
  * unsettled; the pass ends when it reaches the last unsettled node.
1783
3032
  */
1784
- async function settle(budget) {
3033
+ async function settle(budget, folder) {
3034
+ if (!canBatchImportFlush(input.storage, input.importers)) return settleNodeByNode(budget);
3035
+ const fromStart = (budget.after ?? void 0) === void 0;
3036
+ const window = [];
3037
+ let cursor = budget.after ?? void 0;
3038
+ let end = false;
3039
+ while (window.length < budget.candidates) {
3040
+ const page = await input.importers.listNodes(binding.id, {
3041
+ unsettled: true,
3042
+ ...cursor !== void 0 ? { after: cursor } : {},
3043
+ limit: budget.candidates - window.length
3044
+ });
3045
+ window.push(...page.items);
3046
+ cursor = page.items.at(-1)?.sourceId ?? cursor;
3047
+ if (!page.next) {
3048
+ end = true;
3049
+ break;
3050
+ }
3051
+ }
3052
+ if (!window.length) return settleNodeByNode(budget);
3053
+ const parents = new Map((await input.importers.getNodes(binding.id, [...new Set(window.flatMap((node) => node.parentSourceId ? [node.parentSourceId] : []))])).map((node) => [node.sourceId, node]));
3054
+ const pages = new Map((await input.storage.getPages({
3055
+ ids: window.map((node) => node.pageId),
3056
+ read: "all"
3057
+ })).map((page) => [page.id, page]));
3058
+ const visit = [];
3059
+ const movers = [];
3060
+ for (const node of window) {
3061
+ visit.push(node);
3062
+ const parent = node.parentSourceId ? parents.get(node.parentSourceId) : void 0;
3063
+ const page = pages.get(node.pageId);
3064
+ if (parent && page && page.parentId !== parent.pageId) {
3065
+ movers.push({
3066
+ sourceId: node.sourceId,
3067
+ page,
3068
+ destination: parent.pageId
3069
+ });
3070
+ if (movers.length >= budget.moves) break;
3071
+ }
3072
+ }
3073
+ if (visit.length < window.length) end = false;
3074
+ const sourceIds = /* @__PURE__ */ new Set();
3075
+ for (const node of visit) {
3076
+ sourceIds.add(node.sourceId);
3077
+ if (node.parentSourceId) sourceIds.add(node.parentSourceId);
3078
+ for (const link of node.links) sourceIds.add(link.sourceId);
3079
+ }
3080
+ let outcome = null;
3081
+ const fallback = await batchedOver(folder, sourceIds, (rows) => ({
3082
+ paths: movers.flatMap((mover) => {
3083
+ const keys = [];
3084
+ for (let at = rows.pages.get(mover.destination); at && !at.isScope;) {
3085
+ if (at.key === void 0) return [];
3086
+ keys.unshift(at.key);
3087
+ at = at.parentId ? rows.pages.get(at.parentId) : null;
3088
+ }
3089
+ return mover.page.key === void 0 ? [] : [{
3090
+ scopeId: scope.id,
3091
+ path: [...keys, mover.page.key]
3092
+ }];
3093
+ }),
3094
+ positions: movers.map((mover) => mover.destination),
3095
+ notes: [],
3096
+ subtrees: movers.map((mover) => mover.page.id),
3097
+ linkTargets: movers.map((mover) => mover.sourceId),
3098
+ bindings: false
3099
+ }), async () => {
3100
+ outcome = await settleWindow(budget, visit, end, fromStart);
3101
+ });
3102
+ if (fallback === null && outcome) {
3103
+ const settledSlice = outcome;
3104
+ if (!settledSlice.pending && deferredLinkers) {
3105
+ if ((await input.importers.listNodes(binding.id, {
3106
+ unsettled: true,
3107
+ limit: 1
3108
+ })).items.length > 0) return {
3109
+ ...settledSlice,
3110
+ pending: true
3111
+ };
3112
+ }
3113
+ return settledSlice;
3114
+ }
3115
+ result.fallback = result.fallback ? `${result.fallback}; settle: ${fallback}` : `settle: ${fallback}`;
3116
+ return settleNodeByNode(budget);
3117
+ }
3118
+ /**
3119
+ * The node-by-node loop over a window read ahead, for the batched slice: the same caps, the same
3120
+ * savepoint per node, over the working copy.
3121
+ */
3122
+ async function settleWindow(budget, visit, end, fromStart) {
3123
+ let after = budget.after ?? void 0;
3124
+ let moves = 0;
3125
+ let settled = 0;
3126
+ const resumeAt = () => deferredLinkers ? null : after ?? null;
3127
+ for (const node of visit) {
3128
+ if (moves >= budget.moves || Date.now() >= budget.until) return {
3129
+ pending: true,
3130
+ cursor: resumeAt(),
3131
+ settled,
3132
+ fromStart
3133
+ };
3134
+ after = node.sourceId;
3135
+ const embeds = [];
3136
+ try {
3137
+ const outcome = await storage.transaction(() => settleNode(node.sourceId, embeds, moves < budget.moves));
3138
+ if (outcome.moved) moves++;
3139
+ if (outcome.moved || outcome.relinked) settled++;
3140
+ result.embeds.push(...embeds);
3141
+ } catch (error) {
3142
+ if (!refusalFor(error)) throw error;
3143
+ }
3144
+ }
3145
+ if (!end) return {
3146
+ pending: true,
3147
+ cursor: resumeAt(),
3148
+ settled,
3149
+ fromStart
3150
+ };
3151
+ return {
3152
+ pending: false,
3153
+ cursor: null,
3154
+ settled,
3155
+ fromStart
3156
+ };
3157
+ }
3158
+ async function settleNodeByNode(budget) {
1785
3159
  let after = budget.after ?? void 0;
1786
3160
  const fromStart = after === void 0;
1787
3161
  let examined = 0;
@@ -1848,12 +3222,24 @@ async function applyKnowledgeImportFlush(input) {
1848
3222
  moved: false,
1849
3223
  relinked: false
1850
3224
  };
3225
+ if (await stateOf(node) === "merged") {
3226
+ await importers.saveNode({
3227
+ ...node,
3228
+ unsettled: false
3229
+ });
3230
+ return {
3231
+ moved: false,
3232
+ relinked: false
3233
+ };
3234
+ }
1851
3235
  const current = await owned(node.pageId, sourceId);
1852
3236
  let { page, keys } = current;
1853
3237
  let moved = false;
1854
3238
  let relinked = false;
1855
- const parent = current.outside ? null : await nodeOf(node.parentSourceId);
1856
- let misplaced = !current.outside && !!node.parentSourceId && !parent;
3239
+ const sourceParent = current.outside ? null : await nodeOf(node.parentSourceId);
3240
+ const parentMerged = !!sourceParent && await stateOf(sourceParent) === "merged";
3241
+ const parent = parentMerged ? null : sourceParent;
3242
+ let misplaced = !current.outside && !!node.parentSourceId && !parent && !parentMerged;
1857
3243
  if (parent && canMove) {
1858
3244
  const destination = await owned(parent.pageId, parent.sourceId);
1859
3245
  if (page.parentId !== destination.page.id) {
@@ -1862,7 +3248,10 @@ async function applyKnowledgeImportFlush(input) {
1862
3248
  ({page, keys, relinked: rewrote} = await moveOwned(sourceId, page, destination));
1863
3249
  recordRelinked(rewrote, embeds);
1864
3250
  moved = true;
1865
- await syncLinks(() => refreshKnowledgeLinksTo(storage, [page], { withDescendants: true }));
3251
+ await links(null, {
3252
+ pages: [page],
3253
+ withDescendants: true
3254
+ });
1866
3255
  }
1867
3256
  } else if (parent) misplaced = true;
1868
3257
  const out = await relink(node, page);
@@ -2254,6 +3643,14 @@ function hostError(error) {
2254
3643
  failure.cause = error;
2255
3644
  return failure;
2256
3645
  }
3646
+ /** A committed receipt as replayed; receipts written before the `merged` count existed read it as 0. */
3647
+ const storedReceipt = (receipt) => {
3648
+ const stored = receipt;
3649
+ return {
3650
+ ...stored,
3651
+ merged: stored.merged ?? 0
3652
+ };
3653
+ };
2257
3654
  const receiptCounts = (counts) => ({
2258
3655
  created: counts.created ?? 0,
2259
3656
  updated: counts.updated ?? 0,
@@ -2261,6 +3658,7 @@ const receiptCounts = (counts) => ({
2261
3658
  moved: counts.moved ?? 0,
2262
3659
  removed: counts.removed ?? 0,
2263
3660
  stubbed: counts.stubbed ?? 0,
3661
+ merged: counts.merged ?? 0,
2264
3662
  refused: counts.refused ?? 0
2265
3663
  });
2266
3664
  const runReceipt = (run) => {
@@ -2515,7 +3913,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2515
3913
  });
2516
3914
  if (replayed) {
2517
3915
  if (replayed.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
2518
- return replayed.receipt;
3916
+ return storedReceipt(replayed.receipt);
2519
3917
  }
2520
3918
  const [peek, peekRun] = await Promise.all([rootImporters.readWriterGuard(), rootImporters.getRun(flush.runId)]).catch((error) => {
2521
3919
  throw hostError(error);
@@ -2532,15 +3930,17 @@ function createLocalKnowledgeImporterHost(writer, options) {
2532
3930
  }
2533
3931
  let embeds = [];
2534
3932
  let settling = false;
3933
+ let fallbackWarning;
2535
3934
  try {
2536
3935
  const write = (deadlineAt) => storage.transaction(async (tx) => {
3936
+ fallbackWarning = void 0;
2537
3937
  const importers = tx.importers;
2538
3938
  const guard = await importers.lockWriterGuard(peek.firstWriteAt ? "share" : "update");
2539
3939
  const run = await importers.lockRun(flush.runId);
2540
3940
  const stored = await importers.getFlush(flush.runId, flush.generation, flush.seq);
2541
3941
  if (stored) {
2542
3942
  if (stored.digest !== digest) throw conflict("digest_mismatch", "This seq was committed with other content.");
2543
- return stored.receipt;
3943
+ return storedReceipt(stored.receipt);
2544
3944
  }
2545
3945
  if (!run || run.status !== "running") throw conflict("run_not_active", "The run is not running.");
2546
3946
  if (run.generation !== flush.generation || guard.generation !== flush.generation) throw conflict("stale_generation", "The run belongs to an older writer generation.");
@@ -2578,6 +3978,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2578
3978
  }
2579
3979
  } } : {}
2580
3980
  });
3981
+ if (applied.fallback) fallbackWarning = `Knowledge importer: flush ${flush.seq} of run ${run.id} saved op by op instead of batched (${applied.fallback})`;
2581
3982
  const settled = applied.settle;
2582
3983
  const hostUpdates = {};
2583
3984
  if (settled && (settled.cursor ?? "") !== (hostState[SETTLE_CURSOR_KEY] ?? "")) hostUpdates[SETTLE_CURSOR_KEY] = settled.cursor ?? "";
@@ -2588,15 +3989,18 @@ function createLocalKnowledgeImporterHost(writer, options) {
2588
3989
  ...hostUpdates
2589
3990
  };
2590
3991
  if (Object.keys(state).length) await importers.setState(binding.id, state);
2591
- for (const change of applied.changes) await importers.recordRunChange({
3992
+ const changes = applied.changes.map((change) => ({
2592
3993
  runId: run.id,
2593
3994
  ...change
2594
- });
3995
+ }));
3996
+ if (importers.recordRunChanges) await importers.recordRunChanges(changes);
3997
+ else for (const change of changes) await importers.recordRunChange(change);
2595
3998
  const receipt = {
2596
3999
  seq: flush.seq,
2597
4000
  ...applied.counts,
2598
4001
  refused: applied.refused,
2599
- pending: settled?.pending ?? false
4002
+ pending: settled?.pending ?? false,
4003
+ ...applied.fallback ? { fallback: applied.fallback } : {}
2600
4004
  };
2601
4005
  await importers.recordFlush({
2602
4006
  runId: run.id,
@@ -2607,7 +4011,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2607
4011
  counts: {
2608
4012
  ...applied.counts,
2609
4013
  refused: applied.refused.length,
2610
- settled: settled?.settled ?? 0
4014
+ settled: settled?.settled ?? 0,
4015
+ ...applied.fallback ? { fallbacks: 1 } : {}
2611
4016
  }
2612
4017
  });
2613
4018
  if (applied.applied && !guard.firstWriteAt) await importers.markFirstWrite();
@@ -2622,6 +4027,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2622
4027
  if (attempt >= MAX_LEASE_BOUND_ATTEMPTS) throw new KnowledgeImporterHostError("The flush could not be bounded by its run lease; resend it.", 503);
2623
4028
  deadlineAt = Math.min(budgetAt, error.cutoff - LEASE_CUTOFF_MARGIN_MS);
2624
4029
  }
4030
+ if (fallbackWarning) writer.warn(fallbackWarning);
2625
4031
  await runEmbeds(storage, embeds);
2626
4032
  return receipt;
2627
4033
  } catch (error) {
@@ -3323,6 +4729,19 @@ var KnowledgeScopeRuntime = class {
3323
4729
  };
3324
4730
  for (const address of addresses) await this.#materialize(address, principals, provenance, [], run);
3325
4731
  }
4732
+ /**
4733
+ * The parent address a first write would place a not-yet-created scope under, as `#materialize`
4734
+ * chooses it: a template child's own parent, or the one held `belongsTo` candidate. Undefined when
4735
+ * the scope would stay unlinked.
4736
+ */
4737
+ firstWriteParentAddress(address, principals) {
4738
+ const match = this.compiled.match(address);
4739
+ if (!match) return void 0;
4740
+ if (match.compiled.child) return address.slice(0, address.lastIndexOf("/"));
4741
+ if (!match.compiled.belongsTo) return void 0;
4742
+ const candidates = this.#belongsToCandidates(match, this.#held(principals));
4743
+ return candidates.length === 1 && candidates[0] !== address ? candidates[0] : void 0;
4744
+ }
3326
4745
  /** The run's distinct principals grouped by declaration key, matched once. */
3327
4746
  #held(principals) {
3328
4747
  const held = /* @__PURE__ */ new Map();
@@ -4268,9 +5687,24 @@ var Knowledge = class extends MastraBase {
4268
5687
  write
4269
5688
  };
4270
5689
  }
4271
- /** The run's principals as a stable key; throws when the run has none or holds an undeclared scope. @internal */
4272
- __principalsKey(context) {
4273
- return knowledgeRunPrincipals(this.#runtime, context).sort().join("\n");
5690
+ /** Whether the resolved mint declarations need metadata.persona. @internal */
5691
+ async __needsAgentPersona() {
5692
+ await this.#runtime.resolve();
5693
+ return [...this.#runtime.compiled.declarations.values()].some((declaration) => declaration.declaration.mint === "run-identity" && declaration.pattern.params.some((param) => param === "role" || param === "teamId"));
5694
+ }
5695
+ /**
5696
+ * The run's principals as a stable key, or `undefined` when the run has no Knowledge view (no scopes,
5697
+ * or an undeclared scope). Loads the store's declarations first, so a scope only the store declares
5698
+ * counts; a failure loading them rejects. @internal
5699
+ */
5700
+ async __principalsKey(context) {
5701
+ await this.#runtime.resolve();
5702
+ try {
5703
+ return knowledgeRunPrincipals(this.#runtime, context).sort().join("\n");
5704
+ } catch (error) {
5705
+ if (error instanceof KnowledgeRunScopesError || error instanceof KnowledgeDeclarationError) return void 0;
5706
+ throw error;
5707
+ }
4274
5708
  }
4275
5709
  /**
4276
5710
  * The pinned pages a host-run caller with these principals receives, rendered as an agent run
@@ -4297,6 +5731,14 @@ var Knowledge = class extends MastraBase {
4297
5731
  const run = await KnowledgeRun.start(this.#runtime, await this.getStorage(), context);
4298
5732
  return knowledgeDeliveredPins(run, budget, this.#groups().read);
4299
5733
  }
5734
+ /** The scopes a run holds a role on this turn, with that role. @internal */
5735
+ async __heldScopes(context) {
5736
+ const run = await KnowledgeRun.start(this.#runtime, await this.getStorage(), context);
5737
+ return (await heldScopes(run)).flatMap(({ address, role }) => role ? [{
5738
+ address,
5739
+ role
5740
+ }] : []);
5741
+ }
4300
5742
  /** @internal */
4301
5743
  __registerMastra(_mastra) {}
4302
5744
  /** @internal */
@@ -4413,4 +5855,4 @@ var Knowledge = class extends MastraBase {
4413
5855
  function createKnowledgeImporterHost(knowledge, options) {
4414
5856
  return createLocalKnowledgeImporterHost(hostWriterOf(knowledge), options);
4415
5857
  }
4416
- 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 };
5858
+ 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, knowledgeAgentScopes, knowledgeImportKey, knowledgeImporterFlushDigest, knowledgeImporterRegistry, knowledgeLinkRefKey, knowledgeMemoryScopes, knowledgePagePath, knowledgePersonaScopes, knowledgePinDepth, knowledgePositionBetween, knowledgeScopeAddress, knowledgeScopeKey, knowledgeScopeReadable, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, knowledgeVisibleScopeKeys, listKnowledgeTreeChildren, normalizeKnowledgeImporterFinish, parseKnowledgeImporterFlushBody, parseKnowledgeNodeCursor, parseKnowledgePageRef, parseKnowledgeWikilinks, readKnowledgePage, readKnowledgePageActivity, readKnowledgePageGraph, readKnowledgePageLinkCounts, readKnowledgePageLinks, readKnowledgeScopeGrants, runKnowledgeImport, searchKnowledgeExplorerPages };