@mastra/core 1.87.0-alpha.9 → 1.88.0-alpha.0

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 (994) hide show
  1. package/dist/_types/{@internal_ai-sdk-v4@0.0.99 → @internal_ai-sdk-v4@0.0.100}/dist/index.d.ts +1 -1
  2. package/dist/_types/{@internal_ai-sdk-v5@0.0.99 → @internal_ai-sdk-v5@0.0.100}/dist/index.d.ts +1 -1
  3. package/dist/_types/{@internal_ai-v6@0.0.99 → @internal_ai-v6@0.0.100}/dist/index.d.ts +1 -1
  4. package/dist/_types/{@internal_ai-v7@0.0.99 → @internal_ai-v7@0.0.100}/dist/index.d.ts +1 -1
  5. package/dist/_types/@internal_core@0.1.4/dist/knowledge-compat/index.d.ts +79 -3
  6. package/dist/_types/{@internal_voice@0.0.48/dist/_types/@internal_ai-sdk-v5@0.0.99 → @internal_voice@0.0.49/dist/_types/@internal_ai-sdk-v5@0.0.100}/dist/index.d.ts +1 -1
  7. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/voice/aisdk/speech.d.ts +1 -1
  8. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/voice/aisdk/transcription.d.ts +1 -1
  9. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/voice/composite-voice.d.ts +1 -1
  10. package/dist/a2a/index.cjs +1 -1
  11. package/dist/a2a/index.js +1 -1
  12. package/dist/agent/active-run-signal-queues.d.ts +49 -0
  13. package/dist/agent/agent-legacy.d.ts +1 -1
  14. package/dist/agent/agent.d.ts +30 -8
  15. package/dist/agent/agent.types.d.ts +2 -1
  16. package/dist/agent/durable/abort-transport.d.ts +1 -1
  17. package/dist/agent/durable/create-evented-agent.d.ts +2 -1
  18. package/dist/agent/durable/durable-agent.d.ts +4 -3
  19. package/dist/agent/durable/execution-engine.d.ts +14 -0
  20. package/dist/agent/durable/index.cjs +88 -87
  21. package/dist/agent/durable/index.js +4 -3
  22. package/dist/agent/durable/preparation.d.ts +17 -0
  23. package/dist/agent/durable/run-registry.d.ts +56 -25
  24. package/dist/agent/durable/segment-spans.d.ts +7 -0
  25. package/dist/agent/durable/stored-signal-drain.d.ts +100 -0
  26. package/dist/agent/durable/stream-adapter.d.ts +1 -1
  27. package/dist/agent/durable/types.d.ts +51 -2
  28. package/dist/agent/durable/utils/resolve-runtime.d.ts +16 -0
  29. package/dist/agent/durable/utils/serialize-state.d.ts +1 -0
  30. package/dist/agent/durable/workflows/create-durable-agentic-workflow.d.ts +1 -0
  31. package/dist/agent/durable/workflows/durable-loop-builder.d.ts +5 -0
  32. package/dist/agent/durable/workflows/finalize-run.d.ts +7 -1
  33. package/dist/agent/durable/workflows/shared/message-list-state.d.ts +6 -2
  34. package/dist/agent/durable/workflows/shared/schemas.d.ts +2 -0
  35. package/dist/agent/durable/workflows/steps/llm-execution.d.ts +1 -0
  36. package/dist/agent/index.cjs +17 -17
  37. package/dist/agent/index.d.ts +1 -0
  38. package/dist/agent/index.js +4 -4
  39. package/dist/agent/message-list/adapters/AIV4Adapter.d.ts +1 -1
  40. package/dist/agent/message-list/adapters/types.d.ts +1 -1
  41. package/dist/agent/message-list/cache/CacheKeyGenerator.d.ts +1 -1
  42. package/dist/agent/message-list/conversion/output-converter.d.ts +1 -1
  43. package/dist/agent/message-list/conversion/to-prompt.d.ts +1 -1
  44. package/dist/agent/message-list/conversion/utils.d.ts +1 -1
  45. package/dist/agent/message-list/detection/TypeDetector.d.ts +1 -1
  46. package/dist/agent/message-list/index.cjs +1 -1
  47. package/dist/agent/message-list/index.js +1 -1
  48. package/dist/agent/message-list/message-list.d.ts +2 -2
  49. package/dist/agent/message-list/prompt/attachments-to-parts.d.ts +1 -1
  50. package/dist/agent/message-list/prompt/convert-file.d.ts +1 -1
  51. package/dist/agent/message-list/prompt/data-content.d.ts +1 -1
  52. package/dist/agent/message-list/state/MessageStateManager.d.ts +6 -1
  53. package/dist/agent/message-list/state/types.d.ts +2 -2
  54. package/dist/agent/message-list/types.d.ts +9 -9
  55. package/dist/agent/message-list/utils/convert-messages.d.ts +3 -3
  56. package/dist/agent/message-list/utils/provider-compat.d.ts +1 -1
  57. package/dist/agent/request-context-snapshot.d.ts +5 -0
  58. package/dist/agent/scopes.d.ts +8 -0
  59. package/dist/agent/signals.d.ts +8 -4
  60. package/dist/agent/stored-run-signals.d.ts +93 -0
  61. package/dist/agent/stored-signals.d.ts +40 -0
  62. package/dist/agent/streams/abort-transport.d.ts +10 -1
  63. package/dist/agent/streams/constants.d.ts +9 -0
  64. package/dist/agent/streams/publisher.d.ts +3 -1
  65. package/dist/agent/thread-stream-runtime.d.ts +70 -6
  66. package/dist/agent/tool-name.d.ts +21 -0
  67. package/dist/agent/types.d.ts +4 -3
  68. package/dist/agent/workflows/prepare-stream/run-scope-keys.d.ts +1 -1
  69. package/dist/agent-builder/ee/index.cjs +1 -1
  70. package/dist/agent-builder/ee/index.js +1 -1
  71. package/dist/agent-controller/agent-controller.d.ts +8 -1
  72. package/dist/agent-controller/index.cjs +3 -3
  73. package/dist/agent-controller/index.js +3 -3
  74. package/dist/agent-controller/session.d.ts +38 -1
  75. package/dist/agent-controller/types.d.ts +6 -0
  76. package/dist/{agent-controller-fazk0U_b.js → agent-controller-CQDCmsFD.js} +126 -220
  77. package/dist/{agent-controller-ZCQy7cOG.cjs → agent-controller-NQKYmY0W.cjs} +150 -244
  78. package/dist/{agent-skills-resolver-BMoCDoaK.cjs → agent-skills-resolver-2d8k7ioj.cjs} +134 -109
  79. package/dist/{agent-skills-resolver-CUEIMDbx.js → agent-skills-resolver-D2HktP6Y.js} +134 -109
  80. package/dist/auth/defaults/index.d.ts +2 -2
  81. package/dist/auth/defaults/session/cookie.d.ts +2 -2
  82. package/dist/auth/defaults/session/index.d.ts +2 -2
  83. package/dist/auth/defaults/session/memory.d.ts +2 -2
  84. package/dist/auth/ee/capabilities.d.ts +1 -1
  85. package/dist/auth/ee/defaults/index.d.ts +1 -1
  86. package/dist/auth/ee/defaults/rbac/index.d.ts +1 -1
  87. package/dist/auth/ee/defaults/rbac/static.d.ts +1 -1
  88. package/dist/auth/ee/defaults/roles.d.ts +1 -1
  89. package/dist/auth/ee/fga-check.d.ts +1 -1
  90. package/dist/auth/ee/index.d.ts +1 -1
  91. package/dist/auth/ee/interfaces/acl.d.ts +1 -1
  92. package/dist/auth/ee/interfaces/fga.d.ts +1 -1
  93. package/dist/auth/ee/interfaces/index.d.ts +1 -1
  94. package/dist/auth/ee/interfaces/permissions.generated.d.ts +1 -1
  95. package/dist/auth/ee/interfaces/rbac.d.ts +1 -1
  96. package/dist/auth/ee/interfaces/user.d.ts +1 -1
  97. package/dist/auth/ee/license.d.ts +1 -1
  98. package/dist/auth/index.d.ts +2 -2
  99. package/dist/auth/interfaces/credentials.d.ts +1 -1
  100. package/dist/auth/interfaces/index.d.ts +2 -2
  101. package/dist/auth/interfaces/session.d.ts +1 -1
  102. package/dist/auth/interfaces/sso.d.ts +1 -1
  103. package/dist/auth/interfaces/user.d.ts +1 -1
  104. package/dist/background-tasks/index.cjs +1 -1
  105. package/dist/background-tasks/index.js +1 -1
  106. package/dist/background-tasks/manager.d.ts +3 -1
  107. package/dist/background-tasks/workflow-id.d.ts +42 -0
  108. package/dist/{background-tasks-DlLB_pJR.js → background-tasks-B7UygDdO.js} +239 -28
  109. package/dist/{background-tasks-B63welNM.cjs → background-tasks-CeARf1DK.cjs} +262 -27
  110. package/dist/browser/index.cjs +17 -8
  111. package/dist/browser/index.js +17 -8
  112. package/dist/browser/processor.d.ts +1 -0
  113. package/dist/{builder-D82iR2oQ.js → builder-CpAEmMdR.js} +2 -2
  114. package/dist/{builder-DCaL4xmU.cjs → builder-Dmf04g9P.cjs} +3 -3
  115. package/dist/bundler/index.d.ts +2 -2
  116. package/dist/capabilities/302ai.json +197 -197
  117. package/dist/capabilities/abacus.json +2 -96
  118. package/dist/capabilities/abliteratedllm.json +37 -37
  119. package/dist/capabilities/abliteration-ai.json +12 -12
  120. package/dist/capabilities/above.json +17 -17
  121. package/dist/capabilities/adaption.json +12 -12
  122. package/dist/capabilities/adzuki.json +20 -20
  123. package/dist/capabilities/agentrouter.json +8 -8
  124. package/dist/capabilities/agnes.json +4 -4
  125. package/dist/capabilities/ai-router.json +7 -7
  126. package/dist/capabilities/aiand.json +23 -31
  127. package/dist/capabilities/aigrow.json +14 -14
  128. package/dist/capabilities/aimlapi.json +143 -145
  129. package/dist/capabilities/aipg.json +2 -2
  130. package/dist/capabilities/aixy.json +11 -11
  131. package/dist/capabilities/aki-io.json +12 -12
  132. package/dist/capabilities/alibaba-cn.json +119 -128
  133. package/dist/capabilities/alibaba-coding-plan-cn.json +5 -10
  134. package/dist/capabilities/alibaba-coding-plan.json +5 -10
  135. package/dist/capabilities/alibaba-token-plan-cn.json +53 -49
  136. package/dist/capabilities/alibaba-token-plan.json +53 -49
  137. package/dist/capabilities/alibaba.json +101 -70
  138. package/dist/capabilities/ambient.json +10 -28
  139. package/dist/capabilities/amd-tokenlab.json +41 -0
  140. package/dist/capabilities/amd.json +11 -11
  141. package/dist/capabilities/anthropic.json +38 -62
  142. package/dist/capabilities/anyapi.json +18 -18
  143. package/dist/capabilities/arcee.json +7 -7
  144. package/dist/capabilities/augure.json +6 -6
  145. package/dist/capabilities/auriko.json +17 -17
  146. package/dist/capabilities/bailing.json +5 -5
  147. package/dist/capabilities/baseten.json +44 -35
  148. package/dist/capabilities/bee.json +5 -5
  149. package/dist/capabilities/berget.json +2 -35
  150. package/dist/capabilities/bothub.json +14 -14
  151. package/dist/capabilities/boundless.json +32 -32
  152. package/dist/capabilities/bumo.json +42 -42
  153. package/dist/capabilities/byteplus.json +30 -30
  154. package/dist/capabilities/cheapaimodel.json +8 -8
  155. package/dist/capabilities/cheapest-token.json +30 -30
  156. package/dist/capabilities/chutes.json +88 -7
  157. package/dist/capabilities/cline-pass.json +29 -42
  158. package/dist/capabilities/cloudcode.json +6 -6
  159. package/dist/capabilities/cloudflare-workers-ai.json +13 -13
  160. package/dist/capabilities/commandcode.json +141 -156
  161. package/dist/capabilities/concentrate.json +288 -271
  162. package/dist/capabilities/cortecs.json +105 -105
  163. package/dist/capabilities/crossmodel.json +177 -177
  164. package/dist/capabilities/crusoe.json +12 -12
  165. package/dist/capabilities/daoxe.json +9 -9
  166. package/dist/capabilities/databricks.json +136 -128
  167. package/dist/capabilities/deepinfra.json +105 -95
  168. package/dist/capabilities/deepseek.json +3 -3
  169. package/dist/capabilities/digitalocean.json +113 -114
  170. package/dist/capabilities/dinference.json +1 -2
  171. package/dist/capabilities/dothoosh.json +28 -28
  172. package/dist/capabilities/doubleword.json +26 -26
  173. package/dist/capabilities/edenai.json +298 -280
  174. package/dist/capabilities/empiriolabs.json +180 -171
  175. package/dist/capabilities/engy.json +23 -17
  176. package/dist/capabilities/entrim.json +6 -6
  177. package/dist/capabilities/evroc.json +12 -12
  178. package/dist/capabilities/ezkielyna.json +7 -7
  179. package/dist/capabilities/fastrouter.json +81 -85
  180. package/dist/capabilities/fireworks-ai.json +100 -100
  181. package/dist/capabilities/fortytwo.json +4 -4
  182. package/dist/capabilities/freemodel.json +7 -51
  183. package/dist/capabilities/friendli.json +26 -5
  184. package/dist/capabilities/frogbot.json +92 -100
  185. package/dist/capabilities/gisoo.json +19 -19
  186. package/dist/capabilities/gmicloud.json +11 -11
  187. package/dist/capabilities/google.json +43 -43
  188. package/dist/capabilities/graphn.json +14 -14
  189. package/dist/capabilities/greenpt.json +37 -37
  190. package/dist/capabilities/groq.json +7 -20
  191. package/dist/capabilities/helicone.json +80 -82
  192. package/dist/capabilities/hetzner.json +4 -4
  193. package/dist/capabilities/hostinger-router.json +9 -16
  194. package/dist/capabilities/hpc-ai.json +9 -25
  195. package/dist/capabilities/huawei-maas.json +12 -12
  196. package/dist/capabilities/hubris.json +29 -29
  197. package/dist/capabilities/huggingface.json +94 -85
  198. package/dist/capabilities/humain.json +2 -2
  199. package/dist/capabilities/hyper.json +22 -22
  200. package/dist/capabilities/impossibl.json +121 -168
  201. package/dist/capabilities/inception.json +3 -3
  202. package/dist/capabilities/inceptron.json +8 -8
  203. package/dist/capabilities/inco.json +5 -22
  204. package/dist/capabilities/infer.json +11 -11
  205. package/dist/capabilities/inferall.json +3 -19
  206. package/dist/capabilities/inference-coop.json +15 -15
  207. package/dist/capabilities/inference.json +2 -11
  208. package/dist/capabilities/inferenceapis.json +21 -21
  209. package/dist/capabilities/inferris.json +4 -4
  210. package/dist/capabilities/infersia.json +7 -7
  211. package/dist/capabilities/inferx.json +2 -2
  212. package/dist/capabilities/infomaniak.json +3 -3
  213. package/dist/capabilities/io-net.json +3 -13
  214. package/dist/capabilities/iteracompute.json +38 -76
  215. package/dist/capabilities/jalapeno.json +11 -11
  216. package/dist/capabilities/jiekou.json +19 -167
  217. package/dist/capabilities/joingonka.json +4 -4
  218. package/dist/capabilities/jzstoken.json +47 -47
  219. package/dist/capabilities/keln.json +22 -22
  220. package/dist/capabilities/kenari.json +129 -120
  221. package/dist/capabilities/kilo.json +629 -653
  222. package/dist/capabilities/kimchi.json +90 -0
  223. package/dist/capabilities/kimi-code-plan-cn.json +9 -9
  224. package/dist/capabilities/kimi-code-plan-global.json +9 -9
  225. package/dist/capabilities/kitani.json +6 -6
  226. package/dist/capabilities/klavo.json +24 -24
  227. package/dist/capabilities/korouter.json +34 -34
  228. package/dist/capabilities/kunavo.json +4 -4
  229. package/dist/capabilities/liquid.json +11 -11
  230. package/dist/capabilities/lithosai.json +2 -2
  231. package/dist/capabilities/llmgateway-providers.json +934 -943
  232. package/dist/capabilities/llmgateway.json +347 -324
  233. package/dist/capabilities/llmtr.json +22 -60
  234. package/dist/capabilities/longcat.json +2 -2
  235. package/dist/capabilities/lowrouter.json +51 -51
  236. package/dist/capabilities/lyceum.json +16 -16
  237. package/dist/capabilities/meganova.json +0 -1
  238. package/dist/capabilities/melious.json +12 -12
  239. package/dist/capabilities/merge-gateway.json +303 -281
  240. package/dist/capabilities/meta.json +11 -11
  241. package/dist/capabilities/minimax-cn-coding-plan.json +6 -6
  242. package/dist/capabilities/minimax-coding-plan.json +6 -6
  243. package/dist/capabilities/mistral.json +11 -27
  244. package/dist/capabilities/mixlayer.json +5 -5
  245. package/dist/capabilities/moark.json +0 -2
  246. package/dist/capabilities/modal.json +12 -12
  247. package/dist/capabilities/model-oracle-ai.json +18 -26
  248. package/dist/capabilities/modelis.json +17 -17
  249. package/dist/capabilities/modular.json +12 -12
  250. package/dist/capabilities/moneo.json +3 -34
  251. package/dist/capabilities/moonshotai-cn.json +7 -7
  252. package/dist/capabilities/moonshotai.json +7 -7
  253. package/dist/capabilities/morph.json +22 -14
  254. package/dist/capabilities/munito-eu.json +6 -6
  255. package/dist/capabilities/munito.json +10 -10
  256. package/dist/capabilities/nan.json +30 -30
  257. package/dist/capabilities/nano-gpt.json +580 -596
  258. package/dist/capabilities/nearai.json +81 -81
  259. package/dist/capabilities/nebius.json +41 -34
  260. package/dist/capabilities/neon.json +135 -135
  261. package/dist/capabilities/neuralwatt.json +40 -40
  262. package/dist/capabilities/nokeep.json +2 -2
  263. package/dist/capabilities/novita-ai.json +106 -220
  264. package/dist/capabilities/nvidia.json +22 -80
  265. package/dist/capabilities/oathbreaker.json +5 -5
  266. package/dist/capabilities/obscurify.json +24 -24
  267. package/dist/capabilities/oci.json +9 -9
  268. package/dist/capabilities/ofox.json +205 -569
  269. package/dist/capabilities/ollama-cloud.json +57 -57
  270. package/dist/capabilities/openai.json +57 -60
  271. package/dist/capabilities/opencode-go.json +103 -95
  272. package/dist/capabilities/openreason.json +5 -5
  273. package/dist/capabilities/openrouter.json +551 -577
  274. package/dist/capabilities/opper.json +26 -31
  275. package/dist/capabilities/orcarouter.json +414 -199
  276. package/dist/capabilities/outerlabs.json +33 -33
  277. package/dist/capabilities/ovhcloud.json +16 -17
  278. package/dist/capabilities/pareto.json +2 -7
  279. package/dist/capabilities/perplexity-agent.json +101 -66
  280. package/dist/capabilities/perplexity.json +2 -2
  281. package/dist/capabilities/phala.json +34 -34
  282. package/dist/capabilities/pioneer.json +5 -122
  283. package/dist/capabilities/poe.json +140 -140
  284. package/dist/capabilities/poolside.json +3 -3
  285. package/dist/capabilities/powerspring.json +9 -9
  286. package/dist/capabilities/primalabs.json +7 -7
  287. package/dist/capabilities/prime.json +131 -115
  288. package/dist/capabilities/privatemode-ai.json +9 -37
  289. package/dist/capabilities/proxystacks.json +7 -7
  290. package/dist/capabilities/qihang-ai.json +3 -15
  291. package/dist/capabilities/qiniu-ai.json +14 -88
  292. package/dist/capabilities/refuseless.json +4 -11
  293. package/dist/capabilities/regolo-ai.json +6 -10
  294. package/dist/capabilities/requesty.json +249 -208
  295. package/dist/capabilities/routing-run.json +3 -40
  296. package/dist/capabilities/ruapi.json +17 -17
  297. package/dist/capabilities/runcrate.json +13 -13
  298. package/dist/capabilities/runinfra.json +15 -15
  299. package/dist/capabilities/sakana.json +6 -6
  300. package/dist/capabilities/sambanova.json +5 -5
  301. package/dist/capabilities/sandbase.json +23 -23
  302. package/dist/capabilities/sarvam.json +17 -8
  303. package/dist/capabilities/scaleway.json +14 -14
  304. package/dist/capabilities/scnet-token-plan.json +10 -10
  305. package/dist/capabilities/scx-ai.json +12 -28
  306. package/dist/capabilities/sensenova.json +9 -9
  307. package/dist/capabilities/siliconflow-cn.json +63 -97
  308. package/dist/capabilities/siliconflow.json +63 -63
  309. package/dist/capabilities/snowflake-cortex.json +28 -28
  310. package/dist/capabilities/sokkan.json +8 -20
  311. package/dist/capabilities/sparrowcodes.json +19 -19
  312. package/dist/capabilities/stackit.json +1 -2
  313. package/dist/capabilities/standardcompute.json +77 -113
  314. package/dist/capabilities/steadyrouter.json +45 -45
  315. package/dist/capabilities/stepfun-ai-step-plan.json +14 -8
  316. package/dist/capabilities/stepfun-ai.json +21 -7
  317. package/dist/capabilities/stepfun-step-plan.json +14 -7
  318. package/dist/capabilities/stepfun.json +21 -7
  319. package/dist/capabilities/stepping-stone.json +12 -12
  320. package/dist/capabilities/synthetic.json +9 -18
  321. package/dist/capabilities/synthorai.json +22 -22
  322. package/dist/capabilities/teamorouter.json +21 -21
  323. package/dist/capabilities/teapot-router.json +10 -10
  324. package/dist/capabilities/tencent-token-plan-intl.json +20 -20
  325. package/dist/capabilities/tencent-token-plan.json +45 -45
  326. package/dist/capabilities/tencent-tokenhub.json +47 -47
  327. package/dist/capabilities/tensorx.json +50 -50
  328. package/dist/capabilities/tenstorrent.json +6 -6
  329. package/dist/capabilities/the-grid-ai.json +28 -28
  330. package/dist/capabilities/thinkingmachines.json +61 -61
  331. package/dist/capabilities/tinfoil.json +12 -12
  332. package/dist/capabilities/toapis.json +3 -3
  333. package/dist/capabilities/togetherai.json +50 -58
  334. package/dist/capabilities/tokengo.json +21 -21
  335. package/dist/capabilities/tokenharbor.json +738 -0
  336. package/dist/capabilities/tokenify.json +2 -2
  337. package/dist/capabilities/trustedrouter.json +6 -6
  338. package/dist/capabilities/trustedtokens.json +12 -12
  339. package/dist/capabilities/umans-ai-coding-plan.json +14 -14
  340. package/dist/capabilities/umans-ai.json +11 -11
  341. package/dist/capabilities/uncensuredai.json +4 -4
  342. package/dist/capabilities/unorouter.json +1 -22
  343. package/dist/capabilities/unrestricted.json +6 -22
  344. package/dist/capabilities/uplinkswitch.json +20 -20
  345. package/dist/capabilities/upstage.json +3 -15
  346. package/dist/capabilities/vancine.json +21 -21
  347. package/dist/capabilities/vercel.json +628 -593
  348. package/dist/capabilities/verda.json +8 -1
  349. package/dist/capabilities/vivgrid.json +55 -135
  350. package/dist/capabilities/volcengine-coding-plan.json +25 -25
  351. package/dist/capabilities/volcengine.json +24 -24
  352. package/dist/capabilities/vultr.json +12 -65
  353. package/dist/capabilities/wafer.ai.json +17 -17
  354. package/dist/capabilities/wallaby.json +2 -2
  355. package/dist/capabilities/wally.json +9 -9
  356. package/dist/capabilities/wandb.json +21 -21
  357. package/dist/capabilities/watt.json +23 -23
  358. package/dist/capabilities/xai.json +6 -6
  359. package/dist/capabilities/xpersona.json +11 -11
  360. package/dist/capabilities/xxapi.json +25 -25
  361. package/dist/capabilities/zai-coding-plan.json +15 -15
  362. package/dist/capabilities/zai.json +37 -28
  363. package/dist/capabilities/zenifra.json +26 -26
  364. package/dist/capabilities/zenmux.json +151 -194
  365. package/dist/capabilities/zerogpu.json +12 -12
  366. package/dist/capabilities/zhipuai-coding-plan.json +5 -16
  367. package/dist/capabilities/zhipuai.json +44 -28
  368. package/dist/capabilities/zro.json +7 -7
  369. package/dist/channels/index.cjs +24 -24
  370. package/dist/channels/index.js +2 -2
  371. package/dist/channels/reply-tool.d.ts +5 -1
  372. package/dist/{channels-Bs8wDPDl.js → channels-BQ--aLCA.js} +2 -2
  373. package/dist/{channels-BXZbY7TL.cjs → channels-CTCBsS5M.cjs} +6 -6
  374. package/dist/coding-agent/index.cjs +7 -7
  375. package/dist/coding-agent/index.js +4 -4
  376. package/dist/{constants-Bou0hEgY.cjs → constants-B2FVV_2e.cjs} +9 -1
  377. package/dist/{constants-CFWgIaqA.js → constants-Dro9fuhk.js} +9 -1
  378. package/dist/datasets/index.cjs +9 -9
  379. package/dist/datasets/index.js +2 -2
  380. package/dist/deployer/index.d.ts +2 -2
  381. package/dist/docs/SKILL.md +2 -1
  382. package/dist/docs/assets/SOURCE_MAP.json +1253 -1213
  383. package/dist/docs/references/docs-agents-code-mode.md +2 -2
  384. package/dist/docs/references/docs-agents-human-in-the-loop.md +3 -3
  385. package/dist/docs/references/docs-agents-networks.md +1 -1
  386. package/dist/docs/references/docs-agents-overview.md +15 -6
  387. package/dist/docs/references/docs-agents-processors.md +9 -9
  388. package/dist/docs/references/docs-agents-resumable-streams.md +5 -5
  389. package/dist/docs/references/docs-agents-structured-output.md +6 -6
  390. package/dist/docs/references/docs-agents-tools.md +11 -11
  391. package/dist/docs/references/docs-browser.md +1 -1
  392. package/dist/docs/references/docs-channels.md +13 -7
  393. package/dist/docs/references/docs-classifier.md +1 -1
  394. package/dist/docs/references/docs-connections-a2a.md +1 -1
  395. package/dist/docs/references/docs-connections-acp.md +2 -2
  396. package/dist/docs/references/docs-connections-overview.md +1 -1
  397. package/dist/docs/references/docs-connections-sdk-agents.md +6 -6
  398. package/dist/docs/references/docs-deployment-workers.md +11 -5
  399. package/dist/docs/references/docs-develop.md +1 -1
  400. package/dist/docs/references/docs-evals-custom-scorers.md +1 -1
  401. package/dist/docs/references/docs-evals-multi-turn.md +2 -2
  402. package/dist/docs/references/docs-guides-build-an-eval-loop.md +2 -2
  403. package/dist/docs/references/docs-guides-context-engineering.md +3 -3
  404. package/dist/docs/references/docs-guides-streaming.md +1 -1
  405. package/dist/docs/references/docs-harness-agent-controller.md +6 -3
  406. package/dist/docs/references/docs-harness-background-tasks.md +10 -7
  407. package/dist/docs/references/docs-harness-durable-agents.md +22 -19
  408. package/dist/docs/references/docs-harness-goals.md +2 -2
  409. package/dist/docs/references/docs-harness-schedules.md +35 -1
  410. package/dist/docs/references/docs-knowledge-agents-and-tools.md +2 -2
  411. package/dist/docs/references/docs-knowledge-importers.md +22 -1
  412. package/dist/docs/references/docs-knowledge-overview.md +1 -1
  413. package/dist/docs/references/docs-knowledge-scopes-and-access.md +1 -1
  414. package/dist/docs/references/docs-knowledge-search.md +1 -1
  415. package/dist/docs/references/docs-memory-memory-processors.md +8 -8
  416. package/dist/docs/references/docs-memory-message-history.md +5 -3
  417. package/dist/docs/references/docs-memory-observational-memory.md +1 -1
  418. package/dist/docs/references/docs-memory-semantic-recall.md +2 -2
  419. package/dist/docs/references/docs-memory-working-memory.md +3 -2
  420. package/dist/docs/references/docs-sandbox-overview.md +2 -2
  421. package/dist/docs/references/docs-sandbox-skills.md +1 -1
  422. package/dist/docs/references/docs-server-mastra-client.md +1 -1
  423. package/dist/docs/references/docs-server-mcp.md +91 -0
  424. package/dist/docs/references/docs-server-pubsub.md +45 -16
  425. package/dist/docs/references/docs-server-request-context.md +4 -4
  426. package/dist/docs/references/docs-signals-notifications.md +2 -2
  427. package/dist/docs/references/docs-signals-overview.md +1 -1
  428. package/dist/docs/references/docs-signals-running-across-processes.md +12 -3
  429. package/dist/docs/references/docs-signals-sending-signals.md +20 -7
  430. package/dist/docs/references/docs-signals-signal-providers.md +18 -2
  431. package/dist/docs/references/docs-signals-state-signals.md +1 -0
  432. package/dist/docs/references/docs-signals-thread-streams.md +12 -0
  433. package/dist/docs/references/docs-skills.md +8 -5
  434. package/dist/docs/references/docs-storage.md +12 -12
  435. package/dist/docs/references/docs-studio-editor.md +2 -2
  436. package/dist/docs/references/docs-subagents.md +26 -3
  437. package/dist/docs/references/docs-workflows-overview.md +5 -3
  438. package/dist/docs/references/integrations-agentic-ui-copilotkit.md +1 -1
  439. package/dist/docs/references/integrations-agentic-ui-openui.md +1 -1
  440. package/dist/docs/references/integrations-channels-discord.md +1 -1
  441. package/dist/docs/references/integrations-channels-github.md +1 -1
  442. package/dist/docs/references/integrations-channels-imessage.md +2 -2
  443. package/dist/docs/references/integrations-channels-ring.md +2 -2
  444. package/dist/docs/references/integrations-channels-slack.md +1 -1
  445. package/dist/docs/references/integrations-channels-teams.md +1 -1
  446. package/dist/docs/references/integrations-channels-telegram.md +1 -1
  447. package/dist/docs/references/integrations-channels-whatsapp.md +1 -1
  448. package/dist/docs/references/integrations-tools-firecrawl.md +1 -1
  449. package/dist/docs/references/reference-acp-acp-agent.md +1 -1
  450. package/dist/docs/references/reference-acp-create-acp-tool.md +1 -1
  451. package/dist/docs/references/reference-agent-controller-agent-controller-class.md +3 -1
  452. package/dist/docs/references/reference-agent-controller-session.md +54 -7
  453. package/dist/docs/references/reference-agents-agent.md +43 -15
  454. package/dist/docs/references/reference-agents-channels.md +11 -11
  455. package/dist/docs/references/reference-agents-createSkill.md +20 -1
  456. package/dist/docs/references/reference-agents-durable-agent.md +5 -5
  457. package/dist/docs/references/reference-agents-getLLM.md +2 -2
  458. package/dist/docs/references/reference-agents-getMetadata.md +2 -2
  459. package/dist/docs/references/reference-agents-network.md +2 -2
  460. package/dist/docs/references/reference-browser-mastra-browser.md +1 -1
  461. package/dist/docs/references/reference-channels-thread-link.md +1 -1
  462. package/dist/docs/references/reference-classifier-classifier.md +2 -0
  463. package/dist/docs/references/reference-coding-agent-build-base-prompt.md +1 -1
  464. package/dist/docs/references/reference-coding-agent-create-coding-agent.md +7 -7
  465. package/dist/docs/references/reference-configuration.md +75 -14
  466. package/dist/docs/references/reference-core-getAgentById.md +1 -1
  467. package/dist/docs/references/reference-core-mastra-model-gateway.md +1 -1
  468. package/dist/docs/references/reference-datasets-startExperiment.md +1 -1
  469. package/dist/docs/references/reference-editor-mastra-editor.md +2 -2
  470. package/dist/docs/references/reference-file-based-agents-config.md +3 -3
  471. package/dist/docs/references/reference-file-based-agents-schedules.md +1 -1
  472. package/dist/docs/references/reference-file-based-agents-subagents.md +3 -3
  473. package/dist/docs/references/reference-file-based-agents-workspace.md +1 -1
  474. package/dist/docs/references/reference-knowledge-knowledge-class.md +12 -0
  475. package/dist/docs/references/reference-knowledge-knowledge-tools.md +1 -2
  476. package/dist/docs/references/reference-knowledge-limits.md +16 -16
  477. package/dist/docs/references/reference-manual-install.md +1 -1
  478. package/dist/docs/references/reference-memory-memory-class.md +3 -3
  479. package/dist/docs/references/reference-memory-observational-memory.md +7 -3
  480. package/dist/docs/references/reference-observability-metrics-metrics-context.md +63 -3
  481. package/dist/docs/references/reference-observability-tracing-bridges-datadog.md +12 -11
  482. package/dist/docs/references/reference-observability-tracing-configuration.md +2 -2
  483. package/dist/docs/references/reference-observability-tracing-exporters-datadog.md +14 -12
  484. package/dist/docs/references/reference-processors-batch-parts-processor.md +1 -1
  485. package/dist/docs/references/reference-processors-classifier-processor.md +2 -2
  486. package/dist/docs/references/reference-processors-cyber-refusal-handler.md +1 -1
  487. package/dist/docs/references/reference-processors-language-detector.md +1 -1
  488. package/dist/docs/references/reference-processors-message-history-processor.md +1 -1
  489. package/dist/docs/references/reference-processors-model-selection-processor.md +3 -3
  490. package/dist/docs/references/reference-processors-moderation-processor.md +4 -4
  491. package/dist/docs/references/reference-processors-pii-detector.md +2 -2
  492. package/dist/docs/references/reference-processors-prefill-error-handler.md +2 -2
  493. package/dist/docs/references/reference-processors-processor-interface.md +19 -8
  494. package/dist/docs/references/reference-processors-prompt-injection-detector.md +1 -1
  495. package/dist/docs/references/reference-processors-provider-history-compat.md +1 -1
  496. package/dist/docs/references/reference-processors-response-cache.md +1 -1
  497. package/dist/docs/references/reference-processors-semantic-recall-processor.md +1 -1
  498. package/dist/docs/references/reference-processors-skill-search-processor.md +1 -1
  499. package/dist/docs/references/reference-processors-skills-processor.md +1 -1
  500. package/dist/docs/references/reference-processors-stream-error-retry-processor.md +3 -3
  501. package/dist/docs/references/reference-processors-system-prompt-scrubber.md +1 -1
  502. package/dist/docs/references/reference-processors-token-limiter-processor.md +3 -3
  503. package/dist/docs/references/reference-processors-tool-call-filter.md +2 -2
  504. package/dist/docs/references/reference-processors-tool-search-processor.md +3 -3
  505. package/dist/docs/references/reference-processors-unicode-normalizer.md +1 -1
  506. package/dist/docs/references/reference-processors-working-memory-processor.md +1 -1
  507. package/dist/docs/references/reference-pubsub-base.md +2 -2
  508. package/dist/docs/references/reference-pubsub-caching-pubsub.md +1 -1
  509. package/dist/docs/references/reference-pubsub-google-cloud-pubsub.md +13 -7
  510. package/dist/docs/references/reference-pubsub-lease-provider.md +4 -0
  511. package/dist/docs/references/reference-pubsub-redis-streams.md +21 -14
  512. package/dist/docs/references/reference-pubsub-valkey-streams.md +27 -9
  513. package/dist/docs/references/reference-rag-chunking-and-embedding.md +1 -1
  514. package/dist/docs/references/reference-rag-graph-rag-guide.md +2 -2
  515. package/dist/docs/references/reference-rag-retrieval.md +13 -13
  516. package/dist/docs/references/reference-signals-create-notification-inbox-tool.md +1 -1
  517. package/dist/docs/references/reference-signals-time-signal-provider.md +137 -0
  518. package/dist/docs/references/reference-storage-composite.md +4 -0
  519. package/dist/docs/references/reference-storage-overview.md +29 -29
  520. package/dist/docs/references/reference-templates-overview.md +31 -1
  521. package/dist/docs/references/reference-tools-create-code-mode.md +1 -1
  522. package/dist/docs/references/reference-tools-vector-query-tool.md +3 -3
  523. package/dist/docs/references/reference-voice-overview.md +28 -28
  524. package/dist/docs/references/reference-voice-speech-to-speech.md +10 -10
  525. package/dist/docs/references/reference-voice-speech-to-text.md +1 -1
  526. package/dist/docs/references/reference-voice-text-to-speech.md +1 -1
  527. package/dist/docs/references/reference-voice-voice.addInstructions.md +1 -1
  528. package/dist/docs/references/reference-voice-voice.listen.md +1 -1
  529. package/dist/docs/references/reference-workers-overview.md +3 -1
  530. package/dist/docs/references/reference-workflows-run-methods-restart.md +2 -0
  531. package/dist/docs/references/reference-workflows-step.md +1 -1
  532. package/dist/docs/references/reference-workflows-workflow-methods-map.md +1 -1
  533. package/dist/docs/references/reference-workflows-workflow.md +1 -1
  534. package/dist/docs/references/reference-workspace-factory-sandbox.md +2 -0
  535. package/dist/docs/references/reference-workspace-local-filesystem.md +1 -1
  536. package/dist/docs/references/reference-workspace-local-sandbox.md +1 -1
  537. package/dist/docs/references/reference.md +2 -0
  538. package/dist/evals/index.cjs +13 -13
  539. package/dist/evals/index.js +2 -2
  540. package/dist/evals/run/index.d.ts +1 -1
  541. package/dist/evals/scoreTraces/index.cjs +4 -4
  542. package/dist/evals/scoreTraces/index.js +2 -2
  543. package/dist/evals/types.d.ts +1 -1
  544. package/dist/events/caching-pubsub.d.ts +3 -11
  545. package/dist/events/index.cjs +1 -1
  546. package/dist/events/index.js +1 -1
  547. package/dist/events/pubsub.d.ts +3 -4
  548. package/dist/{run-registry-DX_EyboB.cjs → execution-fence-C8Q0wWkG.cjs} +12890 -8734
  549. package/dist/{run-registry-DKiudqVU.js → execution-fence-DGFyUV5h.js} +12380 -8260
  550. package/dist/harness/index.cjs +3 -3
  551. package/dist/harness/index.js +3 -3
  552. package/dist/index.cjs +1 -1
  553. package/dist/index.d.ts +1 -0
  554. package/dist/index.js +1 -1
  555. package/dist/integration/index.cjs +1 -1
  556. package/dist/integration/index.js +1 -1
  557. package/dist/knowledge/importers/overlay.d.ts +170 -0
  558. package/dist/knowledge/importers/sink.d.ts +17 -1
  559. package/dist/knowledge/importers/types.d.ts +14 -0
  560. package/dist/knowledge/index.cjs +2047 -276
  561. package/dist/knowledge/index.d.ts +6 -0
  562. package/dist/knowledge/index.js +1929 -158
  563. package/dist/knowledge/links.d.ts +27 -0
  564. package/dist/knowledge/page-tools.d.ts +2 -0
  565. package/dist/llm/index.cjs +3 -3
  566. package/dist/llm/index.d.ts +2 -2
  567. package/dist/llm/index.js +3 -3
  568. package/dist/llm/model/aisdk/v4/model.d.ts +9 -9
  569. package/dist/llm/model/base.types.d.ts +2 -2
  570. package/dist/llm/model/embedding-router.d.ts +1 -1
  571. package/dist/llm/model/gateways/opencode-session-header.d.ts +28 -0
  572. package/dist/llm/model/mastra-gateway-provider-tools.d.ts +7 -0
  573. package/dist/llm/model/model-settings.d.ts +1 -1
  574. package/dist/llm/model/model.d.ts +1 -1
  575. package/dist/llm/model/model.loop.d.ts +1 -1
  576. package/dist/llm/model/model.loop.types.d.ts +1 -1
  577. package/dist/llm/model/provider-types.generated.d.ts +7162 -7416
  578. package/dist/llm/model/resolve-model.d.ts +1 -0
  579. package/dist/llm/model/shared.types.d.ts +2 -1
  580. package/dist/llm/reasoning/account-switch.d.ts +50 -0
  581. package/dist/llm/reasoning/anthropic-thinking.d.ts +5 -0
  582. package/dist/llm/reasoning/gemini-thinking.d.ts +24 -0
  583. package/dist/llm/reasoning/index.cjs +454 -0
  584. package/dist/llm/reasoning/index.d.ts +9 -0
  585. package/dist/llm/reasoning/index.js +422 -0
  586. package/dist/llm/reasoning/model-fallback.d.ts +75 -0
  587. package/dist/llm/reasoning/model-ids.d.ts +5 -0
  588. package/dist/llm/reasoning/thinking-provider-options.d.ts +10 -0
  589. package/dist/llm/reasoning/thinking-request.d.ts +14 -0
  590. package/dist/llm/reasoning/thinking.d.ts +37 -0
  591. package/dist/{llm-ypGNjEom.cjs → llm-RIAYOAtD.cjs} +34 -14
  592. package/dist/{llm-9xmy8HlF.js → llm-YNjDFSui.js} +34 -14
  593. package/dist/loop/index.cjs +15 -15
  594. package/dist/loop/index.js +2 -2
  595. package/dist/loop/loop-builder.d.ts +1 -1
  596. package/dist/loop/loop-runtime.d.ts +1 -1
  597. package/dist/loop/loop.d.ts +1 -1
  598. package/dist/loop/run-scope-keys.d.ts +1 -1
  599. package/dist/loop/server.cjs +1 -1
  600. package/dist/loop/server.js +1 -1
  601. package/dist/loop/shared/signal-outcome.d.ts +1 -1
  602. package/dist/loop/shared/steps/signal-drain-core.d.ts +9 -3
  603. package/dist/loop/shared/transcript-step.d.ts +1 -1
  604. package/dist/loop/suspended-run-auto-resume.d.ts +15 -0
  605. package/dist/loop/types.d.ts +2 -2
  606. package/dist/loop/workflows/agentic-execution/background-task-check-step.d.ts +1 -1
  607. package/dist/loop/workflows/agentic-execution/build-messages-from-chunks.d.ts +1 -1
  608. package/dist/loop/workflows/agentic-execution/goal-step.d.ts +1 -1
  609. package/dist/loop/workflows/agentic-execution/index.d.ts +1 -1
  610. package/dist/loop/workflows/agentic-execution/is-task-complete-step.d.ts +1 -1
  611. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +1 -1
  612. package/dist/loop/workflows/agentic-execution/llm-mapping-step.d.ts +1 -1
  613. package/dist/loop/workflows/agentic-execution/tool-call-concurrency.d.ts +1 -1
  614. package/dist/loop/workflows/agentic-execution/tool-call-step.d.ts +2 -2
  615. package/dist/loop/workflows/agentic-loop/index.d.ts +1 -1
  616. package/dist/loop/workflows/schema.d.ts +2 -2
  617. package/dist/loop/workflows/stream.d.ts +1 -1
  618. package/dist/{manager-B-QrBhhd.js → manager-DZhtdV6Q.js} +9 -7
  619. package/dist/{manager-CYXV5_vY.cjs → manager-Y-jYcS7T.cjs} +21 -19
  620. package/dist/mastra/index.cjs +1 -1
  621. package/dist/mastra/index.d.ts +67 -12
  622. package/dist/mastra/index.js +1 -1
  623. package/dist/{mastra-zszeli0N.cjs → mastra-B2-HBq1-.cjs} +211 -67
  624. package/dist/{mastra-DPSwJ5ae.js → mastra-BJ54VxOO.js} +171 -27
  625. package/dist/mastra-gateway-provider-tools-C-AjGZis.js +58 -0
  626. package/dist/mastra-gateway-provider-tools-WpH3Tmu4.cjs +81 -0
  627. package/dist/memory/index.cjs +25 -25
  628. package/dist/memory/index.js +3 -3
  629. package/dist/memory/memory.d.ts +1 -1
  630. package/dist/memory/mock.d.ts +2 -3
  631. package/dist/memory/om-events/index.cjs +189 -0
  632. package/dist/memory/om-events/index.d.ts +17 -0
  633. package/dist/memory/om-events/index.js +188 -0
  634. package/dist/memory/types.d.ts +2 -2
  635. package/dist/{message-list-vR3uLAHL.cjs → message-list-C0F2sDNC.cjs} +3 -2
  636. package/dist/{message-list-BGm1DCiG.js → message-list-RgFlLrxG.js} +3 -2
  637. package/dist/{model-UYJb8Zel.js → model-cS3d5rmF.js} +2 -2
  638. package/dist/{model-WLujr8OR.cjs → model-lzZPXaEV.cjs} +2 -2
  639. package/dist/{netlify-wZafLKoe.cjs → netlify-1lti1j4Z.cjs} +97 -3
  640. package/dist/{netlify-DTWAZGpA.js → netlify-ClBjc0Xg.js} +86 -4
  641. package/dist/notifications/index.cjs +18 -18
  642. package/dist/notifications/index.js +2 -2
  643. package/dist/observability/index.cjs +1 -1
  644. package/dist/observability/index.js +1 -1
  645. package/dist/{observability-D7RNOAPx.js → observability-DPDWibyH.js} +648 -648
  646. package/dist/{output-helpers-CVzhy1Y0.js → output-helpers-D-qplq22.js} +70 -74
  647. package/dist/{output-helpers-DgsH4aTb.cjs → output-helpers-D4O_oFne.cjs} +69 -73
  648. package/dist/processor-provider/index.cjs +10 -10
  649. package/dist/processor-provider/index.js +1 -1
  650. package/dist/processors/index.cjs +65 -65
  651. package/dist/processors/index.d.ts +2 -2
  652. package/dist/processors/index.js +2 -2
  653. package/dist/processors/runner.d.ts +1 -1
  654. package/dist/processors/step-schema.d.ts +1 -1
  655. package/dist/{provider-registry-BvpUdOiq.cjs → provider-registry-C6jd3Uxi.cjs} +20494 -21358
  656. package/dist/{provider-registry-COT79RLh.js → provider-registry-C_XQJvu2.js} +20493 -21357
  657. package/dist/provider-registry.json +22407 -23248
  658. package/dist/{registry-generator-Dn1Tuacv.cjs → registry-generator-BYdAlox6.cjs} +1 -1
  659. package/dist/{registry-generator-BKjTPD6B.js → registry-generator-DBrTbThj.js} +1 -1
  660. package/dist/{rehydrate-BK1v65H7.js → rehydrate-4xHubfOY.js} +2 -2
  661. package/dist/{rehydrate-C0xrJUBu.cjs → rehydrate-BtwY0ima.cjs} +14 -14
  662. package/dist/relevance/index.cjs +3 -3
  663. package/dist/relevance/index.js +2 -2
  664. package/dist/{scheduler-B-VZUvv_.js → scheduler-D1qdie5k.js} +75 -23
  665. package/dist/{scheduler-D00X03jQ.cjs → scheduler-DE5lcHJA.cjs} +86 -22
  666. package/dist/server/auth.d.ts +3 -3
  667. package/dist/server/composite-auth.d.ts +1 -1
  668. package/dist/server/index.d.ts +1 -1
  669. package/dist/server/simple-auth.d.ts +1 -1
  670. package/dist/server/types.d.ts +64 -1
  671. package/dist/{signal-provider-BslnAjWG.js → signal-provider-B_mfW-J4.js} +1 -1
  672. package/dist/{signal-provider-BFAvh_AJ.cjs → signal-provider-D9gbevHN.cjs} +1 -1
  673. package/dist/signals/index.cjs +4 -3
  674. package/dist/signals/index.d.ts +1 -0
  675. package/dist/signals/index.js +4 -4
  676. package/dist/signals/time-signal-provider.d.ts +70 -0
  677. package/dist/signals-BwDXGqxc.cjs +358 -0
  678. package/dist/signals-TznxWfM3.js +347 -0
  679. package/dist/skills/create-skill.d.ts +3 -0
  680. package/dist/skills/index.cjs +1 -1
  681. package/dist/skills/index.js +1 -1
  682. package/dist/skills/inline-skill-source.d.ts +5 -1
  683. package/dist/skills/types.d.ts +16 -1
  684. package/dist/{source-fNa6u1kH.js → source-B3He4_mz.js} +7 -0
  685. package/dist/{source-BVOi8Xhp.cjs → source-C_nWbqI0.cjs} +7 -0
  686. package/dist/{state-processor-B9kxpM53.js → state-processor-B_KsS82m.js} +1 -1
  687. package/dist/{state-processor-kRNZ38Nf.cjs → state-processor-DaSmhVUX.cjs} +1 -1
  688. package/dist/storage/constants.cjs +1 -1
  689. package/dist/storage/constants.js +1 -1
  690. package/dist/storage/domains/agents/index.cjs +1 -1
  691. package/dist/storage/domains/agents/index.js +1 -1
  692. package/dist/storage/domains/inmemory-db.d.ts +6 -0
  693. package/dist/storage/domains/knowledge/base.d.ts +140 -5
  694. package/dist/storage/domains/knowledge/importers-inmemory.d.ts +9 -0
  695. package/dist/storage/domains/knowledge/importers.d.ts +31 -0
  696. package/dist/storage/domains/knowledge/inmemory.d.ts +11 -0
  697. package/dist/storage/domains/knowledge/pages-inmemory.d.ts +50 -12
  698. package/dist/storage/domains/knowledge/pages.d.ts +90 -1
  699. package/dist/storage/domains/memory/base.d.ts +122 -0
  700. package/dist/storage/domains/memory/index.d.ts +1 -0
  701. package/dist/storage/domains/memory/inmemory.d.ts +39 -0
  702. package/dist/storage/domains/memory/queue-thread.d.ts +42 -0
  703. package/dist/storage/domains/schedules/base.d.ts +31 -2
  704. package/dist/storage/domains/schedules/inmemory.d.ts +9 -2
  705. package/dist/storage/domains/workflows/base.d.ts +32 -5
  706. package/dist/storage/domains/workflows/inmemory.d.ts +7 -6
  707. package/dist/storage/domains/workflows/journal.d.ts +16 -1
  708. package/dist/storage/index.cjs +192 -186
  709. package/dist/storage/index.js +6 -6
  710. package/dist/storage/types.d.ts +6 -0
  711. package/dist/storage/workflow-snapshot.d.ts +4 -0
  712. package/dist/storage/workflow-step-guard.d.ts +5 -0
  713. package/dist/stream/RunOutput.d.ts +1 -1
  714. package/dist/stream/aisdk/v4/input.d.ts +1 -1
  715. package/dist/stream/aisdk/v5/compat/content.d.ts +1 -1
  716. package/dist/stream/aisdk/v5/compat/prepare-tools.d.ts +1 -1
  717. package/dist/stream/aisdk/v5/compat/ui-message.d.ts +1 -1
  718. package/dist/stream/aisdk/v5/compat/validation.d.ts +1 -1
  719. package/dist/stream/aisdk/v5/execute.d.ts +1 -1
  720. package/dist/stream/aisdk/v5/input.d.ts +1 -1
  721. package/dist/stream/aisdk/v5/output-helpers.d.ts +7 -7
  722. package/dist/stream/aisdk/v5/transform.d.ts +1 -1
  723. package/dist/stream/base/output.d.ts +12 -4
  724. package/dist/stream/base/schema.d.ts +1 -1
  725. package/dist/stream/index.cjs +2 -2
  726. package/dist/stream/index.js +2 -2
  727. package/dist/stream/types.d.ts +2 -2
  728. package/dist/{stream-BmtBm_-L.cjs → stream-DqKDB3nL.cjs} +144 -10
  729. package/dist/{stream-B4LzC6Sz.js → stream-H_wVxqdK.js} +103 -11
  730. package/dist/telemetry/index.cjs +1 -1
  731. package/dist/telemetry/index.js +1 -1
  732. package/dist/test-utils/llm-mock.cjs +1 -1
  733. package/dist/test-utils/llm-mock.d.ts +3 -3
  734. package/dist/test-utils/llm-mock.js +1 -1
  735. package/dist/{tool-Z3bykc1m.js → tool-DIFduuTw.js} +2 -5
  736. package/dist/{tool-CYlT2UA-.cjs → tool-Dn9WSDVn.cjs} +2 -5
  737. package/dist/tool-loop-agent/index.cjs +1 -1
  738. package/dist/tool-loop-agent/index.js +1 -1
  739. package/dist/tool-loop-agent/utils.d.ts +1 -1
  740. package/dist/{tool-loop-agent-BIbw3quM.cjs → tool-loop-agent-D4gSdYuN.cjs} +5 -5
  741. package/dist/{tool-loop-agent-CR2AgmkF.js → tool-loop-agent-DvZcOxWe.js} +4 -4
  742. package/dist/{toolchecks-DrsZdc3S.js → toolchecks-CRAfUe9H.js} +1 -1
  743. package/dist/{toolchecks-MFU48cit.cjs → toolchecks-DbBsQGHW.cjs} +1 -1
  744. package/dist/tools/builtin/web-search.d.ts +9 -1
  745. package/dist/tools/index.cjs +5 -5
  746. package/dist/tools/index.d.ts +1 -0
  747. package/dist/tools/index.js +5 -5
  748. package/dist/tools/is-vercel-tool.cjs +1 -1
  749. package/dist/tools/is-vercel-tool.js +1 -1
  750. package/dist/tools/provider-tool-utils.d.ts +1 -1
  751. package/dist/tools/tool-builder/builder.d.ts +1 -1
  752. package/dist/tools/tool-title.d.ts +1 -1
  753. package/dist/tools/tool.d.ts +2 -4
  754. package/dist/tools/types.d.ts +2 -1
  755. package/dist/{tools-BEYxowf0.cjs → tools-DZoVfKPl.cjs} +43 -18
  756. package/dist/{tools-tPy2FwMI.js → tools-FwJyNoyg.js} +42 -11
  757. package/dist/types/user.d.ts +1 -1
  758. package/dist/{utils-D2Bj0C2E.cjs → utils-Dd4m7z13.cjs} +6 -5
  759. package/dist/{utils-BnG4bq6k.js → utils-h5k_ChdS.js} +6 -5
  760. package/dist/utils.cjs +3 -3
  761. package/dist/utils.d.ts +1 -1
  762. package/dist/utils.js +3 -3
  763. package/dist/{validate-DHEGALaE.js → validate-DQB9spZ1.js} +1 -1
  764. package/dist/{validate-BxgKlbt7.cjs → validate-u6_TUYSo.cjs} +1 -1
  765. package/dist/vector/embed.d.ts +4 -4
  766. package/dist/vector/index.cjs +9 -9
  767. package/dist/vector/index.js +2 -2
  768. package/dist/vector/vector.d.ts +4 -4
  769. package/dist/voice/aisdk/index.d.ts +1 -1
  770. package/dist/voice/aisdk/speech.d.ts +1 -1
  771. package/dist/voice/aisdk/transcription.d.ts +1 -1
  772. package/dist/voice/composite-voice.d.ts +1 -1
  773. package/dist/voice/default-voice.d.ts +1 -1
  774. package/dist/voice/index.d.ts +2 -2
  775. package/dist/voice/voice.d.ts +1 -1
  776. package/dist/worker/index.cjs +1 -1
  777. package/dist/worker/index.d.ts +1 -1
  778. package/dist/worker/index.js +1 -1
  779. package/dist/worker/workers/orchestration-worker.d.ts +13 -0
  780. package/dist/{worker-BRKHC9hv.cjs → worker-0F7Nukyf.cjs} +3 -3
  781. package/dist/{worker-DYBrWSDX.cjs → worker-D-cq8McN.cjs} +129 -39
  782. package/dist/{worker-C-xoXGOt.js → worker-DWOK2M_5.js} +122 -32
  783. package/dist/{worker-1lHN6hT1.js → worker-DmUkyJY_.js} +2 -2
  784. package/dist/{workflow-DGRDgyhs.cjs → workflow-DXE15e-w.cjs} +30 -38
  785. package/dist/{workflow-79JneaJP.js → workflow-DamOke3z.js} +26 -34
  786. package/dist/workflows/builder/index.cjs +1 -1
  787. package/dist/workflows/builder/index.js +1 -1
  788. package/dist/workflows/evented/execution-engine.d.ts +3 -1
  789. package/dist/workflows/evented/index.cjs +10 -10
  790. package/dist/workflows/evented/index.js +1 -1
  791. package/dist/workflows/evented/setup-warning.d.ts +31 -0
  792. package/dist/workflows/evented/workflow-event-processor/index.d.ts +10 -4
  793. package/dist/workflows/evented/workflow-event-processor/loop.d.ts +1 -1
  794. package/dist/workflows/evented/workflow-event-processor/parallel.d.ts +2 -2
  795. package/dist/workflows/evented/workflow-event-processor/sleep.d.ts +2 -2
  796. package/dist/workflows/evented/workflow.d.ts +8 -3
  797. package/dist/workflows/handlers/entry.d.ts +8 -0
  798. package/dist/workflows/index.cjs +57 -55
  799. package/dist/workflows/index.js +6 -6
  800. package/dist/workflows/run-storage.d.ts +27 -3
  801. package/dist/workflows/scheduler/claim.d.ts +51 -0
  802. package/dist/workflows/scheduler/index.d.ts +2 -0
  803. package/dist/workflows/scheduler/types.d.ts +3 -0
  804. package/dist/workflows/types.d.ts +17 -1
  805. package/dist/workflows/workflow.d.ts +88 -11
  806. package/dist/workspace/filesystem/local-filesystem.d.ts +13 -0
  807. package/dist/workspace/index.cjs +1 -1
  808. package/dist/workspace/index.js +1 -1
  809. package/dist/workspace/sandbox/local-sandbox.d.ts +11 -0
  810. package/dist/workspace/sandbox/sandbox.d.ts +2 -0
  811. package/dist/workspace/tools/media.d.ts +2 -2
  812. package/dist/{workspace-C8Zo5_qK.cjs → workspace-BQD4tcQi.cjs} +227 -26
  813. package/dist/{workspace-DOAil8mG.js → workspace-sqcfdZRR.js} +226 -25
  814. package/llm/reasoning.d.ts +1 -0
  815. package/memory/om-events.d.ts +1 -0
  816. package/package.json +36 -15
  817. package/skills/mastra/SKILL.md +171 -0
  818. package/skills/mastra/references/common-errors.md +557 -0
  819. package/skills/mastra/references/core-concepts.md +21 -0
  820. package/skills/mastra/references/create-mastra.md +233 -0
  821. package/skills/mastra/references/embedded-docs.md +103 -0
  822. package/skills/mastra/references/feedback.md +69 -0
  823. package/skills/mastra/references/gateway.md +66 -0
  824. package/skills/mastra/references/mastra-api.md +222 -0
  825. package/skills/mastra/references/migration-guide.md +185 -0
  826. package/skills/mastra/references/model-selection.md +29 -0
  827. package/skills/mastra/references/platform.md +164 -0
  828. package/skills/mastra/references/remote-docs.md +193 -0
  829. package/skills/mastra/references/trace-query.md +150 -0
  830. package/skills/mastra/scripts/provider-registry.mjs +271 -0
  831. package/src/llm/model/provider-types.generated.d.ts +7162 -7416
  832. package/dist/capabilities/ai21.json +0 -4
  833. package/dist/capabilities/clarifai.json +0 -42
  834. package/dist/capabilities/jad-ai.json +0 -20
  835. package/dist/capabilities/llmtech.json +0 -16
  836. package/dist/signals-B1JSj-Ew.cjs +0 -58
  837. package/dist/signals-De9VnwL2.js +0 -53
  838. package/dist/_types/{@internal_ai-sdk-v4@0.0.99 → @internal_ai-sdk-v4@0.0.100}/dist/test.d.ts +0 -0
  839. package/dist/_types/{@internal_ai-sdk-v4@0.0.99 → @internal_ai-sdk-v4@0.0.100}/package.json +0 -0
  840. package/dist/_types/{@internal_ai-sdk-v5@0.0.99 → @internal_ai-sdk-v5@0.0.100}/dist/test.d.ts +0 -0
  841. package/dist/_types/{@internal_ai-sdk-v5@0.0.99 → @internal_ai-sdk-v5@0.0.100}/package.json +0 -0
  842. package/dist/_types/{@internal_ai-v6@0.0.99 → @internal_ai-v6@0.0.100}/package.json +0 -0
  843. package/dist/_types/{@internal_ai-v7@0.0.99 → @internal_ai-v7@0.0.100}/package.json +0 -0
  844. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/_types/@internal_core@0.1.4/dist/base/index.d.ts +0 -0
  845. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/_types/@internal_core@0.1.4/dist/index-Diz1p9N7.d.ts +0 -0
  846. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/capabilities.d.ts +0 -0
  847. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/defaults/index.d.ts +0 -0
  848. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/defaults/rbac/index.d.ts +0 -0
  849. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/defaults/rbac/static.d.ts +0 -0
  850. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/defaults/roles.d.ts +0 -0
  851. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/fga-check.d.ts +0 -0
  852. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/index.d.ts +0 -0
  853. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/interfaces/acl.d.ts +0 -0
  854. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/interfaces/fga.d.ts +0 -0
  855. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/interfaces/index.d.ts +0 -0
  856. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/interfaces/permissions.generated.d.ts +0 -0
  857. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/interfaces/rbac.d.ts +0 -0
  858. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/interfaces/user.d.ts +0 -0
  859. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/ee/license.d.ts +0 -0
  860. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/index.d.ts +0 -0
  861. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/provider/index.d.ts +0 -0
  862. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/session/cookie.d.ts +0 -0
  863. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/session/index.d.ts +0 -0
  864. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/session/memory.d.ts +0 -0
  865. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/dist/types/index.d.ts +0 -0
  866. package/dist/_types/{@internal_auth@0.0.40 → @internal_auth@0.0.41}/package.json +0 -0
  867. package/dist/_types/{@internal_deployer@0.0.5 → @internal_deployer@0.0.6}/dist/_types/@internal_core@0.1.4/dist/index-Diz1p9N7.d.ts +0 -0
  868. package/dist/_types/{@internal_deployer@0.0.5 → @internal_deployer@0.0.6}/dist/_types/@internal_core@0.1.4/dist/logger/index.d.ts +0 -0
  869. package/dist/_types/{@internal_deployer@0.0.5 → @internal_deployer@0.0.6}/dist/bundler.d.ts +0 -0
  870. package/dist/_types/{@internal_deployer@0.0.5 → @internal_deployer@0.0.6}/dist/deployer.d.ts +0 -0
  871. package/dist/_types/{@internal_deployer@0.0.5 → @internal_deployer@0.0.6}/dist/index.d.ts +0 -0
  872. package/dist/_types/{@internal_deployer@0.0.5 → @internal_deployer@0.0.6}/package.json +0 -0
  873. package/dist/_types/{@internal_external-types@0.0.102 → @internal_external-types@0.0.103}/dist/index.d.ts +0 -0
  874. package/dist/_types/{@internal_external-types@0.0.102 → @internal_external-types@0.0.103}/package.json +0 -0
  875. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/@internal_core@0.1.4/dist/base/index.d.ts +0 -0
  876. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/@internal_core@0.1.4/dist/index-Diz1p9N7.d.ts +0 -0
  877. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/@internal_core@0.1.4/dist/request-context/index.d.ts +0 -0
  878. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/@internal_core@0.1.4/dist/types/index.d.ts +0 -0
  879. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/ZodError.d.ts +0 -0
  880. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/errors.d.ts +0 -0
  881. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/external.d.ts +0 -0
  882. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/helpers/enumUtil.d.ts +0 -0
  883. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/helpers/errorUtil.d.ts +0 -0
  884. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/helpers/parseUtil.d.ts +0 -0
  885. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/helpers/partialUtil.d.ts +0 -0
  886. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/helpers/typeAliases.d.ts +0 -0
  887. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/helpers/util.d.ts +0 -0
  888. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/index.d.ts +0 -0
  889. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/locales/en.d.ts +0 -0
  890. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/standard-schema.d.ts +0 -0
  891. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v3/types.d.ts +0 -0
  892. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/checks.d.ts +0 -0
  893. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/coerce.d.ts +0 -0
  894. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/compat.d.ts +0 -0
  895. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/deep-partial.d.ts +0 -0
  896. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/errors.d.ts +0 -0
  897. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/external.d.ts +0 -0
  898. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/from-json-schema.d.ts +0 -0
  899. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/in-out.d.ts +0 -0
  900. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/index.d.ts +0 -0
  901. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/iso.d.ts +0 -0
  902. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/parse.d.ts +0 -0
  903. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/classic/schemas.d.ts +0 -0
  904. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/api.d.ts +0 -0
  905. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/checks.d.ts +0 -0
  906. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/compile.d.ts +0 -0
  907. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/core.d.ts +0 -0
  908. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/doc.d.ts +0 -0
  909. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/errors.d.ts +0 -0
  910. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/index.d.ts +0 -0
  911. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/json-schema-generator.d.ts +0 -0
  912. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/json-schema-processors.d.ts +0 -0
  913. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/json-schema.d.ts +0 -0
  914. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/memoizer.d.ts +0 -0
  915. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/parse.d.ts +0 -0
  916. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/regexes.d.ts +0 -0
  917. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/registries.d.ts +0 -0
  918. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/schemas.d.ts +0 -0
  919. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/standard-schema.d.ts +0 -0
  920. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/to-json-schema.d.ts +0 -0
  921. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/util.d.ts +0 -0
  922. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/core/versions.d.ts +0 -0
  923. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/index.d.cts +0 -0
  924. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ar.d.ts +0 -0
  925. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/az.d.ts +0 -0
  926. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/be.d.ts +0 -0
  927. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/bg.d.ts +0 -0
  928. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/bn.d.ts +0 -0
  929. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ca.d.ts +0 -0
  930. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ckb.d.ts +0 -0
  931. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/cs.d.ts +0 -0
  932. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/da.d.ts +0 -0
  933. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/de.d.ts +0 -0
  934. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/el.d.ts +0 -0
  935. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/en.d.ts +0 -0
  936. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/eo.d.ts +0 -0
  937. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/es.d.ts +0 -0
  938. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/fa.d.ts +0 -0
  939. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/fi.d.ts +0 -0
  940. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/fr-CA.d.ts +0 -0
  941. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/fr.d.ts +0 -0
  942. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/gu.d.ts +0 -0
  943. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/he.d.ts +0 -0
  944. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/hi.d.ts +0 -0
  945. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/hr.d.ts +0 -0
  946. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/hu.d.ts +0 -0
  947. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/hy.d.ts +0 -0
  948. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/id.d.ts +0 -0
  949. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/index.d.ts +0 -0
  950. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/is.d.ts +0 -0
  951. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/it.d.ts +0 -0
  952. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ja.d.ts +0 -0
  953. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ka.d.ts +0 -0
  954. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/kh.d.ts +0 -0
  955. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/km.d.ts +0 -0
  956. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/kn.d.ts +0 -0
  957. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ko.d.ts +0 -0
  958. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/lt.d.ts +0 -0
  959. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/mk.d.ts +0 -0
  960. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ms.d.ts +0 -0
  961. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ne.d.ts +0 -0
  962. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/nl.d.ts +0 -0
  963. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/nn.d.ts +0 -0
  964. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/no.d.ts +0 -0
  965. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ota.d.ts +0 -0
  966. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/pl.d.ts +0 -0
  967. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ps.d.ts +0 -0
  968. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/pt-BR.d.ts +0 -0
  969. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/pt.d.ts +0 -0
  970. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ro.d.ts +0 -0
  971. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ru.d.ts +0 -0
  972. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/sk.d.ts +0 -0
  973. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/sl.d.ts +0 -0
  974. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/sv.d.ts +0 -0
  975. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ta.d.ts +0 -0
  976. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/tg.d.ts +0 -0
  977. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/th.d.ts +0 -0
  978. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/tk.d.ts +0 -0
  979. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/tr.d.ts +0 -0
  980. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ua.d.ts +0 -0
  981. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/uk.d.ts +0 -0
  982. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/ur.d.ts +0 -0
  983. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/uz.d.ts +0 -0
  984. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/vi.d.ts +0 -0
  985. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/yo.d.ts +0 -0
  986. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/zh-CN.d.ts +0 -0
  987. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/_types/zod@4.6.7/v4/locales/zh-TW.d.ts +0 -0
  988. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/index.d.ts +0 -0
  989. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/voice/aisdk/index.d.ts +0 -0
  990. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/voice/default-voice.d.ts +0 -0
  991. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/voice/index.d.ts +0 -0
  992. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/dist/voice/voice.d.ts +0 -0
  993. package/dist/_types/{@internal_voice@0.0.48 → @internal_voice@0.0.49}/package.json +0 -0
  994. package/dist/{observability-B0R_D1PZ.cjs → observability-VaoaeadK.cjs} +647 -647
