@engenty/wizards-runtime 0.15.0 → 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 (243) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +138 -9
  2. package/apps/runtime/dist/agents/website.js +10 -5
  3. package/apps/runtime/dist/app.js +18 -0
  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/index.js +5 -0
  7. package/apps/runtime/dist/broker/rwx.js +255 -7
  8. package/apps/runtime/dist/cli/main.js +7 -0
  9. package/apps/runtime/dist/cli/move-files.js +68 -0
  10. package/apps/runtime/dist/cli/move-folder-sources.js +120 -0
  11. package/apps/runtime/dist/connectors/plugin-connections.js +74 -4
  12. package/apps/runtime/dist/db/migrations/tenant/0042_client_spaces.sql +16 -0
  13. package/apps/runtime/dist/db/migrations/tenant/0043_space_member_invite.sql +19 -0
  14. package/apps/runtime/dist/db/migrations/tenant/0044_client_portal.sql +8 -0
  15. package/apps/runtime/dist/db/migrations/tenant/0045_client_portal_no_slug.sql +2 -0
  16. package/apps/runtime/dist/db/migrations/tenant/0046_space_file_hash.sql +2 -0
  17. package/apps/runtime/dist/db/migrations/tenant/0047_knowledge_folders.sql +3 -0
  18. package/apps/runtime/dist/db/migrations/tenant/0048_space_chunk_kind.sql +1 -0
  19. package/apps/runtime/dist/db/migrations/tenant/0049_knowledge_sources.sql +57 -0
  20. package/apps/runtime/dist/db/migrations/tenant/0050_dateien.sql +71 -0
  21. package/apps/runtime/dist/db/migrations/tenant/0051_dateien_drafts.sql +23 -0
  22. package/apps/runtime/dist/db/migrations/tenant/0052_dateien_plugin_kinds.sql +5 -0
  23. package/apps/runtime/dist/db/migrations/tenant/0053_dateien_file_title.sql +3 -0
  24. package/apps/runtime/dist/db/migrations/tenant/0054_dateien_ocr.sql +14 -0
  25. package/apps/runtime/dist/db/migrations/tenant/0055_dateien_doc_reread.sql +3 -0
  26. package/apps/runtime/dist/db/migrations/tenant/meta/0042_snapshot.json +5286 -0
  27. package/apps/runtime/dist/db/migrations/tenant/meta/0043_snapshot.json +5293 -0
  28. package/apps/runtime/dist/db/migrations/tenant/meta/0044_snapshot.json +5344 -0
  29. package/apps/runtime/dist/db/migrations/tenant/meta/0045_snapshot.json +5329 -0
  30. package/apps/runtime/dist/db/migrations/tenant/meta/0046_snapshot.json +5343 -0
  31. package/apps/runtime/dist/db/migrations/tenant/meta/0047_snapshot.json +5391 -0
  32. package/apps/runtime/dist/db/migrations/tenant/meta/0048_snapshot.json +5398 -0
  33. package/apps/runtime/dist/db/migrations/tenant/meta/0049_snapshot.json +5793 -0
  34. package/apps/runtime/dist/db/migrations/tenant/meta/0050_snapshot.json +6288 -0
  35. package/apps/runtime/dist/db/migrations/tenant/meta/0051_snapshot.json +6461 -0
  36. package/apps/runtime/dist/db/migrations/tenant/meta/0052_snapshot.json +6497 -0
  37. package/apps/runtime/dist/db/migrations/tenant/meta/0053_snapshot.json +6504 -0
  38. package/apps/runtime/dist/db/migrations/tenant/meta/0054_snapshot.json +6504 -0
  39. package/apps/runtime/dist/db/migrations/tenant/meta/0055_snapshot.json +6504 -0
  40. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +98 -0
  41. package/apps/runtime/dist/db/schema.js +294 -5
  42. package/apps/runtime/dist/docs/dev/api.md +25 -0
  43. package/apps/runtime/dist/docs/dev/plugins/connections.md +30 -2
  44. package/apps/runtime/dist/docs/dev/plugins/index.md +1 -1
  45. package/apps/runtime/dist/docs/dev/plugins/reference.md +7 -4
  46. package/apps/runtime/dist/docs/dev/plugins/server.md +11 -5
  47. package/apps/runtime/dist/docs/dev/plugins/space.md +130 -4
  48. package/apps/runtime/dist/docs/dev/plugins/studio.md +13 -3
  49. package/apps/runtime/dist/docs/user-guide/command-line.md +2 -0
  50. package/apps/runtime/dist/docs/user-guide/plugins.md +1 -1
  51. package/apps/runtime/dist/docs/user-guide/space.md +6 -6
  52. package/apps/runtime/dist/docs/user-guide/steps.md +1 -1
  53. package/apps/runtime/dist/documents/ocr.js +72 -0
  54. package/apps/runtime/dist/documents/parse.js +81 -12
  55. package/apps/runtime/dist/elements/caller.js +5 -3
  56. package/apps/runtime/dist/elements/gate.js +1 -1
  57. package/apps/runtime/dist/elements/knowledge.js +181 -12
  58. package/apps/runtime/dist/elements/specs.js +1 -1
  59. package/apps/runtime/dist/elements/wizards.js +15 -2
  60. package/apps/runtime/dist/engenty/connections-google/connectors/drive.js +3 -0
  61. package/apps/runtime/dist/engenty/connections-microsoft/onedrive.js +3 -0
  62. package/apps/runtime/dist/engenty/connections-s3/s3.js +6 -0
  63. package/apps/runtime/dist/engine/runner.js +19 -2
  64. package/apps/runtime/dist/engine/steps.js +1 -1
  65. package/apps/runtime/dist/env.js +6 -0
  66. package/apps/runtime/dist/files/blobs.js +57 -1
  67. package/apps/runtime/dist/files/objects.js +1 -0
  68. package/apps/runtime/dist/files/pictures.js +41 -0
  69. package/apps/runtime/dist/files/storage.js +14 -26
  70. package/apps/runtime/dist/files/thumbs.js +77 -0
  71. package/apps/runtime/dist/files/upload-check.js +2 -2
  72. package/apps/runtime/dist/index.js +22 -0
  73. package/apps/runtime/dist/live/views.js +2 -1
  74. package/apps/runtime/dist/manage.js +4 -1
  75. package/apps/runtime/dist/mcp/tools.js +5 -0
  76. package/apps/runtime/dist/models.js +82 -13
  77. package/apps/runtime/dist/mounts/cache.js +71 -0
  78. package/apps/runtime/dist/mounts/drafts.js +367 -0
  79. package/apps/runtime/dist/mounts/folder.js +148 -0
  80. package/apps/runtime/dist/mounts/mounts.js +1315 -0
  81. package/apps/runtime/dist/mounts/source.js +179 -0
  82. package/apps/runtime/dist/mounts/units.js +97 -0
  83. package/apps/runtime/dist/move-files.js +4 -0
  84. package/apps/runtime/dist/plugins/loader.js +73 -1
  85. package/apps/runtime/dist/plugins/registry.js +2 -0
  86. package/apps/runtime/dist/prompts/goose.md +13 -1
  87. package/apps/runtime/dist/prompts/tools.md +5 -2
  88. package/apps/runtime/dist/render/convert.js +188 -1
  89. package/apps/runtime/dist/routes/api.js +6 -1
  90. package/apps/runtime/dist/routes/client-contract.js +164 -0
  91. package/apps/runtime/dist/routes/client-spaces.js +58 -0
  92. package/apps/runtime/dist/routes/dateien.js +173 -0
  93. package/apps/runtime/dist/routes/elements.js +2 -2
  94. package/apps/runtime/dist/routes/plugins.js +2 -1
  95. package/apps/runtime/dist/routes/runs.js +24 -10
  96. package/apps/runtime/dist/routes/studio.js +168 -8
  97. package/apps/runtime/dist/secrets/signing.js +16 -0
  98. package/apps/runtime/dist/services/client-portal.js +439 -0
  99. package/apps/runtime/dist/services/client-spaces.js +228 -0
  100. package/apps/runtime/dist/services/cloud.js +2 -0
  101. package/apps/runtime/dist/services/knowledge-model.js +24 -8
  102. package/apps/runtime/dist/services/knowledge.js +72 -42
  103. package/apps/runtime/dist/services/links.js +17 -0
  104. package/apps/runtime/dist/services/members-studio.js +5 -1
  105. package/apps/runtime/dist/services/page-pictures.js +162 -0
  106. package/apps/runtime/dist/services/runs.js +22 -6
  107. package/apps/runtime/dist/services/space-categories.js +41 -5
  108. package/apps/runtime/dist/services/space-data.js +165 -8
  109. package/apps/runtime/dist/services/space-files.js +102 -19
  110. package/apps/runtime/dist/services/space-index.js +384 -41
  111. package/apps/runtime/dist/services/space-origin.js +25 -1
  112. package/apps/runtime/dist/services/space-sources.js +937 -0
  113. package/apps/runtime/dist/services/spaces.js +60 -12
  114. package/apps/runtime/dist/services/synced-spaces.js +10 -1
  115. package/apps/runtime/dist/services/work-ai.js +29 -8
  116. package/apps/runtime/dist/services/work-chats.js +3 -2
  117. package/apps/runtime/dist/sharing/index.js +2 -0
  118. package/apps/runtime/dist/store/index.js +29 -8
  119. package/apps/runtime/dist/store/shared-lists.js +30 -17
  120. package/apps/runtime/dist/sync/records.js +22 -27
  121. package/apps/runtime/dist/texts.js +4 -0
  122. package/apps/runtime/dist/tools/pages.js +1 -1
  123. package/apps/runtime/dist/widgets/step.js +2 -1
  124. package/apps/web/dist/assets/AboutDialog-0q4P80yv.js +1 -0
  125. package/apps/web/dist/assets/BlockEditor-CUYFH_CU.js +173 -0
  126. package/apps/web/dist/assets/BlockEditor-CtW6lw0y.css +1 -0
  127. package/apps/web/dist/assets/CapabilitiesPage-BlZP8DYb.js +2 -0
  128. package/apps/web/dist/assets/{ChangelogDialog-Do7pwmFv.js → ChangelogDialog-CDN7kMs1.js} +1 -1
  129. package/apps/web/dist/assets/{CodeEditor-Cdox-51M.js → CodeEditor-D-Y16fdk.js} +1 -1
  130. package/apps/web/dist/assets/EditorPage-CrMVsgUt.js +3 -0
  131. package/apps/web/dist/assets/{FlowPreview-BPS86xzA.js → FlowPreview-DXnk7m9P.js} +1 -1
  132. package/apps/web/dist/assets/{LangSwitch-BRHbi_Sd.js → LangSwitch-Dkd0FBIH.js} +1 -1
  133. package/apps/web/dist/assets/Marketplace-Cty40VwG.js +2 -0
  134. package/apps/web/dist/assets/NewWizardChannels-Czool7s1.js +1 -0
  135. package/apps/web/dist/assets/NewWizardPage-CfVe_4a2.js +7 -0
  136. package/apps/web/dist/assets/OnboardingPage-D3SEpTmt.js +1 -0
  137. package/apps/web/dist/assets/PreviewPane-CQDKQO6z.js +7 -0
  138. package/apps/web/dist/assets/PublicRunner-BDZNnlQw.js +1 -0
  139. package/apps/web/dist/assets/ReadOnly-B7MUySpC.js +1 -0
  140. package/apps/web/dist/assets/SettingsPage-Bgurv3l2.js +2 -0
  141. package/apps/web/dist/assets/SetupPage-C3km8vqv.js +1 -0
  142. package/apps/web/dist/assets/{SharePage-PKHX8a8a.js → SharePage-UwEJBIzq.js} +1 -1
  143. package/apps/web/dist/assets/SkillEditor-BaEiqqXl.js +1 -0
  144. package/apps/web/dist/assets/Skills-Bv6XbKxc.js +9 -0
  145. package/apps/web/dist/assets/SpacePage-D9PXLSU_.js +2 -0
  146. package/apps/web/dist/assets/UpdateCheck-C7I43zFZ.js +2 -0
  147. package/apps/web/dist/assets/changelog-DwgWiSZb.js +1 -0
  148. package/apps/web/dist/assets/circle-check-DDLzlcXP.js +1 -0
  149. package/apps/web/dist/assets/code-DsnwzN1x.js +1 -0
  150. package/apps/web/dist/assets/code-editor-Ca5EAxmd.js +2 -0
  151. package/apps/web/dist/assets/code-xml-S4IFi5Jc.js +1 -0
  152. package/apps/web/dist/assets/connection-sign-in-hI3HXhq4.js +1 -0
  153. package/apps/web/dist/assets/{dist-H1UN89OA.js → dist-B3Ray2U5.js} +1 -1
  154. package/apps/web/dist/assets/dist-CQpLJoQZ.js +10 -0
  155. package/apps/web/dist/assets/{dist-GlRRx9Xl.js → dist-D1uGQ_tB.js} +1 -1
  156. package/apps/web/dist/assets/{dist-BdDd1FxP.js → dist-DFI-tsfx.js} +1 -1
  157. package/apps/web/dist/assets/eye-TJSuiHHO.js +1 -0
  158. package/apps/web/dist/assets/floating-ui.dom-pwdNGv4b.js +1 -0
  159. package/apps/web/dist/assets/host-D5hNHbhF.js +125 -0
  160. package/apps/web/dist/assets/i18n-BBzMbGoo.js +55 -0
  161. package/apps/web/dist/assets/index-CyBrvupM.js +10 -0
  162. package/apps/web/dist/assets/index-w-3J3ZJ9.css +1 -0
  163. package/apps/web/dist/assets/{json-CEsfHdlZ.js → json-Ce3iHrtf.js} +1 -1
  164. package/apps/web/dist/assets/link-CPL8pB1P.js +1 -0
  165. package/apps/web/dist/assets/list-checks-DaxmUPqK.js +1 -0
  166. package/apps/web/dist/assets/{markdown-5-I9_izp.js → markdown-hqKQy2pp.js} +1 -1
  167. package/apps/web/dist/assets/marked.esm-DQ7XA7AC.js +67 -0
  168. package/apps/web/dist/assets/oss-credits-BrwV0a4F.js +1 -0
  169. package/apps/web/dist/assets/pdf-Dg-raaUo.js +54 -0
  170. package/apps/web/dist/assets/pdf.worker.min-68CMzziE.js +1 -0
  171. package/apps/web/dist/assets/pdf.worker.min-CjEcRF4W.mjs +28 -0
  172. package/apps/web/dist/assets/phone-B4uKDBFq.js +1 -0
  173. package/apps/web/dist/assets/read-aloud-Bfp9_bUY.js +1 -0
  174. package/apps/web/dist/assets/{runners-BoPaPsjN.js → runners-CUpBpSji.js} +1 -1
  175. package/apps/web/dist/assets/scroll-text-BEnPzQEi.js +1 -0
  176. package/apps/web/dist/assets/session-CMQo8P-G.js +2 -0
  177. package/apps/web/dist/assets/table-5B9G3oA6.js +1 -0
  178. package/apps/web/dist/assets/theme-CdX0marK.js +11 -0
  179. package/apps/web/dist/assets/ui-BCfu5sia.js +16 -0
  180. package/apps/web/dist/assets/upload-CAlHC232.js +1 -0
  181. package/apps/web/dist/assets/{useMutation-7_FOHoEl.js → useMutation-1fV4Nnxq.js} +1 -1
  182. package/apps/web/dist/assets/viewers-ChriFcRy.js +2 -0
  183. package/apps/web/dist/assets/volume-2-BqlBtCIJ.js +1 -0
  184. package/apps/web/dist/assets/w3c-keyname-BOAvb0qz.js +1 -0
  185. package/apps/web/dist/assets/xlsx-CuSbHU4R.js +141 -0
  186. package/apps/web/dist/index.html +19 -14
  187. package/apps/web/dist/mcp/flow.html +2 -2
  188. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +223 -4
  189. package/node_modules/@engenty/wizards/dist/plugin/mount.d.ts +123 -0
  190. package/node_modules/@engenty/wizards/dist/plugin/mount.js +7 -0
  191. package/node_modules/@engenty/wizards/dist/plugin/studio.d.ts +110 -1
  192. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +1 -1
  193. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +24 -0
  194. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +24 -0
  195. package/node_modules/@engenty/wizards-shared/dist/knowledge.d.ts +33 -4
  196. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +3 -0
  197. package/node_modules/@engenty/wizards-shared/dist/run.js +6 -0
  198. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +21 -4
  199. package/node_modules/@engenty/wizards-shared/dist/rwx.js +27 -3
  200. package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +11 -1
  201. package/node_modules/@engenty/wizards-shared/dist/spaces.js +9 -2
  202. package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +6 -0
  203. package/node_modules/@engenty/wizards-shared/dist/text-merge.js +25 -0
  204. package/package.json +3 -1
  205. package/plugin/.claude-plugin/plugin.json +1 -1
  206. package/plugin/plugin.json +1 -1
  207. package/apps/web/dist/assets/AboutDialog-DaWEIHFN.js +0 -1
  208. package/apps/web/dist/assets/CapabilitiesPage-Dt91U_sK.js +0 -2
  209. package/apps/web/dist/assets/EditorPage-DS_a5K3s.js +0 -3
  210. package/apps/web/dist/assets/Marketplace-CS7JTgiv.js +0 -2
  211. package/apps/web/dist/assets/NewWizardChannels-D-OLsex6.js +0 -1
  212. package/apps/web/dist/assets/NewWizardPage-BM_pkk41.js +0 -7
  213. package/apps/web/dist/assets/OnboardingPage-Cpn5pubC.js +0 -1
  214. package/apps/web/dist/assets/PreviewPane-BOk1-yO4.js +0 -9
  215. package/apps/web/dist/assets/PublicRunner-CgzMZb0r.js +0 -1
  216. package/apps/web/dist/assets/ReadOnly-8DEx-ly3.js +0 -1
  217. package/apps/web/dist/assets/SettingsPage-CcrknFcI.js +0 -2
  218. package/apps/web/dist/assets/SetupPage-D5nzjgPU.js +0 -1
  219. package/apps/web/dist/assets/SkillEditor-BsXTqNli.js +0 -1
  220. package/apps/web/dist/assets/Skills-C_X1ZsKg.js +0 -9
  221. package/apps/web/dist/assets/SpacePage-wZGqUoSQ.js +0 -2
  222. package/apps/web/dist/assets/UpdateCheck-D6x7MqEl.js +0 -2
  223. package/apps/web/dist/assets/changelog-M-eOBqgu.js +0 -1
  224. package/apps/web/dist/assets/circle-alert-DJbCyxcg.js +0 -1
  225. package/apps/web/dist/assets/circle-check-jqtsKi_b.js +0 -1
  226. package/apps/web/dist/assets/code-editor-BpCEnf8H.js +0 -2
  227. package/apps/web/dist/assets/code-xml-q88cSTV8.js +0 -1
  228. package/apps/web/dist/assets/connection-sign-in-UJ6xk-TD.js +0 -1
  229. package/apps/web/dist/assets/dist-EBVTpvRr.js +0 -10
  230. package/apps/web/dist/assets/eye-CgkvVlba.js +0 -1
  231. package/apps/web/dist/assets/host-Bd_bon_c.js +0 -118
  232. package/apps/web/dist/assets/i18n-0fUKyVRE.js +0 -55
  233. package/apps/web/dist/assets/index-D18DvnxX.css +0 -1
  234. package/apps/web/dist/assets/index-DOgwxnto.js +0 -10
  235. package/apps/web/dist/assets/oss-credits-IdX5bc71.js +0 -1
  236. package/apps/web/dist/assets/phone-CjPvZ0nk.js +0 -1
  237. package/apps/web/dist/assets/read-aloud-CLXo_asN.js +0 -1
  238. package/apps/web/dist/assets/scroll-text-2BhJO_W7.js +0 -1
  239. package/apps/web/dist/assets/session-CpYa5hwd.js +0 -2
  240. package/apps/web/dist/assets/theme-Bj3wNQR0.js +0 -11
  241. package/apps/web/dist/assets/ui-CktezodE.js +0 -82
  242. package/apps/web/dist/assets/upload-CHGCFVZK.js +0 -1
  243. package/apps/web/dist/assets/volume-2-Bw5KASy8.js +0 -1
