@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
@@ -3,7 +3,58 @@ import ExcelJS from "exceljs";
3
3
  import { marked } from "marked";
4
4
  import TurndownService from "turndown";
5
5
  import { offlineContext } from "./chromium.js";
6
- const turndown = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced" });
6
+ /** Elements that turndown writes as blocks of their own, with blank lines around them. */
7
+ const BLOCKS = new Set([
8
+ "ADDRESS",
9
+ "ARTICLE",
10
+ "ASIDE",
11
+ "BLOCKQUOTE",
12
+ "DIV",
13
+ "DL",
14
+ "FIGCAPTION",
15
+ "FIGURE",
16
+ "FOOTER",
17
+ "H1",
18
+ "H2",
19
+ "H3",
20
+ "H4",
21
+ "H5",
22
+ "H6",
23
+ "HEADER",
24
+ "HR",
25
+ "LI",
26
+ "OL",
27
+ "P",
28
+ "PRE",
29
+ "SECTION",
30
+ "TABLE",
31
+ "UL",
32
+ ]);
33
+ const holdsBlock = (node) => [...node.childNodes].some((child) => BLOCKS.has(child.nodeName) || holdsBlock(child));
34
+ /**
35
+ * A link around blocks (a teaser: a `<div>` with a picture and a heading in one `<a>`) would come
36
+ * out with blank lines inside its brackets, which no Markdown reads as a link. Its content goes
37
+ * on one line instead: `[![Bild](…) Titel](…)`.
38
+ */
39
+ function linkBlocks(service) {
40
+ return service.addRule("blockLink", {
41
+ filter: (node) => node.nodeName === "A" && Boolean(node.getAttribute("href")) && holdsBlock(node),
42
+ replacement: (text, node) => {
43
+ const inner = text
44
+ .replace(/\s*\n+\s*/g, " ")
45
+ .replace(/(^|\s)#{1,6}\s+/g, "$1")
46
+ .trim();
47
+ if (!inner) {
48
+ return "";
49
+ }
50
+ const el = node;
51
+ const href = (el.getAttribute("href") ?? "").replace(/([()])/g, "\\$1");
52
+ const title = el.getAttribute("title");
53
+ return `[${inner}](${href}${title ? ` "${title.replace(/"/g, '\\"')}"` : ""})`;
54
+ },
55
+ });
56
+ }
57
+ const turndown = linkBlocks(new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced" }));
7
58
  export const MIME = {
8
59
  png: "image/png",
9
60
  mp4: "video/mp4",
@@ -44,6 +95,142 @@ export function htmlToMarkdown(html) {
44
95
  const body = html.match(/<body[^>]*>([\s\S]*)<\/body>/i)?.[1] ?? html;
45
96
  return turndown.turndown(body.replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<script[\s\S]*?<\/script>/gi, ""));
46
97
  }
98
+ // --- a page's content, without what every page of the site has -----------------------------
99
+ /** Elements that are a site's frame, never a page's content. */
100
+ const FRAME_TAGS = new Set([
101
+ "NAV",
102
+ "FOOTER",
103
+ "ASIDE",
104
+ "FORM",
105
+ "DIALOG",
106
+ "BUTTON",
107
+ "IFRAME",
108
+ "NOSCRIPT",
109
+ "TEMPLATE",
110
+ ]);
111
+ const FRAME_ROLES = /^(navigation|banner|contentinfo|search|dialog|alertdialog|complementary|menu|menubar)$/i;
112
+ /** Classes and ids of skip links, cookie notices, breadcrumbs and share buttons. */
113
+ const FRAME_NAMES = /(^|[\s_-])(skip-link|screen-reader-text|cookies?|consent|gdpr|borlabs|breadcrumbs?|share|sharing|social)([\s_-]|$)/i;
114
+ const within = (node, names) => {
115
+ for (let at = node.parentNode; at; at = at.parentNode) {
116
+ if (names.includes(at.nodeName)) {
117
+ return true;
118
+ }
119
+ }
120
+ return false;
121
+ };
122
+ /** An element of the site's frame: its menus, its header and footer, hidden parts, notices. */
123
+ function frame(node) {
124
+ if (FRAME_TAGS.has(node.nodeName)) {
125
+ return true;
126
+ }
127
+ // A header inside an article or the main part is the content's own heading.
128
+ if (node.nodeName === "HEADER" && !within(node, ["ARTICLE", "MAIN"])) {
129
+ return true;
130
+ }
131
+ const get = (name) => node.getAttribute?.(name) ?? "";
132
+ return (get("aria-hidden") === "true" ||
133
+ node.hasAttribute?.("hidden") ||
134
+ FRAME_ROLES.test(get("role")) ||
135
+ FRAME_NAMES.test(`${get("class")} ${get("id")}`));
136
+ }
137
+ // A rule of its own, not `remove`: turndown asks `remove` only of elements no rule converts,
138
+ // and links, pictures and headings have rules.
139
+ const content = linkBlocks(new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced" }).addRule("frame", {
140
+ filter: (node) => frame(node),
141
+ replacement: () => "",
142
+ }));
143
+ /**
144
+ * A web page's content as Markdown: its main part where it marks one (`<main>`,
145
+ * `role="main"`), else its body, without the site's frame — navigation, the site's header and
146
+ * footer, asides, forms, hidden menus, skip links, cookie notices, breadcrumbs.
147
+ */
148
+ export function htmlToContent(html) {
149
+ const main = html.match(/<main\b[^>]*>([\s\S]*)<\/main>/i)?.[1] ??
150
+ html.match(/<[a-z]+\b[^>]*\brole\s*=\s*["']main["'][^>]*>[\s\S]*/i)?.[0];
151
+ const part = main ?? html.match(/<body[^>]*>([\s\S]*)<\/body>/i)?.[1] ?? html;
152
+ return (content
153
+ .turndown(part.replace(/<(script|style|svg)\b[\s\S]*?<\/\1>/gi, ""))
154
+ // A link that held only an icon, now gone, shows nothing.
155
+ .replace(/(?<!!)\[\]\([^)\n]*\)/g, "")
156
+ .replace(/\n{3,}/g, "\n\n")
157
+ .trim());
158
+ }
159
+ /** The largest picture `srcset` offers up to this width; where all are wider, the smallest. */
160
+ const MAX_PICTURE_WIDTH = 2000;
161
+ /** Drawn smaller than this, a picture is an icon or a bullet, not content. */
162
+ const MIN_PICTURE_SIDE = 200;
163
+ /** What an address or a class says of an icon, a sprite, a spinner or a tracking pixel. */
164
+ const NO_PICTURE = /(^|[\s/_.-])(icons?|sprites?|emojis?|spinner|loader|spacer|pixel|tracking)([\s/_.-]|$)/i;
165
+ /** An attribute of a tag by its exact name: `src`, not the `src` of `data-src`. */
166
+ const attrOf = (tag, name) => tag
167
+ .match(new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"))
168
+ ?.slice(2)
169
+ .find((v) => v !== undefined) ?? "";
170
+ /** The candidate of a `srcset` to keep, with its width or its density where the set says one. */
171
+ function fromSrcset(srcset) {
172
+ const candidates = srcset
173
+ .split(/,\s+/)
174
+ .map((part) => part.trim().split(/\s+/))
175
+ .filter(([url]) => url)
176
+ .map(([url, d = "1x"]) => ({
177
+ url: url.replace(/,$/, ""),
178
+ w: d.endsWith("w") ? Number.parseInt(d, 10) : null,
179
+ x: d.endsWith("x") ? Number.parseFloat(d) : null,
180
+ }));
181
+ const wide = candidates.filter((c) => c.w).sort((a, b) => (a.w ?? 0) - (b.w ?? 0));
182
+ if (wide.length) {
183
+ const pick = wide.filter((c) => (c.w ?? 0) <= MAX_PICTURE_WIDTH).pop() ?? wide[0];
184
+ return { url: pick.url, width: pick.w, density: 1 };
185
+ }
186
+ const dense = candidates.sort((a, b) => (a.x ?? 1) - (b.x ?? 1)).pop();
187
+ return dense ? { url: dense.url, width: null, density: dense.x ?? 1 } : null;
188
+ }
189
+ /**
190
+ * A page's `<img>` tags, each pointed at one absolute address: the largest `srcset` entry up to
191
+ * 2000 px, else `src`, or what a lazy loader keeps in `data-srcset`/`data-src`. Icons, sprites,
192
+ * drawings (SVG) and pictures drawn under 200 px on their longer side go: what `htmlToMarkdown` and `htmlToContent`
193
+ * then write as `![alt](url)` is a picture of the page.
194
+ */
195
+ export function absolutePictures(html, base) {
196
+ return html.replace(/<img\b[^>]*>/gi, (tag) => {
197
+ const lazy = (name) => attrOf(tag, `data-${name}`) || attrOf(tag, `data-lazy-${name}`);
198
+ const set = fromSrcset(lazy("srcset") || attrOf(tag, "srcset"));
199
+ const plain = lazy("src") || attrOf(tag, "data-original") || attrOf(tag, "src");
200
+ const raw = set?.url || plain;
201
+ let url;
202
+ try {
203
+ url = new URL(raw.trim(), base);
204
+ }
205
+ catch {
206
+ return "";
207
+ }
208
+ const side = (name) => Number.parseInt(attrOf(tag, name), 10);
209
+ // The size it is drawn at, by its longer side, times the density `srcset` offers it in.
210
+ const drawn = Math.max(side("width") || 0, side("height") || 0) * (set?.density ?? 1);
211
+ const tiny = drawn > 0 && drawn < MIN_PICTURE_SIDE && !((set?.width ?? 0) >= MIN_PICTURE_SIDE);
212
+ if (!/^https?:$/.test(url.protocol) ||
213
+ /\.(svg|ico)$/i.test(url.pathname) ||
214
+ NO_PICTURE.test(url.pathname) ||
215
+ NO_PICTURE.test(attrOf(tag, "class")) ||
216
+ tiny) {
217
+ return "";
218
+ }
219
+ // Markdown ends an address at `)`.
220
+ const href = url.toString().replace(/\(/g, "%28").replace(/\)/g, "%29");
221
+ return `<img src="${href}" alt="${attrOf(tag, "alt").replace(/"/g, "&quot;")}">`;
222
+ });
223
+ }
224
+ /** The pictures Markdown shows, each once, in their order. */
225
+ export function picturesOf(markdown) {
226
+ const seen = new Map();
227
+ for (const m of markdown.matchAll(/!\[([^\]\n]*)\]\((https?:\/\/[^)\s]+)(?:\s+"[^"]*")?\)/g)) {
228
+ if (!seen.has(m[2])) {
229
+ seen.set(m[2], { url: m[2], alt: m[1].trim() });
230
+ }
231
+ }
232
+ return [...seen.values()];
233
+ }
47
234
  export async function htmlToPdf(html) {
48
235
  const context = await offlineContext();
49
236
  try {
@@ -42,7 +42,7 @@ const importSchema = z.object({
42
42
  publish: z.boolean().default(false),
43
43
  });
44
44
  /** Runs a call in the caller's tenant, as the caller's role. */
45
- const inTenantAs = async (who, fn) => {
45
+ export const inTenantAs = async (who, fn) => {
46
46
  try {
47
47
  return await withTenant(who.tenantId, () => asRole(who.role, fn));
48
48
  }
@@ -73,12 +73,17 @@ const tooLarge = bodyLimit({
73
73
  * The caller of an API call, signed in like an MCP client (access token or API key), with the
74
74
  * scopes the call needs; or the answer that turns it away.
75
75
  */
76
- async function caller(c, scopes) {
76
+ export async function caller(c, scopes, { clients = false } = {}) {
77
77
  const authInfo = await authenticate(c.req.raw);
78
78
  if (authInfo instanceof Response) {
79
79
  return authInfo;
80
80
  }
81
81
  const who = principalOf(authInfo);
82
+ // A client of the organization uses its client spaces' elements, nothing else of the API
83
+ // (docs/plans/client-spaces.md).
84
+ if (who.role === "client" && !clients) {
85
+ return c.json({ error: "This isn’t open to clients.", code: "forbidden" }, 403);
86
+ }
82
87
  if (scopes.some((scope) => !who.scopes.includes(scope))) {
83
88
  return c.json({ error: "This token isn’t allowed to do that.", code: "insufficient_scope" }, 403);
84
89
  }
@@ -0,0 +1,164 @@
1
+ import { Hono } from "hono";
2
+ import { z } from "zod";
3
+ import { clientOf } from "../clients.js";
4
+ import { clientChatMessages, clientChatPost, clientChats, clientFile, clientFileInfo, clientFiles, clientForYou, clientMe, clientOpenRun, clientResults, clientSpaces, clientStartWizard, clientWizards, } from "../services/client-portal.js";
5
+ import { caller, inTenantAs } from "./api.js";
6
+ import { notFoundAnswer } from "./lang.js";
7
+ const none = z.object({});
8
+ export const CLIENT_CALLS = {
9
+ me: {
10
+ scope: "data:read",
11
+ space: false,
12
+ description: "Who you are, and the organization you are a client of.",
13
+ input: none,
14
+ run: (who) => clientMe(who),
15
+ },
16
+ spaces: {
17
+ scope: "data:read",
18
+ space: false,
19
+ description: "Your client spaces, each with the firm's space and its brand.",
20
+ input: none,
21
+ run: (who) => clientSpaces(who),
22
+ },
23
+ for_you: {
24
+ scope: "data:read",
25
+ space: true,
26
+ description: "What waits for you in a client space: your runs waiting on a page or an answer, results the firm shared, the wizards you can start.",
27
+ input: none,
28
+ run: (who, spaceId) => clientForYou(who, spaceId),
29
+ },
30
+ wizards: {
31
+ scope: "elements:read",
32
+ space: true,
33
+ description: "The firm's wizards you can start in a client space, each with its engenty (`avatar`) and its number of steps.",
34
+ input: none,
35
+ run: (who, spaceId) => clientWizards(who, spaceId),
36
+ },
37
+ wizard_start: {
38
+ scope: "elements:run",
39
+ space: true,
40
+ description: "Starts one of those wizards in the client space. Gives the run and its ticket for the run's own routes.",
41
+ input: z.object({ wizardId: z.string().min(1).max(64) }),
42
+ run: (who, spaceId, input) => clientStartWizard(who, spaceId, input.wizardId),
43
+ },
44
+ results: {
45
+ scope: "data:read",
46
+ space: true,
47
+ description: "The finished runs of a client space you see: yours, and those the firm shared.",
48
+ input: none,
49
+ run: (who, spaceId) => clientResults(who, spaceId),
50
+ },
51
+ run_open: {
52
+ scope: "data:read",
53
+ space: false,
54
+ description: "One run you see, by its id: a ticket its own routes open with (`?rt=`), and its client space.",
55
+ input: z.object({ runId: z.string().min(1).max(64) }),
56
+ run: (who, _spaceId, input) => clientOpenRun(who, input.runId),
57
+ },
58
+ chats: {
59
+ scope: "data:read",
60
+ space: true,
61
+ description: "The chats of a client space you are a member of.",
62
+ input: none,
63
+ run: (who, spaceId) => clientChats(who, spaceId),
64
+ },
65
+ chat_messages: {
66
+ scope: "data:read",
67
+ space: false,
68
+ description: "One of your chats, by its id: who wrote what, its text and the AI's views and runs as parts in order, and its client space.",
69
+ input: z.object({ chatId: z.string().min(1).max(64) }),
70
+ run: (who, _spaceId, input) => clientChatMessages(who, input.chatId),
71
+ },
72
+ chat_post: {
73
+ scope: "elements:run",
74
+ space: true,
75
+ description: "Writes in one of your chats, or starts a new one. The firm's AI answers every message; the firm's people read the chat too.",
76
+ input: z.object({
77
+ chatId: z.string().min(1).max(64).optional(),
78
+ text: z.string().trim().min(1).max(20_000),
79
+ }),
80
+ run: (who, spaceId, input) => clientChatPost(who, spaceId, input),
81
+ },
82
+ files: {
83
+ scope: "data:read",
84
+ space: true,
85
+ description: "The files of a client space. One file's bytes: GET /client/files/:fileId.",
86
+ input: none,
87
+ run: (who, spaceId) => clientFiles(who, spaceId),
88
+ },
89
+ file: {
90
+ scope: "data:read",
91
+ space: false,
92
+ description: "One file you see, by its id: what it is, and its client space.",
93
+ input: z.object({ fileId: z.string().min(1).max(64) }),
94
+ run: (who, _spaceId, input) => clientFileInfo(who, input.fileId),
95
+ },
96
+ };
97
+ const CALLS = CLIENT_CALLS;
98
+ const callBody = z.object({ input: z.record(z.string(), z.unknown()).default({}) });
99
+ /** The token's person as the services know a client, or the answer that turns the call away. */
100
+ async function clientWho(c, scope) {
101
+ const who = await caller(c, [scope], { clients: true });
102
+ if (who instanceof Response) {
103
+ return who;
104
+ }
105
+ if (who.role !== "client") {
106
+ return c.json({ error: "This is for clients of the organization.", code: "clients_only" }, 403);
107
+ }
108
+ return {
109
+ who: {
110
+ id: who.userId,
111
+ tenantId: who.tenantId,
112
+ role: who.role,
113
+ name: who.name ?? "",
114
+ email: who.email ?? "",
115
+ client: clientOf(c) ?? who.client,
116
+ },
117
+ principal: who,
118
+ };
119
+ }
120
+ async function callClient(c, name, spaceId) {
121
+ const call = CALLS[name];
122
+ if (!call || call.space !== (spaceId !== null)) {
123
+ return c.json(notFoundAnswer(c), 404);
124
+ }
125
+ const signedIn = await clientWho(c, call.scope);
126
+ if (signedIn instanceof Response) {
127
+ return signedIn;
128
+ }
129
+ const { who, principal } = signedIn;
130
+ const body = callBody.safeParse(await c.req.json().catch(() => ({})));
131
+ const input = body.success ? call.input.safeParse(body.data.input) : null;
132
+ if (!input?.success) {
133
+ return c.json({ error: "Invalid input", code: "invalid", issues: input?.error.issues ?? [] }, 400);
134
+ }
135
+ const result = await inTenantAs(principal, () => call.run(who, spaceId ?? "", input.data));
136
+ return c.json({ result });
137
+ }
138
+ export const clientContractRoutes = new Hono()
139
+ .get("/client", (c) => c.json({
140
+ calls: Object.entries(CALLS).map(([name, call]) => ({
141
+ name,
142
+ path: call.space ? `/api/v1/client/spaces/{spaceId}/${name}` : `/api/v1/client/${name}`,
143
+ scope: call.scope,
144
+ description: call.description,
145
+ input: z.toJSONSchema(call.input, { unrepresentable: "any" }),
146
+ })),
147
+ }))
148
+ .get("/client/files/:fileId", async (c) => {
149
+ const signedIn = await clientWho(c, "data:read");
150
+ if (signedIn instanceof Response) {
151
+ return signedIn;
152
+ }
153
+ const { who, principal } = signedIn;
154
+ const file = await inTenantAs(principal, () => clientFile(who, c.req.param("fileId")));
155
+ return new Response(new Uint8Array(file.data), {
156
+ headers: {
157
+ "content-type": file.mime,
158
+ "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}`,
159
+ "cache-control": "private, no-store",
160
+ },
161
+ });
162
+ })
163
+ .post("/client/spaces/:spaceId/:name", (c) => callClient(c, c.req.param("name"), c.req.param("spaceId")))
164
+ .post("/client/:name", (c) => callClient(c, c.req.param("name"), null));
@@ -0,0 +1,58 @@
1
+ import { Hono } from "hono";
2
+ import { z } from "zod";
3
+ import { setOpenToClients } from "../broker/rwx.js";
4
+ import { addSpaceMember, clientOpenOf, createClientSpace, deleteClientSpace, inviteClient, listClientSpaces, listSpaceMembers, removeSpaceMember, renameClientSpace, requireClientSpaces, shareWithClient, } from "../services/client-spaces.js";
5
+ const OPEN_KINDS = ["document", "table", "page", "wizard"];
6
+ export const clientSpaceRoutes = new Hono()
7
+ .get("/spaces/:id/clients", async (c) => c.json({ clients: await listClientSpaces(c.get("user").id, c.req.param("id")) }))
8
+ .post("/spaces/:id/clients", async (c) => {
9
+ const { name } = z.object({ name: z.string().min(1).max(200) }).parse(await c.req.json());
10
+ return c.json(await createClientSpace(c.get("user").id, c.req.param("id"), name));
11
+ })
12
+ .patch("/spaces/:id/client", async (c) => {
13
+ const { name } = z
14
+ .object({ name: z.string().trim().min(1).max(200) })
15
+ .parse(await c.req.json());
16
+ return c.json(await renameClientSpace(c.get("user").id, c.req.param("id"), name));
17
+ })
18
+ // A run of a client space shared with its clients on purpose, or taken back.
19
+ .put("/runs/:id/client-share", async (c) => {
20
+ const { shared } = z.object({ shared: z.boolean() }).parse(await c.req.json());
21
+ return c.json(await shareWithClient(c.get("user").id, c.req.param("id"), shared));
22
+ })
23
+ .delete("/spaces/:id/client", async (c) => {
24
+ await deleteClientSpace(c.get("user").id, c.req.param("id"));
25
+ return c.json({ ok: true });
26
+ })
27
+ .get("/spaces/:id/members", async (c) => c.json({ members: await listSpaceMembers(c.get("user").id, c.req.param("id")) }))
28
+ .put("/spaces/:id/members/:userId", async (c) => {
29
+ const { role } = z.object({ role: z.enum(["member", "client"]) }).parse(await c.req.json());
30
+ await addSpaceMember(c.get("user").id, c.req.param("id"), {
31
+ userId: c.req.param("userId"),
32
+ role,
33
+ });
34
+ return c.json({ ok: true });
35
+ })
36
+ .post("/spaces/:id/invite", async (c) => {
37
+ const { email, lang } = z
38
+ .object({
39
+ email: z.string().trim().email().max(254),
40
+ lang: z.enum(["de", "en"]).default("de"),
41
+ })
42
+ .parse(await c.req.json());
43
+ await inviteClient(c.get("user").id, c.req.param("id"), { email, lang });
44
+ return c.json({ ok: true });
45
+ })
46
+ .delete("/spaces/:id/members/:userId", async (c) => {
47
+ await removeSpaceMember(c.get("user").id, c.req.param("id"), c.req.param("userId"));
48
+ return c.json({ ok: true });
49
+ })
50
+ .get("/spaces/:id/open-to-clients", async (c) => c.json({ open: await clientOpenOf(c.get("user").id, c.req.param("id")) }))
51
+ .put("/spaces/:id/open-to-clients", async (c) => {
52
+ await requireClientSpaces();
53
+ const body = z
54
+ .object({ kind: z.enum(OPEN_KINDS), id: z.string().min(1).max(64), open: z.boolean() })
55
+ .parse(await c.req.json());
56
+ await setOpenToClients(c.get("user").id, c.req.param("id"), { kind: body.kind, id: body.id }, body.open);
57
+ return c.json({ ok: true });
58
+ });
@@ -0,0 +1,173 @@
1
+ import { note } from "@engenty/wizards-shared/run";
2
+ import { AGENT_ACCESS, AUDIENCES } from "@engenty/wizards-shared/rwx";
3
+ import { Hono } from "hono";
4
+ import { z } from "zod";
5
+ import { subjectsOfPerson } from "../broker/rwx.js";
6
+ import { discardDraft, keepMine, mountDrafts, openDraft, publishDraft, publishMount, replaceDraft, saveDraft, } from "../mounts/drafts.js";
7
+ import { completeFolder, createMount, deleteMount, listMounts, mountAccess, mountCanWrite, mountFileContent, mountFiles, mountFileThumb, mountFileView, mountRow, mountView, pickFolder, previewFolder, rescanMount, updateMount, } from "../mounts/mounts.js";
8
+ import { copyToKnowledge } from "../mounts/source.js";
9
+ import { ServiceError } from "../services/errors.js";
10
+ import { ownedSpace } from "../services/spaces.js";
11
+ import { spaceFileResponse } from "./delivery.js";
12
+ const whoOf = (c) => subjectsOfPerson(c.get("user").id, c.get("user").role);
13
+ const access = {
14
+ see: z.array(z.enum(AUDIENCES)).max(AUDIENCES.length),
15
+ wizards: z.union([z.enum(["all", "none"]), z.array(z.string().max(60)).max(200)]),
16
+ // A Work chat reads a folder unless it is told otherwise.
17
+ agents: z.enum(AGENT_ACCESS).default("read"),
18
+ };
19
+ export const dateienRoutes = new Hono()
20
+ .get("/spaces/:id/mounts", async (c) => {
21
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
22
+ return c.json({ mounts: await listMounts(space.id, whoOf(c)) });
23
+ })
24
+ // The system's folder dialog on this computer; `{ path: false }` where there is none.
25
+ .post("/spaces/:id/mounts/pick", async (c) => {
26
+ await ownedSpace(c.get("user").id, c.req.param("id"));
27
+ const { prompt } = z.object({ prompt: z.string().max(200) }).parse(await c.req.json());
28
+ return c.json({ path: await pickFolder(prompt) });
29
+ })
30
+ .get("/spaces/:id/mounts/folders", async (c) => {
31
+ await ownedSpace(c.get("user").id, c.req.param("id"));
32
+ return c.json({ folders: await completeFolder(c.req.query("path") ?? "") });
33
+ })
34
+ // What a folder holds, for the review before it is mounted.
35
+ .post("/spaces/:id/mounts/preview", async (c) => {
36
+ await ownedSpace(c.get("user").id, c.req.param("id"));
37
+ const { path } = z.object({ path: z.string().min(1).max(1000) }).parse(await c.req.json());
38
+ return c.json(await previewFolder(path));
39
+ })
40
+ .post("/spaces/:id/mounts", async (c) => {
41
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
42
+ const body = z
43
+ .object({
44
+ path: z.string().min(1).max(1000).optional(),
45
+ kind: z.string().max(24).optional(),
46
+ source: z.record(z.string(), z.unknown()).optional(),
47
+ name: z.string().max(120).optional(),
48
+ folderCategory: z.string().max(60).nullable().optional(),
49
+ writable: z.boolean().optional(),
50
+ ...access,
51
+ })
52
+ .parse(await c.req.json());
53
+ return c.json(await createMount(c.get("user").id, space.id, body));
54
+ })
55
+ .get("/spaces/:id/mounts/:mountId", async (c) => {
56
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
57
+ const row = await mountRow(space.id, c.req.param("mountId"), whoOf(c));
58
+ const mount = await mountView(space.id, row.id, whoOf(c));
59
+ return c.json({
60
+ ...mount,
61
+ ...(await mountAccess(space.id, mount.id)),
62
+ canWrite: await mountCanWrite(row),
63
+ ...(row.kind === "folder" ? {} : { source: row.source }),
64
+ });
65
+ })
66
+ .patch("/spaces/:id/mounts/:mountId", async (c) => {
67
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
68
+ const body = z
69
+ .object({
70
+ name: z.string().max(120).optional(),
71
+ see: access.see.optional(),
72
+ wizards: access.wizards.optional(),
73
+ agents: access.agents.optional(),
74
+ writable: z.boolean().optional(),
75
+ })
76
+ .parse(await c.req.json());
77
+ return c.json(await updateMount(c.get("user").id, space.id, c.req.param("mountId"), whoOf(c), body));
78
+ })
79
+ .post("/spaces/:id/mounts/:mountId/rescan", async (c) => {
80
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
81
+ await rescanMount(space.id, c.req.param("mountId"), whoOf(c));
82
+ return c.json({ ok: true });
83
+ })
84
+ .delete("/spaces/:id/mounts/:mountId", async (c) => {
85
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
86
+ await deleteMount(space.id, c.req.param("mountId"));
87
+ return c.json({ ok: true });
88
+ })
89
+ .get("/spaces/:id/mounts/:mountId/files", async (c) => {
90
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
91
+ return c.json({ files: await mountFiles(space.id, c.req.param("mountId"), whoOf(c)) });
92
+ })
93
+ .get("/spaces/:id/mount-files/:fileId", async (c) => {
94
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
95
+ return c.json(await mountFileView(space.id, c.req.param("fileId"), whoOf(c)));
96
+ })
97
+ // A mounted file's bytes, read where it lives.
98
+ .get("/spaces/:id/mount-files/:fileId/content", async (c) => {
99
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
100
+ const { file, data } = await mountFileContent(space.id, c.req.param("fileId"), whoOf(c));
101
+ return spaceFileResponse(c, file.mime, data);
102
+ })
103
+ // „In Wissen übernehmen“: a copy of the file in Knowledge, read as an upload is.
104
+ .post("/spaces/:id/mount-files/:fileId/knowledge", async (c) => {
105
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
106
+ const { parentId } = z
107
+ .object({ parentId: z.string().max(40).nullish() })
108
+ .parse(await c.req.json().catch(() => ({})));
109
+ const row = await copyToKnowledge(c.get("user").id, space.id, c.req.param("fileId"), whoOf(c), parentId ?? null);
110
+ return c.json({ id: row.id, name: row.name });
111
+ })
112
+ .get("/spaces/:id/mount-files/:fileId/thumb", async (c) => {
113
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
114
+ const thumb = await mountFileThumb(space.id, c.req.param("fileId"), whoOf(c));
115
+ return thumb ? spaceFileResponse(c, "image/jpeg", thumb) : c.notFound();
116
+ })
117
+ .get("/spaces/:id/mounts/:mountId/drafts", async (c) => {
118
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
119
+ return c.json({ drafts: await mountDrafts(space.id, c.req.param("mountId"), whoOf(c)) });
120
+ })
121
+ // „Veröffentlichen“ for every draft of the mount without a conflict.
122
+ .post("/spaces/:id/mounts/:mountId/publish", async (c) => {
123
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
124
+ return c.json(await publishMount(space.id, c.req.param("mountId"), whoOf(c)));
125
+ })
126
+ // The file's draft, else the file as it stands, to edit.
127
+ .get("/spaces/:id/mount-files/:fileId/draft", async (c) => {
128
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
129
+ return c.json(await openDraft(space.id, c.req.param("fileId"), whoOf(c)));
130
+ })
131
+ .put("/spaces/:id/mount-files/:fileId/draft", async (c) => {
132
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
133
+ const body = z
134
+ .object({
135
+ text: z.string().max(4_000_000),
136
+ base: z
137
+ .object({
138
+ size: z.number().int().min(0),
139
+ modified: z.number(),
140
+ version: z.string().nullable(),
141
+ hash: z.string().max(64),
142
+ })
143
+ .optional(),
144
+ baseText: z.string().max(4_000_000).optional(),
145
+ })
146
+ .parse(await c.req.json());
147
+ const draft = await saveDraft(c.get("user").id, space.id, c.req.param("fileId"), whoOf(c), body);
148
+ return c.json({ draft });
149
+ })
150
+ // A file replaced by an upload (the form's `file`), as a draft.
151
+ .post("/spaces/:id/mount-files/:fileId/draft/replace", async (c) => {
152
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
153
+ const file = (await c.req.formData()).get("file");
154
+ if (!(file instanceof File)) {
155
+ throw new ServiceError("invalid", note("chooseFile"));
156
+ }
157
+ const data = new Uint8Array(await file.arrayBuffer());
158
+ return c.json(await replaceDraft(c.get("user").id, space.id, c.req.param("fileId"), whoOf(c), data, file.type || "application/octet-stream"));
159
+ })
160
+ .delete("/spaces/:id/mount-files/:fileId/draft", async (c) => {
161
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
162
+ await discardDraft(space.id, c.req.param("fileId"), whoOf(c));
163
+ return c.json({ ok: true });
164
+ })
165
+ .post("/spaces/:id/mount-files/:fileId/publish", async (c) => {
166
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
167
+ return c.json(await publishDraft(space.id, c.req.param("fileId"), whoOf(c)));
168
+ })
169
+ // „Meine behalten“: the draft over what stands at the source now.
170
+ .post("/spaces/:id/mount-files/:fileId/keep-mine", async (c) => {
171
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
172
+ return c.json(await keepMine(space.id, c.req.param("fileId"), whoOf(c)));
173
+ });