@@ -1,7 +1,8 @@
1
1
  import { t as MastraBase } from "../base-CKLWBhDo.js";
2
- import { $t as PINNED_READ_MEMO_KEY, Ai as KnowledgePageDepthError, An as strongerKnowledgeRole, Bi as MAX_KNOWLEDGE_PAGE_LIST_LIMIT, Ci as KnowledgeTransactionDeadlineError, Cn as knowledgeReadScopeFor, Cr as knowledgeSemanticDocumentId, Di as inspectKnowledgeSchema, Dn as knowledgeMemoryScopes, Ei as createKnowledgeUlid, En as compileKnowledgeScopes, Er as parseKnowledgeNodeCursor, Fi as MAX_KNOWLEDGE_PAGE_BODY_LINKS, Gi as knowledgeLinkRefKey, Hi as assertKnowledgeNoteTextWithinBound, Ii as MAX_KNOWLEDGE_PAGE_DEPTH, Ji as knowledgePositionBetween, Jo as augmentWithInit, Ki as knowledgePagePath, Li as MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, Mi as KnowledgePageKeyConflictError, Mn as encodeKnowledgeScopeId, Ni as MAX_KNOWLEDGE_MOVE_PAGES, Nn as buildKnowledgeInstructions, Oi as parseKnowledgeWikilinks, On as knowledgeRunScopes, Pi as MAX_KNOWLEDGE_NOTE_TOKENS, Ri as MAX_KNOWLEDGE_PAGE_LINKS, Si as KnowledgeStorage, Sn as knowledgeAccessGrants, Sr as knowledgeScopeKey, Ti as assertKnowledgeSchemaCompatible, Tn as KnowledgeDeclarationError, Tr as knowledgeVisibleScopeKeys, Ui as assertKnowledgePageDescriptionWithinBound, Vi as MAX_KNOWLEDGE_PIN_LIST_DEPTH, Wi as canonicalKnowledgeName, Xi as parseKnowledgePageRef, Yi as knowledgeScopeReadable, Yo as getStorageSource, Zi as KnowledgeInvalidCursorError, _i as KNOWLEDGE_STORAGE_CONTRACT_VERSION, _n as knowledgeSubtree, _r as assertKnowledgeScopeWithinCeiling, an as knowledgeRunPrincipals, bi as KnowledgeNotFoundError, bn as syncKnowledgePageBodyLinks, br as expandKnowledgeScope, cn as addKnowledgeNote, dn as removeKnowledgePage, dr as MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, en as knowledgeDeliveredPins, fn as updateKnowledgeNote, fr as MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, gi as KnowledgeImportersStorage, gn as KnowledgeLinkRefreshIncompleteError, gr as assertKnowledgeRecordTextWithinBound, hi as KnowledgeImporterRunStateError, hr as assertKnowledgeDescriptionWithinBound, in as KnowledgeRunScopesError, ji as KnowledgePageHasChildrenError, jn as decodeKnowledgeScopeId, ki as KnowledgeMoveTooLargeError, kn as knowledgeScopeAddress, ln as moveKnowledgePage, mi as KnowledgeImporterBindingConflictError, mn as KnowledgeSemanticIndex, mr as assertKnowledgeCeilingRaised, nn as heldScopes, on as knowledgeAgentScopes, pi as InMemoryKnowledgeStorage, pn as upsertKnowledgePage, pr as MAX_KNOWLEDGE_SCOPE_TAGS, qi as knowledgePinDepth, rn as KnowledgeRun, sn as knowledgePersonaScopes, tn as buildKnowledgePageTools, un as removeKnowledgeNote, vi as KNOWLEDGE_STORAGE_SCHEMA_VERSION, vn as refreshKnowledgeLinksTo, vr as canonicalizeKnowledgeScope, wi as KnowledgeUnsupportedCapabilityError, wn as knowledgeRoleOn, wr as knowledgeSemanticIdempotencyKey, xi as KnowledgeSchemaResetRequiredError, xn as updateKnowledgeLinks, xr as isKnowledgeScopeVisible, yi as KnowledgeConflictError, yn as reindexKnowledgeLinks, yr as createKnowledgeNodeCursor, zi as MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH } from "../run-registry-DKiudqVU.js";
2
+ import { $n as assertKnowledgeCeilingRaised, $r as KnowledgeImporterBindingConflictError, $t as KnowledgeLinkRepairUnsupportedError, Ai as knowledgeLinkRefKey, Bt as KnowledgeRunScopesError, Ci as MAX_KNOWLEDGE_PAGE_LINKS, Di as assertKnowledgeNoteTextWithinBound, Ei as MAX_KNOWLEDGE_PIN_LIST_DEPTH, Fi as parseKnowledgePageRef, Fo as getStorageSource, Ft as PINNED_READ_MEMO_KEY, Gt as moveKnowledgePage, Ht as knowledgeAgentScopes, Ii as KnowledgeInvalidCursorError, It as knowledgeDeliveredPins, Jt as updateKnowledgeNote, Kt as removeKnowledgeNote, Li as knowledgePageKeyProblem, Lt as buildKnowledgePageTools, Mi as knowledgePinDepth, Ni as knowledgePositionBetween, Oi as assertKnowledgePageDescriptionWithinBound, Pi as knowledgeScopeReadable, Po as augmentWithInit, Qn as MAX_KNOWLEDGE_SCOPE_TAGS, Qr as InMemoryKnowledgeStorage, Qt as KnowledgeLinkRefreshIncompleteError, Rt as heldScopes, Si as MAX_KNOWLEDGE_PAGE_DESCRIPTION_TOKENS, Ti as MAX_KNOWLEDGE_PAGE_LIST_LIMIT, Ut as knowledgePersonaScopes, Vt as knowledgeRunPrincipals, Wt as addKnowledgeNote, Xn as MAX_KNOWLEDGE_NODE_DESCRIPTION_LENGTH, Xt as KnowledgeSemanticIndex, Yt as upsertKnowledgePage, Zn as MAX_KNOWLEDGE_RECORD_TEXT_LENGTH, _i as KnowledgePageKeyConflictError, _n as encodeKnowledgeScopeId, ai as KnowledgeNotFoundError, an as syncKnowledgePageBodyLinks, ar as expandKnowledgeScope, bi as MAX_KNOWLEDGE_PAGE_BODY_LINKS, ci as KnowledgeTransactionDeadlineError, cn as knowledgeReadScopeFor, cr as knowledgeSemanticDocumentId, di as createKnowledgeUlid, dn as compileKnowledgeScopes, dr as parseKnowledgeNodeCursor, ei as KnowledgeImporterRunStateError, en as canRepairKnowledgeLinksInBatch, er as assertKnowledgeDescriptionWithinBound, fi as inspectKnowledgeSchema, fn as knowledgeMemoryScopes, gi as KnowledgePageHasChildrenError, gn as decodeKnowledgeScopeId, hi as KnowledgePageDepthError, hn as strongerKnowledgeRole, ii as KnowledgeConflictError, in as repairKnowledgeLinks, ir as createKnowledgeNodeCursor, ji as knowledgePagePath, ki as canonicalKnowledgeName, li as KnowledgeUnsupportedCapabilityError, ln as knowledgeRoleOn, lr as knowledgeSemanticIdempotencyKey, mi as KnowledgeMoveTooLargeError, mn as knowledgeScopeAddress, ni as KNOWLEDGE_STORAGE_CONTRACT_VERSION, nn as refreshKnowledgeLinksTo, nr as assertKnowledgeScopeWithinCeiling, oi as KnowledgeSchemaResetRequiredError, on as updateKnowledgeLinks, or as isKnowledgeScopeVisible, pi as parseKnowledgeWikilinks, pn as knowledgeRunScopes, qt as removeKnowledgePage, ri as KNOWLEDGE_STORAGE_SCHEMA_VERSION, rn as reindexKnowledgeLinks, rr as canonicalizeKnowledgeScope, si as KnowledgeStorage, sn as knowledgeAccessGrants, sr as knowledgeScopeKey, ti as KnowledgeImportersStorage, tn as knowledgeSubtree, tr as assertKnowledgeRecordTextWithinBound, ui as assertKnowledgeSchemaCompatible, un as KnowledgeDeclarationError, ur as knowledgeVisibleScopeKeys, vi as MAX_KNOWLEDGE_MOVE_PAGES, vn as buildKnowledgeInstructions, wi as MAX_KNOWLEDGE_PAGE_LINK_REF_LENGTH, xi as MAX_KNOWLEDGE_PAGE_DEPTH, yi as MAX_KNOWLEDGE_NOTE_TOKENS, zt as KnowledgeRun } from "../execution-fence-DGFyUV5h.js";
3
3
  import { standardSchemaToJSONSchema, toStandardSchema } from "../schema/index.js";
