@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,367 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mergeText } from "@engenty/wizards-shared/text-merge";
3
+ import { and, eq } from "drizzle-orm";
4
+ import { nanoid } from "nanoid";
5
+ import { assertRwx, decide, forbidden } from "../broker/rwx.js";
6
+ import { db, schema } from "../db/client.js";
7
+ import { getBlob, putBlob, releaseBlob } from "../files/blobs.js";
8
+ import { notFound, ServiceError } from "../services/errors.js";
9
+ import { mountFile, mountRow, readerOf, writtenAtSource } from "./mounts.js";
10
+ /** Larger text files are replaced, not edited in the studio. */
11
+ const MAX_EDIT_BYTES = 2 * 1024 * 1024;
12
+ /** Whether a file is edited as text: Markdown and plain text. */
13
+ export function editsAsText(file) {
14
+ return (file.size <= MAX_EDIT_BYTES &&
15
+ (/^text\/(markdown|plain|x-markdown)$/.test(file.mime) ||
16
+ /\.(md|markdown|txt)$/i.test(file.name)));
17
+ }
18
+ const sha256 = (data) => createHash("sha256").update(data).digest("hex");
19
+ /** UTF-8 text, or null where the bytes are not. */
20
+ function textOf(data) {
21
+ try {
22
+ return new TextDecoder("utf-8", { fatal: true }).decode(data);
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /** The file as it stands at the source: its entry, bytes and hash, read without a change between. */
29
+ async function current(reader, path, id) {
30
+ const opts = id ? { id } : {};
31
+ for (let i = 0; i < 3; i++) {
32
+ const before = await reader.stat(path, opts);
33
+ if (!before) {
34
+ throw new ServiceError("not_found", `"${path}" is not in the folder any more.`);
35
+ }
36
+ const data = await reader.read(path, opts);
37
+ const after = await reader.stat(path, opts);
38
+ if (after && after.size === before.size && after.modified === before.modified) {
39
+ const base = {
40
+ size: after.size,
41
+ modified: after.modified,
42
+ version: after.version,
43
+ hash: sha256(data),
44
+ };
45
+ return { base, data };
46
+ }
47
+ }
48
+ throw new ServiceError("refused", `"${path}" keeps changing. Try again in a moment.`);
49
+ }
50
+ /**
51
+ * Refused unless the mount allows writing and the broker gives `who` `w` on it. A run's wizard
52
+ * never writes to a mount: what it wants changed, a person publishes.
53
+ */
54
+ async function requireWrite(spaceId, mount, who) {
55
+ if (!mount.writable) {
56
+ throw new ServiceError("read_only", "This folder is read only.");
57
+ }
58
+ if (who.some((s) => s.kind === "wizard")) {
59
+ throw forbidden({ kind: "mount", id: mount.id }, "w");
60
+ }
61
+ // An AI working for a person writes where the person may and the mount lets agents write drafts.
62
+ const agents = who.filter((s) => s.kind === "agent");
63
+ const people = who.filter((s) => s.kind !== "agent");
64
+ await assertRwx(spaceId, people, { kind: "mount", id: mount.id }, "w");
65
+ if (agents.length) {
66
+ await assertRwx(spaceId, agents, { kind: "mount", id: mount.id }, "w");
67
+ }
68
+ }
69
+ /** „Veröffentlichen“ is a person's: an AI working for one leaves drafts. */
70
+ function requirePerson(mount, who) {
71
+ if (who.some((s) => s.kind === "agent")) {
72
+ throw forbidden({ kind: "mount", id: mount.id }, "w");
73
+ }
74
+ }
75
+ async function writable(spaceId, mountId, who) {
76
+ const mount = await mountRow(spaceId, mountId, who);
77
+ await requireWrite(spaceId, mount, who);
78
+ return mount;
79
+ }
80
+ async function writableFile(spaceId, fileId, who) {
81
+ const found = await mountFile(spaceId, fileId, who);
82
+ await requireWrite(spaceId, found.mount, who);
83
+ return found;
84
+ }
85
+ const draftOf = (fileId) => db.query.spaceMountDraft.findFirst({ where: eq(schema.spaceMountDraft.fileId, fileId) });
86
+ const viewOf = (draft) => ({
87
+ edit: draft.blob ? "replace" : "text",
88
+ draft: true,
89
+ text: draft.text,
90
+ baseText: draft.baseText,
91
+ base: draft.base,
92
+ conflict: draft.conflict ? { text: draft.conflict.text ?? null } : null,
93
+ updatedAt: draft.updatedAt.toISOString(),
94
+ updatedBy: draft.updatedBy,
95
+ });
96
+ /** The draft of a file, else the file as it stands now, to edit. */
97
+ export async function openDraft(spaceId, fileId, who) {
98
+ const { mount, file } = await writableFile(spaceId, fileId, who);
99
+ const draft = await draftOf(file.id);
100
+ if (draft) {
101
+ return viewOf(draft);
102
+ }
103
+ const text = editsAsText(file);
104
+ const now = text ? await current(await readerOf(mount), file.path, file.sourceId) : null;
105
+ const words = now ? textOf(now.data) : null;
106
+ if (now && words !== null) {
107
+ return {
108
+ edit: "text",
109
+ draft: false,
110
+ text: words,
111
+ baseText: words,
112
+ base: now.base,
113
+ conflict: null,
114
+ updatedAt: null,
115
+ updatedBy: null,
116
+ };
117
+ }
118
+ const stat = await (await readerOf(mount)).stat(file.path, file.sourceId ? { id: file.sourceId } : {});
119
+ return {
120
+ edit: "replace",
121
+ draft: false,
122
+ text: null,
123
+ baseText: null,
124
+ base: { size: stat?.size ?? 0, modified: stat?.modified ?? 0, version: null, hash: "" },
125
+ conflict: null,
126
+ updatedAt: null,
127
+ updatedBy: null,
128
+ };
129
+ }
130
+ /**
131
+ * Keeps a text as the file's draft. The first save names the file as it was opened (`base`, with
132
+ * its text); later ones keep the draft's base. Back to the text it was read as, the draft goes.
133
+ */
134
+ export async function saveDraft(userId, spaceId, fileId, who, input) {
135
+ const { mount, file } = await writableFile(spaceId, fileId, who);
136
+ if (!editsAsText(file)) {
137
+ throw new ServiceError("invalid", `"${file.name}" is not edited as text.`);
138
+ }
139
+ const draft = await draftOf(file.id);
140
+ const d = schema.spaceMountDraft;
141
+ if (draft) {
142
+ if (draft.blob) {
143
+ throw new ServiceError("refused", `"${file.name}" has a replacement waiting.`);
144
+ }
145
+ if (input.text === draft.baseText && !draft.conflict) {
146
+ await db.delete(d).where(eq(d.id, draft.id));
147
+ return null;
148
+ }
149
+ await db
150
+ .update(d)
151
+ .set({ text: input.text, updatedBy: userId, updatedAt: new Date() })
152
+ .where(eq(d.id, draft.id));
153
+ return viewOf((await draftOf(file.id)));
154
+ }
155
+ const { base, baseText } = input;
156
+ if (!base || baseText === undefined || sha256(Buffer.from(baseText)) !== base.hash) {
157
+ throw new ServiceError("invalid", "The draft needs the file as it was opened.");
158
+ }
159
+ if (input.text === baseText) {
160
+ return null;
161
+ }
162
+ await db.insert(d).values({
163
+ id: nanoid(12),
164
+ spaceId,
165
+ mountId: mount.id,
166
+ fileId: file.id,
167
+ base,
168
+ text: input.text,
169
+ baseText,
170
+ mime: file.mime,
171
+ createdBy: userId,
172
+ updatedBy: userId,
173
+ });
174
+ return viewOf((await draftOf(file.id)));
175
+ }
176
+ /** Keeps an upload as the file's draft: it replaces the file as it stands now. */
177
+ export async function replaceDraft(userId, spaceId, fileId, who, data, mime) {
178
+ const { mount, file } = await writableFile(spaceId, fileId, who);
179
+ const old = await draftOf(file.id);
180
+ const { base } = old?.blob ? old : await current(await readerOf(mount), file.path, file.sourceId);
181
+ const blob = await putBlob(data);
182
+ const d = schema.spaceMountDraft;
183
+ if (old) {
184
+ await db
185
+ .update(d)
186
+ .set({
187
+ base,
188
+ text: null,
189
+ baseText: null,
190
+ blob,
191
+ mime,
192
+ updatedBy: userId,
193
+ updatedAt: new Date(),
194
+ })
195
+ .where(eq(d.id, old.id));
196
+ if (old.blob !== blob) {
197
+ await releaseBlob(old.blob);
198
+ }
199
+ }
200
+ else {
201
+ await db.insert(d).values({
202
+ id: nanoid(12),
203
+ spaceId,
204
+ mountId: mount.id,
205
+ fileId: file.id,
206
+ base,
207
+ blob,
208
+ mime,
209
+ createdBy: userId,
210
+ updatedBy: userId,
211
+ });
212
+ }
213
+ return viewOf((await draftOf(file.id)));
214
+ }
215
+ async function dropDraft(draft) {
216
+ await db.delete(schema.spaceMountDraft).where(eq(schema.spaceMountDraft.id, draft.id));
217
+ await releaseBlob(draft.blob);
218
+ }
219
+ /** Throws the draft away: „Verwerfen“, and „Ihre übernehmen“ in a conflict. */
220
+ export async function discardDraft(spaceId, fileId, who) {
221
+ const { file } = await writableFile(spaceId, fileId, who);
222
+ const draft = await draftOf(file.id);
223
+ if (draft) {
224
+ await dropDraft(draft);
225
+ }
226
+ }
227
+ const isConflict = (err) => err?.code === "conflict";
228
+ /**
229
+ * Writes a draft to the source with the version it was read at. A change there meanwhile: a text
230
+ * is merged with it and written when clean; else the draft keeps what stands there now.
231
+ */
232
+ async function publish(mount, file, draft) {
233
+ const reader = await readerOf(mount);
234
+ const id = file.sourceId ? { id: file.sourceId } : {};
235
+ const d = schema.spaceMountDraft;
236
+ let row = draft;
237
+ let merged = false;
238
+ for (let attempt = 0; attempt < 4; attempt++) {
239
+ const data = row.blob ? await getBlob(row.blob) : Buffer.from(row.text ?? "");
240
+ const expected = {
241
+ path: file.path,
242
+ size: row.base.size,
243
+ modified: row.base.modified,
244
+ version: row.base.version,
245
+ ...id,
246
+ };
247
+ let entry = null;
248
+ // A source without versions (a folder) is checked by the bytes as well: its time and size
249
+ // can stay the same through a change.
250
+ const stale = row.base.version === null &&
251
+ sha256(await reader.read(file.path, id).catch(() => new Uint8Array())) !== row.base.hash;
252
+ if (!stale) {
253
+ try {
254
+ entry = await reader.write(file.path, data, expected);
255
+ }
256
+ catch (err) {
257
+ if (!isConflict(err)) {
258
+ throw err;
259
+ }
260
+ }
261
+ }
262
+ if (entry) {
263
+ await dropDraft(row);
264
+ await writtenAtSource(file.id, entry);
265
+ return { ok: true, merged };
266
+ }
267
+ const now = await current(reader, file.path, file.sourceId);
268
+ const theirs = row.blob ? null : textOf(now.data);
269
+ if (row.text !== null && row.baseText !== null && theirs !== null) {
270
+ const merge = mergeText(row.baseText, row.text, theirs);
271
+ if (merge.clean) {
272
+ await db
273
+ .update(d)
274
+ .set({ base: now.base, text: merge.text, baseText: theirs, conflict: null })
275
+ .where(eq(d.id, row.id));
276
+ row = (await draftOf(file.id));
277
+ merged = true;
278
+ continue;
279
+ }
280
+ }
281
+ await db
282
+ .update(d)
283
+ .set({ conflict: { ...now.base, ...(theirs !== null ? { text: theirs } : {}) } })
284
+ .where(eq(d.id, row.id));
285
+ return { ok: false, conflict: { text: theirs } };
286
+ }
287
+ throw new ServiceError("refused", `"${file.path}" keeps changing. Try again in a moment.`);
288
+ }
289
+ /** „Veröffentlichen“ for one file's draft. */
290
+ export async function publishDraft(spaceId, fileId, who) {
291
+ const { mount, file } = await writableFile(spaceId, fileId, who);
292
+ requirePerson(mount, who);
293
+ const draft = await draftOf(file.id);
294
+ if (!draft) {
295
+ throw notFound();
296
+ }
297
+ if (draft.conflict) {
298
+ return { ok: false, conflict: { text: draft.conflict.text ?? null } };
299
+ }
300
+ return publish(mount, file, draft);
301
+ }
302
+ /**
303
+ * „Meine behalten“: the draft over what stands at the source now. It takes the source's version
304
+ * as its base and is written; changed there once more, the conflict comes back.
305
+ */
306
+ export async function keepMine(spaceId, fileId, who) {
307
+ const { mount, file } = await writableFile(spaceId, fileId, who);
308
+ requirePerson(mount, who);
309
+ const draft = await draftOf(file.id);
310
+ if (!draft?.conflict) {
311
+ throw notFound();
312
+ }
313
+ const { text, ...base } = draft.conflict;
314
+ const d = schema.spaceMountDraft;
315
+ await db
316
+ .update(d)
317
+ .set({ base, baseText: text ?? draft.baseText, conflict: null, updatedAt: new Date() })
318
+ .where(eq(d.id, draft.id));
319
+ return publish(mount, file, (await draftOf(file.id)));
320
+ }
321
+ /** A mount's drafts, for whom may write it; none where it is read only. */
322
+ export async function mountDrafts(spaceId, mountId, who) {
323
+ const mount = await mountRow(spaceId, mountId, who);
324
+ if (!mount.writable || !(await decide(spaceId, who, { kind: "mount", id: mount.id }, "w")).ok) {
325
+ return [];
326
+ }
327
+ const rows = await db
328
+ .select({
329
+ fileId: schema.spaceMountDraft.fileId,
330
+ path: schema.spaceMountFile.path,
331
+ conflict: schema.spaceMountDraft.conflict,
332
+ updatedAt: schema.spaceMountDraft.updatedAt,
333
+ updatedBy: schema.spaceMountDraft.updatedBy,
334
+ })
335
+ .from(schema.spaceMountDraft)
336
+ .innerJoin(schema.spaceMountFile, eq(schema.spaceMountFile.id, schema.spaceMountDraft.fileId))
337
+ .where(eq(schema.spaceMountDraft.mountId, mount.id));
338
+ return rows
339
+ .map((r) => ({ ...r, conflict: r.conflict !== null, updatedAt: r.updatedAt.toISOString() }))
340
+ .sort((a, b) => a.path.localeCompare(b.path));
341
+ }
342
+ /** „Veröffentlichen“ for every draft of a mount that has no conflict. */
343
+ export async function publishMount(spaceId, mountId, who) {
344
+ const mount = await writable(spaceId, mountId, who);
345
+ requirePerson(mount, who);
346
+ const drafts = await db.query.spaceMountDraft.findMany({
347
+ where: eq(schema.spaceMountDraft.mountId, mount.id),
348
+ });
349
+ let published = 0;
350
+ const conflicts = [];
351
+ for (const draft of drafts.filter((x) => !x.conflict)) {
352
+ const file = await db.query.spaceMountFile.findFirst({
353
+ where: and(eq(schema.spaceMountFile.id, draft.fileId), eq(schema.spaceMountFile.mountId, mount.id)),
354
+ });
355
+ if (!file) {
356
+ continue;
357
+ }
358
+ const result = await publish(mount, file, draft);
359
+ if (result.ok) {
360
+ published++;
361
+ }
362
+ else {
363
+ conflicts.push(file.id);
364
+ }
365
+ }
366
+ return { published, conflicts };
367
+ }
@@ -0,0 +1,148 @@
1
+ import { watch } from "node:fs";
2
+ import { mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises";
3
+ import { dirname, join, relative, resolve, sep } from "node:path";
4
+ /**
5
+ * A folder on this computer as a mount: the first kind of Dateien. Its files are listed and read
6
+ * where they are; `fs.watch` tells of changes (recursive on macOS, Windows and Linux), and the
7
+ * runtime lists the whole tree again at start and hourly for what a watcher misses.
8
+ */
9
+ /** Files a folder has that are nobody's content: hidden files, Office's lock files, caches. */
10
+ export function leftOut(name) {
11
+ return (name.startsWith(".") ||
12
+ name.startsWith("~$") ||
13
+ name === "Thumbs.db" ||
14
+ name === "desktop.ini" ||
15
+ name === "node_modules" ||
16
+ name.endsWith(".tmp"));
17
+ }
18
+ /** Whether a path in the mount passes through a part that is left out. */
19
+ const leftOutPath = (path) => path.split("/").some(leftOut);
20
+ export class FolderReader {
21
+ root;
22
+ /** Paths fs.watch named since the last `changes`, or null after it overflowed or failed. */
23
+ touched = new Set();
24
+ watcher = null;
25
+ turn = 0;
26
+ constructor(root) {
27
+ this.root = resolve(root);
28
+ }
29
+ /** The absolute path of a path in the mount; never outside the folder. */
30
+ full(path) {
31
+ const full = resolve(this.root, path);
32
+ if (full !== this.root && !full.startsWith(this.root + sep)) {
33
+ throw new Error(`"${path}" is outside the folder.`);
34
+ }
35
+ return full;
36
+ }
37
+ relativeOf(full) {
38
+ return relative(this.root, full).split(sep).join("/");
39
+ }
40
+ async entryOf(path) {
41
+ const s = await stat(this.full(path)).catch(() => null);
42
+ return s?.isFile()
43
+ ? { path, size: s.size, modified: Math.floor(s.mtimeMs), version: null }
44
+ : null;
45
+ }
46
+ async *list(path = "", opts = {}) {
47
+ const dirs = [this.full(path)];
48
+ while (dirs.length) {
49
+ opts.signal?.throwIfAborted();
50
+ const dir = dirs.pop();
51
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
52
+ for (const e of entries) {
53
+ if (leftOut(e.name)) {
54
+ continue;
55
+ }
56
+ const full = join(dir, e.name);
57
+ if (e.isDirectory()) {
58
+ dirs.push(full);
59
+ }
60
+ else if (e.isFile()) {
61
+ const entry = await this.entryOf(this.relativeOf(full));
62
+ if (entry) {
63
+ yield entry;
64
+ }
65
+ }
66
+ }
67
+ }
68
+ }
69
+ async changes(cursor) {
70
+ const next = String(++this.turn);
71
+ if (cursor === null) {
72
+ this.touched = new Set();
73
+ return { changed: [], gone: [], cursor: next };
74
+ }
75
+ const touched = this.touched;
76
+ this.touched = new Set();
77
+ // Another turn's cursor, or the watcher lost events: only a whole listing says it.
78
+ if (!touched || cursor !== String(this.turn - 1)) {
79
+ return { changed: [], gone: [], cursor: next, relist: true };
80
+ }
81
+ const changed = [];
82
+ const gone = [];
83
+ for (const path of touched) {
84
+ const s = await stat(this.full(path)).catch(() => null);
85
+ if (!s) {
86
+ gone.push(path);
87
+ }
88
+ else if (s.isDirectory()) {
89
+ // A folder moved in or renamed: everything under it.
90
+ for await (const entry of this.list(path)) {
91
+ changed.push(entry);
92
+ }
93
+ }
94
+ else if (s.isFile()) {
95
+ changed.push({ path, size: s.size, modified: Math.floor(s.mtimeMs), version: null });
96
+ }
97
+ }
98
+ return { changed, gone, cursor: next };
99
+ }
100
+ async read(path) {
101
+ return readFile(this.full(path));
102
+ }
103
+ stat(path) {
104
+ return this.entryOf(path);
105
+ }
106
+ async write(path, data, expected) {
107
+ const now = await this.entryOf(path);
108
+ if (expected ? !now || now.size !== expected.size || now.modified !== expected.modified : now) {
109
+ throw Object.assign(new Error(`"${path}" changed in the folder.`), { code: "conflict" });
110
+ }
111
+ const full = this.full(path);
112
+ await mkdir(dirname(full), { recursive: true });
113
+ // Written beside it and moved over it: a reader never sees half a file.
114
+ const temp = `${full}.~engenty`;
115
+ await writeFile(temp, data);
116
+ await rename(temp, full);
117
+ return (await this.entryOf(path));
118
+ }
119
+ watch(changed) {
120
+ try {
121
+ this.watcher = watch(this.root, { recursive: true }, (_event, name) => {
122
+ if (!name) {
123
+ // The system dropped events: list everything next time.
124
+ this.touched = null;
125
+ }
126
+ else {
127
+ const path = String(name).split(sep).join("/");
128
+ if (!leftOutPath(path)) {
129
+ this.touched?.add(path);
130
+ }
131
+ }
132
+ changed();
133
+ });
134
+ this.watcher.on("error", () => {
135
+ this.touched = null;
136
+ changed();
137
+ });
138
+ }
139
+ catch {
140
+ this.touched = null;
141
+ }
142
+ return () => this.close();
143
+ }
144
+ close() {
145
+ this.watcher?.close();
146
+ this.watcher = null;
147
+ }
148
+ }