@engenty/wizards-runtime 0.14.2 → 0.16.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 (263) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +180 -4
  2. package/apps/runtime/dist/agents/website.js +10 -5
  3. package/apps/runtime/dist/app.js +27 -2
  4. package/apps/runtime/dist/auth/index.js +5 -0
  5. package/apps/runtime/dist/broker/account.js +5 -0
  6. package/apps/runtime/dist/broker/call.js +2 -0
  7. package/apps/runtime/dist/broker/host.js +1 -0
  8. package/apps/runtime/dist/broker/index.js +5 -0
  9. package/apps/runtime/dist/broker/rwx.js +293 -11
  10. package/apps/runtime/dist/cli/main.js +7 -0
  11. package/apps/runtime/dist/cli/move-files.js +68 -0
  12. package/apps/runtime/dist/cli/move-folder-sources.js +120 -0
  13. package/apps/runtime/dist/connectors/plugin-connections.js +74 -4
  14. package/apps/runtime/dist/db/migrations/tenant/0040_rwx_elements.sql +21 -0
  15. package/apps/runtime/dist/db/migrations/tenant/0041_broker_log_client.sql +1 -0
  16. package/apps/runtime/dist/db/migrations/tenant/0042_client_spaces.sql +16 -0
  17. package/apps/runtime/dist/db/migrations/tenant/0043_space_member_invite.sql +19 -0
  18. package/apps/runtime/dist/db/migrations/tenant/0044_client_portal.sql +8 -0
  19. package/apps/runtime/dist/db/migrations/tenant/0045_client_portal_no_slug.sql +2 -0
  20. package/apps/runtime/dist/db/migrations/tenant/0046_space_file_hash.sql +2 -0
  21. package/apps/runtime/dist/db/migrations/tenant/0047_knowledge_folders.sql +3 -0
  22. package/apps/runtime/dist/db/migrations/tenant/0048_space_chunk_kind.sql +1 -0
  23. package/apps/runtime/dist/db/migrations/tenant/0049_knowledge_sources.sql +57 -0
  24. package/apps/runtime/dist/db/migrations/tenant/0050_dateien.sql +71 -0
  25. package/apps/runtime/dist/db/migrations/tenant/0051_dateien_drafts.sql +23 -0
  26. package/apps/runtime/dist/db/migrations/tenant/0052_dateien_plugin_kinds.sql +5 -0
  27. package/apps/runtime/dist/db/migrations/tenant/0053_dateien_file_title.sql +3 -0
  28. package/apps/runtime/dist/db/migrations/tenant/0054_dateien_ocr.sql +14 -0
  29. package/apps/runtime/dist/db/migrations/tenant/0055_dateien_doc_reread.sql +3 -0
  30. package/apps/runtime/dist/db/migrations/tenant/meta/0040_snapshot.json +5153 -0
  31. package/apps/runtime/dist/db/migrations/tenant/meta/0041_snapshot.json +5160 -0
  32. package/apps/runtime/dist/db/migrations/tenant/meta/0042_snapshot.json +5286 -0
  33. package/apps/runtime/dist/db/migrations/tenant/meta/0043_snapshot.json +5293 -0
  34. package/apps/runtime/dist/db/migrations/tenant/meta/0044_snapshot.json +5344 -0
  35. package/apps/runtime/dist/db/migrations/tenant/meta/0045_snapshot.json +5329 -0
  36. package/apps/runtime/dist/db/migrations/tenant/meta/0046_snapshot.json +5343 -0
  37. package/apps/runtime/dist/db/migrations/tenant/meta/0047_snapshot.json +5391 -0
  38. package/apps/runtime/dist/db/migrations/tenant/meta/0048_snapshot.json +5398 -0
  39. package/apps/runtime/dist/db/migrations/tenant/meta/0049_snapshot.json +5793 -0
  40. package/apps/runtime/dist/db/migrations/tenant/meta/0050_snapshot.json +6288 -0
  41. package/apps/runtime/dist/db/migrations/tenant/meta/0051_snapshot.json +6461 -0
  42. package/apps/runtime/dist/db/migrations/tenant/meta/0052_snapshot.json +6497 -0
  43. package/apps/runtime/dist/db/migrations/tenant/meta/0053_snapshot.json +6504 -0
  44. package/apps/runtime/dist/db/migrations/tenant/meta/0054_snapshot.json +6504 -0
  45. package/apps/runtime/dist/db/migrations/tenant/meta/0055_snapshot.json +6504 -0
  46. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +112 -0
  47. package/apps/runtime/dist/db/schema.js +296 -5
  48. package/apps/runtime/dist/docs/dev/api.md +49 -2
  49. package/apps/runtime/dist/docs/dev/architecture.md +13 -2
  50. package/apps/runtime/dist/docs/dev/plugins/connections.md +30 -2
  51. package/apps/runtime/dist/docs/dev/plugins/index.md +1 -1
  52. package/apps/runtime/dist/docs/dev/plugins/reference.md +7 -4
  53. package/apps/runtime/dist/docs/dev/plugins/server.md +11 -5
  54. package/apps/runtime/dist/docs/dev/plugins/space.md +130 -4
  55. package/apps/runtime/dist/docs/dev/plugins/studio.md +13 -3
  56. package/apps/runtime/dist/docs/user-guide/command-line.md +2 -0
  57. package/apps/runtime/dist/docs/user-guide/plugins.md +1 -1
  58. package/apps/runtime/dist/docs/user-guide/space.md +6 -6
  59. package/apps/runtime/dist/docs/user-guide/steps.md +1 -1
  60. package/apps/runtime/dist/documents/ocr.js +72 -0
  61. package/apps/runtime/dist/documents/parse.js +81 -12
  62. package/apps/runtime/dist/elements/caller.js +47 -0
  63. package/apps/runtime/dist/elements/catalogue.js +14 -0
  64. package/apps/runtime/dist/elements/connections.js +60 -0
  65. package/apps/runtime/dist/elements/gate.js +81 -0
  66. package/apps/runtime/dist/elements/knowledge.js +308 -0
  67. package/apps/runtime/dist/elements/outside.js +103 -0
  68. package/apps/runtime/dist/elements/specs.js +102 -0
  69. package/apps/runtime/dist/elements/wizards.js +72 -0
  70. package/apps/runtime/dist/engenty/connections-google/connectors/drive.js +3 -0
  71. package/apps/runtime/dist/engenty/connections-microsoft/onedrive.js +3 -0
  72. package/apps/runtime/dist/engenty/connections-s3/s3.js +6 -0
  73. package/apps/runtime/dist/engine/runner.js +19 -2
  74. package/apps/runtime/dist/engine/steps.js +1 -1
  75. package/apps/runtime/dist/env.js +11 -2
  76. package/apps/runtime/dist/files/blobs.js +57 -1
  77. package/apps/runtime/dist/files/objects.js +1 -0
  78. package/apps/runtime/dist/files/pictures.js +41 -0
  79. package/apps/runtime/dist/files/storage.js +14 -26
  80. package/apps/runtime/dist/files/thumbs.js +77 -0
  81. package/apps/runtime/dist/files/upload-check.js +2 -2
  82. package/apps/runtime/dist/index.js +22 -0
  83. package/apps/runtime/dist/live/views.js +2 -1
  84. package/apps/runtime/dist/manage.js +4 -1
  85. package/apps/runtime/dist/mcp/elements.js +88 -0
  86. package/apps/runtime/dist/mcp/handler.js +2 -0
  87. package/apps/runtime/dist/mcp/scopes.js +5 -0
  88. package/apps/runtime/dist/mcp/tools.js +5 -0
  89. package/apps/runtime/dist/models.js +82 -13
  90. package/apps/runtime/dist/mounts/cache.js +71 -0
  91. package/apps/runtime/dist/mounts/drafts.js +367 -0
  92. package/apps/runtime/dist/mounts/folder.js +148 -0
  93. package/apps/runtime/dist/mounts/mounts.js +1315 -0
  94. package/apps/runtime/dist/mounts/source.js +179 -0
  95. package/apps/runtime/dist/mounts/units.js +97 -0
  96. package/apps/runtime/dist/move-files.js +4 -0
  97. package/apps/runtime/dist/plugins/loader.js +73 -1
  98. package/apps/runtime/dist/plugins/registry.js +2 -0
  99. package/apps/runtime/dist/prompts/authoring.md +2 -2
  100. package/apps/runtime/dist/prompts/goose.md +13 -1
  101. package/apps/runtime/dist/prompts/tools.md +8 -2
  102. package/apps/runtime/dist/render/convert.js +188 -1
  103. package/apps/runtime/dist/routes/api.js +7 -2
  104. package/apps/runtime/dist/routes/client-contract.js +164 -0
  105. package/apps/runtime/dist/routes/client-spaces.js +58 -0
  106. package/apps/runtime/dist/routes/dateien.js +173 -0
  107. package/apps/runtime/dist/routes/elements.js +76 -0
  108. package/apps/runtime/dist/routes/plugins.js +2 -1
  109. package/apps/runtime/dist/routes/runs.js +24 -10
  110. package/apps/runtime/dist/routes/studio.js +168 -8
  111. package/apps/runtime/dist/secrets/signing.js +16 -0
  112. package/apps/runtime/dist/services/client-portal.js +439 -0
  113. package/apps/runtime/dist/services/client-spaces.js +228 -0
  114. package/apps/runtime/dist/services/cloud.js +2 -0
  115. package/apps/runtime/dist/services/knowledge-model.js +24 -8
  116. package/apps/runtime/dist/services/knowledge.js +72 -42
  117. package/apps/runtime/dist/services/links.js +17 -0
  118. package/apps/runtime/dist/services/members-studio.js +5 -1
  119. package/apps/runtime/dist/services/page-pictures.js +162 -0
  120. package/apps/runtime/dist/services/runs.js +22 -6
  121. package/apps/runtime/dist/services/space-categories.js +41 -5
  122. package/apps/runtime/dist/services/space-data.js +165 -8
  123. package/apps/runtime/dist/services/space-files.js +102 -19
  124. package/apps/runtime/dist/services/space-index.js +384 -41
  125. package/apps/runtime/dist/services/space-origin.js +25 -1
  126. package/apps/runtime/dist/services/space-sources.js +937 -0
  127. package/apps/runtime/dist/services/spaces.js +60 -12
  128. package/apps/runtime/dist/services/synced-spaces.js +10 -1
  129. package/apps/runtime/dist/services/work-ai.js +53 -24
  130. package/apps/runtime/dist/services/work-chats.js +3 -2
  131. package/apps/runtime/dist/services/work-connections.js +2 -2
  132. package/apps/runtime/dist/sharing/index.js +2 -0
  133. package/apps/runtime/dist/store/index.js +29 -8
  134. package/apps/runtime/dist/store/shared-lists.js +30 -17
  135. package/apps/runtime/dist/sync/records.js +22 -27
  136. package/apps/runtime/dist/texts.js +4 -0
  137. package/apps/runtime/dist/tools/index.js +5 -4
  138. package/apps/runtime/dist/tools/pages.js +1 -1
  139. package/apps/runtime/dist/tools/skills.js +80 -54
  140. package/apps/runtime/dist/tools/space.js +8 -152
  141. package/apps/runtime/dist/widgets/step.js +2 -1
  142. package/apps/web/dist/assets/AboutDialog-0q4P80yv.js +1 -0
  143. package/apps/web/dist/assets/BlockEditor-CUYFH_CU.js +173 -0
  144. package/apps/web/dist/assets/BlockEditor-CtW6lw0y.css +1 -0
  145. package/apps/web/dist/assets/CapabilitiesPage-BlZP8DYb.js +2 -0
  146. package/apps/web/dist/assets/{ChangelogDialog-D_dQOMIq.js → ChangelogDialog-CDN7kMs1.js} +1 -1
  147. package/apps/web/dist/assets/{CodeEditor-nxoOt8ge.js → CodeEditor-D-Y16fdk.js} +1 -1
  148. package/apps/web/dist/assets/EditorPage-CrMVsgUt.js +3 -0
  149. package/apps/web/dist/assets/{FlowPreview-aMfwcPul.js → FlowPreview-DXnk7m9P.js} +1 -1
  150. package/apps/web/dist/assets/{LangSwitch-DpD0inR4.js → LangSwitch-Dkd0FBIH.js} +1 -1
  151. package/apps/web/dist/assets/Marketplace-Cty40VwG.js +2 -0
  152. package/apps/web/dist/assets/NewWizardChannels-Czool7s1.js +1 -0
  153. package/apps/web/dist/assets/NewWizardPage-CfVe_4a2.js +7 -0
  154. package/apps/web/dist/assets/OnboardingPage-D3SEpTmt.js +1 -0
  155. package/apps/web/dist/assets/PreviewPane-CQDKQO6z.js +7 -0
  156. package/apps/web/dist/assets/PublicRunner-BDZNnlQw.js +1 -0
  157. package/apps/web/dist/assets/ReadOnly-B7MUySpC.js +1 -0
  158. package/apps/web/dist/assets/SettingsPage-Bgurv3l2.js +2 -0
  159. package/apps/web/dist/assets/SetupPage-C3km8vqv.js +1 -0
  160. package/apps/web/dist/assets/{SharePage-N80EhoD7.js → SharePage-UwEJBIzq.js} +1 -1
  161. package/apps/web/dist/assets/SkillEditor-BaEiqqXl.js +1 -0
  162. package/apps/web/dist/assets/Skills-Bv6XbKxc.js +9 -0
  163. package/apps/web/dist/assets/SpacePage-D9PXLSU_.js +2 -0
  164. package/apps/web/dist/assets/UpdateCheck-C7I43zFZ.js +2 -0
  165. package/apps/web/dist/assets/changelog-DwgWiSZb.js +1 -0
  166. package/apps/web/dist/assets/circle-check-DDLzlcXP.js +1 -0
  167. package/apps/web/dist/assets/code-DsnwzN1x.js +1 -0
  168. package/apps/web/dist/assets/code-editor-Ca5EAxmd.js +2 -0
  169. package/apps/web/dist/assets/code-xml-S4IFi5Jc.js +1 -0
  170. package/apps/web/dist/assets/connection-sign-in-hI3HXhq4.js +1 -0
  171. package/apps/web/dist/assets/{dist-H1UN89OA.js → dist-B3Ray2U5.js} +1 -1
  172. package/apps/web/dist/assets/dist-CQpLJoQZ.js +10 -0
  173. package/apps/web/dist/assets/{dist-GlRRx9Xl.js → dist-D1uGQ_tB.js} +1 -1
  174. package/apps/web/dist/assets/{dist-BdDd1FxP.js → dist-DFI-tsfx.js} +1 -1
  175. package/apps/web/dist/assets/eye-TJSuiHHO.js +1 -0
  176. package/apps/web/dist/assets/floating-ui.dom-pwdNGv4b.js +1 -0
  177. package/apps/web/dist/assets/host-D5hNHbhF.js +125 -0
  178. package/apps/web/dist/assets/i18n-BBzMbGoo.js +55 -0
  179. package/apps/web/dist/assets/index-CyBrvupM.js +10 -0
  180. package/apps/web/dist/assets/index-w-3J3ZJ9.css +1 -0
  181. package/apps/web/dist/assets/{json-CEsfHdlZ.js → json-Ce3iHrtf.js} +1 -1
  182. package/apps/web/dist/assets/link-CPL8pB1P.js +1 -0
  183. package/apps/web/dist/assets/list-checks-DaxmUPqK.js +1 -0
  184. package/apps/web/dist/assets/{markdown-5-I9_izp.js → markdown-hqKQy2pp.js} +1 -1
  185. package/apps/web/dist/assets/marked.esm-DQ7XA7AC.js +67 -0
  186. package/apps/web/dist/assets/oss-credits-BrwV0a4F.js +1 -0
  187. package/apps/web/dist/assets/pdf-Dg-raaUo.js +54 -0
  188. package/apps/web/dist/assets/pdf.worker.min-68CMzziE.js +1 -0
  189. package/apps/web/dist/assets/pdf.worker.min-CjEcRF4W.mjs +28 -0
  190. package/apps/web/dist/assets/phone-B4uKDBFq.js +1 -0
  191. package/apps/web/dist/assets/read-aloud-Bfp9_bUY.js +1 -0
  192. package/apps/web/dist/assets/{runners-CyIvJIHr.js → runners-CUpBpSji.js} +1 -1
  193. package/apps/web/dist/assets/scroll-text-BEnPzQEi.js +1 -0
  194. package/apps/web/dist/assets/session-CMQo8P-G.js +2 -0
  195. package/apps/web/dist/assets/table-5B9G3oA6.js +1 -0
  196. package/apps/web/dist/assets/theme-CdX0marK.js +11 -0
  197. package/apps/web/dist/assets/ui-BCfu5sia.js +16 -0
  198. package/apps/web/dist/assets/upload-CAlHC232.js +1 -0
  199. package/apps/web/dist/assets/{useMutation-DEkZhp5c.js → useMutation-1fV4Nnxq.js} +1 -1
  200. package/apps/web/dist/assets/viewers-ChriFcRy.js +2 -0
  201. package/apps/web/dist/assets/volume-2-BqlBtCIJ.js +1 -0
  202. package/apps/web/dist/assets/w3c-keyname-BOAvb0qz.js +1 -0
  203. package/apps/web/dist/assets/xlsx-CuSbHU4R.js +141 -0
  204. package/apps/web/dist/index.html +19 -14
  205. package/apps/web/dist/mcp/flow.html +2 -2
  206. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +223 -4
  207. package/node_modules/@engenty/wizards/dist/plugin/mount.d.ts +123 -0
  208. package/node_modules/@engenty/wizards/dist/plugin/mount.js +7 -0
  209. package/node_modules/@engenty/wizards/dist/plugin/studio.d.ts +110 -1
  210. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +1 -1
  211. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +24 -0
  212. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +24 -0
  213. package/node_modules/@engenty/wizards-shared/dist/knowledge.d.ts +33 -4
  214. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +6 -0
  215. package/node_modules/@engenty/wizards-shared/dist/run.js +12 -0
  216. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +21 -4
  217. package/node_modules/@engenty/wizards-shared/dist/rwx.js +30 -3
  218. package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +11 -1
  219. package/node_modules/@engenty/wizards-shared/dist/spaces.js +9 -2
  220. package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +6 -0
  221. package/node_modules/@engenty/wizards-shared/dist/text-merge.js +25 -0
  222. package/package.json +3 -1
  223. package/plugin/.claude-plugin/plugin.json +1 -1
  224. package/plugin/README.md +3 -0
  225. package/plugin/plugin.json +1 -1
  226. package/plugin/skills/work-in-space/SKILL.md +16 -0
  227. package/apps/web/dist/assets/AboutDialog-Cag3RJuT.js +0 -1
  228. package/apps/web/dist/assets/CapabilitiesPage-BQYiN0gT.js +0 -2
  229. package/apps/web/dist/assets/EditorPage-C4_8LsQN.js +0 -3
  230. package/apps/web/dist/assets/Marketplace-CpzD9pNQ.js +0 -2
  231. package/apps/web/dist/assets/NewWizardChannels-CcE3UMVb.js +0 -1
  232. package/apps/web/dist/assets/NewWizardPage-BzN7zrQx.js +0 -7
  233. package/apps/web/dist/assets/OnboardingPage-ztHT01ah.js +0 -1
  234. package/apps/web/dist/assets/PreviewPane-BabMbBZI.js +0 -9
  235. package/apps/web/dist/assets/PublicRunner-D-JmtqCi.js +0 -1
  236. package/apps/web/dist/assets/ReadOnly-GAORKKqV.js +0 -1
  237. package/apps/web/dist/assets/SettingsPage-BKAiYmXl.js +0 -2
  238. package/apps/web/dist/assets/SetupPage-C1EZZHIp.js +0 -1
  239. package/apps/web/dist/assets/SkillEditor-CqQMg2MC.js +0 -1
  240. package/apps/web/dist/assets/Skills-CnhpgoOA.js +0 -9
  241. package/apps/web/dist/assets/SpacePage-CRR8JvV1.js +0 -2
  242. package/apps/web/dist/assets/UpdateCheck-CfXZBQNv.js +0 -2
  243. package/apps/web/dist/assets/changelog-6MqC8Vy8.js +0 -1
  244. package/apps/web/dist/assets/circle-alert-C8Ma-bPY.js +0 -1
  245. package/apps/web/dist/assets/circle-check-Bu9Z3mlJ.js +0 -1
  246. package/apps/web/dist/assets/code-editor-CfTGqOpp.js +0 -2
  247. package/apps/web/dist/assets/code-xml-B4kLFZSj.js +0 -1
  248. package/apps/web/dist/assets/connection-sign-in-B2D0O8W-.js +0 -1
  249. package/apps/web/dist/assets/dist-EBVTpvRr.js +0 -10
  250. package/apps/web/dist/assets/eye-BpoKpIdt.js +0 -1
  251. package/apps/web/dist/assets/host-BlKXX7YK.js +0 -118
  252. package/apps/web/dist/assets/i18n-BJ7Ld6O6.js +0 -55
  253. package/apps/web/dist/assets/index-66tE1oti.js +0 -10
  254. package/apps/web/dist/assets/index-D18DvnxX.css +0 -1
  255. package/apps/web/dist/assets/oss-credits-IdX5bc71.js +0 -1
  256. package/apps/web/dist/assets/phone-Ctvf-Am-.js +0 -1
  257. package/apps/web/dist/assets/read-aloud-Da_RSm2S.js +0 -1
  258. package/apps/web/dist/assets/scroll-text-ChrjRu9Y.js +0 -1
  259. package/apps/web/dist/assets/session-SXPtTWRK.js +0 -2
  260. package/apps/web/dist/assets/theme-Br1S0j5h.js +0 -11
  261. package/apps/web/dist/assets/ui-Uqnx1UpK.js +0 -82
  262. package/apps/web/dist/assets/upload-BchUnQGV.js +0 -1
  263. package/apps/web/dist/assets/volume-2-CU_oy81Z.js +0 -1