4
- import { i as createStandardSchemaIssuesError } from "../tool-Z3bykc1m.js";
4
+ import { i as createStandardSchemaIssuesError } from "../tool-DIFduuTw.js";
5
+ import { mt as estimateTokenCount } from "../workspace-sqcfdZRR.js";
5
6
  import { randomUUID } from "crypto";
6
7
  // src/knowledge/changes.ts
7
8
  const page = (op) => (result) => {
@@ -22,6 +23,39 @@ const note = (op) => (result) => {
22
23
  noteId: id
23
24
  };
24
25
  };
26
+ /** The event each single write would emit for `write`, so a batch emits what its single writes would. */
27
+ function describePageWrite(write) {
28
+ switch (write.op) {
29
+ case "create":
30
+ case "update":
31
+ case "delete": return {
32
+ kind: "page",
33
+ op: write.op,
34
+ pageId: write.id,
35
+ scopeId: write.scopeId
36
+ };
37
+ case "move": return {
38
+ kind: "page",
39
+ op: "move",
40
+ pageId: write.id,
41
+ scopeId: write.scopeId,
42
+ fromScopeId: write.fromScopeId
43
+ };
44
+ case "add-note": return {
45
+ kind: "note",
46
+ op: "add",
47
+ pageId: write.pageId,
48
+ noteId: write.id
49
+ };
50
+ case "remove-note": return {
51
+ kind: "note",
52
+ op: "remove",
53
+ pageId: write.pageId,
54
+ noteId: write.id
55
+ };
56
+ case "replace-links": return null;
57
+ }
58
+ }
25
59
  /** The page-store writes that emit, and the event each one's result maps to. */
