@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
@@ -8,7 +8,7 @@ import PostalMime from "postal-mime";
8
8
  import { z } from "zod";
9
9
  import { parseCsvMatrix } from "../engenty/csv-import/csv-matrix.js";
10
10
  import { readXlsxWorkbook } from "../engenty/csv-import/xlsx-workbook.js";
11
- import { splitMarkdownByPageBreaks } from "../engenty/doc-converter/page-break.js";
11
+ import { joinPagesWithBreaks, splitMarkdownByPageBreaks, } from "../engenty/doc-converter/page-break.js";
12
12
  import { LocalProvider } from "../engenty/doc-converter/providers/local/index.js";
13
13
  import { invoiceSchema, receiptSchema } from "../engenty/document-scanner/schemas/index.js";
14
14
  import { env } from "../env.js";
@@ -16,6 +16,7 @@ import { NotedError } from "../model-errors.js";
16
16
  import { costOf, textModel } from "../models.js";
17
17
  import { prompt } from "../prompts.js";
18
18
  import { htmlToMarkdown } from "../render/convert.js";
19
+ import { OcrProvider } from "./ocr.js";
19
20
  export class UnreadableDocument extends NotedError {
20
21
  }
21
22
  const DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
@@ -114,6 +115,31 @@ class VisionProvider {
114
115
  }
115
116
  }
116
117
  const local = new LocalProvider();