@@ -0,0 +1,937 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { and, asc, desc, eq, inArray, like } from "drizzle-orm";
3
+ import { nanoid } from "nanoid";
4
+ import { db, schema } from "../db/client.js";
5
+ import { loadedPlugins, pluginsOf } from "../plugins/registry.js";
6
+ import { currentTenant } from "../tenants/tenant.js";
7
+ import { requireWritableSpace } from "./access.js";
8
+ import { notFound, ServiceError } from "./errors.js";
9
+ import { pageTree } from "./knowledge.js";
10
+ import { placeItem } from "./space-data.js";
11
+ import { originData } from "./space-origin.js";
12
+ /** How many entries a source lists at most; a run reads the first 200 of them. */
13
+ export const MAX_FOUND = 1000;
14
+ export const MAX_RUN = 200;
15
+ /** Below the source's folder, folders go this deep; deeper paths stand in the last one. */
16
+ const MAX_DEPTH = 4;
17
+ export const originOf = (sourceId) => `source:${sourceId}`;
18
+ const ROOT = "root";
19
+ const dirKey = (path) => `dir:${path.join("/")}`;
20
+ /** What the core's own kinds are written as, in place of a plugin. */
21
+ export const CORE = "core";
22
+ /** The core's own kinds („Aus Dateien übernehmen“), each with when a tenant has it. */
23
+ const coreKinds = new Map();
24
+ export function registerCoreSource(source, on) {
25
+ coreKinds.set(source.kind, { source, on });
26
+ }
27
+ export const isCoreKind = (kind) => coreKinds.has(kind);
28
+ /** The kinds of the current tenant: the core's that are on, then its plugins'. */
29
+ export async function kindsOf() {
30
+ const core = [];
31
+ for (const { source, on } of coreKinds.values()) {
32
+ if (await on()) {
33
+ core.push({ plugin: CORE, source });
34
+ }
35
+ }
36
+ return [
37
+ ...core,
38
+ ...(await pluginsOf(currentTenant())).flatMap((plugin) => [...plugin.knowledgeSources.values()].map((source) => ({ plugin: plugin.source.id, source }))),
39
+ ];
40
+ }
41
+ /** A source's kind, wherever its plugin is loaded: null when the plugin is gone. */
42
+ function kindOfRow(row) {
43
+ if (row.plugin === CORE) {
44
+ const core = coreKinds.get(row.kind);
45
+ return core ? { plugin: CORE, source: core.source } : null;
46
+ }
47
+ const plugin = loadedPlugins().find((p) => p.source.id === row.plugin);
48
+ const source = plugin?.knowledgeSources.get(row.kind);
49
+ return plugin && source ? { plugin: plugin.source.id, source } : null;
50
+ }
51
+ /** The rule an address falls under; null when none does. Case does not matter. */
52
+ export function ruleFor(address, rules) {
53
+ const a = address.toLowerCase();
54
+ for (const rule of rules) {
55
+ const p = rule.pattern.toLowerCase().trim();
56
+ if (!p) {
57
+ continue;
58
+ }
59
+ if (p.includes("*")) {
60
+ const re = new RegExp(`^${p
61
+ .split("*")
62
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
63
+ .join(".*")}$`);
64
+ if (re.test(a) || re.test(a.replace(/[?#].*$/, ""))) {
65
+ return rule;
66
+ }
67
+ }
68
+ else if (a.includes(p)) {
69
+ return rule;
70
+ }
71
+ }
72
+ return null;
73
+ }
74
+ // --- rows -----------------------------------------------------------------------------------
75
+ async function sourceRow(spaceId, sourceId) {
76
+ const row = await db.query.spaceSource.findFirst({
77
+ where: and(eq(schema.spaceSource.id, sourceId), eq(schema.spaceSource.spaceId, spaceId)),
78
+ });
79
+ if (!row) {
80
+ throw notFound();
81
+ }
82
+ return row;
83
+ }
84
+ async function updateSource(sourceId, patch) {
85
+ await db
86
+ .update(schema.spaceSource)
87
+ .set({ ...patch, updatedAt: new Date() })
88
+ .where(eq(schema.spaceSource.id, sourceId));
89
+ }
90
+ async function updateEntry(entryId, patch) {
91
+ await db
92
+ .update(schema.spaceSourceEntry)
93
+ .set({ ...patch, updatedAt: new Date() })
94
+ .where(eq(schema.spaceSourceEntry.id, entryId));
95
+ }
96
+ async function entriesOf(sourceId) {
97
+ return db.query.spaceSourceEntry.findMany({
98
+ where: eq(schema.spaceSourceEntry.sourceId, sourceId),
99
+ orderBy: [asc(schema.spaceSourceEntry.address)],
100
+ });
101
+ }
102
+ const infoOf = (row) => ({
103
+ id: row.id,
104
+ space: row.spaceId,
105
+ kind: row.kind,
106
+ address: row.address,
107
+ label: row.label,
108
+ rules: row.rules,
109
+ });
110
+ /** The page that is a source's folder; null before it is taken or when it was removed. */
111
+ async function folderOf(row) {
112
+ return ((await db.query.spacePage.findFirst({
113
+ where: and(eq(schema.spacePage.spaceId, row.spaceId), eq(schema.spacePage.origin, originOf(row.id)), eq(schema.spacePage.originKey, ROOT)),
114
+ columns: { id: true, parentId: true },
115
+ })) ?? null);
116
+ }
117
+ export async function sourceView(row) {
118
+ return {
119
+ ...infoOf(row),
120
+ plugin: row.plugin,
121
+ state: row.state,
122
+ everyHours: row.everyHours,
123
+ token: row.token,
124
+ status: row.status,
125
+ error: row.error,
126
+ lastRunAt: row.lastRunAt?.toISOString() ?? null,
127
+ folderId: (await folderOf(row))?.id ?? null,
128
+ };
129
+ }
130
+ const entryView = (e) => ({
131
+ id: e.id,
132
+ address: e.address,
133
+ title: e.title,
134
+ path: e.path,
135
+ included: e.included,
136
+ reason: e.reason,
137
+ decidedBy: e.decidedBy,
138
+ status: e.status,
139
+ result: e.result,
140
+ note: e.note,
141
+ updatedAt: e.updatedAt.toISOString(),
142
+ });
143
+ /**
144
+ * Takes in what a source holds now: new addresses come in under the rules (a rule leaves one
145
+ * out, with its reason), known ones keep what a person decided. Returns the entries that are no
146
+ * longer there.
147
+ */
148
+ async function mergeFound(row, found, opts = {}) {
149
+ const known = await entriesOf(row.id);
150
+ const byAddress = new Map(known.map((e) => [e.address, e]));
151
+ for (const f of found.slice(0, MAX_FOUND)) {
152
+ const path = (f.path ?? []).map((p) => p.trim().slice(0, 120)).filter(Boolean);
153
+ const was = byAddress.get(f.address);
154
+ if (was) {
155
+ if ((f.title && !was.title) || path.join("/") !== was.path.join("/")) {
156
+ await updateEntry(was.id, { title: was.title || f.title || null, path });
157
+ }
158
+ continue;
159
+ }
160
+ const rule = ruleFor(f.address, row.rules);
161
+ await db
162
+ .insert(schema.spaceSourceEntry)
163
+ .values({
164
+ id: nanoid(12),
165
+ sourceId: row.id,
166
+ address: f.address.slice(0, 2000),
167
+ title: f.title?.slice(0, 300) || null,
168
+ path,
169
+ included: !rule,
170
+ reason: rule?.reason ?? null,
171
+ decidedBy: rule ? "rule" : null,
172
+ status: "new",
173
+ result: null,
174
+ note: null,
175
+ fingerprint: null,
176
+ })
177
+ .onConflictDoNothing();
178
+ }
179
+ if (opts.keepMissing) {
180
+ return [];
181
+ }
182
+ const there = new Set(found.map((f) => f.address));
183
+ return known.filter((e) => !there.has(e.address));
184
+ }
185
+ /** Runs going on in this process, by source: a source runs once at a time. */
186
+ const running = new Map();
187
+ /** Sources asked to run while they ran: they run once more after. */
188
+ const again = new Set();
189
+ async function runsOf(sourceId, limit = 5) {
190
+ const rows = await db.query.spaceSourceRun.findMany({
191
+ where: eq(schema.spaceSourceRun.sourceId, sourceId),
192
+ orderBy: [desc(schema.spaceSourceRun.startedAt)],
193
+ limit,
194
+ });
195
+ return rows.map((r) => ({
196
+ id: r.id,
197
+ startedAt: r.startedAt.toISOString(),
198
+ endedAt: r.endedAt?.toISOString() ?? null,
199
+ status: r.status,
200
+ written: r.written,
201
+ unchanged: r.unchanged,
202
+ failed: r.failed,
203
+ leftOut: r.leftOut,
204
+ log: r.log,
205
+ }));
206
+ }
207
+ /**
208
+ * A space's sources, each with its counts, what it is doing now and how its last run went (its
209
+ * log's last line, not the whole log); and the kinds the tenant's plugins bring.
210
+ */
211
+ export async function listSources(spaceId) {
212
+ const rows = await db.query.spaceSource.findMany({
213
+ where: eq(schema.spaceSource.spaceId, spaceId),
214
+ orderBy: [asc(schema.spaceSource.createdAt)],
215
+ });
216
+ const entries = rows.length
217
+ ? await db.query.spaceSourceEntry.findMany({
218
+ where: inArray(schema.spaceSourceEntry.sourceId, rows.map((r) => r.id)),
219
+ columns: { sourceId: true, included: true, status: true },
220
+ })
221
+ : [];
222
+ const sources = await Promise.all(rows.map(async (r) => {
223
+ const own = entries.filter((e) => e.sourceId === r.id && e.included);
224
+ const [last] = await runsOf(r.id, 1);
225
+ const { log, ...lastRun } = last ?? { log: [] };
226
+ return {
227
+ ...(await sourceView(r)),
228
+ available: Boolean(kindOfRow(r)),
229
+ manual: Boolean(kindOfRow(r)?.source.manual),
230
+ counts: {
231
+ entries: entries.filter((e) => e.sourceId === r.id).length,
232
+ included: own.length,
233
+ done: own.filter((e) => e.status === "done" || e.status === "kept").length,
234
+ check: own.filter((e) => e.status === "check").length,
235
+ failed: own.filter((e) => e.status === "failed").length,
236
+ },
237
+ running: running.has(r.id),
238
+ now: running.get(r.id)?.now ?? null,
239
+ lastRun: last ? { ...lastRun, lastLine: log.at(-1) ?? null } : null,
240
+ };
241
+ }));
242
+ const kinds = (await kindsOf()).map((k) => ({
243
+ kind: k.source.kind,
244
+ plugin: k.plugin,
245
+ manual: Boolean(k.source.manual),
246
+ }));
247
+ return { sources, kinds };
248
+ }
249
+ /** One source with its entries and its last runs, as its settings show it. */
250
+ export async function getSource(spaceId, sourceId) {
251
+ const row = await sourceRow(spaceId, sourceId);
252
+ const kind = kindOfRow(row);
253
+ return {
254
+ source: {
255
+ ...(await sourceView(row)),
256
+ available: Boolean(kind),
257
+ manual: Boolean(kind?.source.manual),
258
+ running: running.has(row.id),
259
+ now: running.get(row.id)?.now ?? null,
260
+ },
261
+ entries: (await entriesOf(row.id)).map(entryView),
262
+ runs: await runsOf(row.id),
263
+ };
264
+ }
265
+ export async function proposalOf(row) {
266
+ const entries = await entriesOf(row.id);
267
+ return {
268
+ id: row.id,
269
+ label: row.label,
270
+ kind: row.kind,
271
+ plugin: row.plugin,
272
+ address: row.address,
273
+ state: row.state,
274
+ found: entries.length,
275
+ included: entries.filter((e) => e.included).length,
276
+ leftOut: entries
277
+ .filter((e) => !e.included)
278
+ .slice(0, 6)
279
+ .map((e) => ({ title: e.title || e.address, reason: e.reason ?? "" })),
280
+ categories: row.categories.map((c) => ({
281
+ name: c.name,
282
+ type: c.type,
283
+ ...(c.unit ? { unit: c.unit } : {}),
284
+ ...(c.hint ? { hint: c.hint } : {}),
285
+ })),
286
+ folderId: (await folderOf(row))?.id ?? null,
287
+ };
288
+ }
289
+ /** What a source is called before anyone named it: the folder's name, the site and its path. */
290
+ function nameOf(address) {
291
+ try {
292
+ const url = new URL(address);
293
+ return `${url.host.replace(/^www\./, "")}${url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "")}`;
294
+ }
295
+ catch {
296
+ return address.replace(/\/+$/, "").split(/[/\\]/).pop() || address;
297
+ }
298
+ }
299
+ /** The kind that takes what a person named: the one asked for, else the first that matches. */
300
+ async function pickKind(address, kind) {
301
+ const kinds = await kindsOf();
302
+ if (kind) {
303
+ const k = kinds.find((x) => x.source.kind === kind);
304
+ if (!k) {
305
+ throw new ServiceError("invalid", `There is no source of the kind "${kind}".`);
306
+ }
307
+ return { kind: k, address: k.source.match?.(address) ?? address.trim() };
308
+ }
309
+ for (const k of kinds) {
310
+ const matched = k.source.match?.(address);
311
+ if (matched) {
312
+ return { kind: k, address: matched };
313
+ }
314
+ }
315
+ throw new ServiceError("invalid", "No source here reads that.", { code: "no_kind" });
316
+ }
317
+ /**
318
+ * Proposes a source of the space: lists it, leaves out by rule, and lets the kind propose a name,
319
+ * Kategorien and the entries that do not belong. Nothing is written into Knowledge before a
320
+ * person takes it. The same address again proposes anew, unless it is taken already.
321
+ */
322
+ export async function proposeSource(spaceId, input, ctx = {}) {
323
+ await requireWritableSpace(spaceId);
324
+ const signal = ctx.signal ?? new AbortController().signal;
325
+ const emit = ctx.emit ?? (() => { });
326
+ const picked = await pickKind(input.address, input.kind);
327
+ const { source: kind, plugin } = picked.kind;
328
+ const same = await db.query.spaceSource.findFirst({
329
+ where: and(eq(schema.spaceSource.spaceId, spaceId), eq(schema.spaceSource.kind, kind.kind), eq(schema.spaceSource.address, picked.address)),
330
+ });
331
+ if (same?.state === "taken") {
332
+ return proposalOf(same);
333
+ }
334
+ if (same) {
335
+ await db.delete(schema.spaceSource).where(eq(schema.spaceSource.id, same.id));
336
+ }
337
+ const id = nanoid(12);
338
+ const row = {
339
+ id,
340
+ tenantId: currentTenant(),
341
+ spaceId,
342
+ kind: kind.kind,
343
+ plugin,
344
+ address: picked.address,
345
+ label: (input.label?.trim() || nameOf(picked.address)).slice(0, 120),
346
+ state: "proposed",
347
+ rules: kind.rules ?? [],
348
+ categories: [],
349
+ everyHours: null,
350
+ token: randomBytes(18).toString("base64url"),
351
+ status: "idle",
352
+ error: null,
353
+ lastRunAt: null,
354
+ createdAt: new Date(),
355
+ updatedAt: new Date(),
356
+ };
357
+ // A source whose entries come by hand starts with the address it was named by.
358
+ let found = kind.manual ? [{ address: picked.address }] : [];
359
+ if (!kind.manual) {
360
+ try {
361
+ found = await kind.reader.list(infoOf(row), { signal, emit });
362
+ }
363
+ catch (err) {
364
+ throw new ServiceError("invalid", err.message, { code: "not_readable" });
365
+ }
366
+ if (!found.length) {
367
+ throw new ServiceError("invalid", "There is nothing to read there.", { code: "empty" });
368
+ }
369
+ }
370
+ await db.insert(schema.spaceSource).values(row);
371
+ await mergeFound(row, found);
372
+ if (kind.reader.propose) {
373
+ const entries = (await entriesOf(id)).slice(0, MAX_FOUND);
374
+ try {
375
+ const proposal = await kind.reader.propose(infoOf(row), entries.map((e) => ({
376
+ address: e.address,
377
+ title: e.title,
378
+ included: e.included,
379
+ reason: e.reason,
380
+ })), { signal, emit });
381
+ await updateSource(id, {
382
+ label: (input.label?.trim() || proposal.label?.trim() || row.label).slice(0, 120),
383
+ categories: (proposal.categories ?? []).slice(0, 7).map((c) => ({
384
+ name: c.name.trim().slice(0, 80),
385
+ type: c.type,
386
+ ...(c.unit ? { unit: c.unit } : {}),
387
+ ...(c.type === "choice" && c.multiple ? { multiple: true } : {}),
388
+ ...(c.hint ? { hint: c.hint.slice(0, 120) } : {}),
389
+ ...(c.type === "choice" && c.values?.length ? { values: c.values.slice(0, 60) } : {}),
390
+ })),
391
+ });
392
+ const byAddress = new Map(entries.map((e) => [e.address, e]));
393
+ for (const out of proposal.leaveOut ?? []) {
394
+ const e = byAddress.get(out.address);
395
+ if (e?.included) {
396
+ await updateEntry(e.id, {
397
+ included: false,
398
+ reason: out.reason.slice(0, 120),
399
+ decidedBy: "model",
400
+ });
401
+ }
402
+ }
403
+ }
404
+ catch (err) {
405
+ // Without a model the source is still proposed: by its rules, without Kategorien.
406
+ if (err.code !== "no_model") {
407
+ console.warn(`[sources] ${plugin} proposes:`, err.message);
408
+ }
409
+ }
410
+ }
411
+ return proposalOf(await sourceRow(spaceId, id));
412
+ }
413
+ /**
414
+ * Takes a proposed source: its Kategorien go into the space, its folder is made (in `parentId`,
415
+ * or at the top), its first run starts.
416
+ */
417
+ export async function takeSource(spaceId, sourceId, opts = {}) {
418
+ await requireWritableSpace(spaceId);
419
+ const row = await sourceRow(spaceId, sourceId);
420
+ const kind = kindOfRow(row);
421
+ if (row.state !== "taken") {
422
+ if (row.categories.length) {
423
+ await originData(originOf(row.id)).putCategories({
424
+ space: spaceId,
425
+ categories: row.categories,
426
+ });
427
+ }
428
+ await updateSource(row.id, {
429
+ state: "taken",
430
+ everyHours: row.everyHours ?? kind?.source.everyHours ?? null,
431
+ });
432
+ const folder = await ensureFolder({ ...row, state: "taken" });
433
+ if (opts.parentId) {
434
+ await placeItem(spaceId, `p:${folder}`, opts.parentId);
435
+ }
436
+ }
437
+ startSource(row.id);
438
+ return proposalOf(await sourceRow(spaceId, row.id));
439
+ }
440
+ /** The source's folder, made when it is missing: a page named as the source, at the top. */
441
+ async function ensureFolder(row) {
442
+ const had = await folderOf(row);
443
+ if (had) {
444
+ return had.id;
445
+ }
446
+ const made = await originData(originOf(row.id)).putPage({
447
+ space: row.spaceId,
448
+ key: ROOT,
449
+ label: row.label,
450
+ title: row.label,
451
+ markdown: "",
452
+ });
453
+ return made.id;
454
+ }
455
+ // --- changing ------------------------------------------------------------------------------
456
+ export async function updateSourceSettings(spaceId, sourceId, patch) {
457
+ await requireWritableSpace(spaceId);
458
+ const row = await sourceRow(spaceId, sourceId);
459
+ await updateSource(row.id, patch);
460
+ if (patch.label && patch.label !== row.label) {
461
+ // The folder is called as the source; a person who renamed it keeps their name.
462
+ const folder = await folderOf(row);
463
+ if (folder) {
464
+ await db
465
+ .update(schema.spacePage)
466
+ .set({ title: patch.label, originLabel: patch.label, updatedAt: new Date() })
467
+ .where(and(eq(schema.spacePage.id, folder.id), eq(schema.spacePage.kept, false)));
468
+ }
469
+ }
470
+ return sourceView(await sourceRow(spaceId, row.id));
471
+ }
472
+ /** The eye: a person leaves an entry out of Knowledge, or takes it in again. */
473
+ export async function setEntryIncluded(spaceId, sourceId, entryId, included) {
474
+ await requireWritableSpace(spaceId);
475
+ const row = await sourceRow(spaceId, sourceId);
476
+ const e = await db.query.spaceSourceEntry.findFirst({
477
+ where: and(eq(schema.spaceSourceEntry.id, entryId), eq(schema.spaceSourceEntry.sourceId, row.id)),
478
+ });
479
+ if (!e) {
480
+ throw notFound();
481
+ }
482
+ await updateEntry(e.id, {
483
+ included,
484
+ reason: included ? null : "Von Hand",
485
+ decidedBy: "person",
486
+ });
487
+ if (row.state === "taken") {
488
+ startSource(row.id, [e.id]);
489
+ }
490
+ return entryView({ ...e, included });
491
+ }
492
+ /** Adds addresses to a source whose entries come by hand, and reads them. */
493
+ export async function addSourceEntries(spaceId, sourceId, addresses) {
494
+ await requireWritableSpace(spaceId);
495
+ const row = await sourceRow(spaceId, sourceId);
496
+ await mergeFound(row, addresses.map((address) => ({ address })), { keepMissing: true });
497
+ if (row.state === "taken") {
498
+ startSource(row.id);
499
+ }
500
+ return (await entriesOf(row.id)).map(entryView);
501
+ }
502
+ /**
503
+ * Removes a source and what it wrote. What a person took over stays, as theirs: it moves to where
504
+ * the source's folder stood.
505
+ */
506
+ export async function removeSource(spaceId, sourceId) {
507
+ await requireWritableSpace(spaceId);
508
+ const row = await sourceRow(spaceId, sourceId);
509
+ stopSource(row.id);
510
+ const origin = originOf(row.id);
511
+ const folder = await folderOf(row);
512
+ const parentId = folder?.parentId ?? null;
513
+ const kept = await Promise.all([
514
+ db.query.spacePage.findMany({
515
+ where: and(eq(schema.spacePage.origin, origin), eq(schema.spacePage.kept, true)),
516
+ columns: { id: true },
517
+ }),
518
+ db.query.spaceTable.findMany({
519
+ where: and(eq(schema.spaceTable.origin, origin), eq(schema.spaceTable.kept, true)),
520
+ columns: { id: true },
521
+ }),
522
+ ]);
523
+ const tree = await pageTree(spaceId);
524
+ for (const page of kept[0]) {
525
+ // Out of the folders that go; a kept page under another kept page stays under it.
526
+ const parent = tree.get(page.id)?.parentId;
527
+ if (!parent || !kept[0].some((k) => k.id === parent)) {
528
+ await placeItem(spaceId, `p:${page.id}`, parentId);
529
+ }
530
+ }
531
+ for (const table of kept[1]) {
532
+ await placeItem(spaceId, `t:${table.id}`, parentId);
533
+ }
534
+ for (const table of [schema.spacePage, schema.spaceTable]) {
535
+ await db
536
+ .update(table)
537
+ .set({ origin: null, originKey: null })
538
+ .where(and(eq(table.origin, origin), eq(table.kept, true)));
539
+ }
540
+ await originData(origin).remove(spaceId);
541
+ await db.delete(schema.spaceSource).where(eq(schema.spaceSource.id, row.id));
542
+ }
543
+ /**
544
+ * „Als eigene Seite übernehmen“: a page or table a source wrote becomes the space's own. The
545
+ * source no longer writes it, and it stays when the source goes.
546
+ */
547
+ export async function keepItem(spaceId, key) {
548
+ await requireWritableSpace(spaceId);
549
+ const id = key.slice(2);
550
+ const table = key[0] === "p" ? schema.spacePage : key[0] === "t" ? schema.spaceTable : null;
551
+ if (!table) {
552
+ throw notFound();
553
+ }
554
+ const done = await db
555
+ .update(table)
556
+ .set({ kept: true, updatedAt: new Date() })
557
+ .where(and(eq(table.id, id), eq(table.spaceId, spaceId), like(table.origin, "source:%")))
558
+ .returning({ id: table.id });
559
+ if (!done.length) {
560
+ throw notFound();
561
+ }
562
+ }
563
+ // --- running ---------------------------------------------------------------------------------
564
+ export const isRunning = (sourceId) => running.has(sourceId);
565
+ export function stopSource(sourceId) {
566
+ again.delete(sourceId);
567
+ running.get(sourceId)?.stop.abort();
568
+ }
569
+ const hashOf = (text) => `h:${createHash("sha256").update(text).digest("hex").slice(0, 16)}`;
570
+ /** What each entry's path is below the folder, cut to the depth folders go. */
571
+ const pathOf = (e) => e.path.slice(0, MAX_DEPTH);
572
+ /** Writes what the reader read of one entry into the source's folder. */
573
+ async function writeEntry(row, kind, e, read, dirs) {
574
+ if (read.kind === "unchanged") {
575
+ return { kind: "unchanged", status: e.status };
576
+ }
577
+ if (read.kind === "failed") {
578
+ return {
579
+ kind: "failed",
580
+ status: "failed",
581
+ note: read.note.slice(0, 300),
582
+ fingerprint: read.fingerprint ?? null,
583
+ };
584
+ }
585
+ const data = originData(originOf(row.id));
586
+ const path = pathOf(e);
587
+ // The source's own folder's text: a README at the top of what it reads.
588
+ const isRoot = read.kind === "page" && path.length === 0 && Boolean(read.folder);
589
+ // A page whose path is a folder of others is that folder's text.
590
+ const isDir = read.kind === "page" && path.length > 0 && dirs.has(path.join("/"));
591
+ // The last part of its path is its own name.
592
+ const where = path.slice(0, -1);
593
+ const parent = where.length ? dirKey(where) : ROOT;
594
+ if (read.kind === "page") {
595
+ const fingerprint = read.fingerprint ?? hashOf(read.markdown);
596
+ if (e.result && e.status !== "failed" && fingerprint === e.fingerprint) {
597
+ return { kind: "unchanged", status: e.status };
598
+ }
599
+ const key = isRoot ? ROOT : isDir ? dirKey(path) : `e:${e.id}`;
600
+ const put = await data.putPage({
601
+ space: row.spaceId,
602
+ key,
603
+ label: row.label,
604
+ ...(isRoot ? {} : { parent }),
605
+ // A folder's text keeps the folder's name: the source's, its path's last part.
606
+ title: isRoot
607
+ ? row.label
608
+ : isDir && read.folder
609
+ ? titleOfSegment(path[path.length - 1])
610
+ : read.title,
611
+ markdown: read.markdown.slice(0, 190_000),
612
+ images: read.images,
613
+ fill: kind.fill,
614
+ });
615
+ if (put.state === "kept") {
616
+ return { kind: "unchanged", status: "kept", fingerprint, itemKey: key };
617
+ }
618
+ return {
619
+ kind: "written",
620
+ status: "done",
621
+ itemKey: key,
622
+ result: { kind: "page", id: put.id, path: put.path, title: read.title },
623
+ note: null,
624
+ fingerprint,
625
+ };
626
+ }
627
+ const key = `e:${e.id}`;
628
+ const doc = await data.putDocument({
629
+ space: row.spaceId,
630
+ key,
631
+ label: row.label,
632
+ name: read.name,
633
+ mime: read.mime,
634
+ data: read.data,
635
+ fill: kind.fill,
636
+ });
637
+ const folder = await db.query.spacePage.findFirst({
638
+ where: and(eq(schema.spacePage.spaceId, row.spaceId), eq(schema.spacePage.origin, originOf(row.id)), eq(schema.spacePage.originKey, parent)),
639
+ columns: { id: true },
640
+ });
641
+ if (folder) {
642
+ await placeItem(row.spaceId, `f:${doc.id}`, folder.id);
643
+ }
644
+ if (doc.state === "kept") {
645
+ return { kind: "unchanged", status: "kept", fingerprint: read.fingerprint, itemKey: key };
646
+ }
647
+ const first = doc.items[0];
648
+ return {
649
+ kind: "written",
650
+ status: doc.review ? "check" : "done",
651
+ itemKey: key,
652
+ result: first
653
+ ? { kind: first.kind, id: first.id, path: first.path, title: first.title }
654
+ : { kind: "file", id: doc.id, path: doc.path, title: read.name },
655
+ note: doc.review,
656
+ fingerprint: read.fingerprint ?? null,
657
+ };
658
+ }
659
+ /**
660
+ * The folders a source's entries stand in: made where missing, named by their path's last part.
661
+ * Folders no entry stands in any more go, unless a person took them or something stands in them.
662
+ */
663
+ async function syncFolders(row, entries) {
664
+ const data = originData(originOf(row.id));
665
+ const dirs = new Set();
666
+ for (const e of entries.filter((x) => x.included)) {
667
+ const path = pathOf(e);
668
+ for (let i = 1; i < path.length; i++) {
669
+ dirs.add(path.slice(0, i).join("/"));
670
+ }
671
+ }
672
+ // An entry whose path is a folder of others writes the folder's text.
673
+ const own = await db.query.spacePage.findMany({
674
+ where: and(eq(schema.spacePage.spaceId, row.spaceId), eq(schema.spacePage.origin, originOf(row.id)), like(schema.spacePage.originKey, "dir:%")),
675
+ columns: { id: true, originKey: true, kept: true },
676
+ });
677
+ const have = new Set(own.map((p) => p.originKey));
678
+ for (const dir of [...dirs].sort((a, b) => a.split("/").length - b.split("/").length)) {
679
+ const path = dir.split("/");
680
+ if (!have.has(dirKey(path))) {
681
+ await data.putPage({
682
+ space: row.spaceId,
683
+ key: dirKey(path),
684
+ label: row.label,
685
+ parent: path.length > 1 ? dirKey(path.slice(0, -1)) : ROOT,
686
+ title: titleOfSegment(path[path.length - 1]),
687
+ markdown: "",
688
+ });
689
+ }
690
+ }
691
+ const gone = own.filter((p) => !p.kept && !dirs.has((p.originKey ?? "").slice(4)));
692
+ if (gone.length) {
693
+ const tree = await pageTree(row.spaceId);
694
+ for (const p of gone) {
695
+ const holds = [...tree.values()].some((n) => n.parentId === p.id);
696
+ if (!holds) {
697
+ await data.remove(row.spaceId, p.originKey ?? "");
698
+ }
699
+ }
700
+ }
701
+ return dirs;
702
+ }
703
+ /** A folder's name from a part of an address: `foerder-programme` → „Foerder programme“. */
704
+ function titleOfSegment(segment) {
705
+ let s = segment;
706
+ try {
707
+ s = decodeURIComponent(segment);
708
+ }
709
+ catch { }
710
+ s = s
711
+ .replace(/\.[a-z0-9]{2,5}$/i, "")
712
+ .replace(/[-_+]+/g, " ")
713
+ .trim();
714
+ return (s.charAt(0).toUpperCase() + s.slice(1)).slice(0, 120) || segment;
715
+ }
716
+ /** Takes an entry's item out of Knowledge; a folder that holds others keeps them, without text. */
717
+ async function removeEntryItem(row, e) {
718
+ const key = e.itemKey ?? `e:${e.id}`;
719
+ const data = originData(originOf(row.id));
720
+ // The source's folder stays: only its text goes.
721
+ if (key === ROOT) {
722
+ await db
723
+ .update(schema.spacePage)
724
+ .set({ markdown: "", updatedAt: new Date() })
725
+ .where(and(eq(schema.spacePage.spaceId, row.spaceId), eq(schema.spacePage.origin, originOf(row.id)), eq(schema.spacePage.originKey, ROOT), eq(schema.spacePage.kept, false)));
726
+ return;
727
+ }
728
+ if (key.startsWith("dir:")) {
729
+ const page = await db.query.spacePage.findFirst({
730
+ where: and(eq(schema.spacePage.spaceId, row.spaceId), eq(schema.spacePage.origin, originOf(row.id)), eq(schema.spacePage.originKey, key)),
731
+ columns: { id: true, kept: true },
732
+ });
733
+ const tree = await pageTree(row.spaceId);
734
+ if (page && !page.kept && [...tree.values()].some((n) => n.parentId === page.id)) {
735
+ await db
736
+ .update(schema.spacePage)
737
+ .set({ markdown: "", updatedAt: new Date() })
738
+ .where(eq(schema.spacePage.id, page.id));
739
+ return;
740
+ }
741
+ }
742
+ await data.remove(row.spaceId, key);
743
+ }
744
+ const line = (code, ...parts) => [code, ...parts.map((p) => p.replace(/\s+/g, " ").trim())].join("\t");
745
+ /**
746
+ * Runs a source: lists it again, reads what is in and changed, takes out what was left out or
747
+ * went away. `only`: these entries alone, without listing the source again.
748
+ */
749
+ export async function runSource(sourceId, opts = {}) {
750
+ const summary = { written: 0, unchanged: 0, failed: 0, leftOut: 0 };
751
+ const row = await db.query.spaceSource.findFirst({
752
+ where: eq(schema.spaceSource.id, sourceId),
753
+ });
754
+ if (row?.state !== "taken") {
755
+ return summary;
756
+ }
757
+ if (running.has(row.id)) {
758
+ // Asked again while it reads: once more when it is done, for what changed meanwhile.
759
+ again.add(row.id);
760
+ return summary;
761
+ }
762
+ const kind = kindOfRow(row);
763
+ if (!kind) {
764
+ await updateSource(row.id, {
765
+ status: "failed",
766
+ error: row.plugin === CORE
767
+ ? `There is no source of the kind "${row.kind}" here.`
768
+ : `The plugin "${row.plugin}" that reads it is not there.`,
769
+ });
770
+ return summary;
771
+ }
772
+ const stop = new AbortController();
773
+ const now = { phase: "listing", reading: [], done: 0, of: 0 };
774
+ running.set(row.id, { stop, now });
775
+ const signal = opts.signal ? AbortSignal.any([opts.signal, stop.signal]) : stop.signal;
776
+ const ctx = { signal, emit: () => { } };
777
+ const runId = nanoid(12);
778
+ const log = [];
779
+ const save = (values) => db
780
+ .update(schema.spaceSourceRun)
781
+ .set({ ...summary, log: log.slice(-200), ...values })
782
+ .where(eq(schema.spaceSourceRun.id, runId));
783
+ await db.insert(schema.spaceSourceRun).values({
784
+ id: runId,
785
+ sourceId: row.id,
786
+ startedAt: new Date(),
787
+ status: "running",
788
+ ...summary,
789
+ log: [],
790
+ });
791
+ await updateSource(row.id, { status: "running", error: null });
792
+ try {
793
+ await ensureFolder(row);
794
+ let found = [];
795
+ if (!opts.only && !kind.source.manual) {
796
+ found = await kind.source.reader.list(infoOf(row), ctx);
797
+ const gone = await mergeFound(row, found);
798
+ for (const e of gone) {
799
+ if (e.result) {
800
+ await removeEntryItem(row, e);
801
+ }
802
+ log.push(line("gone", e.title || e.address));
803
+ }
804
+ if (gone.length) {
805
+ await db.delete(schema.spaceSourceEntry).where(inArray(schema.spaceSourceEntry.id, gone.map((e) => e.id)));
806
+ }
807
+ }
808
+ const byAddress = new Map(found.map((f) => [f.address, f]));
809
+ const all = await entriesOf(row.id);
810
+ const dirs = await syncFolders(row, all);
811
+ const entries = all.filter((e) => !opts.only || opts.only.includes(e.id));
812
+ // What was left out since it was written goes out of Knowledge.
813
+ for (const e of entries.filter((x) => !x.included && x.result)) {
814
+ await removeEntryItem(row, e);
815
+ await updateEntry(e.id, {
816
+ result: null,
817
+ itemKey: null,
818
+ status: "new",
819
+ fingerprint: null,
820
+ note: null,
821
+ });
822
+ summary.leftOut++;
823
+ }
824
+ // What the list says did not change is not read and does not count against a run's reads.
825
+ const same = (e) => {
826
+ const f = byAddress.get(e.address);
827
+ return Boolean(e.result && e.status !== "failed" && f?.fingerprint && f.fingerprint === e.fingerprint);
828
+ };
829
+ const included = entries.filter((e) => e.included);
830
+ for (const e of included.filter(same)) {
831
+ summary.unchanged++;
832
+ log.push(line("unchanged", e.result?.title ?? e.title ?? e.address));
833
+ }
834
+ const work = included.filter((e) => !same(e));
835
+ const todo = work.slice(0, MAX_RUN);
836
+ now.phase = "reading";
837
+ now.of = todo.length;
838
+ for (let i = 0; i < todo.length && !signal.aborted; i += 3) {
839
+ const batch = todo.slice(i, i + 3);
840
+ now.reading = batch.map((e) => e.title || e.address);
841
+ await Promise.all(batch.map(async (e) => {
842
+ try {
843
+ const f = byAddress.get(e.address) ?? null;
844
+ const out = await writeEntry(row, kind.source, e, await kind.source.reader.read(infoOf(row), {
845
+ id: e.id,
846
+ address: e.address,
847
+ title: e.title,
848
+ fingerprint: e.fingerprint,
849
+ found: f,
850
+ }, ctx), dirs);
851
+ summary[out.kind]++;
852
+ if (out.kind !== "unchanged" || out.status !== e.status) {
853
+ await updateEntry(e.id, {
854
+ status: out.status,
855
+ ...(out.itemKey !== undefined ? { itemKey: out.itemKey } : {}),
856
+ ...(out.result !== undefined ? { result: out.result } : {}),
857
+ ...(out.note !== undefined ? { note: out.note } : {}),
858
+ ...(out.fingerprint !== undefined ? { fingerprint: out.fingerprint } : {}),
859
+ });
860
+ }
861
+ if (out.kind === "written") {
862
+ log.push(line("read", out.result?.title ?? e.address));
863
+ }
864
+ else if (out.kind === "unchanged") {
865
+ log.push(line("unchanged", e.result?.title ?? e.title ?? e.address));
866
+ }
867
+ else {
868
+ log.push(line("failed", e.title || e.address, out.note ?? ""));
869
+ }
870
+ }
871
+ catch (err) {
872
+ if (signal.aborted) {
873
+ return;
874
+ }
875
+ summary.failed++;
876
+ const message = err.message.slice(0, 300);
877
+ log.push(line("error", e.title || e.address, message));
878
+ await updateEntry(e.id, { status: "failed", note: message });
879
+ }
880
+ }));
881
+ now.done = Math.min(i + 3, todo.length);
882
+ await save({});
883
+ }
884
+ now.phase = "finishing";
885
+ now.reading = [];
886
+ if (work.length > MAX_RUN) {
887
+ log.push(line("limit", String(MAX_RUN)));
888
+ // The core's kinds ask no model: the next reads follow at once.
889
+ if (row.plugin === CORE && !signal.aborted) {
890
+ again.add(row.id);
891
+ }
892
+ }
893
+ // The values the source filled get an Übersicht once they have three items.
894
+ if (summary.written && kind.source.fill && !signal.aborted) {
895
+ for (const c of row.categories.filter((x) => x.type === "choice")) {
896
+ await originData(originOf(row.id))
897
+ .summarize(row.spaceId, c.name)
898
+ .catch((err) => {
899
+ log.push(line("summary", c.name, err.message));
900
+ });
901
+ }
902
+ }
903
+ await save({ status: signal.aborted ? "stopped" : "done", endedAt: new Date() });
904
+ await updateSource(row.id, { status: "idle", lastRunAt: new Date() });
905
+ return summary;
906
+ }
907
+ catch (err) {
908
+ const message = err.message.slice(0, 300);
909
+ log.push(line("aborted", message));
910
+ await save({ status: "failed", endedAt: new Date() });
911
+ await updateSource(row.id, { status: "failed", error: message, lastRunAt: new Date() });
912
+ return summary;
913
+ }
914
+ finally {
915
+ running.delete(row.id);
916
+ if (again.delete(row.id)) {
917
+ startSource(row.id);
918
+ }
919
+ }
920
+ }
921
+ /** A run in the background, as a route, a signal or the schedule starts it. */
922
+ export function startSource(sourceId, only) {
923
+ void runSource(sourceId, { only }).catch((err) => console.error("[sources] run", err));
924
+ }
925
+ /** Runs the sources of a plugin's kinds whose hours are up: its turn of `every`. */
926
+ export async function runDueSources(pluginId, now = Date.now()) {
927
+ const rows = await db.query.spaceSource.findMany({
928
+ where: and(eq(schema.spaceSource.plugin, pluginId), eq(schema.spaceSource.state, "taken")),
929
+ });
930
+ for (const r of rows) {
931
+ if (r.everyHours &&
932
+ !running.has(r.id) &&
933
+ (!r.lastRunAt || now - r.lastRunAt.getTime() >= r.everyHours * 3_600_000)) {
934
+ startSource(r.id);
935
+ }
936
+ }
937
+ }