26
60
  const WRITES = {
27
61
  materializeScope: (result) => {
@@ -57,6 +91,7 @@ const WRITES = {
57
91
  fromScopeId
58
92
  };
59
93
  },
94
+ applyPageWrites: (_result, input) => input.writes.map(describePageWrite).filter((change) => change !== null),
60
95
  addNote: note("add"),
61
96
  restampNote: note("restamp"),
62
97
  removeNote: note("remove"),
@@ -142,9 +177,15 @@ function emitKnowledgeChanges(storage, emit, listening, onError, chain) {
142
177
  }
143
178
  const result = await value.call(target, input, ...rest);
144
179
  if (!listening()) return result;
180
+ let changes = [];
145
181
  try {
146
182
  const change = describe(result, input, fromScopeId);
147
- if (change) report(change);
183
+ changes = Array.isArray(change) ? change : change ? [change] : [];
184
+ } catch (error) {
185
+ onError(error);
186
+ }
187
+ for (const one of changes) try {
188
+ report(one);
148
189
  } catch (error) {
149
190
  onError(error);
150
191
  }
@@ -284,7 +325,8 @@ const DECLARATION_FIELDS = {
284
325
  required: true
285
326
  },
286
327
  parent: { kind: "nullableString" },
287
- fallbackParent: { kind: "nonEmpty" }
328
+ fallbackParent: { kind: "nonEmpty" },
329
+ path: { kind: "segments" }
288
330
  };