@@ -1,8 +1,8 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { featureOn } from "@engenty/wizards-shared/features";
3
3
  import { note } from "@engenty/wizards-shared/run";
4
- import { RWX_ALL, RWX_LIMITS, RWX_ROLES, } from "@engenty/wizards-shared/rwx";
5
- import { and, eq, inArray } from "drizzle-orm";
4
+ import { AUDIENCES, RWX_ALL, RWX_LIMITS, RWX_ROLES, } from "@engenty/wizards-shared/rwx";
5
+ import { and, eq, inArray, isNull } from "drizzle-orm";
6
6
  import { nanoid } from "nanoid";
7
7
  import { db, schema } from "../db/client.js";
8
8
  import { currentFeatures } from "../features.js";
@@ -38,6 +38,8 @@ export async function brokerOn() {
38
38
  */
39
39
  export const SYSTEM = Object.freeze({ kind: "system", id: null });
40
40
  export const subjectsOfGuest = () => [{ kind: "guest", id: null }];
41
+ /** An AI working for a person: a Work chat, a client's chat, Claude or Codex through MCP. */
42
+ export const AGENT = Object.freeze({ kind: "agent", id: null });
41
43
  /** A signed-in person: their own rows, and their role's. */
42
44
  export const subjectsOfPerson = (userId, role) => [
43
45
  { kind: "person", id: userId },
@@ -101,7 +103,10 @@ export async function runHolder(run) {
101
103
  return { kind: "guest", id: run.visitorId ?? run.id };
102
104
  }
103
105
  // --- deciding --------------------------------------------------------------------------------
104
- const about = (rule, subjects) => subjects.some((s) => s.kind === rule.subjectKind && (s.id ?? null) === (rule.subjectId ?? null));
106
+ /** A rule is about a subject of its kind with its id; a wizard rule on `*` about every wizard. */
107
+ const about = (rule, subjects) => subjects.some((s) => s.kind === rule.subjectKind &&
108
+ ((s.id ?? null) === (rule.subjectId ?? null) ||
109
+ (rule.subjectKind === "wizard" && rule.subjectId === RWX_ALL)));
105
110
  const names = (rule, resource) => rule.resourceKind === resource.kind &&
106
111
  (rule.resourceId === RWX_ALL || rule.resourceId === resource.id);
107
112
  /** The first rule about the subjects and the resource that says `flag` for `perm`. */
@@ -112,7 +117,8 @@ const matching = (rules, subjects, resource, perm, flag) => rules.find((r) => ab
112
117
  */
113
118
  function decideSystem(rules, others, resource, perm) {
114
119
  const behind = resource.fileId ? [{ kind: "document", id: resource.fileId }] : [];
115
- for (const r of [{ kind: resource.kind, id: resource.id }, ...behind]) {
120
+ const folders = (resource.folders ?? []).map((id) => ({ kind: "page", id }));
121
+ for (const r of [{ kind: resource.kind, id: resource.id }, ...behind, ...folders]) {
116
122
  const deny = matching(rules, others, r, perm, "deny");
117
123
  if (deny) {
118
124
  return { ok: false, rule: deny.id, reason: `${r.kind} ${r.id}: denied`, of: r };
@@ -154,7 +160,38 @@ export function decideWith(rules, subjects, resource, perm) {
154
160
  const others = subjects.filter((s) => s !== SYSTEM);
155
161
  return decideSystem(rules, others, resource, perm);
156
162
  }
157
- const own = decideOne(rules, subjects, resource, perm);
163
+ // A folder's rule names it by id: its deny closes what lies in it, its allow opens it.
164
+ const inFolder = (flag) => {
165
+ for (const id of resource.folders ?? []) {
166
+ const r = rules.find((x) => about(x, subjects) &&
167
+ x.resourceKind === "page" &&
168
+ x.resourceId === id &&
169
+ x[perm] === flag);
170
+ if (r) {
171
+ return { rule: r, id };
172
+ }
173
+ }
174
+ return null;
175
+ };
176
+ const closed = inFolder("deny");
177
+ if (closed) {
178
+ return {
179
+ ok: false,
180
+ rule: closed.rule.id,
181
+ reason: `${resource.kind} ${resource.id}: denied in folder ${closed.id}`,
182
+ of: { kind: resource.kind, id: resource.id },
183
+ };
184
+ }
185
+ let own = decideOne(rules, subjects, resource, perm);
186
+ const opened = own.ok ? null : inFolder("allow");
187
+ if (opened && !own.rule) {
188
+ own = {
189
+ ok: true,
190
+ rule: opened.rule.id,
191
+ reason: `${resource.kind} ${resource.id}: allowed in folder ${opened.id}`,
192
+ of: own.of,
193
+ };
194
+ }
158
195
  if (!(own.ok && resource.fileId)) {
159
196
  return own;
160
197
  }
@@ -175,7 +212,56 @@ export async function decide(spaceId, subjects, resource, perm) {
175
212
  if (!(await brokerOn())) {
176
213
  return { ok: true, reason: "off", of: { kind: resource.kind, id: resource.id } };
177
214
  }
178
- return decideWith(await rulesOf(spaceId), subjects, resource, perm);
215
+ const rules = await rulesOf(spaceId);
216
+ const [item] = await withFolders(spaceId, rules, [resource]);
217
+ return decideWith(rules, subjects, item, perm);
218
+ }
219
+ const KNOWLEDGE_KINDS = new Set(["document", "page", "table"]);
220
+ /**
221
+ * The items with the folders they lie in, where the space has a rule on a folder: a rule on a
222
+ * page by its id. Without one, nothing is looked up.
223
+ */
224
+ async function withFolders(spaceId, rules, items) {
225
+ const onFolders = rules.some((r) => r.resourceKind === "page" && r.resourceId !== RWX_ALL);
226
+ const asked = items.filter((i) => KNOWLEDGE_KINDS.has(i.kind) && !i.folders);
227
+ if (!(onFolders && asked.length)) {
228
+ return items;
229
+ }
230
+ const ids = (kind) => asked.filter((i) => i.kind === kind).map((i) => i.id);
231
+ const [pages, files, tables] = await Promise.all([
232
+ db.query.spacePage.findMany({
233
+ where: eq(schema.spacePage.spaceId, spaceId),
234
+ columns: { id: true, parentId: true },
235
+ }),
236
+ ids("document").length
237
+ ? db.query.spaceFile.findMany({
238
+ where: inArray(schema.spaceFile.id, ids("document")),
239
+ columns: { id: true, parentId: true },
240
+ })
241
+ : [],
242
+ ids("table").length
243
+ ? db.query.spaceTable.findMany({
244
+ where: inArray(schema.spaceTable.id, ids("table")),
245
+ columns: { id: true, parentId: true },
246
+ })
247
+ : [],
248
+ ]);
249
+ const parentOf = new Map(pages.map((p) => [p.id, p.parentId]));
250
+ const parentOfItem = new Map([
251
+ ...files.map((f) => [`document:${f.id}`, f.parentId]),
252
+ ...tables.map((t) => [`table:${t.id}`, t.parentId]),
253
+ ...pages.map((p) => [`page:${p.id}`, p.parentId]),
254
+ ]);
255
+ const chain = (from) => {
256
+ const out = [];
257
+ for (let at = from; at && !out.includes(at); at = parentOf.get(at)) {
258
+ out.push(at);
259
+ }
260
+ return out;
261
+ };
262
+ return items.map((i) => KNOWLEDGE_KINDS.has(i.kind) && !i.folders
263
+ ? { ...i, folders: chain(parentOfItem.get(`${i.kind}:${i.id}`)) }
264
+ : i);
179
265
  }
180
266
  const WHAT = {
181
267
  document: "rwxDocument",
@@ -188,6 +274,7 @@ const WHAT = {
188
274
  wizard: "rwxWizard",
189
275
  skill: "rwxSkill",
190
276
  setup: "rwxSetup",
277
+ mount: "rwxMount",
191
278
  };
192
279
  const VERB = { r: "rwxRead", w: "rwxWrite", x: "rwxRun" };
193
280
  /** The refusal: *verboten*, the resource's kind and id, nothing of its content. */
@@ -205,13 +292,34 @@ export async function readable(spaceId, subjects, items) {
205
292
  return new Set(items.map((i) => i.id));
206
293
  }
207
294
  const rules = await rulesOf(spaceId);
208
- return new Set(items.filter((i) => decideWith(rules, subjects, i, "r").ok).map((i) => i.id));
295
+ const known = await withFolders(spaceId, rules, items);
296
+ return new Set(known.filter((i) => decideWith(rules, subjects, i, "r").ok).map((i) => i.id));
209
297
  }
210
298
  /** The ids of `kind` among `ids` the subjects may read, in their order. */
211
299
  export async function readableIds(spaceId, subjects, kind, ids) {
212
300
  const ok = await readable(spaceId, subjects, ids.map((id) => ({ kind, id })));
213
301
  return ids.filter((id) => ok.has(id));
214
302
  }
303
+ /**
304
+ * The mounts of Dateien among `ids` the subjects may read: the people (a person, Goose, a guest)
305
+ * by their rules, and a run's wizard by its own as well. A mount's rules are written with it
306
+ * (mounts/mounts.ts): who in the space sees it, which wizards may use it.
307
+ */
308
+ export async function readableMounts(spaceId, subjects, ids) {
309
+ if (!(await brokerOn())) {
310
+ return new Set(ids);
311
+ }
312
+ const rules = await rulesOf(spaceId);
313
+ // The person, the run's wizard and an AI working for the person each need the mount's rules.
314
+ const wizards = subjects.filter((s) => s.kind === "wizard");
315
+ const agents = subjects.filter((s) => s.kind === "agent");
316
+ const people = subjects.filter((s) => s.kind !== "wizard" && s.kind !== "agent");
317
+ const ok = (who, id) => decideWith(rules, who, { kind: "mount", id }, "r").ok;
318
+ return new Set(ids.filter((id) => subjects.length > 0 &&
319
+ (!people.length || ok(people, id)) &&
320
+ (!wizards.length || ok(wizards, id)) &&
321
+ (!agents.length || ok(agents, id))));
322
+ }
215
323
  /** Pages by id with the document behind each, for `readable`. */
216
324
  export async function pageResources(pageIds) {
217
325
  if (!pageIds.length) {
@@ -255,6 +363,10 @@ export async function readsEverything(spaceId, subjects) {
255
363
  */
256
364
  export async function seedRwx(spaceId) {
257
365
  const seeded = [];
366
+ const space = await db.query.space.findFirst({
367
+ columns: { kind: true },
368
+ where: eq(schema.space.id, spaceId),
369
+ });
258
370
  for (const kind of ENFORCED) {
259
371
  for (const role of ["admin", "owner"]) {
260
372
  seeded.push(rule("role", role, kind, { r: "allow", w: "allow", x: "allow" }));
@@ -264,6 +376,12 @@ export async function seedRwx(spaceId) {
264
376
  if (guest) {
265
377
  seeded.push(rule("guest", null, kind, guest));
266
378
  }
379
+ // A client space's clients work with their own data, and run what the space lets them. A
380
+ // space gets no rule for clients: what of it a client reads, a rule opens item by item.
381
+ const client = space?.kind === "client" ? CLIENT_SEED[kind] : undefined;
382
+ if (client) {
383
+ seeded.push(rule("role", "client", kind, client));
384
+ }
267
385
  }
268
386
  await db
269
387
  .insert(schema.rwxRule)
@@ -280,6 +398,17 @@ const MEMBER_SEED = {
280
398
  wizard: { r: "allow", w: null, x: "allow" },
281
399
  skill: { r: "allow", w: null, x: "allow" },
282
400
  };
401
+ /**
402
+ * A client's seed in their client space (docs/plans/client-spaces.md): its data read and written,
403
+ * wizards and skills read and run; never its setup.
404
+ */
405
+ const CLIENT_SEED = {
406
+ document: { r: "allow", w: "allow", x: null },
407
+ table: { r: "allow", w: "allow", x: null },
408
+ page: { r: "allow", w: "allow", x: null },
409
+ wizard: { r: "allow", w: null, x: "allow" },
410
+ skill: { r: "allow", w: null, x: "allow" },
411
+ };
283
412
  /** A guest's seed: data read, a skill read and run in its run; no wizard, no setup. */
284
413
  const GUEST_SEED = {
285
414
  document: { r: "allow", w: null, x: null },
@@ -399,3 +528,122 @@ export async function deleteRule(userId, spaceId, ruleId) {
399
528
  reason: "An RWX rule was deleted.",
400
529
  });
401
530
  }
531
+ /**
532
+ * Opens one item of a space to the clients of its client spaces, or closes it again
533
+ * (docs/plans/client-spaces.md): a rule for the role `client` on that item, read (and run for a
534
+ * wizard). Its admins decide; the change is a line of the log.
535
+ */
536
+ export async function setOpenToClients(userId, spaceId, resource, open) {
537
+ const space = await ownedSpace(userId, spaceId);
538
+ await requireBroker();
539
+ requireRuleAdmin();
540
+ await rulesOf(space.id);
541
+ const where = and(eq(schema.rwxRule.spaceId, space.id), eq(schema.rwxRule.subjectKind, "role"), eq(schema.rwxRule.subjectId, "client"), eq(schema.rwxRule.resourceKind, resource.kind), eq(schema.rwxRule.resourceId, resource.id));
542
+ await db.delete(schema.rwxRule).where(where);
543
+ if (open) {
544
+ const opened = {
545
+ subjectKind: "role",
546
+ subjectId: "client",
547
+ resourceKind: resource.kind,
548
+ resourceId: resource.id,
549
+ r: "allow",
550
+ w: null,
551
+ x: resource.kind === "wizard" ? "allow" : null,
552
+ };
553
+ await db.insert(schema.rwxRule).values(row(space.id, opened, userId));
554
+ }
555
+ await logRuleChange({
556
+ userId,
557
+ spaceId: space.id,
558
+ connectionId: "rwx",
559
+ summary: { [resource.kind]: resource.id, clients: open },
560
+ reason: `${resource.kind} ${resource.id} ${open ? "opened to" : "closed to"} the space's clients.`,
561
+ });
562
+ }
563
+ /**
564
+ * The rules a Wissen folder's audience writes, on the folder (a page) by its id: the team and
565
+ * guests read by the space's seed, so leaving them out closes the folder to them; clients read
566
+ * nothing of the space by their seed, so taking them in opens it. What lies in the folder follows
567
+ * (`withFolders`).
568
+ */
569
+ function folderRules(folderId, see) {
570
+ const on = (subjectKind, subjectId, flags) => ({
571
+ subjectKind,
572
+ subjectId,
573
+ resourceKind: "page",
574
+ resourceId: folderId,
575
+ r: null,
576
+ w: null,
577
+ x: null,
578
+ ...flags,
579
+ });
580
+ return [
581
+ ...(see.includes("team") ? [] : [on("role", "member", { r: "deny", w: "deny" })]),
582
+ ...(see.includes("guests") ? [] : [on("guest", null, { r: "deny" })]),
583
+ ...(see.includes("clients") ? [on("role", "client", { r: "allow" })] : []),
584
+ ];
585
+ }
586
+ const AUDIENCE_SUBJECTS = [
587
+ ["role", "member"],
588
+ ["role", "client"],
589
+ ["guest", null],
590
+ ];
591
+ async function knowledgeFolder(userId, spaceId, folderId) {
592
+ const space = await ownedSpace(userId, spaceId);
593
+ const folder = await db.query.spacePage.findFirst({
594
+ columns: { id: true },
595
+ where: and(eq(schema.spacePage.spaceId, space.id), eq(schema.spacePage.id, folderId)),
596
+ });
597
+ if (!folder) {
598
+ throw notFound();
599
+ }
600
+ return { space, folder };
601
+ }
602
+ /** Who besides the admins sees a Wissen folder, as its rules say. */
603
+ export async function folderAudience(userId, spaceId, folderId) {
604
+ const { space, folder } = await knowledgeFolder(userId, spaceId, folderId);
605
+ const rules = (await rulesOf(space.id)).filter((r) => r.resourceKind === "page" && r.resourceId === folder.id);
606
+ const has = (kind, id, flag) => rules.some((r) => r.subjectKind === kind && (r.subjectId ?? null) === id && r.r === flag);
607
+ return AUDIENCES.filter((a) => a === "team"
608
+ ? !has("role", "member", "deny")
609
+ : a === "guests"
610
+ ? !has("guest", null, "deny")
611
+ : has("role", "client", "allow"));
612
+ }
613
+ /** Sets who besides the admins sees a Wissen folder and everything in it. Admins only. */
614
+ export async function setFolderAudience(userId, spaceId, folderId, see) {
615
+ const { space, folder } = await knowledgeFolder(userId, spaceId, folderId);
616
+ await requireBroker();
617
+ requireRuleAdmin();
618
+ await rulesOf(space.id);
619
+ const r = schema.rwxRule;
620
+ for (const [kind, id] of AUDIENCE_SUBJECTS) {
621
+ await db
622
+ .delete(r)
623
+ .where(and(eq(r.spaceId, space.id), eq(r.resourceKind, "page"), eq(r.resourceId, folder.id), eq(r.subjectKind, kind), id === null ? isNull(r.subjectId) : eq(r.subjectId, id)));
624
+ }
625
+ const rules = folderRules(folder.id, see);
626
+ if (rules.length) {
627
+ await db.insert(r).values(rules.map((x) => row(space.id, x, userId)));
628
+ }
629
+ await logRuleChange({
630
+ userId,
631
+ spaceId: space.id,
632
+ connectionId: "rwx",
633
+ summary: { page: folder.id, see: see.join(",") || "admins" },
634
+ reason: `Folder ${folder.id} seen by ${see.length ? see.join(", ") : "the admins alone"}.`,
635
+ });
636
+ }
637
+ /** The ids of each kind a space opened to its clients. */
638
+ export async function openToClients(spaceId) {
639
+ const rows = await db.query.rwxRule.findMany({
640
+ where: and(eq(schema.rwxRule.spaceId, spaceId), eq(schema.rwxRule.subjectKind, "role"), eq(schema.rwxRule.subjectId, "client")),
641
+ });
642
+ const out = { document: [], table: [], page: [], wizard: [] };
643
+ for (const r of rows) {
644
+ if (r.resourceKind in out && r.resourceId !== RWX_ALL && r.r === "allow") {
645
+ out[r.resourceKind].push(r.resourceId);
646
+ }
647
+ }
648
+ return out;
649
+ }
@@ -56,6 +56,8 @@ ${line(`${command()} disconnect`, "remove your wizards from those apps (same nam
56
56
  ${line(`${command()} mcp`, "run the MCP server over stdio (AI apps start this)")}
57
57
  ${line(`${command()} uninstall`, "take it off this computer: shows the plan, asks about your data (kept by default)")}
58
58
  ${more("--dry-run only shows it; --yes asks nothing and keeps your data; --yes --delete-data")}
59
+ ${line(`${command()} move-files`, "move the spaces’ files to where 0.16 keeps them; runs by itself at start, by hand for a second try")}
60
+ ${line(`${command()} move-folder-sources`, "once with Dateien on: the Sources plugin’s folders become mounts, taken into Wissen from there")}
59
61
  ${line(`${command()} validate`, "check wizards without the studio: .wizard files, unpacked packages, wizard JSON")}
60
62
  ${more("--json prints the issues as JSON. A space’s connectors and plugins are checked on import.")}
61
63
 
@@ -219,6 +221,11 @@ async function main(argv) {
219
221
  return mcp(paths);
220
222
  case "features":
221
223
  return featuresCommand(args.apps);
224
+ case "move-files":
225
+ // Opens the databases: loaded only for this command.
226
+ return (await import("./move-files.js")).moveFiles();
227
+ case "move-folder-sources":
228
+ return (await import("./move-folder-sources.js")).moveFolderSources();
222
229
  case "validate":
223
230
  // The paths are the person's, from where they typed the command (install-env.ts).
224
231
  process.chdir(startedIn);
@@ -0,0 +1,68 @@
1
+ import { eq, isNull } from "drizzle-orm";
2
+ import { db, knownTenants, migrateControlDb, schema, withTenant } from "../db/client.js";
3
+ import { blobThumb, putBlob } from "../files/blobs.js";
4
+ import { objects } from "../files/objects.js";
5
+ /**
6
+ * `wizards move-files` — once, after the update to 0.16: a space file's bytes move from the
7
+ * asset it lived in (`assets/<id>.<ext>`) to the blob store by their hash (`blobs/`), with the
8
+ * thumbnail of a picture or PDF, for every tenant this runtime knows. Until then such a file
9
+ * doesn't open. What moved is not moved again, so a second run moves only what the first could
10
+ * not reach. The runtime runs it by itself when it starts (`moveFilesAtStart`); by hand it is
11
+ * for a second try. In the cloud it runs as `node apps/runtime/dist/move-files.js`, with the
12
+ * runtime's environment.
13
+ */
14
+ export async function moveFiles() {
15
+ await migrateControlDb();
16
+ let failed = 0;
17
+ for (const tenant of await knownTenants()) {
18
+ const { moved, missing } = await withTenant(tenant, moveTenantFiles);
19
+ if (moved || missing.length) {
20
+ console.log(`${tenant}: ${moved} moved${missing.length ? `, ${missing.length} without their bytes` : ""}`);
21
+ }
22
+ for (const file of missing) {
23
+ console.log(` ${file}`);
24
+ }
25
+ failed += missing.length;
26
+ }
27
+ console.log(failed ? "Done; the files listed have no bytes to move." : "Done.");
28
+ return failed ? 1 : 0;
29
+ }
30
+ /**
31
+ * At the start of a runtime that serves the studio, after the tenants' databases are current:
32
+ * the files of before 0.16 move, so nobody has to run a command after the update. Quiet when
33
+ * there is nothing to move.
34
+ */
35
+ export async function moveFilesAtStart() {
36
+ for (const tenant of await knownTenants()) {
37
+ try {
38
+ const { moved, missing } = await withTenant(tenant, moveTenantFiles);
39
+ if (moved || missing.length) {
40
+ console.log(`[move-files] ${tenant}: ${moved} moved${missing.length ? `, ${missing.length} without their bytes: ${missing.join("; ")}` : ""}`);
41
+ }
42
+ }
43
+ catch (err) {
44
+ console.error(`[move-files] ${tenant}:`, err.message);
45
+ }
46
+ }
47
+ }
48
+ async function moveTenantFiles() {
49
+ const rows = await db.query.spaceFile.findMany({ where: isNull(schema.spaceFile.hash) });
50
+ let moved = 0;
51
+ const missing = [];
52
+ for (const row of rows) {
53
+ const asset = await db.query.asset.findFirst({ where: eq(schema.asset.id, row.id) });
54
+ const bytes = asset ? await objects.get(`assets/${asset.path}`) : null;
55
+ if (!asset || !bytes) {
56
+ missing.push(`${row.name} (${row.id}, space ${row.spaceId})`);
57
+ continue;
58
+ }
59
+ const hash = await putBlob(bytes);
60
+ await db.update(schema.spaceFile).set({ hash }).where(eq(schema.spaceFile.id, row.id));
61
+ // The file reads from the blob now; its asset goes.
62
+ await db.delete(schema.asset).where(eq(schema.asset.id, asset.id));
63
+ await objects.remove(`assets/${asset.path}`);
64
+ await blobThumb(hash, row.mime);
65
+ moved++;
66
+ }
67
+ return { moved, missing };
68
+ }
@@ -0,0 +1,120 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { relative, resolve, sep } from "node:path";
5
+ import { featureOn } from "@engenty/wizards-shared/features";
6
+ import { and, eq, like, sql } from "drizzle-orm";
7
+ import { nanoid } from "nanoid";
8
+ import { db, knownTenants, migrateControlDb, schema, withTenant } from "../db/client.js";
9
+ import { currentFeatures } from "../features.js";
10
+ import { addMount } from "../mounts/mounts.js";
11
+ import { addressOf, KIND } from "../mounts/source.js";
12
+ import { removeOrigin } from "../services/space-data.js";
13
+ import { CORE } from "../services/space-sources.js";
14
+ import { currentTenant } from "../tenants/tenant.js";
15
+ const ORIGIN = "data-sourcer";
16
+ export async function moveFolderSources() {
17
+ await migrateControlDb();
18
+ let failed = 0;
19
+ for (const tenant of await knownTenants()) {
20
+ failed += await withTenant(tenant, moveTenantSources);
21
+ }
22
+ console.log(failed ? "Done; the sources listed stay as they were." : "Done.");
23
+ return failed ? 1 : 0;
24
+ }
25
+ async function moveTenantSources() {
26
+ const tenant = currentTenant();
27
+ const table = await db.all(sql `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'data_sourcer_source'`);
28
+ if (!table.length) {
29
+ return 0;
30
+ }
31
+ const old = await db.all(sql `SELECT * FROM data_sourcer_source WHERE kind = 'folder' ORDER BY created_at`);
32
+ if (!old.length) {
33
+ return 0;
34
+ }
35
+ const features = await currentFeatures();
36
+ if (!(featureOn(features, "dateien") && featureOn(features, "knowledgeTree"))) {
37
+ console.log(`${tenant}: ${old.length} folder sources wait: switch on dateien and knowledgeTree first (wizards features).`);
38
+ return old.length;
39
+ }
40
+ let failed = 0;
41
+ for (const source of old) {
42
+ const path = resolve(source.address.replace(/^~(?=$|\/)/, homedir()));
43
+ if (!(await stat(path).catch(() => null))?.isDirectory()) {
44
+ console.log(`${tenant}: “${source.label}”: there is no folder ${path} on this computer.`);
45
+ failed++;
46
+ continue;
47
+ }
48
+ // A mount that holds the folder already takes it; else the folder is mounted, for admins.
49
+ const mounts = await db.query.spaceMount.findMany({
50
+ where: eq(schema.spaceMount.spaceId, source.space_id),
51
+ });
52
+ const folders = mounts.flatMap((m) => m.kind === "folder" ? [{ ...m, path: m.source.path }] : []);
53
+ const holding = folders.find((m) => path === m.path || path.startsWith(m.path + sep));
54
+ const mount = holding
55
+ ? { slug: holding.slug, name: holding.name }
56
+ : await addMount("local", source.space_id, {
57
+ path,
58
+ see: [],
59
+ wizards: "none",
60
+ agents: "read",
61
+ });
62
+ const folder = holding ? relative(holding.path, path).split(sep).join("/") : "";
63
+ const address = addressOf(mount.slug, folder);
64
+ if (source.state === "taken") {
65
+ await db.insert(schema.spaceSource).values({
66
+ id: nanoid(12),
67
+ tenantId: tenant,
68
+ spaceId: source.space_id,
69
+ kind: KIND,
70
+ plugin: CORE,
71
+ address,
72
+ label: source.label,
73
+ state: "taken",
74
+ rules: JSON.parse(source.rules || "[]"),
75
+ categories: JSON.parse(source.categories || "[]"),
76
+ everyHours: 24,
77
+ token: randomBytes(18).toString("base64url"),
78
+ status: "idle",
79
+ error: null,
80
+ lastRunAt: null,
81
+ createdAt: new Date(),
82
+ updatedAt: new Date(),
83
+ });
84
+ await dropWritten(source);
85
+ }
86
+ await db.run(sql `DELETE FROM data_sourcer_run WHERE source_id = ${source.id}`);
87
+ await db.run(sql `DELETE FROM data_sourcer_entry WHERE source_id = ${source.id}`);
88
+ await db.run(sql `DELETE FROM data_sourcer_source WHERE id = ${source.id}`);
89
+ console.log(`${tenant}: “${source.label}” → Dateien › ${mount.name}${source.state === "taken" ? `, and Wissen takes ${address} from it` : ""}`);
90
+ }
91
+ return failed;
92
+ }
93
+ /**
94
+ * What the old source wrote, under its keys `<source>:<entry>`: what a person took over becomes
95
+ * the space's own, the rest goes.
96
+ */
97
+ async function dropWritten(source) {
98
+ const prefix = `${source.id}:%`;
99
+ const keys = new Set();
100
+ for (const t of [schema.spacePage, schema.spaceTable, schema.spaceFile]) {
101
+ const rows = await db
102
+ .select({ key: t.originKey })
103
+ .from(t)
104
+ .where(and(eq(t.spaceId, source.space_id), eq(t.origin, ORIGIN), like(t.originKey, prefix)));
105
+ for (const r of rows) {
106
+ if (r.key) {
107
+ keys.add(r.key);
108
+ }
109
+ }
110
+ }
111
+ for (const t of [schema.spacePage, schema.spaceTable]) {
112
+ await db
113
+ .update(t)
114
+ .set({ origin: null, originKey: null, originLabel: null })
115
+ .where(and(eq(t.spaceId, source.space_id), eq(t.origin, ORIGIN), eq(t.kept, true), like(t.originKey, prefix)));
116
+ }
117
+ for (const key of keys) {
118
+ await removeOrigin(ORIGIN, source.space_id, key);
119
+ }
120
+ }
@@ -1,15 +1,24 @@
1
1
  import { DEFAULT_CONNECTION_RULES } from "@engenty/wizards-shared/connectors";
2
2
  import { and, desc, eq } from "drizzle-orm";
3
3
  import { nanoid } from "nanoid";
4
- import { brokerCall, currentCaller, kindOf, reachesOutside } from "../broker/index.js";
4
+ import { brokerCall, currentCaller, grantedScopes, kindOf, reachesOutside, } from "../broker/index.js";
5
5
  import { db, schema } from "../db/client.js";
6
6
  import { buildAuthorizationUrl, createOAuth2Pkce, exchangeAuthorizationCode, } from "../engenty/connections-sdk/oauth2.js";
7
+ import { managed } from "../manage.js";
7
8
  import { seal, unseal } from "../secrets/crypto.js";
8
9
  import { currentTenant } from "../tenants/tenant.js";
9
10
  import { builtinConnector, connectorFetch, resolveEnv, usable, viaAccount } from "./builtin.js";
10
11
  import { connectRedirectUri as redirectUri } from "./index.js";
11
12
  import { keepSpaceSignIn, } from "./space-connections.js";
12
13
  import { AccountConnectError, redeemTicket, startThroughAccount } from "./via-account.js";
14
+ /** The broker's name for a plugin's own request through a connection (`connections.request`). */
15
+ const REQUEST = "request";
16
+ /**
17
+ * What a plugin's connection reaches: the public internet in the cloud; on a local install the
18
+ * local network too, where a person's own bucket (a NAS, a MinIO) is. A wizard's connections stay
19
+ * on the public internet everywhere (`connectorFetch`).
20
+ */
21
+ const pluginFetch = managed ? connectorFetch : (input, init) => fetch(input, init);
13
22
  function oauthConnector(id) {
14
23
  const connector = builtinConnector(id);
15
24
  if (connector?.auth.kind !== "oauth2") {
@@ -176,13 +185,13 @@ export function pluginConnections(plugin) {
176
185
  }
177
186
  return out;
178
187
  },
179
- async start({ space, connector: connectorId, actions, lang }) {
188
+ async start({ space, connector: connectorId, actions, scopes: more, lang }) {
180
189
  const connector = oauthConnector(connectorId);
181
190
  if (connector.auth.kind !== "oauth2") {
182
191
  throw new Error("not an oauth connector");
183
192
  }
184
193
  await spaceExists(space);
185
- const scopes = scopesOf(connector, actions);
194
+ const scopes = [...new Set([...scopesOf(connector, actions), ...(more ?? [])])];
186
195
  const base = {
187
196
  plugin,
188
197
  tenantId: currentTenant(),
@@ -238,7 +247,7 @@ export function pluginConnections(plugin) {
238
247
  }
239
248
  let account;
240
249
  try {
241
- account = await connector.auth.apiKey.verify(keys, connectorFetch);
250
+ account = await connector.auth.apiKey.verify(keys, pluginFetch);
242
251
  }
243
252
  catch (err) {
244
253
  throw Object.assign(new Error(String(err?.message ?? err).slice(0, 300)), {
@@ -307,6 +316,67 @@ export function pluginConnections(plugin) {
307
316
  }
308
317
  return out.result;
309
318
  },
319
+ async request(id, request) {
320
+ const row = await own(id);
321
+ if (!row) {
322
+ throw new Error(`There is no connection "${id}".`);
323
+ }
324
+ const connector = connectorOf(row.connectorId);
325
+ const capability = connector.request;
326
+ if (!capability) {
327
+ throw new Error(`${connector.name} takes no requests of a plugin.`);
328
+ }
329
+ const kind = request.kind ?? "read";
330
+ const caller = currentCaller() ?? {
331
+ who: { kind: "plugin", id: plugin },
332
+ where: { spaceId: row.spaceId },
333
+ };
334
+ reachesOutside(`plugin:${plugin}`, { connection: row.connectorId, action: REQUEST, kind });
335
+ const out = await brokerCall({
336
+ who: caller.who,
337
+ where: { ...caller.where, spaceId: caller.where.spaceId ?? row.spaceId },
338
+ connection: { kind: "space_connection", row, connector },
339
+ action: { id: REQUEST, kind },
340
+ input: { method: request.method ?? "GET", url: request.url.split("?")[0] },
341
+ handler: async (account) => {
342
+ const url = new URL(request.url);
343
+ if (!capability.origins(account.ctx).includes(url.origin)) {
344
+ throw new Error(`${connector.name} takes no requests to ${url.origin}.`);
345
+ }
346
+ const body = request.body;
347
+ const unsigned = new Request(url, {
348
+ method: request.method ?? "GET",
349
+ headers: request.headers,
350
+ body,
351
+ });
352
+ if (!capability.sign) {
353
+ unsigned.headers.set("authorization", `Bearer ${account.ctx.accessToken}`);
354
+ }
355
+ const signed = capability.sign ? await capability.sign(account.ctx, unsigned) : unsigned;
356
+ const res = await pluginFetch(signed.url, {
357
+ method: signed.method,
358
+ headers: signed.headers,
359
+ body,
360
+ signal: request.signal,
361
+ });
362
+ // The service turned the sign-in down: the broker hears of it, as of an action's.
363
+ if (res.status === 401) {
364
+ throw Object.assign(new Error(`${connector.name} refused the sign-in (401).`), {
365
+ status: 401,
366
+ });
367
+ }
368
+ return res;
369
+ },
370
+ });
371
+ if (!out.ok) {
372
+ throw new Error(out.reason);
373
+ }
374
+ return out.result;
375
+ },
376
+ async scopes(id) {
377
+ const row = await own(id);
378
+ return row ? grantedScopes(row) : [];
379
+ },
310
380
  async remove(id) {
311
381
  await db
312
382
  .delete(schema.spaceConnection)