118
+ const ocr = new OcrProvider();
119
+ /** A page with fewer letters than this is a scan, and so is a picture. */
120
+ const SCAN_LETTERS = 60;
121
+ const letters = (markdown) => markdown.replace(/<page-break[^>]*><\/page-break>|\s/g, "").length;
122
+ /** OCR that doesn't work (no models without the internet, a broken file) reads nothing. */
123
+ async function ocrPages(data, name, pages) {
124
+ return ocr.pages(data, pages).catch((err) => {
125
+ console.error("[ocr]", name, err);
126
+ return new Map();
127
+ });
128
+ }
129
+ /** Old Word files (Word 97–2003): their body, headers and footnotes. */
130
+ async function readWord97(data) {
131
+ const { default: WordExtractor } = await import("word-extractor");
132
+ const doc = await new WordExtractor().extract(Buffer.from(data));
133
+ return [
134
+ doc.getHeaders({ includeFooters: false }),
135
+ doc.getBody(),
136
+ doc.getFootnotes(),
137
+ doc.getFooters(),
138
+ ]
139
+ .map((part) => part.trim())
140
+ .filter(Boolean)
141
+ .join("\n\n");
142
+ }
117
143
  function tableMarkdown(columns, rows, limit = 400) {
118
144
  const cell = (v) => v.replace(/\|/g, "\\|").replace(/\s+/g, " ").trim();
119
145
  const head = `| ${columns.map(cell).join(" | ")} |\n|${columns.map(() => " --- ").join("|")}|`;
@@ -141,14 +167,26 @@ async function parseMail(data) {
141
167
  const CACHE_DIR = join(env.dataDir, "parsed");
142
168
  mkdirSync(CACHE_DIR, { recursive: true });
143
169
  /**
144
- * Turns a file into Markdown: PDFs and Word files by their own text, scans and photos by a
145
- * vision model, spreadsheets and CSV as tables, saved mails with their headers. The result is
146
- * kept by content, so a file is read (and paid for) once.
170
+ * Turns a file into Markdown: PDFs and Word files by their own text, scans and photos by OCR on
171
+ * this computer, else by a vision model, spreadsheets and CSV as tables, saved mails with their
172
+ * headers. The result is kept by content, so a file is read (and paid for) once.
147
173
  */
148
174
  export async function parseDocument(input, opts = {}) {
149
175
  const mime = documentMime(input.name, input.mime);
150
176
  return kept(input.data, mime, () => read({ ...input, mime }, opts));
151
177
  }
178
+ /**
179
+ * A file's text, read without a model: a scanned PDF by OCR, a photo not at all (null). What a
180
+ * mounted file is indexed and searched by; not kept here, the mounts keep a bounded cache of
181
+ * their own.
182
+ */
183
+ export async function ownText(input) {
184
+ const mime = documentMime(input.name, input.mime);
185
+ if (mime.startsWith("image/")) {
186
+ return null;
187
+ }
188
+ return read({ ...input, mime }, { vision: false });
189
+ }
152
190
  /** What was made of a file, kept by its content: the same bytes are never worked through twice. */
153
191
  async function kept(data, variant, make) {
154
192
  const file = join(CACHE_DIR, `${createHash("sha256").update(data).update(variant).digest("hex")}.json`);
@@ -163,6 +201,12 @@ async function read(input, opts) {
163
201
  const { data, name, mime } = input;
164
202
  const vision = new VisionProvider(opts.charge, opts.signal, opts.call);
165
203
  if (mime.startsWith("image/")) {
204
+ if (ocr.canConvert(mime)) {
205
+ const text = [...(await ocrPages(data, name)).values()].join("\n\n");
206
+ if (letters(text) >= SCAN_LETTERS) {
207
+ return { markdown: text, pages: 1, via: "ocr" };
208
+ }
209
+ }
166
210
  if (!vision.canConvert(mime)) {
167
211
  throw new UnreadableDocument(note("imageTypeNotReadable", { mime }));
168
212
  }
@@ -170,19 +214,44 @@ async function read(input, opts) {
170
214
  return { markdown: result.markdown, pages: 1, via: "vision" };
171
215
  }
172
216
  if (mime === "application/pdf") {
173
- const result = await local.convert(data, name, mime);
174
- const pages = result.metadata.page_count ?? null;
175
- const letters = result.markdown.replace(/<page-break[^>]*><\/page-break>|\s/g, "").length;
176
- // Hardly any text per page: the PDF is a scan.
177
- if (letters < 60 * Math.max(1, pages ?? 1)) {
178
- const seen = await vision.convert(data, name, mime);
217
+ const own = await local.convert(data, name, mime);
218
+ const total = own.metadata.page_count ?? 0;
219
+ const byPage = new Map(splitMarkdownByPageBreaks(own.markdown).map((page) => [page.number, page.markdown]));
220
+ // Pages with hardly any text of their own are scans: OCR reads them.
221
+ const scanned = Array.from({ length: total }, (_, i) => i + 1).filter((n) => letters(byPage.get(n) ?? "") < SCAN_LETTERS);
222
+ let via = "text";
223
+ for (const [n, text] of scanned.length ? await ocrPages(data, name, scanned) : []) {
224
+ if (letters(text) > letters(byPage.get(n) ?? "")) {
225
+ byPage.set(n, text);
226
+ via = "ocr";
227
+ }
228
+ }
229
+ const markdown = via === "ocr"
230
+ ? joinPagesWithBreaks([...byPage]
231
+ .sort(([a], [b]) => a - b)
232
+ .map(([number, text]) => ({ number, markdown: text })), total)
233
+ : own.markdown;
234
+ // Still hardly any text per page: a vision model reads it, where one may.
235
+ if (opts.vision !== false && letters(markdown) < SCAN_LETTERS * Math.max(1, total)) {
236
+ const seen = await vision.convert(data, name, mime).catch((err) => {
237
+ if (letters(markdown)) {
238
+ return null;
239
+ }
240
+ throw err;
241
+ });
242
+ if (!seen) {
243
+ return { markdown, pages: total || null, via };
244
+ }
179
245
  return {
180
246
  markdown: seen.markdown,
181
- pages: pages ?? (splitMarkdownByPageBreaks(seen.markdown).length || null),
247
+ pages: total || splitMarkdownByPageBreaks(seen.markdown).length || null,
182
248
  via: "vision",
183
249
  };
184
250
  }
185
- return { markdown: result.markdown, pages, via: "text" };
251
+ return { markdown, pages: total || null, via };
252
+ }
253
+ if (mime === "application/msword") {
254
+ return { markdown: await readWord97(data), pages: null, via: "text" };
186
255
  }
187
256
  if (local.canConvert(mime)) {
188
257
  return { markdown: (await local.convert(data, name, mime)).markdown, pages: null, via: "text" };
@@ -0,0 +1,47 @@
1
+ import { whereOf, whoOf } from "../broker/call.js";
2
+ import { AGENT, subjectsOf, subjectsOfGoose, subjectsOfPerson, } from "../broker/rwx.js";
3
+ /** A step of a run: its holder and its wizard, in the run. */
4
+ export function stepCaller(ctx, sandbox = null) {
5
+ return {
6
+ // The run's data: a client space's Knowledge reaches through to its parent as the rules allow.
7
+ space: ctx.dataSpace,
8
+ who: whoOf(ctx.store.holder, ctx.holder.kind === "person" ? ctx.holder.role : undefined),
9
+ subjects: subjectsOf(ctx),
10
+ where: whereOf(ctx),
11
+ signal: ctx.signal,
12
+ note: (note) => ctx.emit("tool", note),
13
+ sandbox,
14
+ };
15
+ }
16
+ /** A signed-in person: in a Work chat, or through an outside client that signed in as them. */
17
+ export function personCaller(input) {
18
+ return {
19
+ space: input.space,
20
+ who: whoOf(`u:${input.userId}`, input.role),
21
+ // An AI for the person: what the person may, and what the space lets agents do (Dateien).
22
+ subjects: [...subjectsOfPerson(input.userId, input.role), AGENT],
23
+ where: {
24
+ spaceId: input.space.id,
25
+ ...(input.chatId ? { chatId: input.chatId } : {}),
26
+ ...(input.client ? { client: input.client } : {}),
27
+ },
28
+ signal: input.signal,
29
+ client: input.client,
30
+ sandbox: input.sandbox ?? null,
31
+ };
32
+ }
33
+ /** Goose for a person: its own rules count, and the person's. */
34
+ export function gooseCaller(input) {
35
+ return {
36
+ space: input.space,
37
+ who: {
38
+ kind: "goose",
39
+ id: input.userId,
40
+ admin: input.role === "owner" || input.role === "admin",
41
+ },
42
+ subjects: subjectsOfGoose(input.userId, input.role),
43
+ where: { spaceId: input.space.id, ...(input.chatId ? { chatId: input.chatId } : {}) },
44
+ signal: input.signal,
45
+ note: input.note,
46
+ };
47
+ }
@@ -0,0 +1,14 @@
1
+ import { skillToolsOf } from "../tools/skills.js";
2
+ import { connectionElementTools } from "./connections.js";
3
+ import { knowledgeTools } from "./knowledge.js";
4
+ import { wizardTools } from "./wizards.js";
5
+ /** The element tools for the caller, by what it asks for. */
6
+ export async function elementTools(caller, request) {
7
+ return {
8
+ ...(request.knowledge ? await knowledgeTools(caller) : {}),
9
+ ...(request.skills ? skillToolsOf(request.skills, caller) : {}),
10
+ ...(request.wizards ? await wizardTools(caller) : {}),
11
+ ...(request.connections ? await connectionElementTools(caller) : {}),
12
+ };
13
+ }
14
+ export { ELEMENT_TOOL_NAMES } from "./specs.js";
@@ -0,0 +1,60 @@
1
+ import { createTool } from "@mastra/core/tools";
2
+ import { z } from "zod";
3
+ import { chatConnectionTools } from "../services/work-connections.js";
4
+ import { callConnection, connectionResult } from "../tools/connections.js";
5
+ import { attempt } from "../tools/shared.js";
6
+ import { ELEMENT_SPECS } from "./specs.js";
7
+ /**
8
+ * The space's connections for an outside client (docs/plans/modular.md, phase 3): the actions the
9
+ * person may use, as a Work chat has them, behind two calls. Each call is the broker's
10
+ * (`brokerCall`), which decides it by the connection's audience and rules and writes its line
11
+ * with the client's name. A write, a send or a delete runs only where the rules say *Immer*: the
12
+ * person's yes is never taken from the client (I4), and a call that waits for the space's
13
+ * admins („Mit Freigabe“) is refused with why. Its secret stays in the broker (I5).
14
+ */
15
+ const personOf = (caller) => (caller.who.kind === "person" || caller.who.kind === "admin") && caller.who.id
16
+ ? caller.who.id
17
+ : null;
18
+ export async function connectionElementTools(caller) {
19
+ const userId = personOf(caller);
20
+ if (!userId) {
21
+ return {};
22
+ }
23
+ const tools = await chatConnectionTools(caller.space.id, userId, caller.who);
24
+ if (!tools.length) {
25
+ return {};
26
+ }
27
+ const service = (t) => `${t.row.name} (${t.connector.name})`;
28
+ return {
29
+ connection_list: createTool({
30
+ id: "connection_list",
31
+ description: ELEMENT_SPECS.connection_list.description(),
32
+ inputSchema: ELEMENT_SPECS.connection_list.input,
33
+ execute: async () => ({
34
+ actions: tools.map((t) => ({
35
+ name: t.name,
36
+ service: service(t),
37
+ does: t.action.summary || t.action.id,
38
+ kind: t.kind,
39
+ input: t.action.inputSchema
40
+ ? z.toJSONSchema(t.action.inputSchema, { unrepresentable: "any" })
41
+ : {},
42
+ })),
43
+ }),
44
+ }),
45
+ connection_call: createTool({
46
+ id: "connection_call",
47
+ description: ELEMENT_SPECS.connection_call.description(),
48
+ inputSchema: ELEMENT_SPECS.connection_call.input,
49
+ execute: ({ name, input }) => attempt(async () => {
50
+ const tool = tools.find((t) => t.name === name);
51
+ if (!tool) {
52
+ return { error: `No action ${name}. connection_list names the ones you may use.` };
53
+ }
54
+ // No ask and no yes: a write that needs one is refused by the broker, not run.
55
+ const out = await callConnection(tool, caller.who, caller.where, input);
56
+ return connectionResult(out, service(tool));
57
+ }),
58
+ }),
59
+ };
60
+ }
@@ -0,0 +1,81 @@
1
+ import { summarizeInput, writeLog } from "../broker/log.js";
2
+ import { decide, ENFORCED, forbidden } from "../broker/rwx.js";
3
+ import { attempt } from "../tools/shared.js";
4
+ const KIND = { r: "read", w: "write", x: "run" };
5
+ /** The log's name for what was called: `knowledge`, `skill:<name>`, `wizard:<id>`, `setup`. */
6
+ const subjectOf = (call) => call.resource ? `${call.resource.kind}:${call.resource.id}` : (call.about ?? "knowledge");
7
+ const sizeOf = (result) => {
8
+ try {
9
+ return JSON.stringify(result ?? null).length;
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ };
15
+ async function logCall(caller, call, outcome, result, started, extra = {}) {
16
+ await writeLog({
17
+ at: new Date(started),
18
+ durationMs: Date.now() - started,
19
+ whoKind: caller.who.kind,
20
+ whoId: caller.who.id ?? null,
21
+ runId: caller.where.runId ?? null,
22
+ stepId: caller.where.stepId ?? null,
23
+ chatId: caller.where.chatId ?? null,
24
+ wizardId: caller.where.wizardId ?? null,
25
+ spaceId: caller.space.id,
26
+ client: caller.client ?? null,
27
+ connectionId: subjectOf(call),
28
+ actionId: call.action,
29
+ kind: KIND[call.perm],
30
+ inputSummary: summarizeInput(call.input),
31
+ outcome,
32
+ rule: extra.rule ?? null,
33
+ reason: extra.reason ?? null,
34
+ result,
35
+ resultSize: extra.resultSize ?? null,
36
+ });
37
+ }
38
+ /** Whether the caller may do `perm` on the resource, without running anything or logging. */
39
+ export async function mayDo(caller, resource, perm) {
40
+ return (await decide(caller.space.id, caller.subjects, resource, perm)).ok;
41
+ }
42
+ /**
43
+ * Runs `run` once the rules allow the call, and logs it either way. A refusal throws the
44
+ * broker's 403 (`forbidden`), which a tool hands the model as its error.
45
+ */
46
+ export async function elementCall(caller, call, run) {
47
+ const started = Date.now();
48
+ if (call.resource && ENFORCED.includes(call.resource.kind)) {
49
+ const decision = await decide(call.rulesIn ?? caller.space.id, caller.subjects, call.resource, call.perm);
50
+ if (!decision.ok) {
51
+ await logCall(caller, call, "deny", "forbidden", started, {
52
+ rule: decision.rule,
53
+ reason: decision.reason,
54
+ });
55
+ throw forbidden(decision.of, call.perm);
56
+ }
57
+ }
58
+ try {
59
+ const result = await run();
60
+ await logCall(caller, call, "allow", "ok", started, { resultSize: sizeOf(result) });
61
+ return result;
62
+ }
63
+ catch (err) {
64
+ const name = err?.code ?? err?.name ?? "error";
65
+ await logCall(caller, call, "allow", String(name).slice(0, 40), started);
66
+ throw err;
67
+ }
68
+ }
69
+ /**
70
+ * A tool whose every call goes through the gate: `callOf` says, from the model's input, what the
71
+ * call is about. A refusal comes back to the model as the tool's error.
72
+ */
73
+ export function brokered(tool, caller, callOf) {
74
+ const execute = tool.execute;
75
+ if (!execute) {
76
+ return tool;
77
+ }
78
+ return Object.assign(Object.create(Object.getPrototypeOf(tool)), tool, {
79
+ execute: (input, ...rest) => attempt(() => elementCall(caller, callOf(input), async () => execute.call(tool, input, ...rest))),
80
+ });
81
+ }
@@ -0,0 +1,308 @@
1
+ import { createTool } from "@mastra/core/tools";
2
+ import { and, eq, inArray } from "drizzle-orm";
3
+ import { z } from "zod";
4
+ import { assertRwx, decide } from "../broker/rwx.js";
5
+ import { db, schema } from "../db/client.js";
6
+ import { openDraft, saveDraft } from "../mounts/drafts.js";
7
+ import { fileByPath, mountFileText, usableMounts } from "../mounts/mounts.js";
8
+ import { prompt } from "../prompts.js";
9
+ import { filePaths, knowledgeCounts, listForStep, readPage, readTable, resolvePath, } from "../services/knowledge.js";
10
+ import { documentText, hasIndexEntries, searchKnowledge } from "../services/space-index.js";
11
+ import { attempt, clip } from "../tools/shared.js";
12
+ import { elementCall } from "./gate.js";
13
+ import { ELEMENT_SPECS } from "./specs.js";
14
+ /**
15
+ * The space's Knowledge as tools of the catalogue: search it (a question, filtered by categories
16
+ * first, checked by a classifier after), list it by categories, read a page, a table or a file
17
+ * whole by its path. Hits and reads look like files — a path, front matter, Markdown or CSV — so
18
+ * a model reads them as it reads files. The search also finds what the space's plugins put into
19
+ * the index. Every read is the caller's: the broker decides each item before it is handed out
20
+ * (broker/rwx.ts), and each call is a line of its log (gate.ts).
21
+ */
22
+ export { pageReadInput } from "./specs.js";
23
+ /**
24
+ * Where the caller's Knowledge is read: the space, and for a client space its parent too
25
+ * (docs/plans/client-spaces.md). The rules decide each item of the parent as for any reader: a
26
+ * client reads only what the parent opened to clients, the firm reads all of it.
27
+ */
28
+ async function readsFrom(spaceId) {
29
+ const space = await db.query.space.findFirst({
30
+ columns: { id: true, name: true, kind: true, parentId: true },
31
+ where: eq(schema.space.id, spaceId),
32
+ });
33
+ if (!(space?.kind === "client" && space.parentId)) {
34
+ return [{ id: spaceId, name: space?.name ?? "", own: true }];
35
+ }
36
+ const parent = await db.query.space.findFirst({
37
+ columns: { id: true, name: true },
38
+ where: eq(schema.space.id, space.parentId),
39
+ });
40
+ return [
41
+ { id: spaceId, name: space.name, own: true },
42
+ ...(parent ? [{ id: parent.id, name: parent.name, own: false }] : []),
43
+ ];
44
+ }
45
+ /** The first space that has it: the client space before its parent. A refusal stands. */
46
+ async function firstFound(spaces, read) {
47
+ let missing = null;
48
+ for (const space of spaces) {
49
+ try {
50
+ return await read(space.id);
51
+ }
52
+ catch (err) {
53
+ if (err?.code === "forbidden") {
54
+ throw err;
55
+ }
56
+ missing ??= err;
57
+ }
58
+ }
59
+ throw missing;
60
+ }
61
+ /** A page of Knowledge by its path, for the caller: its front matter and Markdown, in parts. */
62
+ export function readKnowledgePage(caller, input) {
63
+ return attempt(() => elementCall(caller, { action: "page_read", perm: "r", input }, async () => {
64
+ const read = await firstFound(await readsFrom(caller.space.id), (spaceId) => readPage(spaceId, input.path, input, caller.subjects));
65
+ await caller.note?.({ code: "reads", params: { name: read.path } });
66
+ return read;
67
+ }));
68
+ }
69
+ /** The Knowledge tools for the caller; none where the space has no Knowledge yet. */
70
+ export async function knowledgeTools(caller) {
71
+ const spaceId = caller.space.id;
72
+ const who = caller.subjects;
73
+ const spaces = await readsFrom(spaceId);
74
+ const counts = { pages: 0, tables: 0, files: 0 };
75
+ let entries = false;
76
+ for (const space of spaces) {
77
+ const of = await knowledgeCounts(space.id);
78
+ counts.pages += of.pages;
79
+ counts.tables += of.tables;
80
+ counts.files += of.files;
81
+ entries ||= await hasIndexEntries(space.id);
82
+ }
83
+ // The folders of Dateien the caller may use: searched, and read by their path.
84
+ const mounted = (await usableMounts(spaceId, who)).length > 0;
85
+ if (!(counts.pages || counts.tables || counts.files || entries || mounted)) {
86
+ return {};
87
+ }
88
+ const call = (action, input, run) => attempt(() => elementCall(caller, { action, perm: "r", input }, run));
89
+ const tools = {
90
+ space_search: createTool({
91
+ id: "space_search",
92
+ description: prompt("tools", "tool.space_search"),
93
+ inputSchema: ELEMENT_SPECS.space_search.input,
94
+ execute: (input) => call("space_search", input, async () => {
95
+ const found = await searchAll(spaces, input.query, {
96
+ where: input.where,
97
+ limit: input.limit,
98
+ signal: caller.signal,
99
+ who,
100
+ });
101
+ await caller.note?.({
102
+ code: "searchesKnowledge",
103
+ params: {
104
+ query: input.query.slice(0, 60),
105
+ relevant: found.hits.length,
106
+ candidates: found.candidates,
107
+ },
108
+ });
109
+ return {
110
+ hits: found.hits.map((h) => ({
111
+ ...(h.path ? { path: h.path } : {}),
112
+ ...(h.mount ? { in: `Dateien › ${h.mount.name}` } : {}),
113
+ ...(h.open ? { open: h.open } : {}),
114
+ title: h.title,
115
+ ...(h.categories.length ? { categories: h.categories } : {}),
116
+ ...(h.heading ? { section: h.heading } : {}),
117
+ ...(h.sheet ? { page: h.sheet } : {}),
118
+ ...(h.relevance !== null ? { relevance: h.relevance } : {}),
119
+ text: clip(h.text, 1500),
120
+ })),
121
+ checked: found.checked,
122
+ candidates: found.candidates,
123
+ ...(found.filtered !== null ? { filtered: found.filtered } : {}),
124
+ };
125
+ }),
126
+ }),
127
+ space_list: createTool({
128
+ id: "space_list",
129
+ description: prompt("tools", "tool.space_list"),
130
+ inputSchema: ELEMENT_SPECS.space_list.input,
131
+ execute: (input) => call("space_list", input, async () => {
132
+ const listed = await listForStep(spaceId, input.where, who);
133
+ const parent = spaces.find((p) => !p.own);
134
+ if (parent) {
135
+ return {
136
+ ...listed,
137
+ [`from ${parent.name}`]: await listForStep(parent.id, input.where, who),
138
+ };
139
+ }
140
+ await caller.note?.({ code: "listsKnowledge" });
141
+ return listed;
142
+ }),
143
+ }),
144
+ };
145
+ if (counts.pages) {
146
+ tools.page_read = createTool({
147
+ id: "page_read",
148
+ description: prompt("tools", "tool.page_read.knowledge"),
149
+ inputSchema: ELEMENT_SPECS.page_read.input,
150
+ execute: (input) => readKnowledgePage(caller, input),
151
+ });
152
+ }
153
+ if (counts.tables) {
154
+ tools.table_read = createTool({
155
+ id: "table_read",
156
+ description: prompt("tools", "tool.table_read"),
157
+ inputSchema: ELEMENT_SPECS.table_read.input,
158
+ execute: (input) => call("table_read", input, async () => {
159
+ const read = await firstFound(spaces, (id) => readTable(id, input.path, input, who));
160
+ await caller.note?.({ code: "reads", params: { name: read.path } });
161
+ return read;
162
+ }),
163
+ });
164
+ }
165
+ if (counts.files || mounted) {
166
+ tools.space_document = createTool({
167
+ id: "space_document",
168
+ description: prompt("tools", "tool.space_document"),
169
+ inputSchema: ELEMENT_SPECS.space_document.input,
170
+ execute: (input) => call("space_document", input, async () => {
171
+ const { path, from } = input;
172
+ if (path.startsWith("dateien/")) {
173
+ return readMounted(path, from);
174
+ }
175
+ const wanted = path.startsWith("files/") ? path : `files/${path}`;
176
+ const inSpace = await firstFound(spaces, async (id) => {
177
+ const hit = await resolvePath(id, wanted);
178
+ if (hit?.kind !== "file") {
179
+ throw new Error("not here");
180
+ }
181
+ return id;
182
+ }).catch(() => spaceId);
183
+ const found = await resolvePath(inSpace, wanted);
184
+ if (found?.kind !== "file") {
185
+ const there = [...(await filePaths(spaceId)).values()].slice(0, 40);
186
+ throw new Error(`No file "${path}". There are: ${there.join(", ")}`);
187
+ }
188
+ const file = await db.query.spaceFile.findFirst({
189
+ where: and(eq(schema.spaceFile.id, found.id), eq(schema.spaceFile.spaceId, inSpace)),
190
+ });
191
+ if (!file) {
192
+ throw new Error(`No file "${path}".`);
193
+ }
194
+ await assertRwx(inSpace, who, { kind: "document", id: file.id }, "r");
195
+ await caller.note?.({ code: "reads", params: { name: file.name } });
196
+ const text = (await documentText(file)) || file.description;
197
+ const start = Math.min(from ?? 0, text.length);
198
+ const part = text.slice(start, start + 12_000);
199
+ return {
200
+ path: found.path,
201
+ text: clip(part, 12_000),
202
+ next: start + part.length < text.length ? start + part.length : null,
203
+ length: text.length,
204
+ };
205
+ }),
206
+ });
207
+ }
208
+ // A Work chat's AI writes drafts of a mounted folder's files where the folder lets agents do it;
209
+ // a person publishes them. Not offered to outside clients: their scopes don't write yet.
210
+ const drafts = !caller.client &&
211
+ caller.who.id &&
212
+ who.some((s) => s.kind === "agent") &&
213
+ (await draftableMounts(spaceId, who)).length > 0;
214
+ if (drafts) {
215
+ const userId = caller.who.id;
216
+ tools.dateien_draft = createTool({
217
+ id: "dateien_draft",
218
+ description: prompt("tools", "tool.dateien_draft"),
219
+ inputSchema: z.object({
220
+ path: z.string().describe("The file's path in Dateien: dateien/…"),
221
+ text: z.string().max(200_000).describe("The file's whole new text"),
222
+ }),
223
+ execute: (input) => attempt(() => elementCall(caller, { action: "dateien_draft", perm: "w", input: { path: input.path } }, async () => {
224
+ const found = await fileByPath(spaceId, input.path, who);
225
+ if (!found) {
226
+ throw new Error(`No file "${input.path}" in the folders you may use.`);
227
+ }
228
+ const open = await openDraft(spaceId, found.file.id, who);
229
+ if (open.edit !== "text") {
230
+ throw new Error(`"${input.path}" is not a text file: it can't be written as text.`);
231
+ }
232
+ await saveDraft(userId, spaceId, found.file.id, who, {
233
+ text: input.text,
234
+ ...(open.draft ? {} : { base: open.base, baseText: open.baseText ?? undefined }),
235
+ });
236
+ return {
237
+ ok: true,
238
+ note: "Kept as a draft. A person publishes it in Dateien.",
239
+ };
240
+ })),
241
+ });
242
+ }
243
+ return tools;
244
+ /** A file of a mount, read from where it lives: the mount's rules decided before. */
245
+ async function readMounted(path, from) {
246
+ const found = await fileByPath(spaceId, path, who);
247
+ if (!found) {
248
+ throw new Error(`No file "${path}" in the folders you may use.`);
249
+ }
250
+ await caller.note?.({ code: "reads", params: { name: found.file.name } });
251
+ const text = await mountFileText(found.mount, found.file).catch(() => {
252
+ throw new Error(`"${path}" can't be read now: its folder is not there.`);
253
+ });
254
+ if (!text) {
255
+ return { path, text: "", note: `${found.file.mime}: no text of its own.`, length: 0 };
256
+ }
257
+ const start = Math.min(from ?? 0, text.length);
258
+ const part = text.slice(start, start + 12_000);
259
+ return {
260
+ path,
261
+ text: clip(part, 12_000),
262
+ next: start + part.length < text.length ? start + part.length : null,
263
+ length: text.length,
264
+ };
265
+ }
266
+ }
267
+ /** The mounts an AI for the caller may write drafts in: changeable, and agents may write. */
268
+ async function draftableMounts(spaceId, who) {
269
+ const ids = (await usableMounts(spaceId, who)).map((m) => m.id);
270
+ const agents = who.filter((s) => s.kind === "agent");
271
+ const ok = await Promise.all(ids.map(async (id) => (await decide(spaceId, agents, { kind: "mount", id }, "w")).ok));
272
+ return writableMountIds(spaceId, ids.filter((_, i) => ok[i]));
273
+ }
274
+ /** The mounts among these whose files may be changed. */
275
+ async function writableMountIds(spaceId, ids) {
276
+ if (!ids.length) {
277
+ return [];
278
+ }
279
+ const rows = await db.query.spaceMount.findMany({
280
+ columns: { id: true },
281
+ where: and(eq(schema.spaceMount.spaceId, spaceId), eq(schema.spaceMount.writable, true), inArray(schema.spaceMount.id, ids)),
282
+ });
283
+ return rows.map((r) => r.id);
284
+ }
285
+ /** A search over the client space and its parent, the best of both by relevance. */
286
+ async function searchAll(spaces, query, opts) {
287
+ if (spaces.length === 1) {
288
+ return searchKnowledge(spaces[0].id, query, opts);
289
+ }
290
+ const each = await Promise.all(spaces.map((p) => searchKnowledge(p.id, query, opts)));
291
+ const limit = Math.min(Math.max(1, opts?.limit ?? 6), 12);
292
+ const hits = each
293
+ .flatMap((found) => found.hits)
294
+ .sort((a, b) => (b.relevance ?? 0) - (a.relevance ?? 0))
295
+ .slice(0, limit);
296
+ return {
297
+ hits,
298
+ checked: each.every((f) => f.checked),
299
+ candidates: each.reduce((n, f) => n + f.candidates, 0),
300
+ filtered: each.some((f) => f.filtered !== null)
301
+ ? each.reduce((n, f) => n + (f.filtered ?? 0), 0)
302
+ : null,
303
+ hidden: each
304
+ .flatMap((found) => found.hidden)
305
+ .sort((a, b) => (b.relevance ?? 0) - (a.relevance ?? 0))
306
+ .slice(0, limit),
307
+ };
308
+ }