289
331
  const ITEM_FIELDS = {
290
332
  ...DECLARATION_FIELDS,
@@ -330,6 +372,9 @@ function checkFields(value, fields, where) {
330
372
  case "aliases":
331
373
  out[key] = checkDenseArray(field, at).map((alias, index) => checkString(alias, `${at}[${index}]`, true));
332
374
  break;
375
+ case "segments":
376
+ out[key] = checkDenseArray(field, at).map((segment, index) => checkString(segment, `${at}[${index}]`));
377
+ break;
333
378
  case "links": out[key] = checkDenseArray(field, at).map((link, index) => checkFields(link, {
334
379
  sourceId: {
335
380
  kind: "nonEmpty",
@@ -1032,6 +1077,991 @@ async function finishRun(host, request, lastSeq, unsettledSeq, withRetries) {
1032
1077
  function encodedBytes(value) {
1033
1078
  return new TextEncoder().encode(JSON.stringify(value)).byteLength;
1034
1079
  }
1080
+ // src/knowledge/importers/overlay.ts
1081
+ /**
1082
+ * The working copy a batched importer flush decides over (batched-flush plan v3.1 §1). The sink's
1083
+ * rule code runs unchanged against {@link ImportOverlay.storage} and {@link ImportOverlay.importers}:
1084
+ * reads come from rows gathered in a few set-based queries and locked, writes are applied to the
1085
+ * working copy and kept, in call order, for one batched write after every op is decided.
1086
+ *
1087
+ * A read of something not gathered throws {@link KnowledgeImportNotGatheredError} and names it, so
1088
+ * the caller gathers it and decides again. A call the working copy can't model throws
1089
+ * {@link KnowledgeImportBatchUnsupportedError}, and the flush takes the per-op path instead.
1090
+ *
1091
+ * @internal
1092
+ */
1093
+ /** The overlay was asked for a row it wasn't given. The caller gathers it and decides again. */
1094
+ var KnowledgeImportNotGatheredError = class extends Error {
1095
+ constructor(what) {
1096
+ super(`Not gathered for the batched import flush: ${what}`);
1097
+ this.name = "KnowledgeImportNotGatheredError";
1098
+ }
1099
+ };
1100
+ /** The flush needs a call the overlay doesn't model: it falls back to the per-op path. */
1101
+ /**
1102
+ * The gather read the rows once, its plan writing pages only in place, and the decide pass went to
1103
+ * create, move or delete a page anyway: one more pass reads them again under the lock.
1104
+ */
1105
+ var KnowledgeImportRereadRequiredError = class extends Error {
1106
+ constructor(what) {
1107
+ super(`The batched import flush needs its rows read again under the lock: ${what}`);
1108
+ this.name = "KnowledgeImportRereadRequiredError";
1109
+ }
1110
+ };
1111
+ var KnowledgeImportBatchUnsupportedError = class extends Error {
1112
+ call;
1113
+ constructor(call) {
1114
+ super(`Not supported by the batched import flush: ${call}`);
1115
+ this.call = call;
1116
+ this.name = "KnowledgeImportBatchUnsupportedError";
1117
+ }
1118
+ };
1119
+ const nodeKey = (bindingId, sourceId) => `${bindingId}\u0000${sourceId}`;
1120
+ /** The key {@link ImportOverlayRows.paths} holds a scope path under. */
1121
+ const importPathKey = (scopeId, path) => JSON.stringify([scopeId, ...path]);
1122
+ const pathKey = importPathKey;
1123
+ /**
1124
+ * The key path of each live page whose whole chain to its scope is among `pages`, to that page: a
1125
+ * path a read chain already answers, with no `getPagesByPaths`. One key path has one live page.
1126
+ */
1127
+ function importChainPaths(pages) {
1128
+ const out = /* @__PURE__ */ new Map();
1129
+ for (const page of pages.values()) {
1130
+ if (!page || page.isScope) continue;
1131
+ const path = [];
1132
+ let at = page;
1133
+ while (at && !at.isScope) {
1134
+ if (at.key === void 0 || at.deletedAt || at.mergedInto || path.length >= 10) {
1135
+ at = void 0;
1136
+ break;
1137
+ }
1138
+ path.unshift(at.key);
1139
+ at = at.parentId ? pages.get(at.parentId) : null;
1140
+ }
1141
+ if (at) out.set(pathKey(at.id, path), page.id);
1142
+ }
1143
+ return out;
1144
+ }
1145
+ const childKey = (parentId, key) => `${parentId}\u0000${key}`;
1146
+ 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;
1147
+ /** UTF-8 byte order, as the stores sort source IDs. */
1148
+ const byteOrder = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
1149
+ const emptyImportOverlayMissing = () => ({
1150
+ pages: /* @__PURE__ */ new Set(),
1151
+ nodes: /* @__PURE__ */ new Set(),
1152
+ nodesByPage: /* @__PURE__ */ new Set(),
1153
+ paths: /* @__PURE__ */ new Map(),
1154
+ notes: /* @__PURE__ */ new Set(),
1155
+ positions: /* @__PURE__ */ new Set(),
1156
+ locks: /* @__PURE__ */ new Set(),
1157
+ subtrees: /* @__PURE__ */ new Set(),
1158
+ linkTargets: /* @__PURE__ */ new Set(),
1159
+ bindings: /* @__PURE__ */ new Set()
1160
+ });
1161
+ const emptyImportOverlayRows = () => ({
1162
+ pages: /* @__PURE__ */ new Map(),
1163
+ nodes: /* @__PURE__ */ new Map(),
1164
+ nodesByPage: /* @__PURE__ */ new Map(),
1165
+ paths: /* @__PURE__ */ new Map(),
1166
+ notes: /* @__PURE__ */ new Map(),
1167
+ positions: /* @__PURE__ */ new Map(),
1168
+ locked: /* @__PURE__ */ new Set(),
1169
+ complete: /* @__PURE__ */ new Set(),
1170
+ tooLarge: /* @__PURE__ */ new Set(),
1171
+ linkTargets: /* @__PURE__ */ new Set(),
1172
+ tooManyLinkers: /* @__PURE__ */ new Set()
1173
+ });
1174
+ /** The binding and targets of a deferred mark, so back-to-back marks for one binding run as one. */
1175
+ const markTargets = /* @__PURE__ */ new WeakMap();
1176
+ const copyRows = (rows) => ({
1177
+ pages: new Map(rows.pages),
1178
+ nodes: new Map(rows.nodes),
1179
+ nodesByPage: new Map(rows.nodesByPage),
1180
+ paths: new Map(rows.paths),
1181
+ notes: new Map(rows.notes),
1182
+ positions: new Map(rows.positions),
1183
+ locked: new Set(rows.locked),
1184
+ complete: new Set(rows.complete),
1185
+ tooLarge: new Set(rows.tooLarge),
1186
+ linkTargets: new Set(rows.linkTargets),
1187
+ tooManyLinkers: new Set(rows.tooManyLinkers),
1188
+ ...rows.bindings ? { bindings: rows.bindings } : {},
1189
+ ...rows.inPlace ? { inPlace: true } : {},
1190
+ ...rows.readOnce ? { readOnce: true } : {}
1191
+ });
1192
+ const copyState = (state) => ({
1193
+ rows: copyRows(state.rows),
1194
+ writes: [...state.writes],
1195
+ touched: new Set(state.touched),
1196
+ marks: [...state.marks],
1197
+ links: [...state.links],
1198
+ moved: new Set(state.moved),
1199
+ freed: new Set(state.freed),
1200
+ stalePositions: new Set(state.stalePositions)
1201
+ });
1202
+ /** Every method the given implementation lacks throws {@link KnowledgeImportBatchUnsupportedError}. */
1203
+ function only(impl, name) {
1204
+ return new Proxy(impl, { get(target, prop, receiver) {
1205
+ if (prop in target) return Reflect.get(target, prop, receiver);
1206
+ if (typeof prop !== "string" || prop === "then") return void 0;
1207
+ return () => {
1208
+ throw new KnowledgeImportBatchUnsupportedError(`${name}.${prop}`);
1209
+ };
1210
+ } });
1211
+ }
1212
+ var ImportOverlay = class {
1213
+ missing = emptyImportOverlayMissing();
1214
+ #state;
1215
+ storage;
1216
+ importers;
1217
+ constructor(base, now = () => /* @__PURE__ */ new Date()) {
1218
+ this.#state = {
1219
+ rows: copyRows(base),
1220
+ writes: [],
1221
+ touched: /* @__PURE__ */ new Set(),
1222
+ marks: [],
1223
+ links: [],
1224
+ moved: /* @__PURE__ */ new Set(),
1225
+ freed: /* @__PURE__ */ new Set(),
1226
+ stalePositions: /* @__PURE__ */ new Set()
1227
+ };
1228
+ this.storage = this.#storage(now);
1229
+ this.importers = this.#importers();
1230
+ }
1231
+ get writes() {
1232
+ return this.#state.writes;
1233
+ }
1234
+ get marks() {
1235
+ return this.#state.marks;
1236
+ }
1237
+ get links() {
1238
+ return this.#state.links;
1239
+ }
1240
+ /** Link-index work the sink would run now; it runs, in one batch, after the batched write instead. */
1241
+ deferLinks(...work) {
1242
+ this.#state.links.push(...work);
1243
+ }
1244
+ /** The node writes decided: each touched node's last record, or a delete when it ends up gone. */
1245
+ nodeWrites(base) {
1246
+ const deletes = [];
1247
+ const saves = [];
1248
+ for (const key of this.#state.touched) {
1249
+ const node = this.#state.rows.nodes.get(key);
1250
+ if (node) {
1251
+ const { updatedAt: _updatedAt, ...record } = node;
1252
+ saves.push(record);
1253
+ } else if (base.nodes.get(key)) {
1254
+ const [bindingId, sourceId] = key.split("\0");
1255
+ deletes.push({
1256
+ bindingId,
1257
+ sourceId
1258
+ });
1259
+ }
1260
+ }
1261
+ return {
1262
+ deletes,
1263
+ saves
1264
+ };
1265
+ }
1266
+ #page(id) {
1267
+ const { pages } = this.#state.rows;
1268
+ if (!pages.has(id)) {
1269
+ this.missing.pages.add(id);
1270
+ throw new KnowledgeImportNotGatheredError(`page ${id}`);
1271
+ }
1272
+ return pages.get(id);
1273
+ }
1274
+ #livePage(id) {
1275
+ const page = this.#page(id);
1276
+ if (!page || page.deletedAt || page.mergedInto) throw new KnowledgeNotFoundError("page", id);
1277
+ return page;
1278
+ }
1279
+ /** Levels below the home scope, from the working copy's chain. */
1280
+ #depth(page) {
1281
+ let depth = 0;
1282
+ let at = page;
1283
+ while (at && !at.isScope) {
1284
+ depth++;
1285
+ at = at.parentId ? this.#page(at.parentId) : null;
1286
+ }
1287
+ return depth;
1288
+ }
1289
+ /** The page's key path from its scope, or null when the chain doesn't reach one. */
1290
+ #keys(page) {
1291
+ const path = [];
1292
+ let at = page;
1293
+ while (at && !at.isScope) {
1294
+ if (at.key === void 0 || at.deletedAt || at.mergedInto) return null;
1295
+ path.unshift(at.key);
1296
+ at = at.parentId ? this.#page(at.parentId) : null;
1297
+ }
1298
+ return at ? {
1299
+ scopeId: at.id,
1300
+ path
1301
+ } : null;
1302
+ }
1303
+ /**
1304
+ * Live ordinary children by parent, sorted by position: built on first use, dropped on each page
1305
+ * write, and keyed by the pages map, which a rolled-back transaction replaces.
1306
+ */
1307
+ #childIndex;
1308
+ #setPage(id, page) {
1309
+ this.#state.rows.pages.set(id, page);
1310
+ this.#childIndex = void 0;
1311
+ this.#chainPaths = void 0;
1312
+ }
1313
+ /** {@link importChainPaths} of the working copy, kept like the child index. */
1314
+ #chainPaths;
1315
+ #pathFromChains(key) {
1316
+ const { pages } = this.#state.rows;
1317
+ if (this.#chainPaths?.pages !== pages) this.#chainPaths = {
1318
+ pages,
1319
+ byPath: importChainPaths(pages)
1320
+ };
1321
+ return this.#chainPaths.byPath.get(key);
1322
+ }
1323
+ /** Live ordinary children by position, once gathered. */
1324
+ #children(parentId) {
1325
+ const { pages, complete } = this.#state.rows;
1326
+ if (!complete.has(parentId)) {
1327
+ this.missing.subtrees.add(parentId);
1328
+ throw new KnowledgeImportNotGatheredError(`children of ${parentId}`);
1329
+ }
1330
+ if (this.#childIndex?.pages !== pages) {
1331
+ const byParent = /* @__PURE__ */ new Map();
1332
+ for (const page of pages.values()) {
1333
+ if (!page || !page.parentId || page.isScope || page.deletedAt) continue;
1334
+ const siblings = byParent.get(page.parentId);
1335
+ if (siblings) siblings.push(page);
1336
+ else byParent.set(page.parentId, [page]);
1337
+ }
1338
+ for (const siblings of byParent.values()) siblings.sort(byPosition);
1339
+ this.#childIndex = {
1340
+ pages,
1341
+ byParent
1342
+ };
1343
+ }
1344
+ return [...this.#childIndex.byParent.get(parentId) ?? []];
1345
+ }
1346
+ /** The next position under a parent, as `createPage` and `movePage` would place a page. */
1347
+ #nextPosition(parentId) {
1348
+ const { positions, complete } = this.#state.rows;
1349
+ if (this.#state.stalePositions.has(parentId)) {
1350
+ if (!complete.has(parentId)) throw new KnowledgeImportBatchUnsupportedError("a position under a parent its last child left");
1351
+ return knowledgePositionBetween(this.#children(parentId).at(-1)?.position);
1352
+ }
1353
+ if (!positions.has(parentId)) {
1354
+ this.missing.positions.add(parentId);
1355
+ throw new KnowledgeImportNotGatheredError(`last child position of ${parentId}`);
1356
+ }
1357
+ return knowledgePositionBetween(positions.get(parentId) ?? void 0);
1358
+ }
1359
+ /** A page left `parentId`: its next position is still the gathered one unless it was the last child. */
1360
+ #left(parentId, position) {
1361
+ if (!parentId) return;
1362
+ const last = this.#state.rows.positions.get(parentId);
1363
+ if (last === void 0 || last === position) this.#state.stalePositions.add(parentId);
1364
+ }
1365
+ /** Points the path map at where `pages` are now; `before` holds their old paths. */
1366
+ #repath(pages, before) {
1367
+ const { paths } = this.#state.rows;
1368
+ const ids = new Set(pages.map((page) => page.id));
1369
+ for (const [key, id] of paths) if (id && ids.has(id)) paths.set(key, null);
1370
+ for (const old of before) if (old) paths.set(pathKey(old.scopeId, old.path), null);
1371
+ for (const page of pages) {
1372
+ const keys = this.#rowKeys(page);
1373
+ if (keys) paths.set(pathKey(keys.scopeId, keys.path), page.id);
1374
+ }
1375
+ }
1376
+ /** {@link #keys} on the working copy's current row. */
1377
+ #rowKeys(page) {
1378
+ return this.#keys(this.#state.rows.pages.get(page.id) ?? page);
1379
+ }
1380
+ #node(key) {
1381
+ const { nodes } = this.#state.rows;
1382
+ if (!nodes.has(key)) {
1383
+ this.missing.nodes.add(key);
1384
+ throw new KnowledgeImportNotGatheredError(`node ${key}`);
1385
+ }
1386
+ return nodes.get(key);
1387
+ }
1388
+ #setNode(key, node) {
1389
+ const { nodes, nodesByPage } = this.#state.rows;
1390
+ const before = nodes.get(key);
1391
+ if (before && nodesByPage.get(before.pageId) === key) nodesByPage.set(before.pageId, null);
1392
+ nodes.set(key, node);
1393
+ if (node) nodesByPage.set(node.pageId, key);
1394
+ this.#state.touched.add(key);
1395
+ }
1396
+ #storage(now) {
1397
+ const rows = () => this.#state.rows;
1398
+ const impl = {
1399
+ transaction: async (fn) => {
1400
+ const saved = copyState(this.#state);
1401
+ try {
1402
+ return await fn(this.storage);
1403
+ } catch (error) {
1404
+ this.#state = saved;
1405
+ throw error;
1406
+ }
1407
+ },
1408
+ getPage: async ({ id }) => this.#page(id),
1409
+ getPageParents: async ({ parentId }) => {
1410
+ const parents = [];
1411
+ let id = parentId;
1412
+ while (id && parents.length <= 10) {
1413
+ const page = this.#page(id);
1414
+ if (!page) break;
1415
+ parents.push(page);
1416
+ id = page.parentId;
1417
+ }
1418
+ return parents;
1419
+ },
1420
+ getPageByPath: async ({ scopeId, path }) => {
1421
+ if (path.length === 0) return null;
1422
+ const key = pathKey(scopeId, path);
1423
+ if (!rows().paths.has(key)) {
1424
+ const id = this.#pathFromChains(key);
1425
+ if (id) return this.#page(id);
1426
+ this.missing.paths.set(key, {
1427
+ scopeId,
1428
+ path
1429
+ });
1430
+ throw new KnowledgeImportNotGatheredError(`path ${key}`);
1431
+ }
1432
+ const id = rows().paths.get(key);
1433
+ return id ? this.#page(id) : null;
1434
+ },
1435
+ lockPages: async (ids) => {
1436
+ const unlocked = ids.filter((id) => !rows().locked.has(id));
1437
+ if (unlocked.length) {
1438
+ for (const id of unlocked) this.missing.locks.add(id);
1439
+ throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
1440
+ }
1441
+ return [];
1442
+ },
1443
+ listNotes: async ({ pageId }) => {
1444
+ if (!rows().notes.has(pageId)) {
1445
+ this.missing.notes.add(pageId);
1446
+ throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
1447
+ }
1448
+ return { notes: rows().notes.get(pageId).filter((note) => !note.deletedAt) };
1449
+ },
1450
+ createPage: async (input) => {
1451
+ if (rows().readOnce) throw new KnowledgeImportRereadRequiredError("createPage");
1452
+ if (input.id !== void 0 || input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("createPage with id or position");
1453
+ if (!input.name.trim()) throw new Error("Knowledge page name must not be empty");
1454
+ assertKnowledgePageDescriptionWithinBound(input.description || void 0);
1455
+ const parent = this.#livePage(input.parentId);
1456
+ const scopeId = parent.isScope ? parent.id : parent.scopeId;
1457
+ const id = randomUUID();
1458
+ const depth = this.#depth(parent) + 1;
1459
+ if (depth > 10) throw new KnowledgePageDepthError(id);
1460
+ let path = null;
1461
+ if (input.key !== void 0) {
1462
+ const problem = knowledgePageKeyProblem(input.key);
1463
+ if (problem) throw new Error(problem);
1464
+ const parentKeys = parent.isScope ? {
1465
+ scopeId: parent.id,
1466
+ path: []
1467
+ } : this.#keys(parent);
1468
+ if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("createPage under a broken chain");
1469
+ path = [...parentKeys.path, input.key];
1470
+ if (await impl.getPageByPath({
1471
+ scopeId,
1472
+ path,
1473
+ read: "all"
1474
+ })) throw new KnowledgePageKeyConflictError(input.key, parent.id);
1475
+ }
1476
+ if (input.key !== void 0 && this.#state.freed.has(childKey(parent.id, input.key))) throw new KnowledgeImportBatchUnsupportedError("createPage at a key a move left");
1477
+ const position = this.#nextPosition(parent.id);
1478
+ const at = now();
1479
+ const page = {
1480
+ id,
1481
+ scopeId,
1482
+ parentId: parent.id,
1483
+ isScope: false,
1484
+ ...input.key !== void 0 ? { key: input.key } : {},
1485
+ position,
1486
+ name: input.name,
1487
+ ...input.description ? { description: input.description } : {},
1488
+ ...input.body !== void 0 ? { body: input.body } : {},
1489
+ version: 1,
1490
+ createdBy: structuredClone(input.provenance),
1491
+ updatedBy: structuredClone(input.provenance),
1492
+ createdAt: at,
1493
+ updatedAt: at
1494
+ };
1495
+ const state = rows();
1496
+ this.#setPage(id, page);
1497
+ state.positions.set(parent.id, position);
1498
+ state.positions.set(id, null);
1499
+ state.notes.set(id, []);
1500
+ state.nodesByPage.set(id, null);
1501
+ state.locked.add(id);
1502
+ state.complete.add(id);
1503
+ if (path) state.paths.set(pathKey(scopeId, path), id);
1504
+ this.#state.writes.push({
1505
+ op: "create",
1506
+ id,
1507
+ scopeId,
1508
+ parentId: parent.id,
1509
+ ...input.key !== void 0 ? { key: input.key } : {},
1510
+ name: input.name,
1511
+ ...input.description !== void 0 ? { description: input.description } : {},
1512
+ ...input.body !== void 0 ? { body: input.body } : {},
1513
+ position,
1514
+ depth,
1515
+ provenance: input.provenance
1516
+ });
1517
+ return structuredClone(page);
1518
+ },
1519
+ updatePage: async (input) => {
1520
+ const page = this.#livePage(input.id);
1521
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(page.id);
1522
+ if (input.name !== void 0 && !input.name.trim()) throw new Error("Knowledge page name must not be empty");
1523
+ assertKnowledgePageDescriptionWithinBound(input.description || void 0);
1524
+ const next = {
1525
+ ...page,
1526
+ version: page.version + 1,
1527
+ updatedBy: structuredClone(input.provenance)
1528
+ };
1529
+ next.updatedAt = now();
1530
+ if (input.name !== void 0) next.name = input.name;
1531
+ if (input.description !== void 0) {
1532
+ if (input.description) next.description = input.description;
1533
+ else delete next.description;
1534
+ }
1535
+ if (input.body !== void 0) next.body = input.body;
1536
+ this.#setPage(page.id, next);
1537
+ this.#state.writes.push({
1538
+ op: "update",
1539
+ id: page.id,
1540
+ scopeId: page.scopeId,
1541
+ expectedVersion: input.expectedVersion,
1542
+ ...input.name !== void 0 ? { name: input.name } : {},
1543
+ ...input.description !== void 0 ? { description: input.description } : {},
1544
+ ...input.body !== void 0 ? { body: input.body } : {},
1545
+ provenance: input.provenance
1546
+ });
1547
+ return structuredClone(next);
1548
+ },
1549
+ listChildPages: async ({ parentId, read, cursor, limit }) => {
1550
+ if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("listChildPages with a read scope");
1551
+ const children = this.#children(parentId);
1552
+ const start = cursor ? Number(cursor) : 0;
1553
+ const end = limit === void 0 ? children.length : start + limit;
1554
+ return {
1555
+ pages: children.slice(start, end).map((page) => structuredClone(page)),
1556
+ ...end < children.length ? { nextCursor: String(end) } : {}
1557
+ };
1558
+ },
1559
+ countChildPages: async ({ parentIds, read }) => {
1560
+ if (read !== "all") throw new KnowledgeImportBatchUnsupportedError("countChildPages with a read scope");
1561
+ return Object.fromEntries(parentIds.map((id) => [id, this.#children(id).length]));
1562
+ },
1563
+ lockSubtree: async (rootId) => {
1564
+ if (rows().tooLarge.has(rootId)) throw new KnowledgeMoveTooLargeError(rootId, 501);
1565
+ const ids = [];
1566
+ const parents = [rootId];
1567
+ while (parents.length) {
1568
+ for (const child of this.#children(parents.shift())) {
1569
+ ids.push(child.id);
1570
+ parents.push(child.id);
1571
+ }
1572
+ if (ids.length >= 500) throw new KnowledgeMoveTooLargeError(rootId, ids.length + 1);
1573
+ }
1574
+ const unlocked = ids.filter((id) => !rows().locked.has(id));
1575
+ if (unlocked.length) {
1576
+ for (const id of unlocked) this.missing.locks.add(id);
1577
+ throw new KnowledgeImportNotGatheredError(`locks ${unlocked.join(", ")}`);
1578
+ }
1579
+ return ids;
1580
+ },
1581
+ movePage: async (input) => {
1582
+ if (rows().readOnce) throw new KnowledgeImportRereadRequiredError("movePage");
1583
+ if (input.position !== void 0) throw new KnowledgeImportBatchUnsupportedError("movePage with a position");
1584
+ const page = this.#livePage(input.id);
1585
+ if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be moved`);
1586
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(page.id);
1587
+ const parent = this.#livePage(input.parentId);
1588
+ const subtree = [];
1589
+ const visit = (at, depth) => {
1590
+ subtree.push({
1591
+ page: at,
1592
+ depth
1593
+ });
1594
+ for (const child of this.#children(at.id)) visit(child, depth + 1);
1595
+ };
1596
+ visit(page, 0);
1597
+ 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`);
1598
+ if (subtree.length > 500) throw new KnowledgeMoveTooLargeError(page.id, subtree.length);
1599
+ const parentDepth = parent.isScope ? 0 : this.#depth(parent);
1600
+ if (parentDepth + 1 + Math.max(...subtree.map((entry) => entry.depth)) > 10) throw new KnowledgePageDepthError(page.id);
1601
+ const scopeId = parent.isScope ? parent.id : parent.scopeId;
1602
+ if (scopeId !== page.scopeId) throw new KnowledgeImportBatchUnsupportedError("movePage across scopes");
1603
+ const key = input.key ?? page.key;
1604
+ if (input.key !== void 0) {
1605
+ const problem = knowledgePageKeyProblem(input.key);
1606
+ if (problem) throw new Error(problem);
1607
+ }
1608
+ if (key !== void 0) {
1609
+ const parentKeys = parent.isScope ? {
1610
+ scopeId: parent.id,
1611
+ path: []
1612
+ } : this.#keys(parent);
1613
+ if (!parentKeys) throw new KnowledgeImportBatchUnsupportedError("movePage under a broken chain");
1614
+ const clash = await impl.getPageByPath({
1615
+ scopeId,
1616
+ path: [...parentKeys.path, key],
1617
+ read: "all"
1618
+ });
1619
+ if (clash && clash.id !== page.id) throw new KnowledgePageKeyConflictError(key, parent.id);
1620
+ }
1621
+ if (this.#state.moved.has(page.id)) throw new KnowledgeImportBatchUnsupportedError("a second move of a page");
1622
+ const position = this.#nextPosition(parent.id);
1623
+ const before = subtree.map((entry) => this.#keys(entry.page));
1624
+ const at = now();
1625
+ const moved = {
1626
+ ...page,
1627
+ ...key !== void 0 ? { key } : {},
1628
+ parentId: parent.id,
1629
+ position,
1630
+ version: page.version + 1,
1631
+ updatedBy: structuredClone(input.provenance),
1632
+ updatedAt: at
1633
+ };
1634
+ const state = rows();
1635
+ this.#setPage(page.id, moved);
1636
+ state.positions.set(parent.id, position);
1637
+ this.#left(page.parentId, page.position);
1638
+ if (page.parentId && page.key !== void 0) this.#state.freed.add(childKey(page.parentId, page.key));
1639
+ this.#state.moved.add(page.id);
1640
+ this.#repath(subtree.map((entry) => state.pages.get(entry.page.id)), before);
1641
+ this.#state.writes.push({
1642
+ op: "move",
1643
+ id: page.id,
1644
+ fromScopeId: page.scopeId,
1645
+ expectedVersion: input.expectedVersion,
1646
+ parentId: parent.id,
1647
+ ...input.key !== void 0 ? { key: input.key } : {},
1648
+ scopeId,
1649
+ depth: parentDepth + 1,
1650
+ position,
1651
+ provenance: input.provenance
1652
+ });
1653
+ return structuredClone(moved);
1654
+ },
1655
+ deletePage: async (input) => {
1656
+ if (rows().readOnce) throw new KnowledgeImportRereadRequiredError("deletePage");
1657
+ const page = this.#livePage(input.id);
1658
+ if (page.isScope) throw new Error(`Knowledge scope page ${page.id} can't be deleted`);
1659
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(page.id);
1660
+ if (this.#children(page.id).length) throw new KnowledgePageHasChildrenError(page.id);
1661
+ const at = now();
1662
+ const deleted = {
1663
+ ...page,
1664
+ deletedAt: at,
1665
+ deletedBy: input.deletedBy,
1666
+ version: page.version + 1,
1667
+ updatedAt: at
1668
+ };
1669
+ this.#setPage(page.id, deleted);
1670
+ this.#left(page.parentId, page.position);
1671
+ for (const [key, id] of rows().paths) if (id === page.id) rows().paths.set(key, null);
1672
+ this.#state.writes.push({
1673
+ op: "delete",
1674
+ id: page.id,
1675
+ scopeId: page.scopeId,
1676
+ expectedVersion: input.expectedVersion,
1677
+ deletedBy: input.deletedBy
1678
+ });
1679
+ return structuredClone(deleted);
1680
+ },
1681
+ addNote: async (input) => {
1682
+ const page = this.#livePage(input.pageId);
1683
+ assertKnowledgeNoteTextWithinBound(input.text);
1684
+ if (input.mentions.length) throw new KnowledgeImportBatchUnsupportedError("addNote with mentions");
1685
+ const notes = this.#notesOf(page.id);
1686
+ const id = input.id ?? randomUUID();
1687
+ if (notes.some((note) => note.id === id)) throw new KnowledgeConflictError(id);
1688
+ const at = now();
1689
+ const note = {
1690
+ id,
1691
+ pageId: page.id,
1692
+ text: input.text,
1693
+ ...input.when ? { when: new Date(input.when) } : {},
1694
+ stampScopeIds: [...new Set(input.stampScopeIds)],
1695
+ mentions: [],
1696
+ provenance: structuredClone(input.provenance),
1697
+ version: 1,
1698
+ createdAt: at,
1699
+ updatedAt: at
1700
+ };
1701
+ rows().notes.set(page.id, [...notes, note]);
1702
+ this.#state.writes.push({
1703
+ op: "add-note",
1704
+ id,
1705
+ pageId: page.id,
1706
+ scopeId: page.scopeId,
1707
+ text: input.text,
1708
+ ...input.when ? { when: input.when } : {},
1709
+ stampScopeIds: input.stampScopeIds,
1710
+ mentions: [],
1711
+ provenance: input.provenance
1712
+ });
1713
+ return structuredClone(note);
1714
+ },
1715
+ removeNote: async (input) => {
1716
+ for (const [pageId, notes] of rows().notes) {
1717
+ const note = notes.find((each) => each.id === input.id);
1718
+ if (!note) continue;
1719
+ if (note.deletedAt) throw new KnowledgeNotFoundError("note", input.id);
1720
+ if (this.#state.writes.some((write) => write.op === "add-note" && write.id === input.id)) throw new KnowledgeImportBatchUnsupportedError("removeNote of a note this flush added");
1721
+ const page = this.#livePage(pageId);
1722
+ const at = now();
1723
+ const removed = {
1724
+ ...note,
1725
+ deletedAt: at,
1726
+ deletedBy: input.deletedBy,
1727
+ version: note.version + 1,
1728
+ updatedAt: at
1729
+ };
1730
+ rows().notes.set(pageId, notes.map((each) => each.id === input.id ? removed : each));
1731
+ this.#state.writes.push({
1732
+ op: "remove-note",
1733
+ id: input.id,
1734
+ pageId,
1735
+ scopeId: page.scopeId,
1736
+ deletedBy: input.deletedBy,
1737
+ provenance: input.provenance
1738
+ });
1739
+ return structuredClone(removed);
1740
+ }
1741
+ throw new KnowledgeImportBatchUnsupportedError("removeNote of a note not gathered");
1742
+ }
1743
+ };
1744
+ return only(impl, "storage");
1745
+ }
1746
+ #notesOf(pageId) {
1747
+ const { notes } = this.#state.rows;
1748
+ if (!notes.has(pageId)) {
1749
+ this.missing.notes.add(pageId);
1750
+ throw new KnowledgeImportNotGatheredError(`notes of ${pageId}`);
1751
+ }
1752
+ return notes.get(pageId);
1753
+ }
1754
+ #importers() {
1755
+ const rows = () => this.#state.rows;
1756
+ return only({
1757
+ getNode: async (bindingId, sourceId) => structuredClone(this.#node(nodeKey(bindingId, sourceId))),
1758
+ getNodes: async (bindingId, sourceIds) => {
1759
+ const nodes = [];
1760
+ const unread = [...new Set(sourceIds)].filter((sourceId) => !rows().nodes.has(nodeKey(bindingId, sourceId)));
1761
+ if (unread.length) {
1762
+ for (const sourceId of unread) this.missing.nodes.add(nodeKey(bindingId, sourceId));
1763
+ throw new KnowledgeImportNotGatheredError(`nodes ${unread.join(", ")}`);
1764
+ }
1765
+ for (const sourceId of new Set(sourceIds)) {
1766
+ const node = rows().nodes.get(nodeKey(bindingId, sourceId));
1767
+ if (node) nodes.push(structuredClone(node));
1768
+ }
1769
+ return nodes;
1770
+ },
1771
+ getNodeByPage: async (pageId) => {
1772
+ if (!rows().nodesByPage.has(pageId)) {
1773
+ this.missing.nodesByPage.add(pageId);
1774
+ throw new KnowledgeImportNotGatheredError(`node of page ${pageId}`);
1775
+ }
1776
+ const key = rows().nodesByPage.get(pageId);
1777
+ return key ? structuredClone(this.#node(key)) : null;
1778
+ },
1779
+ getNodesByPages: async (pageIds) => {
1780
+ const unread = [...new Set(pageIds)].filter((pageId) => !rows().nodesByPage.has(pageId));
1781
+ if (unread.length) {
1782
+ for (const pageId of unread) this.missing.nodesByPage.add(pageId);
1783
+ throw new KnowledgeImportNotGatheredError(`nodes of pages ${unread.join(", ")}`);
1784
+ }
1785
+ return [...new Set(pageIds)].flatMap((pageId) => {
1786
+ const node = rows().nodesByPage.get(pageId) ? this.#node(rows().nodesByPage.get(pageId)) : null;
1787
+ return node ? [structuredClone(node)] : [];
1788
+ });
1789
+ },
1790
+ saveNode: async (node) => {
1791
+ const key = nodeKey(node.bindingId, node.sourceId);
1792
+ const mapped = rows().nodesByPage.get(node.pageId);
1793
+ if (mapped === void 0) {
1794
+ this.missing.nodesByPage.add(node.pageId);
1795
+ throw new KnowledgeImportNotGatheredError(`node of page ${node.pageId}`);
1796
+ }
1797
+ if (mapped && mapped !== key) throw new KnowledgeImportBatchUnsupportedError("saveNode onto a mapped page");
1798
+ this.#setNode(key, {
1799
+ ...structuredClone(node),
1800
+ updatedAt: /* @__PURE__ */ new Date()
1801
+ });
1802
+ },
1803
+ deleteNode: async (bindingId, sourceId) => {
1804
+ const key = nodeKey(bindingId, sourceId);
1805
+ this.#node(key);
1806
+ this.#setNode(key, null);
1807
+ },
1808
+ markLinkingNodesUnsettled: async (bindingId, targetSourceIds) => {
1809
+ const targets = new Set(targetSourceIds);
1810
+ for (const [key, node] of rows().nodes) if (node && node.bindingId === bindingId && node.links.some((link) => targets.has(link.sourceId))) rows().nodes.set(key, {
1811
+ ...node,
1812
+ unsettled: true
1813
+ });
1814
+ const marks = this.#state.marks;
1815
+ const last = marks.at(-1);
1816
+ const prior = last && markTargets.get(last);
1817
+ const all = prior?.bindingId === bindingId ? [.../* @__PURE__ */ new Set([...prior.targets, ...targetSourceIds])] : [...targetSourceIds];
1818
+ if (prior?.bindingId === bindingId) marks.pop();
1819
+ const mark = (_, importers) => importers.markLinkingNodesUnsettled(bindingId, all);
1820
+ markTargets.set(mark, {
1821
+ bindingId,
1822
+ targets: all
1823
+ });
1824
+ marks.push(mark);
1825
+ },
1826
+ setState: async (bindingId, state) => {
1827
+ this.#state.marks.push((_, importers) => importers.setState(bindingId, state));
1828
+ },
1829
+ listLinkingNodes: async (bindingId, targetSourceIds, options = {}) => {
1830
+ const keys = [...new Set(targetSourceIds)].map((sourceId) => nodeKey(bindingId, sourceId));
1831
+ if (keys.some((key) => rows().tooManyLinkers.has(key))) throw new KnowledgeImportBatchUnsupportedError("listLinkingNodes past the gathered linking nodes");
1832
+ const unread = keys.filter((key) => !rows().linkTargets.has(key));
1833
+ if (unread.length) {
1834
+ for (const key of unread) this.missing.linkTargets.add(key);
1835
+ throw new KnowledgeImportNotGatheredError(`linking nodes of ${unread.join(", ")}`);
1836
+ }
1837
+ const targets = new Set(targetSourceIds);
1838
+ 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);
1839
+ const limit = options.limit ?? 500;
1840
+ const items = ids.slice(0, limit);
1841
+ return {
1842
+ items,
1843
+ next: ids.length > limit ? items[items.length - 1] : null
1844
+ };
1845
+ },
1846
+ listBindings: async () => {
1847
+ const { bindings } = rows();
1848
+ if (!bindings) {
1849
+ this.missing.bindings.add("bindings");
1850
+ throw new KnowledgeImportNotGatheredError("bindings");
1851
+ }
1852
+ return structuredClone(bindings);
1853
+ }
1854
+ }, "importers");
1855
+ }
1856
+ };
1857
+ /** True when the stores implement every set-based method the batched flush needs. */
1858
+ function canBatchImportFlush(storage, importers) {
1859
+ return !!(storage.getPageChains && storage.getPagesByPaths && storage.getLastChildPositions && storage.listNotesByPages && storage.getPageSubtrees && storage.applyPageWrites && canRepairKnowledgeLinksInBatch(storage) && importers.getNodes && importers.getNodesByPages && importers.writeNodes);
1860
+ }
1861
+ async function readImportRows(input) {
1862
+ const { storage, importers, bindingId, missing } = input;
1863
+ const rows = emptyImportOverlayRows();
1864
+ const sourceIds = new Set(input.sourceIds);
1865
+ for (const key of missing?.nodes ?? []) {
1866
+ const [binding, sourceId] = key.split("\0");
1867
+ if (binding === bindingId) sourceIds.add(sourceId);
1868
+ }
1869
+ const nodes = sourceIds.size ? await importers.getNodes(bindingId, [...sourceIds]) : [];
1870
+ for (const sourceId of sourceIds) rows.nodes.set(nodeKey(bindingId, sourceId), null);
1871
+ for (const node of nodes) {
1872
+ rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
1873
+ rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
1874
+ }
1875
+ const addChains = async (ids) => {
1876
+ const wanted = [...ids].filter((id) => !rows.pages.has(id));
1877
+ if (!wanted.length) return;
1878
+ const chains = await storage.getPageChains({
1879
+ ids: wanted,
1880
+ read: "all"
1881
+ });
1882
+ for (const id of wanted) {
1883
+ const chain = chains[id] ?? [];
1884
+ if (!chain.length) rows.pages.set(id, null);
1885
+ for (const page of chain) rows.pages.set(page.id, page);
1886
+ const last = chain.at(-1);
1887
+ if (last?.parentId && chain.length <= 10 && !rows.pages.has(last.parentId)) rows.pages.set(last.parentId, null);
1888
+ }
1889
+ };
1890
+ await addChains(/* @__PURE__ */ new Set([
1891
+ ...input.pageIds,
1892
+ ...nodes.map((node) => node.pageId),
1893
+ ...missing?.pages ?? [],
1894
+ ...missing?.locks ?? []
1895
+ ]));
1896
+ let plan = input.plan(rows);
1897
+ const carried = [];
1898
+ let held = [];
1899
+ let settled = false;
1900
+ for (let stage = 0; stage < GATHER_PLAN_STAGES; stage++) {
1901
+ if (stage) plan = input.plan(rows);
1902
+ const before = rows.pages.size + rows.paths.size + rows.complete.size;
1903
+ const roots = [.../* @__PURE__ */ new Set([...plan.subtrees, ...stage ? [] : missing?.subtrees ?? []])].filter((id) => !rows.complete.has(id) && !rows.tooLarge.has(id));
1904
+ if (roots.length) {
1905
+ const subtrees = await storage.getPageSubtrees({
1906
+ rootIds: roots,
1907
+ limit: 499
1908
+ });
1909
+ for (const root of roots) {
1910
+ const pages = subtrees[root];
1911
+ if (!pages) {
1912
+ rows.tooLarge.add(root);
1913
+ continue;
1914
+ }
1915
+ rows.complete.add(root);
1916
+ for (const page of pages) {
1917
+ rows.pages.set(page.id, page);
1918
+ rows.complete.add(page.id);
1919
+ carried.push(page.id);
1920
+ }
1921
+ }
1922
+ const unmapped = carried.filter((id) => !rows.nodesByPage.has(id));
1923
+ if (unmapped.length) {
1924
+ for (const id of unmapped) rows.nodesByPage.set(id, null);
1925
+ for (const node of await importers.getNodesByPages(unmapped)) {
1926
+ const key = nodeKey(node.bindingId, node.sourceId);
1927
+ rows.nodes.set(key, node);
1928
+ rows.nodesByPage.set(node.pageId, key);
1929
+ }
1930
+ }
1931
+ }
1932
+ const paths = new Map(plan.paths.map((each) => [pathKey(each.scopeId, each.path), each]));
1933
+ if (!stage) for (const [key, each] of missing?.paths ?? []) paths.set(key, each);
1934
+ for (const key of [...paths.keys()]) if (rows.paths.has(key)) paths.delete(key);
1935
+ const byScope = /* @__PURE__ */ new Map();
1936
+ for (const [key, { scopeId, path }] of paths) {
1937
+ if (path.length === 0) continue;
1938
+ byScope.set(scopeId, [...byScope.get(scopeId) ?? [], {
1939
+ key,
1940
+ path
1941
+ }]);
1942
+ }
1943
+ for (const [scopeId, entries] of byScope) {
1944
+ const found = await storage.getPagesByPaths({
1945
+ scopeId,
1946
+ paths: entries.map((each) => each.path),
1947
+ read: "all"
1948
+ });
1949
+ entries.forEach((each, i) => {
1950
+ const page = found[i] ?? null;
1951
+ rows.paths.set(each.key, page?.id ?? null);
1952
+ if (page && !rows.pages.has(page.id)) rows.pages.set(page.id, page);
1953
+ });
1954
+ }
1955
+ held = [...rows.paths.values()].filter((id) => !!id);
1956
+ await addChains(new Set(held.map((id) => rows.pages.get(id)?.parentId).filter((id) => !!id)));
1957
+ const byPage = [...new Set([
1958
+ ...held,
1959
+ ...plan.holders ?? [],
1960
+ ...stage ? [] : missing?.nodesByPage ?? []
1961
+ ].filter((id) => !rows.nodesByPage.has(id)))];
1962
+ if (byPage.length) {
1963
+ for (const id of byPage) rows.nodesByPage.set(id, null);
1964
+ for (const node of await importers.getNodesByPages(byPage)) {
1965
+ const key = nodeKey(node.bindingId, node.sourceId);
1966
+ rows.nodes.set(key, node);
1967
+ rows.nodesByPage.set(node.pageId, key);
1968
+ }
1969
+ }
1970
+ if (rows.pages.size + rows.paths.size + rows.complete.size === before) {
1971
+ settled = true;
1972
+ break;
1973
+ }
1974
+ }
1975
+ const targets = new Set(plan.linkTargets);
1976
+ for (const id of carried) {
1977
+ const key = rows.nodesByPage.get(id);
1978
+ const node = key ? rows.nodes.get(key) : null;
1979
+ if (node?.bindingId === bindingId) targets.add(node.sourceId);
1980
+ }
1981
+ for (const key of missing?.linkTargets ?? []) {
1982
+ const [binding, sourceId] = key.split("\0");
1983
+ if (binding === bindingId) targets.add(sourceId);
1984
+ }
1985
+ const wanted = [...targets].filter((sourceId) => !rows.linkTargets.has(nodeKey(bindingId, sourceId)));
1986
+ if (wanted.length) {
1987
+ const linking = await importers.listLinkingNodes(bindingId, wanted, { limit: LINKING_NODES_READ });
1988
+ for (const sourceId of wanted) (linking.next ? rows.tooManyLinkers : rows.linkTargets).add(nodeKey(bindingId, sourceId));
1989
+ const readNodes = async (sourceIds) => {
1990
+ const unread = [...new Set(sourceIds)].filter((sourceId) => !rows.nodes.has(nodeKey(bindingId, sourceId)));
1991
+ if (!unread.length) return [];
1992
+ for (const sourceId of unread) rows.nodes.set(nodeKey(bindingId, sourceId), null);
1993
+ const read = await importers.getNodes(bindingId, unread);
1994
+ for (const node of read) {
1995
+ rows.nodes.set(nodeKey(node.bindingId, node.sourceId), node);
1996
+ rows.nodesByPage.set(node.pageId, nodeKey(node.bindingId, node.sourceId));
1997
+ }
1998
+ return read;
1999
+ };
2000
+ const linkers = await readNodes(linking.items);
2001
+ 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] : []]));
2002
+ await addChains(new Set([...linkers, ...reached].map((node) => node.pageId)));
2003
+ }
2004
+ if (plan.bindings || missing?.bindings.size) rows.bindings ??= await importers.listBindings();
2005
+ const notes = [.../* @__PURE__ */ new Set([
2006
+ ...plan.notes,
2007
+ ...held,
2008
+ ...missing?.notes ?? []
2009
+ ])];
2010
+ if (notes.length) {
2011
+ const listed = await storage.listNotesByPages({
2012
+ pageIds: notes,
2013
+ read: "all"
2014
+ });
2015
+ for (const id of notes) rows.notes.set(id, listed[id] ?? []);
2016
+ }
2017
+ const positions = [.../* @__PURE__ */ new Set([...plan.positions, ...missing?.positions ?? []])];
2018
+ if (positions.length) {
2019
+ const last = await storage.getLastChildPositions({ parentIds: positions });
2020
+ for (const id of positions) rows.positions.set(id, last[id] ?? null);
2021
+ }
2022
+ rows.inPlace = settled && !!plan.inPlace;
2023
+ return rows;
2024
+ }
2025
+ /** Times one gather plans again from what it read (path folders, then the page at the path, then its children). */
2026
+ const GATHER_PLAN_STAGES = 4;
2027
+ /** Most linking nodes one gather reads; past it, a flush that lists them is saved op by op. */
2028
+ const LINKING_NODES_READ = 500;
2029
+ /** Live, non-scope pages among the rows: the ones a decide pass may lock. */
2030
+ const lockable = (rows) => [...rows.pages.values()].filter((page) => !!page && !page.isScope && !page.deletedAt && !page.mergedInto).map((page) => page.id);
2031
+ /**
2032
+ * Reads every row a decide pass needs in a few set-based queries, locks the live pages among them
2033
+ * in one sorted call, and reads again under the lock: what the second read returns can't change
2034
+ * until commit (a new page at an empty path is refused by the unique key when written). Pages the
2035
+ * second read finds that the first didn't are locked too, and read again, up to `rounds` times.
2036
+ */
2037
+ async function gatherImportRows(input) {
2038
+ const locked = new Set(input.locked ?? []);
2039
+ let rows = await readImportRows(input);
2040
+ if (input.storage.getCapabilities().serializedWriteTransactions && rows.notes.size === 0) {
2041
+ for (const id of lockable(rows)) locked.add(id);
2042
+ rows.locked = locked;
2043
+ return rows;
2044
+ }
2045
+ for (let round = 0; round < (input.rounds ?? 3); round++) {
2046
+ const unlocked = lockable(rows).filter((id) => !locked.has(id));
2047
+ if (!unlocked.length) {
2048
+ rows.locked = locked;
2049
+ return rows;
2050
+ }
2051
+ const versions = await input.storage.lockPages(unlocked.sort());
2052
+ for (const id of unlocked) locked.add(id);
2053
+ if (round === 0 && !input.reread && rows.inPlace && rows.notes.size === 0 && Array.isArray(versions) && versions.length === unlocked.length) {
2054
+ const read = new Map(versions.map((row) => [row.id, row.version]));
2055
+ if (unlocked.every((id) => read.get(id) === rows.pages.get(id)?.version)) {
2056
+ rows.locked = locked;
2057
+ rows.readOnce = true;
2058
+ return rows;
2059
+ }
2060
+ }
2061
+ rows = await readImportRows(input);
2062
+ }
2063
+ return null;
2064
+ }
1035
2065
  // src/knowledge/importers/sink.ts
1036
2066
  /**
1037
2067
  * Applies one flush's ops to pages and the node map, on a transaction view. Pages are found by id
@@ -1088,6 +2118,17 @@ const ownText = (body, section) => {
1088
2118
  if (body === section) return "";
1089
2119
  return body.endsWith(`\n\n${section}`) ? body.slice(0, body.length - section.length - 2) : null;
1090
2120
  };
2121
+ /** Decide passes a batched flush makes before it falls back: each reads what the last one lacked. */
2122
+ const BATCH_DECIDE_PASSES = 4;
2123
+ /** The batched flush can't land this one: its savepoint rolls back and the ops go one by one. */
2124
+ var BatchFallback = class extends Error {
2125
+ reason;
2126
+ constructor(reason) {
2127
+ super(`Batched import flush fell back: ${reason}`);
2128
+ this.reason = reason;
2129
+ this.name = "BatchFallback";
2130
+ }
2131
+ };
1091
2132
  /** A per-item refusal: its savepoint rolls back and the flush goes on. */
1092
2133
  var KnowledgeImportRefusalError = class extends Error {
1093
2134
  reason;
@@ -1117,6 +2158,47 @@ function knowledgeImportKey(sourceId) {
1117
2158
  return sourceId.replace(/[/#%:~]/g, (char) => `~${char.charCodeAt(0).toString(16).toUpperCase()}`);
1118
2159
  }
1119
2160
  const live = (page) => !!page && !page.deletedAt && !page.mergedInto;
2161
+ /** Source IDs the host keeps for the folders it makes on an item's path; importers can't send them. */
2162
+ const KNOWLEDGE_IMPORT_PATH_STUB_PREFIX = "~path:";
2163
+ /**
2164
+ * An item's description cut to the page bound, ending in `…`. Every store refuses a longer one, and
2165
+ * that error would roll back the whole flush, leaving the cursor on this item for every later run.
2166
+ * Cuts between code points, at the last word break when one is in the back half.
2167
+ */
2168
+ function fitKnowledgeImportDescription(description) {
2169
+ if (estimateTokenCount(description) <= 100) return description;
2170
+ const chars = [...description];
2171
+ const cut = (length) => {
2172
+ let text = chars.slice(0, length).join("");
2173
+ const lastBreak = text.search(/\s\S*$/);
2174
+ if (lastBreak > text.length / 2) text = text.slice(0, lastBreak);
2175
+ return `${text.trimEnd()}\u2026`;
2176
+ };
2177
+ let low = 0;
2178
+ let high = chars.length - 1;
2179
+ while (low < high) {
2180
+ const mid = Math.ceil((low + high) / 2);
2181
+ if (estimateTokenCount(cut(mid)) <= 100) low = mid;
2182
+ else high = mid - 1;
2183
+ }
2184
+ return cut(low);
2185
+ }
2186
+ /**
2187
+ * Why an item can never land, whatever the store holds: a reserved `sourceId`, or a `path` the host
2188
+ * can't place (with `parent` or `fallbackParent`, empty, an empty or blank segment, a page key too long to
2189
+ * link to, or deeper than a page can sit under a target `targetDepth` keys deep). Null when it can.
2190
+ */
2191
+ function knowledgeImportItemProblem(item, targetDepth) {
2192
+ if (item.sourceId.startsWith("~path:")) return `sourceId must not start with "${KNOWLEDGE_IMPORT_PATH_STUB_PREFIX}"`;
2193
+ const { path } = item;
2194
+ if (path === void 0) return null;
2195
+ if (item.parent != null || item.fallbackParent !== void 0) return "path is not allowed with parent or fallbackParent";
2196
+ if (path.length === 0) return "path must have at least one segment";
2197
+ if (path.some((segment) => !segment.trim())) return "path segments must not be empty or blank";
2198
+ if (path.some((segment) => knowledgeImportKey(segment).length > 512)) return `path segment keys must be at most 512 characters`;
2199
+ if (targetDepth + path.length > 10) return `path would sit more than 10 levels below the scope`;
2200
+ return null;
2201
+ }
1120
2202
  /** Core errors that mean "this op can't land here", by name: an adapter may carry its own core copy. */
1121
2203
  function refusalFor(error) {
1122
2204
  if (error instanceof KnowledgeImportRefusalError) return error.reason;
@@ -1152,11 +2234,17 @@ function order(ops) {
1152
2234
  const id = op.op === "remove" ? op.sourceId : op.item.sourceId;
1153
2235
  const before = last.get(id);
1154
2236
  if (op.op === "declare" && before?.op === "upsert") {
2237
+ const { parent, fallbackParent, path, ...rest } = before.item;
2238
+ const kept = op.item.path !== void 0 ? rest : op.item.parent !== void 0 || op.item.fallbackParent !== void 0 ? {
2239
+ ...rest,
2240
+ ...parent !== void 0 ? { parent } : {},
2241
+ ...fallbackParent !== void 0 ? { fallbackParent } : {}
2242
+ } : before.item;
1155
2243
  last.delete(id);
1156
2244
  last.set(id, {
1157
2245
  op: "upsert",
1158
2246
  item: {
1159
- ...before.item,
2247
+ ...kept,
1160
2248
  ...op.item
1161
2249
  }
1162
2250
  });
@@ -1183,7 +2271,27 @@ function order(ops) {
1183
2271
  return [...sorted, ...removes];
1184
2272
  }
1185
2273
  async function applyKnowledgeImportFlush(input) {
1186
- const { storage, importers, binding, scope, provenance } = input;
2274
+ const { binding, scope, provenance } = input;
2275
+ let { storage, importers } = input;
2276
+ let overlay = null;
2277
+ /**
2278
+ * Link-index work for a written page: a sync of its body links, then maybe a refresh of the links to
2279
+ * it. Run now, or after the batched write in one repair when deciding over the working copy.
2280
+ */
2281
+ const links = async (sync, refresh) => {
2282
+ if (overlay) {
2283
+ if (sync) overlay.deferLinks({ sync });
2284
+ for (const page of refresh?.pages ?? []) overlay.deferLinks({
2285
+ refresh: page,
2286
+ withDescendants: !!refresh.withDescendants
2287
+ });
2288
+ return;
2289
+ }
2290
+ await syncLinks(async () => {
2291
+ if (sync) await syncKnowledgePageBodyLinks(storage, sync);
2292
+ if (refresh) await refreshKnowledgeLinksTo(storage, refresh.pages, { withDescendants: refresh.withDescendants });
2293
+ });
2294
+ };
1187
2295
  const target = parseKnowledgeImportTarget(binding.target);
1188
2296
  const result = {
1189
2297
  counts: {
@@ -1200,7 +2308,19 @@ async function applyKnowledgeImportFlush(input) {
1200
2308
  embeds: [],
1201
2309
  applied: false
1202
2310
  };
1203
- const ops = order(input.ops);
2311
+ const rekey = !!storage.getCapabilities().supportsPageRekey;
2312
+ let ops = order(input.ops).filter((op) => {
2313
+ const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
2314
+ const problem = op.op === "remove" ? sourceId.startsWith(KNOWLEDGE_IMPORT_PATH_STUB_PREFIX) : !!knowledgeImportItemProblem(op.item, 1);
2315
+ const unplaceable = op.op !== "remove" && op.item.path !== void 0 && !rekey;
2316
+ if (!problem && !unplaceable) return true;
2317
+ if (!problem) result.pathsUnsupported = true;
2318
+ result.refused.push({
2319
+ sourceId,
2320
+ reason: "invalid"
2321
+ });
2322
+ return false;
2323
+ });
1204
2324
  if (ops.length === 0 && !(input.settle && binding.anchorPageId)) {
1205
2325
  if (input.settle) result.settle = {
1206
2326
  pending: false,
@@ -1213,9 +2333,11 @@ async function applyKnowledgeImportFlush(input) {
1213
2333
  const keyPath = async (page) => {
1214
2334
  const keys = [];
1215
2335
  const ids = [];
2336
+ const versions = [];
1216
2337
  if (page.isScope) return page.id === scope.id ? {
1217
2338
  keys,
1218
- ids
2339
+ ids,
2340
+ versions
1219
2341
  } : null;
1220
2342
  const parents = page.parentId ? await storage.getPageParents({
1221
2343
  parentId: page.parentId,
@@ -1224,11 +2346,13 @@ async function applyKnowledgeImportFlush(input) {
1224
2346
  for (const at of [page, ...parents]) {
1225
2347
  if (at.isScope) return at.id === scope.id ? {
1226
2348
  keys,
1227
- ids
2349
+ ids,
2350
+ versions
1228
2351
  } : null;
1229
2352
  if (!live(at) || at.key === void 0) return null;
1230
2353
  keys.unshift(at.key);
1231
2354
  ids.unshift(at.id);
2355
+ versions.unshift(at.version);
1232
2356
  }
1233
2357
  return null;
1234
2358
  };
@@ -1261,8 +2385,17 @@ async function applyKnowledgeImportFlush(input) {
1261
2385
  read: "all"
1262
2386
  });
1263
2387
  const path = live(page) ? await keyPath(page) : null;
2388
+ if (page && path && storage.getCapabilities().serializedWriteTransactions) return {
2389
+ page,
2390
+ keys: path.keys
2391
+ };
1264
2392
  if (page && path) {
1265
- await storage.lockPages(path.ids);
2393
+ const read = new Map(path.ids.map((id, i) => [id, path.versions[i]]));
2394
+ const locked = await storage.lockPages(path.ids);
2395
+ if (Array.isArray(locked) && locked.length === read.size && locked.every((row) => read.get(row.id) === row.version)) return {
2396
+ page,
2397
+ keys: path.keys
2398
+ };
1266
2399
  const fresh = await storage.getPage({
1267
2400
  id: page.id,
1268
2401
  read: "all"
@@ -1343,6 +2476,15 @@ async function applyKnowledgeImportFlush(input) {
1343
2476
  return result;
1344
2477
  }
1345
2478
  const anchorPath = anchor?.keys ?? [];
2479
+ ops = ops.filter((op) => {
2480
+ if (op.op === "remove" || !op.item.path) return true;
2481
+ if (anchorPath.length + op.item.path.length <= 10) return true;
2482
+ result.refused.push({
2483
+ sourceId: op.item.sourceId,
2484
+ reason: "invalid"
2485
+ });
2486
+ return false;
2487
+ });
1346
2488
  /**
1347
2489
  * A page this binding owns, checked after locking: live, in the target's scope, mapped back to the
1348
2490
  * node. A person may have moved it out of the anchor, under anyone's pages: it is still the
@@ -1435,13 +2577,97 @@ async function applyKnowledgeImportFlush(input) {
1435
2577
  });
1436
2578
  await importers.markLinkingNodesUnsettled(binding.id, [node.sourceId]);
1437
2579
  await importers.deleteNode(binding.id, node.sourceId);
1438
- if (old) await syncLinks(() => refreshKnowledgeLinksTo(storage, [old]));
2580
+ if (old) await links(null, { pages: [old] });
1439
2581
  };
1440
2582
  const liveNodeOf = async (sourceId) => {
1441
2583
  const node = await nodeOf(sourceId);
1442
2584
  return node && await stateOf(node) === "live" ? node : null;
1443
2585
  };
1444
2586
  const ref = (keys) => `${target.scope}#${keys.join("/")}`;
2587
+ /** The folders an op's path made, counted as created once the op lands. */
2588
+ let madeFolders = [];
2589
+ /**
2590
+ * The page a path item goes under: the anchor, then each segment but the last. A live page at a
2591
+ * segment is used as it is, whoever wrote it; a missing one (a merged page reads as missing, as a
2592
+ * merged parent does for a new child) becomes an empty folder this binding owns, keyed
2593
+ * `~path:<keys>`, that the item sending that path takes over. Returns the node the item is under,
2594
+ * when it is this binding's.
2595
+ */
2596
+ const pathFolders = async (path) => {
2597
+ let at = anchor;
2598
+ let parentSourceId = null;
2599
+ let holderOf = null;
2600
+ const readHolder = async () => {
2601
+ if (!holderOf) return;
2602
+ const holder = await importers.getNodeByPage(holderOf.id);
2603
+ parentSourceId = holder?.bindingId === binding.id ? holder.sourceId : null;
2604
+ holderOf = null;
2605
+ };
2606
+ const relative = [];
2607
+ for (const segment of path.slice(0, -1)) {
2608
+ const key = knowledgeImportKey(segment);
2609
+ relative.push(key);
2610
+ const keys = [...at.keys, key];
2611
+ const found = await storage.getPageByPath({
2612
+ scopeId: scope.id,
2613
+ path: keys,
2614
+ read: "all"
2615
+ });
2616
+ if (found) {
2617
+ await storage.lockPages([found.id]);
2618
+ const fresh = await storage.getPage({
2619
+ id: found.id,
2620
+ read: "all"
2621
+ });
2622
+ if (!live(fresh) || fresh.parentId !== at.page.id || fresh.key !== key) throw new KnowledgeImportRefusalError("conflict");
2623
+ holderOf = fresh;
2624
+ at = {
2625
+ page: fresh,
2626
+ keys
2627
+ };
2628
+ continue;
2629
+ }
2630
+ await readHolder();
2631
+ const sourceId = KNOWLEDGE_IMPORT_PATH_STUB_PREFIX + relative.join("/");
2632
+ const page = await storage.createPage({
2633
+ parentId: at.page.id,
2634
+ key,
2635
+ name: segment,
2636
+ body: "",
2637
+ provenance
2638
+ });
2639
+ await importers.saveNode({
2640
+ bindingId: binding.id,
2641
+ sourceId,
2642
+ pageId: page.id,
2643
+ kind: null,
2644
+ parentSourceId,
2645
+ aliases: [],
2646
+ unresolvedLinks: [],
2647
+ links: [],
2648
+ linkSection: null,
2649
+ stub: false,
2650
+ adopted: false,
2651
+ unsettled: false
2652
+ });
2653
+ await links(page, { pages: [page] });
2654
+ madeFolders.push({
2655
+ sourceId,
2656
+ page,
2657
+ keys
2658
+ });
2659
+ parentSourceId = sourceId;
2660
+ at = {
2661
+ page,
2662
+ keys
2663
+ };
2664
+ }
2665
+ await readHolder();
2666
+ return {
2667
+ destination: at,
2668
+ parentSourceId
2669
+ };
2670
+ };
1445
2671
  const linkLine = async (link, node) => {
1446
2672
  const page = node ? await storage.getPage({
1447
2673
  id: node.pageId,
@@ -1522,7 +2748,7 @@ async function applyKnowledgeImportFlush(input) {
1522
2748
  body,
1523
2749
  provenance
1524
2750
  });
1525
- await syncLinks(() => syncKnowledgePageBodyLinks(storage, page));
2751
+ await links(page);
1526
2752
  return {
1527
2753
  page,
1528
2754
  changed: true,
@@ -1547,7 +2773,7 @@ async function applyKnowledgeImportFlush(input) {
1547
2773
  * and the pages it rewrote; the caller counts them once its op lands.
1548
2774
  */
1549
2775
  let deferredLinkers = false;
1550
- const moveOwned = async (self, page, parent) => {
2776
+ const moveOwned = async (self, page, parent, key) => {
1551
2777
  const targets = [];
1552
2778
  const othersTargets = /* @__PURE__ */ new Map();
1553
2779
  await storage.lockSubtree(page.id);
@@ -1561,6 +2787,7 @@ async function applyKnowledgeImportFlush(input) {
1561
2787
  id: page.id,
1562
2788
  expectedVersion: page.version,
1563
2789
  parentId: parent.page.id,
2790
+ ...key !== void 0 && key !== page.key ? { key } : {},
1564
2791
  provenance
1565
2792
  });
1566
2793
  const keys = [...parent.keys, moved.key];
@@ -1616,6 +2843,97 @@ async function applyKnowledgeImportFlush(input) {
1616
2843
  });
1617
2844
  }
1618
2845
  };
2846
+ /**
2847
+ * Frees `key` under `destination` for a path item's own page to move onto. A folder of this binding's
2848
+ * that holds the path is absorbed: its children move under the item's page in order, their nodes
2849
+ * point at the item, a body a person wrote in it is kept in a note on the item's page, and the empty
2850
+ * folder goes. A folder someone left notes on, or whose body would replace a body the item's page
2851
+ * already keeps, is not absorbed: the item is refused `occupied`, as for any other page at the path.
2852
+ * An item inside the folder, sent at the folder's path, leaves it first under a key no item uses, so
2853
+ * it never moves under itself; the move after this one gives it the folder's key. Returns whether it
2854
+ * kept a body (the item then holds a person's text, so its removal gives that back) and the item's
2855
+ * page as it is now.
2856
+ */
2857
+ const absorbAt = async (self, destination, key, page) => {
2858
+ const held = await storage.getPageByPath({
2859
+ scopeId: scope.id,
2860
+ path: [...destination.keys, key],
2861
+ read: "all"
2862
+ });
2863
+ if (!held || held.id === page.id) return {
2864
+ kept: false,
2865
+ page
2866
+ };
2867
+ await storage.lockPages([held.id]);
2868
+ const stub = await storage.getPage({
2869
+ id: held.id,
2870
+ read: "all"
2871
+ });
2872
+ if (!live(stub) || stub.parentId !== destination.page.id || stub.key !== key) throw new KnowledgeImportRefusalError("occupied");
2873
+ const holder = await importers.getNodeByPage(stub.id);
2874
+ if (holder?.bindingId !== binding.id || !holder.sourceId.startsWith("~path:")) throw new KnowledgeImportRefusalError("occupied");
2875
+ if ((await storage.listNotes({
2876
+ pageId: stub.id,
2877
+ read: "all",
2878
+ limit: 1
2879
+ })).notes.length > 0) throw new KnowledgeImportRefusalError("occupied");
2880
+ if (stub.body && (await keptBodyNotes(page.id)).length > 0) throw new KnowledgeImportRefusalError("occupied");
2881
+ const children = [];
2882
+ let cursor;
2883
+ do {
2884
+ const out = await storage.listChildPages({
2885
+ parentId: stub.id,
2886
+ read: "all",
2887
+ ...cursor ? { cursor } : {}
2888
+ });
2889
+ children.push(...out.pages);
2890
+ cursor = out.nextCursor;
2891
+ } while (cursor);
2892
+ let inside = page.parentId;
2893
+ while (inside && inside !== stub.id) inside = (await storage.getPage({
2894
+ id: inside,
2895
+ read: "all"
2896
+ }))?.parentId ?? null;
2897
+ if (inside) {
2898
+ await storage.lockSubtree(page.id);
2899
+ page = await storage.movePage({
2900
+ id: page.id,
2901
+ expectedVersion: page.version,
2902
+ parentId: destination.page.id,
2903
+ key: `~absorbing-${randomUUID()}`,
2904
+ provenance
2905
+ });
2906
+ }
2907
+ for (const child of children.filter((child) => child.id !== page.id)) {
2908
+ await storage.lockSubtree(child.id);
2909
+ await storage.movePage({
2910
+ id: child.id,
2911
+ expectedVersion: child.version,
2912
+ parentId: page.id,
2913
+ provenance
2914
+ });
2915
+ const node = await importers.getNodeByPage(child.id);
2916
+ if (node?.bindingId === binding.id && node.parentSourceId === holder.sourceId) await importers.saveNode({
2917
+ ...node,
2918
+ parentSourceId: self
2919
+ });
2920
+ }
2921
+ if (stub.body) await keepBody(page.id, stub.body);
2922
+ const emptied = await storage.getPage({
2923
+ id: stub.id,
2924
+ read: "all"
2925
+ });
2926
+ await storage.deletePage({
2927
+ id: stub.id,
2928
+ expectedVersion: emptied.version,
2929
+ deletedBy: provenance.author
2930
+ });
2931
+ await importers.deleteNode(binding.id, holder.sourceId);
2932
+ return {
2933
+ kept: !!stub.body,
2934
+ page
2935
+ };
2936
+ };
1619
2937
  const write = async (item, hasBody) => {
1620
2938
  let existing = await importers.getNode(binding.id, item.sourceId);
1621
2939
  const state = existing ? await stateOf(existing) : null;
@@ -1630,15 +2948,26 @@ async function applyKnowledgeImportFlush(input) {
1630
2948
  const parentMerged = parentState === "merged";
1631
2949
  const misplaced = !!item.parent && !sourceParent && !parentMerged;
1632
2950
  const parentNode = sourceParent ?? await liveNodeOf(item.fallbackParent);
1633
- const destination = parentNode ? await owned(parentNode.pageId, parentNode.sourceId) : anchor;
2951
+ let destination = parentNode ? await owned(parentNode.pageId, parentNode.sourceId) : anchor;
2952
+ let key = knowledgeImportKey(item.sourceId);
2953
+ let parentSourceId = item.parent ?? null;
2954
+ if (item.path) {
2955
+ const current = existing ? await owned(existing.pageId, item.sourceId) : null;
2956
+ if (current?.outside) {
2957
+ key = current.page.key;
2958
+ parentSourceId = existing.parentSourceId;
2959
+ } else {
2960
+ ({destination, parentSourceId} = await pathFolders(item.path));
2961
+ key = knowledgeImportKey(item.path.at(-1));
2962
+ }
2963
+ }
1634
2964
  if (existing && destination.page.id === existing.pageId) throw new KnowledgeImportRefusalError("invalid");
1635
2965
  let rendered = hasBody ? await renderBody(item) : void 0;
1636
2966
  let fields = {
1637
2967
  name: item.title,
1638
- ...item.description !== void 0 ? { description: item.description } : {},
2968
+ ...item.description !== void 0 ? { description: fitKnowledgeImportDescription(item.description) } : {},
1639
2969
  ...rendered ? { body: rendered.body } : {}
1640
2970
  };
1641
- const key = knowledgeImportKey(item.sourceId);
1642
2971
  let page;
1643
2972
  let change;
1644
2973
  let moved = false;
@@ -1658,9 +2987,34 @@ async function applyKnowledgeImportFlush(input) {
1658
2987
  read: "all"
1659
2988
  });
1660
2989
  if (!live(fresh) || fresh.parentId !== destination.page.id || fresh.key !== key) throw new KnowledgeImportRefusalError("occupied");
1661
- const imported = await release(fresh.id);
2990
+ const holder = await importers.getNodeByPage(fresh.id);
1662
2991
  renamed = fields.name !== fresh.name;
1663
- if (!imported) await keepBody(fresh.id, fresh.body ?? "");
2992
+ if (holder?.bindingId === binding.id) {
2993
+ if (!holder.sourceId.startsWith("~path:")) throw new KnowledgeImportRefusalError("occupied");
2994
+ const childIds = [];
2995
+ let cursor;
2996
+ do {
2997
+ const out = await storage.listChildPages({
2998
+ parentId: fresh.id,
2999
+ read: "all",
3000
+ ...cursor ? { cursor } : {}
3001
+ });
3002
+ childIds.push(...out.pages.map((child) => child.id));
3003
+ cursor = out.nextCursor;
3004
+ } while (cursor);
3005
+ const childNodes = importers.getNodesByPages ? await importers.getNodesByPages(childIds) : (await Promise.all(childIds.map((id) => importers.getNodeByPage(id)))).filter((n) => !!n);
3006
+ await importers.deleteNode(binding.id, holder.sourceId);
3007
+ for (const child of childNodes) if (child.bindingId === binding.id && child.parentSourceId === holder.sourceId) await importers.saveNode({
3008
+ ...child,
3009
+ parentSourceId: item.sourceId
3010
+ });
3011
+ if (fresh.body) await keepBody(fresh.id, fresh.body);
3012
+ adopted = !!fresh.body;
3013
+ } else {
3014
+ await release(fresh.id);
3015
+ if (!holder) await keepBody(fresh.id, fresh.body ?? "");
3016
+ adopted = true;
3017
+ }
1664
3018
  page = await storage.updatePage({
1665
3019
  id: fresh.id,
1666
3020
  expectedVersion: fresh.version,
@@ -1668,7 +3022,6 @@ async function applyKnowledgeImportFlush(input) {
1668
3022
  provenance
1669
3023
  });
1670
3024
  change = "updated";
1671
- adopted = true;
1672
3025
  } else if (!existing) {
1673
3026
  page = await storage.createPage({
1674
3027
  parentId: destination.page.id,
@@ -1682,9 +3035,15 @@ async function applyKnowledgeImportFlush(input) {
1682
3035
  const current = await owned(existing.pageId, item.sourceId);
1683
3036
  page = current.page;
1684
3037
  if (existing.stub && existing.adopted && !REMOVED_BODIES.has(page.body ?? "")) await keepBody(page.id, page.body ?? "");
1685
- if (!current.outside && !parentMerged && page.parentId !== destination.page.id) {
3038
+ const rekey = !!item.path && !current.outside && page.key !== key;
3039
+ if (!current.outside && !parentMerged && (page.parentId !== destination.page.id || rekey)) {
1686
3040
  if (destination.keys.length > current.keys.length && sameKeys(destination.keys.slice(0, current.keys.length), current.keys)) throw new KnowledgeImportRefusalError("invalid");
1687
- ({page, relinked} = await moveOwned(item.sourceId, page, destination));
3041
+ if (item.path) {
3042
+ const absorbed = await absorbAt(item.sourceId, destination, key, page);
3043
+ page = absorbed.page;
3044
+ if (absorbed.kept) adopted = true;
3045
+ }
3046
+ ({page, relinked} = await moveOwned(item.sourceId, page, destination, item.path ? key : void 0));
1688
3047
  moved = true;
1689
3048
  if (hasBody) {
1690
3049
  rendered = await renderBody(item);
@@ -1721,7 +3080,7 @@ async function applyKnowledgeImportFlush(input) {
1721
3080
  sourceId: item.sourceId,
1722
3081
  pageId: page.id,
1723
3082
  kind: item.kind ?? existing?.kind ?? null,
1724
- parentSourceId: item.parent ?? null,
3083
+ parentSourceId,
1725
3084
  aliases: item.aliases ?? existing?.aliases ?? [],
1726
3085
  unresolvedLinks: rendered ? rendered.unresolved : existing?.unresolvedLinks ?? [],
1727
3086
  links: rendered ? rendered.links : existing?.links ?? [],
@@ -1730,10 +3089,10 @@ async function applyKnowledgeImportFlush(input) {
1730
3089
  adopted,
1731
3090
  unsettled: misplaced || (rendered ? rendered.unresolved : existing?.unresolvedLinks ?? []).length > 0
1732
3091
  });
1733
- if (change !== "unchanged" || existing?.stub) await syncLinks(async () => {
1734
- await syncKnowledgePageBodyLinks(storage, page);
1735
- if (change === "created" || renamed || moved) await refreshKnowledgeLinksTo(storage, [page], { withDescendants: moved });
1736
- });
3092
+ if (change !== "unchanged" || existing?.stub) await links(page, change === "created" || renamed || moved ? {
3093
+ pages: [page],
3094
+ withDescendants: moved
3095
+ } : void 0);
1737
3096
  return {
1738
3097
  page,
1739
3098
  change,
@@ -1741,143 +3100,166 @@ async function applyKnowledgeImportFlush(input) {
1741
3100
  relinked
1742
3101
  };
1743
3102
  };
1744
- const depth = /* @__PURE__ */ new Map();
1745
- for (const op of ops) {
1746
- if (op.op !== "remove") continue;
1747
- const node = await importers.getNode(binding.id, op.sourceId);
1748
- const page = node ? await storage.getPage({
1749
- id: node.pageId,
1750
- read: "all"
1751
- }) : null;
1752
- const path = live(page) ? await keyPath(page) : null;
1753
- depth.set(op.sourceId, path?.keys.length ?? 0);
1754
- }
1755
- const writes = ops.filter((op) => op.op !== "remove");
1756
- const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
1757
- for (const op of [...writes, ...removes]) {
1758
- const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
1759
- const embeds = [];
1760
- try {
1761
- await storage.transaction(async () => {
1762
- if (op.op === "remove") {
1763
- const node = await importers.getNode(binding.id, sourceId);
1764
- if (!node) return;
1765
- const state = await stateOf(node);
1766
- if (state === "merged") return;
1767
- if (state === "gone") {
1768
- await forget(node);
3103
+ const runOps = async () => {
3104
+ const depth = /* @__PURE__ */ new Map();
3105
+ for (const op of ops) {
3106
+ if (op.op !== "remove") continue;
3107
+ const node = await importers.getNode(binding.id, op.sourceId);
3108
+ const page = node ? await storage.getPage({
3109
+ id: node.pageId,
3110
+ read: "all"
3111
+ }) : null;
3112
+ const path = live(page) ? await keyPath(page) : null;
3113
+ depth.set(op.sourceId, path?.keys.length ?? 0);
3114
+ }
3115
+ const writes = ops.filter((op) => op.op !== "remove");
3116
+ const removes = ops.filter((op) => op.op === "remove").sort((a, b) => depth.get(b.sourceId) - depth.get(a.sourceId));
3117
+ for (const op of [...writes, ...removes]) {
3118
+ const sourceId = op.op === "remove" ? op.sourceId : op.item.sourceId;
3119
+ const embeds = [];
3120
+ madeFolders = [];
3121
+ try {
3122
+ await storage.transaction(async () => {
3123
+ if (op.op === "remove") {
3124
+ const node = await importers.getNode(binding.id, sourceId);
3125
+ if (!node) return;
3126
+ const state = await stateOf(node);
3127
+ if (state === "merged") return;
3128
+ if (state === "gone") {
3129
+ await forget(node);
3130
+ result.applied = true;
3131
+ return;
3132
+ }
3133
+ const current = await owned(node.pageId, sourceId);
3134
+ await storage.lockSubtree(current.page.id);
3135
+ const children = (await storage.countChildPages({
3136
+ parentIds: [current.page.id],
3137
+ read: "all"
3138
+ }))[current.page.id] ?? 0;
3139
+ const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
3140
+ if (children > 0 || node.adopted || folder) {
3141
+ if (node.stub) return;
3142
+ const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
3143
+ const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
3144
+ const original = heading ? note.text.slice(heading.length) : note?.text;
3145
+ const page = await storage.updatePage({
3146
+ id: current.page.id,
3147
+ expectedVersion: current.page.version,
3148
+ 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."),
3149
+ provenance
3150
+ });
3151
+ await importers.saveNode({
3152
+ ...node,
3153
+ stub: true
3154
+ });
3155
+ await links(page);
3156
+ embeds.push({
3157
+ kind: "index",
3158
+ pageId: page.id
3159
+ });
3160
+ result.counts.stubbed++;
3161
+ result.changes.push({
3162
+ sourceId,
3163
+ pageId: page.id,
3164
+ change: "stubbed",
3165
+ title: page.name,
3166
+ path: ref(current.keys)
3167
+ });
3168
+ } else {
3169
+ const deleted = await storage.deletePage({
3170
+ id: current.page.id,
3171
+ expectedVersion: current.page.version,
3172
+ deletedBy: provenance.author
3173
+ });
3174
+ await importers.deleteNode(binding.id, sourceId);
3175
+ if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
3176
+ await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
3177
+ await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: randomUUID() });
3178
+ deferredLinkers = true;
3179
+ }
3180
+ await links(deleted, { pages: [deleted] });
3181
+ embeds.push({
3182
+ kind: "remove",
3183
+ pageId: deleted.id
3184
+ });
3185
+ result.counts.removed++;
3186
+ result.changes.push({
3187
+ sourceId,
3188
+ pageId: null,
3189
+ change: "removed",
3190
+ title: deleted.name,
3191
+ path: ref(current.keys)
3192
+ });
3193
+ }
1769
3194
  result.applied = true;
1770
3195
  return;
1771
3196
  }
1772
- const current = await owned(node.pageId, sourceId);
1773
- await storage.lockSubtree(current.page.id);
1774
- const children = (await storage.countChildPages({
1775
- parentIds: [current.page.id],
1776
- read: "all"
1777
- }))[current.page.id] ?? 0;
1778
- const folder = (await importers.listBindings()).some((other) => other.id !== binding.id && other.anchorPageId === current.page.id);
1779
- if (children > 0 || node.adopted || folder) {
1780
- if (node.stub) return;
1781
- const note = node.adopted ? (await keptBodyNotes(current.page.id)).at(-1) : void 0;
1782
- const heading = ORIGINAL_BODY_NOTE_HEADINGS.find((h) => note?.text.startsWith(h));
1783
- const original = heading ? note.text.slice(heading.length) : note?.text;
1784
- const page = await storage.updatePage({
1785
- id: current.page.id,
1786
- expectedVersion: current.page.version,
1787
- 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."),
1788
- provenance
1789
- });
1790
- await importers.saveNode({
1791
- ...node,
1792
- stub: true
1793
- });
1794
- await syncLinks(() => syncKnowledgePageBodyLinks(storage, page));
3197
+ const written = await write(op.item, op.op === "upsert");
3198
+ for (const folder of madeFolders) {
3199
+ result.applied = true;
3200
+ result.counts.created++;
1795
3201
  embeds.push({
1796
3202
  kind: "index",
1797
- pageId: page.id
1798
- });
1799
- result.counts.stubbed++;
1800
- result.changes.push({
1801
- sourceId,
1802
- pageId: page.id,
1803
- change: "stubbed",
1804
- title: page.name,
1805
- path: ref(current.keys)
1806
- });
1807
- } else {
1808
- const deleted = await storage.deletePage({
1809
- id: current.page.id,
1810
- expectedVersion: current.page.version,
1811
- deletedBy: provenance.author
1812
- });
1813
- await importers.deleteNode(binding.id, sourceId);
1814
- if ((await importers.listLinkingNodes(binding.id, [sourceId], { limit: 1 })).items.length > 0) {
1815
- await importers.markLinkingNodesUnsettled(binding.id, [sourceId]);
1816
- await importers.setState(binding.id, { [KNOWLEDGE_IMPORT_SETTLE_RESTART_KEY]: randomUUID() });
1817
- deferredLinkers = true;
1818
- }
1819
- await syncLinks(async () => {
1820
- await syncKnowledgePageBodyLinks(storage, deleted);
1821
- await refreshKnowledgeLinksTo(storage, [deleted]);
1822
- });
1823
- embeds.push({
1824
- kind: "remove",
1825
- pageId: deleted.id
3203
+ pageId: folder.page.id
1826
3204
  });
1827
- result.counts.removed++;
1828
3205
  result.changes.push({
1829
- sourceId,
1830
- pageId: null,
1831
- change: "removed",
1832
- title: deleted.name,
1833
- path: ref(current.keys)
3206
+ sourceId: folder.sourceId,
3207
+ pageId: folder.page.id,
3208
+ change: "created",
3209
+ title: folder.page.name,
3210
+ path: ref(folder.keys)
1834
3211
  });
1835
3212
  }
3213
+ if (!written) {
3214
+ result.counts.merged++;
3215
+ return;
3216
+ }
3217
+ const { page, change, moved, relinked } = written;
3218
+ recordRelinked(relinked, embeds);
3219
+ if (change === "unchanged") {
3220
+ result.counts.unchanged++;
3221
+ return;
3222
+ }
1836
3223
  result.applied = true;
1837
- return;
1838
- }
1839
- const written = await write(op.item, op.op === "upsert");
1840
- if (!written) {
1841
- result.counts.merged++;
1842
- return;
1843
- }
1844
- const { page, change, moved, relinked } = written;
1845
- recordRelinked(relinked, embeds);
1846
- if (change === "unchanged") {
1847
- result.counts.unchanged++;
1848
- return;
1849
- }
1850
- result.applied = true;
1851
- if (change !== "moved") embeds.push({
1852
- kind: "index",
1853
- pageId: page.id
3224
+ if (change !== "moved") embeds.push({
3225
+ kind: "index",
3226
+ pageId: page.id
3227
+ });
3228
+ if (change === "created") result.counts.created++;
3229
+ else if (change === "updated") result.counts.updated++;
3230
+ if (moved) result.counts.moved++;
3231
+ const path = await keyPath(page);
3232
+ result.changes.push({
3233
+ sourceId,
3234
+ pageId: page.id,
3235
+ change,
3236
+ title: page.name,
3237
+ path: path ? ref(path.keys) : ""
3238
+ });
1854
3239
  });
1855
- if (change === "created") result.counts.created++;
1856
- else if (change === "updated") result.counts.updated++;
1857
- if (moved) result.counts.moved++;
1858
- const path = await keyPath(page);
1859
- result.changes.push({
3240
+ result.embeds.push(...embeds);
3241
+ } catch (error) {
3242
+ const reason = refusalFor(error);
3243
+ if (!reason) throw error;
3244
+ result.refused.push({
1860
3245
  sourceId,
1861
- pageId: page.id,
1862
- change,
1863
- title: page.name,
1864
- path: path ? ref(path.keys) : ""
3246
+ reason
1865
3247
  });
1866
- });
1867
- result.embeds.push(...embeds);
1868
- } catch (error) {
1869
- const reason = refusalFor(error);
1870
- if (!reason) throw error;
1871
- result.refused.push({
1872
- sourceId,
1873
- reason
1874
- });
3248
+ }
3249
+ }
3250
+ };
3251
+ if (!canBatchImportFlush(input.storage, input.importers)) await runOps();
3252
+ else if (ops.length) {
3253
+ const fallback = await applyBatched(anchor?.page ?? null);
3254
+ if (fallback) {
3255
+ result.fallback = fallback;
3256
+ await runOps();
1875
3257
  }
1876
3258
  }
1877
3259
  if (input.settle) {
1878
3260
  if (anchor) {
1879
3261
  input.settle.onStart?.();
1880
- result.settle = await settle(input.settle);
3262
+ result.settle = await settle(input.settle, anchor.page);
1881
3263
  } else result.settle = {
1882
3264
  pending: false,
1883
3265
  cursor: null,
@@ -1887,13 +3269,369 @@ async function applyKnowledgeImportFlush(input) {
1887
3269
  }
1888
3270
  return result;
1889
3271
  /**
3272
+ * Decides every op over a working copy (overlay.ts) and writes what they decided in a few
3273
+ * set-based statements, all in one savepoint (batched-flush plan v3.1). Returns why it fell back,
3274
+ * with the savepoint rolled back and the result as before, or null once the ops landed.
3275
+ */
3276
+ async function applyBatched(folder) {
3277
+ const writeOps = new Map(ops.flatMap((op) => op.op === "remove" ? [] : [[op.item.sourceId, op]]));
3278
+ const removed = ops.flatMap((op) => op.op === "remove" ? [op.sourceId] : []);
3279
+ const sourceIds = new Set(removed);
3280
+ for (const op of writeOps.values()) {
3281
+ sourceIds.add(op.item.sourceId);
3282
+ if (op.item.parent) sourceIds.add(op.item.parent);
3283
+ if (op.item.fallbackParent) sourceIds.add(op.item.fallbackParent);
3284
+ for (const link of ("links" in op.item ? op.item.links : void 0) ?? []) sourceIds.add(link.sourceId);
3285
+ }
3286
+ const plan = (rows) => {
3287
+ const keysOf = (page) => {
3288
+ const keys = [];
3289
+ for (let at = page; at && !at.isScope; at = at.parentId ? rows.pages.get(at.parentId) : null) {
3290
+ if (!live(at) || at.key === void 0) return null;
3291
+ keys.unshift(at.key);
3292
+ if (keys.length > 10) return null;
3293
+ }
3294
+ return keys;
3295
+ };
3296
+ const chains = importChainPaths(rows.pages);
3297
+ const pageAt = (keys) => {
3298
+ const key = importPathKey(scope.id, keys);
3299
+ return rows.paths.has(key) ? rows.paths.get(key) : chains.get(key);
3300
+ };
3301
+ const at = (sourceId, seen) => {
3302
+ if (!sourceId) return null;
3303
+ const node = rows.nodes.get(`${binding.id}\u0000${sourceId}`);
3304
+ const page = node ? rows.pages.get(node.pageId) : null;
3305
+ if (live(page ?? null) && page.scopeId === scope.id) {
3306
+ const keys = keysOf(page);
3307
+ if (keys) return {
3308
+ id: page.id,
3309
+ keys
3310
+ };
3311
+ }
3312
+ const op = writeOps.get(sourceId);
3313
+ if (!op || seen.has(sourceId)) return null;
3314
+ return {
3315
+ id: null,
3316
+ keys: [...destinationOf(op, /* @__PURE__ */ new Set([...seen, sourceId])).keys, leafOf(op)]
3317
+ };
3318
+ };
3319
+ const leafOf = (op) => knowledgeImportKey(op.item.path?.at(-1) ?? op.item.sourceId);
3320
+ const destinationOf = (op, seen) => {
3321
+ if (op.item.path) {
3322
+ const keys = [...anchorPath, ...op.item.path.slice(0, -1).map(knowledgeImportKey)];
3323
+ return {
3324
+ id: op.item.path.length === 1 ? folder.id : pageAt(keys),
3325
+ keys
3326
+ };
3327
+ }
3328
+ return at(op.item.parent, seen) ?? at(op.item.fallbackParent, seen) ?? {
3329
+ id: folder.id,
3330
+ keys: anchorPath
3331
+ };
3332
+ };
3333
+ const out = {
3334
+ paths: [],
3335
+ positions: [],
3336
+ notes: [],
3337
+ holders: [],
3338
+ subtrees: [],
3339
+ linkTargets: removed,
3340
+ bindings: removed.length > 0,
3341
+ inPlace: removed.length === 0
3342
+ };
3343
+ const nodeAt = (sourceId) => rows.nodes.get(`${binding.id}\u0000${sourceId}`);
3344
+ const left = /* @__PURE__ */ new Set();
3345
+ for (const op of writeOps.values()) {
3346
+ const destination = destinationOf(op, /* @__PURE__ */ new Set([op.item.sourceId]));
3347
+ const leaf = [...destination.keys, leafOf(op)];
3348
+ const page = rows.pages.get(nodeAt(op.item.sourceId)?.pageId ?? "");
3349
+ if (destination.id && live(page ?? null) && page.parentId === destination.id && (!op.item.path || page.key === leafOf(op))) {
3350
+ if (op.item.path && op.item.path.length > 1) out.holders.push(destination.id);
3351
+ continue;
3352
+ }
3353
+ out.inPlace = false;
3354
+ out.paths.push({
3355
+ scopeId: scope.id,
3356
+ path: leaf
3357
+ });
3358
+ if (destination.id) out.positions.push(destination.id);
3359
+ if (destination.id !== void 0 && live(page ?? null) && (page.parentId !== destination.id || op.item.path && page.key !== leafOf(op))) {
3360
+ out.subtrees.push(page.id);
3361
+ if (page.parentId) left.add(page.parentId);
3362
+ }
3363
+ if (!op.item.path) continue;
3364
+ out.positions.push(folder.id);
3365
+ for (let i = anchorPath.length + 1; i < leaf.length; i++) {
3366
+ out.paths.push({
3367
+ scopeId: scope.id,
3368
+ path: leaf.slice(0, i)
3369
+ });
3370
+ const prefix = pageAt(leaf.slice(0, i));
3371
+ if (prefix) out.positions.push(prefix);
3372
+ }
3373
+ const held = pageAt(leaf);
3374
+ if (held && held !== page?.id) {
3375
+ out.subtrees.push(held);
3376
+ out.notes.push(held);
3377
+ if (page) {
3378
+ out.notes.push(page.id);
3379
+ out.positions.push(page.id);
3380
+ const keys = keysOf(page);
3381
+ if (keys) {
3382
+ for (const child of rows.pages.values()) if (child?.parentId === held && live(child) && child.key !== void 0) out.paths.push({
3383
+ scopeId: scope.id,
3384
+ path: [...keys, child.key]
3385
+ });
3386
+ }
3387
+ }
3388
+ }
3389
+ }
3390
+ for (const id of out.positions) if (left.has(id)) out.subtrees.push(id);
3391
+ for (const sourceId of removed) {
3392
+ const node = nodeAt(sourceId);
3393
+ if (!node) continue;
3394
+ out.subtrees.push(node.pageId);
3395
+ if (node.adopted) out.notes.push(node.pageId);
3396
+ }
3397
+ for (const node of rows.nodes.values()) if (node?.stub && node.adopted) out.notes.push(node.pageId);
3398
+ return out;
3399
+ };
3400
+ return batchedOver(folder, sourceIds, plan, runOps);
3401
+ }
3402
+ /**
3403
+ * Runs `decide` over a working copy of the rows `plan` names, then writes what it decided in a few
3404
+ * set-based statements, all in one savepoint. Returns why it fell back, with the savepoint rolled
3405
+ * back and the result as before, or null once the writes landed.
3406
+ */
3407
+ async function batchedOver(folder, sourceIds, plan, decide) {
3408
+ const real = {
3409
+ storage: input.storage,
3410
+ importers: input.importers
3411
+ };
3412
+ const before = structuredClone(result);
3413
+ const deferredBefore = deferredLinkers;
3414
+ const reset = () => {
3415
+ const copy = structuredClone(before);
3416
+ Object.assign(result, copy);
3417
+ deferredLinkers = deferredBefore;
3418
+ };
3419
+ const missing = emptyImportOverlayMissing();
3420
+ let locked = /* @__PURE__ */ new Set();
3421
+ let reread = false;
3422
+ try {
3423
+ return await real.storage.transaction(async () => {
3424
+ for (let pass = 0; pass < BATCH_DECIDE_PASSES; pass++) {
3425
+ const rows = await gatherImportRows({
3426
+ storage: real.storage,
3427
+ importers: real.importers,
3428
+ bindingId: binding.id,
3429
+ sourceIds,
3430
+ pageIds: folder ? [folder.id] : [],
3431
+ plan,
3432
+ missing,
3433
+ locked,
3434
+ reread
3435
+ });
3436
+ if (!rows) throw new BatchFallback("lock-churn");
3437
+ locked = rows.locked;
3438
+ const working = new ImportOverlay(rows);
3439
+ reset();
3440
+ overlay = working;
3441
+ storage = working.storage;
3442
+ importers = working.importers;
3443
+ try {
3444
+ await decide();
3445
+ } catch (error) {
3446
+ if (error instanceof KnowledgeImportNotGatheredError) {
3447
+ for (const [name, set] of Object.entries(working.missing)) {
3448
+ const into = missing[name];
3449
+ if (into instanceof Map) for (const [k, v] of set) into.set(k, v);
3450
+ else for (const k of set) into.add(k);
3451
+ }
3452
+ continue;
3453
+ }
3454
+ if (error instanceof KnowledgeImportRereadRequiredError) {
3455
+ reread = true;
3456
+ continue;
3457
+ }
3458
+ if (error instanceof KnowledgeImportBatchUnsupportedError) throw new BatchFallback(error.call);
3459
+ throw error;
3460
+ } finally {
3461
+ overlay = null;
3462
+ storage = real.storage;
3463
+ importers = real.importers;
3464
+ }
3465
+ try {
3466
+ if (working.writes.length) await real.storage.applyPageWrites({ writes: working.writes });
3467
+ } catch (error) {
3468
+ if (!refusalFor(error)) throw error;
3469
+ throw new BatchFallback(`page writes: ${error.name}`);
3470
+ }
3471
+ for (const work of working.marks) await work(real.storage, real.importers);
3472
+ const nodes = working.nodeWrites(rows);
3473
+ try {
3474
+ if (nodes.deletes.length || nodes.saves.length) await real.importers.writeNodes(nodes);
3475
+ } catch (error) {
3476
+ if (!refusalFor(error)) throw error;
3477
+ throw new BatchFallback(`node writes: ${error.name}`);
3478
+ }
3479
+ try {
3480
+ await repairKnowledgeLinks(real.storage, {
3481
+ synced: working.links.flatMap((work) => "sync" in work ? [work.sync] : []),
3482
+ refreshed: working.links.flatMap((work) => "refresh" in work ? [{
3483
+ page: work.refresh,
3484
+ withDescendants: work.withDescendants
3485
+ }] : [])
3486
+ });
3487
+ } catch (error) {
3488
+ if (error instanceof KnowledgeLinkRepairUnsupportedError) throw new BatchFallback(error.reason);
3489
+ if (error instanceof KnowledgeUnsupportedCapabilityError) throw new BatchFallback(`link repair: ${error.name}`);
3490
+ throw error;
3491
+ }
3492
+ return null;
3493
+ }
3494
+ throw new BatchFallback("gather passes");
3495
+ });
3496
+ } catch (error) {
3497
+ if (!(error instanceof BatchFallback)) throw error;
3498
+ reset();
3499
+ return error.reason;
3500
+ }
3501
+ }
3502
+ /**
1890
3503
  * One settle slice (O3 §C, §C′): visits the binding's unsettled nodes after `budget.after`, each
1891
3504
  * in its own savepoint, moving a page under a source parent that has arrived since and writing
1892
3505
  * links whose targets now resolve. Stops at the candidate, move or time cap and leaves the rest
1893
3506
  * for the next slice. A node it can't settle (refused, or still waiting) is skipped and stays
1894
3507
  * unsettled; the pass ends when it reaches the last unsettled node.
1895
3508
  */
1896
- async function settle(budget) {
3509
+ async function settle(budget, folder) {
3510
+ if (!canBatchImportFlush(input.storage, input.importers)) return settleNodeByNode(budget);
3511
+ const fromStart = (budget.after ?? void 0) === void 0;
3512
+ const window = [];
3513
+ let cursor = budget.after ?? void 0;
3514
+ let end = false;
3515
+ while (window.length < budget.candidates) {
3516
+ const page = await input.importers.listNodes(binding.id, {
3517
+ unsettled: true,
3518
+ ...cursor !== void 0 ? { after: cursor } : {},
3519
+ limit: budget.candidates - window.length
3520
+ });
3521
+ window.push(...page.items);
3522
+ cursor = page.items.at(-1)?.sourceId ?? cursor;
3523
+ if (!page.next) {
3524
+ end = true;
3525
+ break;
3526
+ }
3527
+ }
3528
+ if (!window.length) return settleNodeByNode(budget);
3529
+ const parents = new Map((await input.importers.getNodes(binding.id, [...new Set(window.flatMap((node) => node.parentSourceId ? [node.parentSourceId] : []))])).map((node) => [node.sourceId, node]));
3530
+ const pages = new Map((await input.storage.getPages({
3531
+ ids: window.map((node) => node.pageId),
3532
+ read: "all"
3533
+ })).map((page) => [page.id, page]));
3534
+ const visit = [];
3535
+ const movers = [];
3536
+ for (const node of window) {
3537
+ visit.push(node);
3538
+ const parent = node.parentSourceId ? parents.get(node.parentSourceId) : void 0;
3539
+ const page = pages.get(node.pageId);
3540
+ if (parent && page && page.parentId !== parent.pageId) {
3541
+ movers.push({
3542
+ sourceId: node.sourceId,
3543
+ page,
3544
+ destination: parent.pageId
3545
+ });
3546
+ if (movers.length >= budget.moves) break;
3547
+ }
3548
+ }
3549
+ if (visit.length < window.length) end = false;
3550
+ const sourceIds = /* @__PURE__ */ new Set();
3551
+ for (const node of visit) {
3552
+ sourceIds.add(node.sourceId);
3553
+ if (node.parentSourceId) sourceIds.add(node.parentSourceId);
3554
+ for (const link of node.links) sourceIds.add(link.sourceId);
3555
+ }
3556
+ let outcome = null;
3557
+ const fallback = await batchedOver(folder, sourceIds, (rows) => ({
3558
+ paths: movers.flatMap((mover) => {
3559
+ const keys = [];
3560
+ for (let at = rows.pages.get(mover.destination); at && !at.isScope;) {
3561
+ if (at.key === void 0) return [];
3562
+ keys.unshift(at.key);
3563
+ at = at.parentId ? rows.pages.get(at.parentId) : null;
3564
+ }
3565
+ return mover.page.key === void 0 ? [] : [{
3566
+ scopeId: scope.id,
3567
+ path: [...keys, mover.page.key]
3568
+ }];
3569
+ }),
3570
+ positions: movers.map((mover) => mover.destination),
3571
+ notes: [],
3572
+ subtrees: movers.map((mover) => mover.page.id),
3573
+ linkTargets: movers.map((mover) => mover.sourceId),
3574
+ bindings: false
3575
+ }), async () => {
3576
+ outcome = await settleWindow(budget, visit, end, fromStart);
3577
+ });
3578
+ if (fallback === null && outcome) {
3579
+ const settledSlice = outcome;
3580
+ if (!settledSlice.pending && deferredLinkers) {
3581
+ if ((await input.importers.listNodes(binding.id, {
3582
+ unsettled: true,
3583
+ limit: 1
3584
+ })).items.length > 0) return {
3585
+ ...settledSlice,
3586
+ pending: true
3587
+ };
3588
+ }
3589
+ return settledSlice;
3590
+ }
3591
+ result.fallback = result.fallback ? `${result.fallback}; settle: ${fallback}` : `settle: ${fallback}`;
3592
+ return settleNodeByNode(budget);
3593
+ }
3594
+ /**
3595
+ * The node-by-node loop over a window read ahead, for the batched slice: the same caps, the same
3596
+ * savepoint per node, over the working copy.
3597
+ */
3598
+ async function settleWindow(budget, visit, end, fromStart) {
3599
+ let after = budget.after ?? void 0;
3600
+ let moves = 0;
3601
+ let settled = 0;
3602
+ const resumeAt = () => deferredLinkers ? null : after ?? null;
3603
+ for (const node of visit) {
3604
+ if (moves >= budget.moves || Date.now() >= budget.until) return {
3605
+ pending: true,
3606
+ cursor: resumeAt(),
3607
+ settled,
3608
+ fromStart
3609
+ };
3610
+ after = node.sourceId;
3611
+ const embeds = [];
3612
+ try {
3613
+ const outcome = await storage.transaction(() => settleNode(node.sourceId, embeds, moves < budget.moves));
3614
+ if (outcome.moved) moves++;
3615
+ if (outcome.moved || outcome.relinked) settled++;
3616
+ result.embeds.push(...embeds);
3617
+ } catch (error) {
3618
+ if (!refusalFor(error)) throw error;
3619
+ }
3620
+ }
3621
+ if (!end) return {
3622
+ pending: true,
3623
+ cursor: resumeAt(),
3624
+ settled,
3625
+ fromStart
3626
+ };
3627
+ return {
3628
+ pending: false,
3629
+ cursor: null,
3630
+ settled,
3631
+ fromStart
3632
+ };
3633
+ }
3634
+ async function settleNodeByNode(budget) {
1897
3635
  let after = budget.after ?? void 0;
1898
3636
  const fromStart = after === void 0;
1899
3637
  let examined = 0;
@@ -1986,7 +3724,10 @@ async function applyKnowledgeImportFlush(input) {
1986
3724
  ({page, keys, relinked: rewrote} = await moveOwned(sourceId, page, destination));
1987
3725
  recordRelinked(rewrote, embeds);
1988
3726
  moved = true;
1989
- await syncLinks(() => refreshKnowledgeLinksTo(storage, [page], { withDescendants: true }));
3727
+ await links(null, {
3728
+ pages: [page],
3729
+ withDescendants: true
3730
+ });
1990
3731
  }
1991
3732
  } else if (parent) misplaced = true;
1992
3733
  const out = await relink(node, page);
@@ -2456,6 +4197,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2456
4197
  /** Store time (epoch ms) at which a running run stops being live under `leaseMs`. */
2457
4198
  const liveUntil = (run) => Math.min((run.heartbeatAt ?? run.startedAt).getTime() + (leaseMs ?? Infinity), run.deadlineAt?.getTime() ?? Infinity);
2458
4199
  const listBindings = async () => typeof options.bindings === "function" ? await options.bindings() : options.bindings;
4200
+ const pathWarned = /* @__PURE__ */ new Set();
2459
4201
  const storageAndImporters = async () => {
2460
4202
  const storage = await writer.getStorage();
2461
4203
  const importers = storage.importers;
@@ -2499,7 +4241,10 @@ function createLocalKnowledgeImporterHost(writer, options) {
2499
4241
  * flushes and finish are refused as `run_not_active`; exact replays still return receipts.
2500
4242
  */
2501
4243
  const staleAfter = leaseMs ?? options.staleRunAfterMs ?? DEFAULT_STALE_RUN_AFTER_MS;
2502
- /** Ends `run` if it isn't live; the caller holds the guard and the run's lock. */
4244
+ /**
4245
+ * Ends `run` if it isn't live; the caller holds the guard and the run's lock. The caller clears the
4246
+ * run's path-warning marker once its transaction commits: a rollback brings the run back.
4247
+ */
2503
4248
  const expireLocked = async (importers, run) => {
2504
4249
  const why = lapsed(run, await clock(importers), staleAfter);
2505
4250
  if (!why) return false;
@@ -2511,13 +4256,16 @@ function createLocalKnowledgeImporterHost(writer, options) {
2511
4256
  });
2512
4257
  return true;
2513
4258
  };
4259
+ /** Ends the binding's runs that aren't live, returning the ones it ended. */
2514
4260
  const reclaimStaleRuns = async (importers, bindingId) => {
4261
+ const ended = [];
2515
4262
  for (const candidate of await importers.listRuns(bindingId)) {
2516
4263
  if (candidate.status !== "running") continue;
2517
4264
  const run = await importers.lockRun(candidate.id);
2518
4265
  if (!run || run.status !== "running") continue;
2519
- await expireLocked(importers, run);
4266
+ if (await expireLocked(importers, run)) ended.push(run.id);
2520
4267
  }
4268
+ return ended;
2521
4269
  };
2522
4270
  /**
2523
4271
  * Counts a settle flush that timed out, outside its rolled-back transaction. Best effort, and
@@ -2574,7 +4322,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2574
4322
  importer: binding.importer,
2575
4323
  target: binding.target
2576
4324
  });
2577
- await reclaimStaleRuns(importers, binding.id);
4325
+ const ended = await reclaimStaleRuns(importers, binding.id);
2578
4326
  if (start?.admit) try {
2579
4327
  await start.admit(unwrapKnowledgeStorage(tx));
2580
4328
  } catch (error) {
@@ -2596,7 +4344,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2596
4344
  const saved = run.status === "started" ? await importers.getState(binding.id) : {};
2597
4345
  return {
2598
4346
  run,
2599
- state: Object.fromEntries(Object.entries(saved).filter(([key]) => !key.startsWith(RESERVED_STATE_PREFIX)))
4347
+ state: Object.fromEntries(Object.entries(saved).filter(([key]) => !key.startsWith(RESERVED_STATE_PREFIX))),
4348
+ ended
2600
4349
  };
2601
4350
  });
2602
4351
  let result;
@@ -2607,6 +4356,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2607
4356
  exclusive = true;
2608
4357
  result = await attempt();
2609
4358
  }
4359
+ for (const runId of result.ended) pathWarned.delete(runId);
2610
4360
  if (result.run.status !== "started") return {
2611
4361
  status: "skipped",
2612
4362
  runId: result.run.run.id
@@ -2665,8 +4415,12 @@ function createLocalKnowledgeImporterHost(writer, options) {
2665
4415
  }
2666
4416
  let embeds = [];
2667
4417
  let settling = false;
4418
+ let fallbackWarning;
4419
+ let pathsUnsupported = false;
2668
4420
  try {
2669
4421
  const write = (deadlineAt) => storage.transaction(async (tx) => {
4422
+ fallbackWarning = void 0;
4423
+ pathsUnsupported = false;
2670
4424
  const importers = tx.importers;
2671
4425
  const guard = await importers.lockWriterGuard(peek.firstWriteAt ? "share" : "update");
2672
4426
  const run = await importers.lockRun(flush.runId);
@@ -2711,6 +4465,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2711
4465
  }
2712
4466
  } } : {}
2713
4467
  });
4468
+ if (applied.fallback) fallbackWarning = `Knowledge importer: flush ${flush.seq} of run ${run.id} saved op by op instead of batched (${applied.fallback})`;
4469
+ pathsUnsupported = !!applied.pathsUnsupported;
2714
4470
  const settled = applied.settle;
2715
4471
  const hostUpdates = {};
2716
4472
  if (settled && (settled.cursor ?? "") !== (hostState[SETTLE_CURSOR_KEY] ?? "")) hostUpdates[SETTLE_CURSOR_KEY] = settled.cursor ?? "";
@@ -2721,15 +4477,18 @@ function createLocalKnowledgeImporterHost(writer, options) {
2721
4477
  ...hostUpdates
2722
4478
  };
2723
4479
  if (Object.keys(state).length) await importers.setState(binding.id, state);
2724
- for (const change of applied.changes) await importers.recordRunChange({
4480
+ const changes = applied.changes.map((change) => ({
2725
4481
  runId: run.id,
2726
4482
  ...change
2727
- });
4483
+ }));
4484
+ if (importers.recordRunChanges) await importers.recordRunChanges(changes);
4485
+ else for (const change of changes) await importers.recordRunChange(change);
2728
4486
  const receipt = {
2729
4487
  seq: flush.seq,
2730
4488
  ...applied.counts,
2731
4489
  refused: applied.refused,
2732
- pending: settled?.pending ?? false
4490
+ pending: settled?.pending ?? false,
4491
+ ...applied.fallback ? { fallback: applied.fallback } : {}
2733
4492
  };
2734
4493
  await importers.recordFlush({
2735
4494
  runId: run.id,
@@ -2740,7 +4499,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2740
4499
  counts: {
2741
4500
  ...applied.counts,
2742
4501
  refused: applied.refused.length,
2743
- settled: settled?.settled ?? 0
4502
+ settled: settled?.settled ?? 0,
4503
+ ...applied.fallback ? { fallbacks: 1 } : {}
2744
4504
  }
2745
4505
  });
2746
4506
  if (applied.applied && !guard.firstWriteAt) await importers.markFirstWrite();
@@ -2755,6 +4515,11 @@ function createLocalKnowledgeImporterHost(writer, options) {
2755
4515
  if (attempt >= MAX_LEASE_BOUND_ATTEMPTS) throw new KnowledgeImporterHostError("The flush could not be bounded by its run lease; resend it.", 503);
2756
4516
  deadlineAt = Math.min(budgetAt, error.cutoff - LEASE_CUTOFF_MARGIN_MS);
2757
4517
  }
4518
+ if (fallbackWarning) writer.warn(fallbackWarning);
4519
+ if (pathsUnsupported && !pathWarned.has(flush.runId)) {
4520
+ pathWarned.add(flush.runId);
4521
+ writer.warn(`Knowledge importer: run ${flush.runId} refused items placed by path: path placement needs a store that supports page re-key; ${Object.getPrototypeOf(storage).constructor.name} does not`);
4522
+ }
2758
4523
  await runEmbeds(storage, embeds);
2759
4524
  return receipt;
2760
4525
  } catch (error) {
@@ -2822,7 +4587,10 @@ function createLocalKnowledgeImporterHost(writer, options) {
2822
4587
  await importers.lockWriterGuard("share");
2823
4588
  const run = await importers.lockRun(runId);
2824
4589
  return !!run && run.status === "running" && await expireLocked(importers, run);
2825
- })) expired.push(runId);
4590
+ })) {
4591
+ expired.push(runId);
4592
+ pathWarned.delete(runId);
4593
+ }
2826
4594
  return { expired };
2827
4595
  } catch (error) {
2828
4596
  throw hostError(error);
@@ -2846,7 +4614,7 @@ function createLocalKnowledgeImporterHost(writer, options) {
2846
4614
  }
2847
4615
  const { storage } = await storageAndImporters();
2848
4616
  try {
2849
- return await storage.transaction(async (tx) => {
4617
+ const receipt = await storage.transaction(async (tx) => {
2850
4618
  const importers = tx.importers;
2851
4619
  const guard = await importers.lockWriterGuard("share");
2852
4620
  const run = await importers.lockRun(request.runId);
@@ -2890,6 +4658,8 @@ function createLocalKnowledgeImporterHost(writer, options) {
2890
4658
  });
2891
4659
  return runReceipt(finished);
2892
4660
  });
4661
+ pathWarned.delete(request.runId);
4662
+ return receipt;
2893
4663
  } catch (error) {
2894
4664
  throw hostError(error);
2895
4665
  }
@@ -4267,7 +6037,8 @@ var Knowledge = class extends MastraBase {
4267
6037
  warn: (message) => this.logger.warn(message),
4268
6038
  maxTokens: this.#tools.maxTokens,
4269
6039
  ...principals ? { principals } : {},
4270
- ...options?.author ? { author: options.author } : {}
6040
+ ...options?.author ? { author: options.author } : {},
6041
+ ...options?.requireExpectedVersion ? { requireExpectedVersion: true } : {}
4271
6042
  }, this.#groups(options), (context) => context?.requestContext?.delete?.(PINNED_READ_MEMO_KEY));
4272
6043
  }
4273
6044
  /**