@engenty/wizards-runtime 0.17.0 → 0.17.2

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 (149) hide show
  1. package/apps/runtime/dist/app.js +2 -0
  2. package/apps/runtime/dist/broker/account.js +20 -1
  3. package/apps/runtime/dist/broker/call.js +116 -20
  4. package/apps/runtime/dist/broker/host.js +8 -2
  5. package/apps/runtime/dist/broker/index.js +3 -2
  6. package/apps/runtime/dist/broker/log.js +149 -14
  7. package/apps/runtime/dist/broker/over.js +38 -0
  8. package/apps/runtime/dist/broker/rights.js +192 -0
  9. package/apps/runtime/dist/broker/rwx.js +295 -51
  10. package/apps/runtime/dist/broker/send.js +25 -12
  11. package/apps/runtime/dist/bundles/discover.js +133 -0
  12. package/apps/runtime/dist/bundles/fetch.js +119 -0
  13. package/apps/runtime/dist/bundles/index.js +621 -0
  14. package/apps/runtime/dist/bundles/read.js +607 -0
  15. package/apps/runtime/dist/connectors/external.js +540 -61
  16. package/apps/runtime/dist/connectors/person-sign-ins.js +1 -0
  17. package/apps/runtime/dist/connectors/reload.js +73 -0
  18. package/apps/runtime/dist/connectors/space-connections.js +73 -6
  19. package/apps/runtime/dist/db/migrations/tenant/0058_mcp_state_across_roles.sql +26 -0
  20. package/apps/runtime/dist/db/migrations/tenant/0059_space_connection_paused.sql +2 -0
  21. package/apps/runtime/dist/db/migrations/tenant/0060_space_bundle.sql +21 -0
  22. package/apps/runtime/dist/db/migrations/tenant/0061_space_connection_limits.sql +2 -0
  23. package/apps/runtime/dist/db/migrations/tenant/meta/0058_snapshot.json +6696 -0
  24. package/apps/runtime/dist/db/migrations/tenant/meta/0059_snapshot.json +6710 -0
  25. package/apps/runtime/dist/db/migrations/tenant/meta/0060_snapshot.json +6857 -0
  26. package/apps/runtime/dist/db/migrations/tenant/meta/0061_snapshot.json +6871 -0
  27. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +28 -0
  28. package/apps/runtime/dist/db/schema.js +81 -3
  29. package/apps/runtime/dist/docs/dev/broker.md +312 -32
  30. package/apps/runtime/dist/docs/dev/skills.md +8 -1
  31. package/apps/runtime/dist/docs/user-guide/capabilities.md +127 -5
  32. package/apps/runtime/dist/docs/user-guide/connectors.md +103 -5
  33. package/apps/runtime/dist/docs/user-guide/protocol.md +15 -4
  34. package/apps/runtime/dist/docs/user-guide/skills.md +11 -1
  35. package/apps/runtime/dist/docs/user-guide/test-and-share.md +1 -1
  36. package/apps/runtime/dist/elements/caller.js +2 -2
  37. package/apps/runtime/dist/engenty/connections-external/build-connector.js +23 -8
  38. package/apps/runtime/dist/engenty/connections-external/import-service.js +18 -9
  39. package/apps/runtime/dist/engenty/connections-external/importer/classify.js +12 -0
  40. package/apps/runtime/dist/engenty/connections-external/invoke/http-invoker.js +1 -0
  41. package/apps/runtime/dist/engenty/connections-external/net/guarded-fetch.js +6 -3
  42. package/apps/runtime/dist/engenty/connections-sdk/oauth2.js +2 -2
  43. package/apps/runtime/dist/engenty/shims/web-ingest.js +64 -0
  44. package/apps/runtime/dist/engine/resources.js +15 -6
  45. package/apps/runtime/dist/engine/runner.js +2 -1
  46. package/apps/runtime/dist/env.js +2 -0
  47. package/apps/runtime/dist/index.js +11 -2
  48. package/apps/runtime/dist/mcp/handler.js +2 -2
  49. package/apps/runtime/dist/mcp/seen.js +71 -51
  50. package/apps/runtime/dist/mcp/tools.js +5 -1
  51. package/apps/runtime/dist/prompts/mcp.md +1 -1
  52. package/apps/runtime/dist/prompts/tools.md +16 -0
  53. package/apps/runtime/dist/routes/broker.js +1 -1
  54. package/apps/runtime/dist/routes/bundles.js +91 -0
  55. package/apps/runtime/dist/routes/connections.js +14 -3
  56. package/apps/runtime/dist/routes/discover.js +1 -0
  57. package/apps/runtime/dist/routes/rules.js +53 -9
  58. package/apps/runtime/dist/routes/studio.js +23 -18
  59. package/apps/runtime/dist/services/cloud.js +2 -0
  60. package/apps/runtime/dist/services/discover.js +9 -3
  61. package/apps/runtime/dist/services/draft-events.js +79 -6
  62. package/apps/runtime/dist/services/files.js +2 -2
  63. package/apps/runtime/dist/services/skills.js +61 -5
  64. package/apps/runtime/dist/services/space-index.js +113 -11
  65. package/apps/runtime/dist/services/synced-spaces.js +5 -1
  66. package/apps/runtime/dist/services/wizards.js +48 -2
  67. package/apps/runtime/dist/sharing/jobs.js +6 -2
  68. package/apps/runtime/dist/sync/records.js +6 -1
  69. package/apps/runtime/dist/texts.js +36 -1
  70. package/apps/runtime/dist/tools/connections.js +8 -0
  71. package/apps/runtime/dist/tools/connector.js +13 -1
  72. package/apps/runtime/dist/tools/index.js +8 -3
  73. package/apps/runtime/dist/tools/skills.js +11 -1
  74. package/apps/web/dist/assets/{AboutDialog-B2Xmxyj4.js → AboutDialog-NzB-GEj_.js} +1 -1
  75. package/apps/web/dist/assets/{BlockEditor-D0HoUSih.js → BlockEditor-HyDf8fOb.js} +1 -1
  76. package/apps/web/dist/assets/Bundle-B0Bhs0By.js +1 -0
  77. package/apps/web/dist/assets/CapabilitiesPage-CQSaMsWK.js +2 -0
  78. package/apps/web/dist/assets/{ChangelogDialog-BIrJbAKi.js → ChangelogDialog-Ngxuqubx.js} +1 -1
  79. package/apps/web/dist/assets/{CodeEditor-DUVcXI5P.js → CodeEditor-C2LBf4pS.js} +1 -1
  80. package/apps/web/dist/assets/EditorPage-Dysvvadu.js +3 -0
  81. package/apps/web/dist/assets/{FlowPreview-BIag8_Be.js → FlowPreview-CGfSaeYu.js} +1 -1
  82. package/apps/web/dist/assets/LangSwitch-B7UQlGh5.js +1 -0
  83. package/apps/web/dist/assets/Marketplace-BkIxd1PW.js +2 -0
  84. package/apps/web/dist/assets/{NewWizardChannels-DI3SQ4iS.js → NewWizardChannels-BWLaVFld.js} +1 -1
  85. package/apps/web/dist/assets/NewWizardPage-BpRd8tDF.js +7 -0
  86. package/apps/web/dist/assets/OnboardingPage-ScEcQcR0.js +1 -0
  87. package/apps/web/dist/assets/PreviewPane-CaC1FYxZ.js +7 -0
  88. package/apps/web/dist/assets/ProtocolSection-CILRCYLD.js +1 -0
  89. package/apps/web/dist/assets/PublicRunner-DHX431Pr.js +1 -0
  90. package/apps/web/dist/assets/{ReadOnly-CWf5x74a.js → ReadOnly-DqS1UDQs.js} +1 -1
  91. package/apps/web/dist/assets/SettingsPage-Dp2-rHXu.js +2 -0
  92. package/apps/web/dist/assets/SetupPage-mzMLQcD5.js +1 -0
  93. package/apps/web/dist/assets/SharePage-CBDgqEH7.js +1 -0
  94. package/apps/web/dist/assets/SkillEditor-Cf6FqkkU.js +1 -0
  95. package/apps/web/dist/assets/{Skills-CN4QE7Kx.js → Skills-DqV5Oqqu.js} +5 -5
  96. package/apps/web/dist/assets/SpacePage-C3SXe2hs.js +2 -0
  97. package/apps/web/dist/assets/{UpdateCheck-QhBI3rlQ.js → UpdateCheck-B51jMIhp.js} +2 -2
  98. package/apps/web/dist/assets/brand-CG35IRgr.js +2 -0
  99. package/apps/web/dist/assets/changelog-DN6sziTl.js +1 -0
  100. package/apps/web/dist/assets/{code-editor-DkPo1C-L.js → code-editor-Bsyy7cuT.js} +2 -2
  101. package/apps/web/dist/assets/{host-D6H6Z9Jp.js → host-DaDyLfqT.js} +16 -16
  102. package/apps/web/dist/assets/i18n-CyrHWeGk.js +55 -0
  103. package/apps/web/dist/assets/index-Db9JthZr.css +1 -0
  104. package/apps/web/dist/assets/index-LjwVRoki.js +10 -0
  105. package/apps/web/dist/assets/minus-BpYkOkYw.js +1 -0
  106. package/apps/web/dist/assets/plug-De3mHDFV.js +1 -0
  107. package/apps/web/dist/assets/{read-aloud-CnFwDSGD.js → read-aloud-DCTouK7J.js} +1 -1
  108. package/apps/web/dist/assets/{runners-0sTPbWzr.js → runners-DtiBHvG7.js} +1 -1
  109. package/apps/web/dist/assets/session-DKGZUy6h.js +1 -0
  110. package/apps/web/dist/assets/{theme-CkNTe-_Z.js → theme-Bcj8TXQr.js} +2 -2
  111. package/apps/web/dist/assets/{ui-DAk_vjrL.js → ui-C6vSmisV.js} +1 -1
  112. package/apps/web/dist/assets/{useMutation-isHfB33W.js → useMutation-B8hJ5Z6N.js} +1 -1
  113. package/apps/web/dist/assets/{viewers-ijNZHJFG.js → viewers-b9FdC42r.js} +2 -2
  114. package/apps/web/dist/assets/{volume-2-BqlBtCIJ.js → volume-2-B1roRk6x.js} +1 -1
  115. package/apps/web/dist/index.html +15 -13
  116. package/apps/web/dist/mcp/flow.html +2 -2
  117. package/node_modules/@engenty/wizards-shared/dist/bundles.d.ts +219 -0
  118. package/node_modules/@engenty/wizards-shared/dist/bundles.js +19 -0
  119. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +105 -4
  120. package/node_modules/@engenty/wizards-shared/dist/connectors.js +6 -0
  121. package/node_modules/@engenty/wizards-shared/dist/discover.d.ts +28 -1
  122. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +8 -0
  123. package/node_modules/@engenty/wizards-shared/dist/run.js +16 -0
  124. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +84 -1
  125. package/node_modules/@engenty/wizards-shared/dist/rwx.js +69 -1
  126. package/node_modules/@engenty/wizards-shared/dist/skills.d.ts +20 -3
  127. package/node_modules/@engenty/wizards-shared/dist/skills.js +5 -2
  128. package/package.json +1 -1
  129. package/plugin/.claude-plugin/plugin.json +1 -1
  130. package/plugin/plugin.json +1 -1
  131. package/apps/web/dist/assets/CapabilitiesPage-C1th2cZE.js +0 -2
  132. package/apps/web/dist/assets/EditorPage-56sIqEfF.js +0 -3
  133. package/apps/web/dist/assets/LangSwitch-CJ00IgaO.js +0 -1
  134. package/apps/web/dist/assets/Marketplace-D7-ot9Dz.js +0 -2
  135. package/apps/web/dist/assets/NewWizardPage-CytheHxX.js +0 -7
  136. package/apps/web/dist/assets/OnboardingPage-_91Pa8Ad.js +0 -1
  137. package/apps/web/dist/assets/PreviewPane-BDsYm-_K.js +0 -7
  138. package/apps/web/dist/assets/ProtocolSection-D_zaxHEL.js +0 -1
  139. package/apps/web/dist/assets/PublicRunner-CEgXSk3r.js +0 -1
  140. package/apps/web/dist/assets/SettingsPage-Dr8SDk-L.js +0 -2
  141. package/apps/web/dist/assets/SetupPage-B68n0l4I.js +0 -1
  142. package/apps/web/dist/assets/SharePage-DfznN7ar.js +0 -1
  143. package/apps/web/dist/assets/SkillEditor-BIcIczRc.js +0 -1
  144. package/apps/web/dist/assets/SpacePage-DiVTwhnJ.js +0 -2
  145. package/apps/web/dist/assets/changelog-a_CuplMX.js +0 -1
  146. package/apps/web/dist/assets/i18n-BaPKbQ1s.js +0 -55
  147. package/apps/web/dist/assets/index-CCUG6Vnh.css +0 -1
  148. package/apps/web/dist/assets/index-De0Wb42y.js +0 -10
  149. package/apps/web/dist/assets/session-BMiUrqHg.js +0 -2
@@ -0,0 +1,192 @@
1
+ import { RWX_ALL, } from "@engenty/wizards-shared/rwx";
2
+ import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";
3
+ import { db, schema } from "../db/client.js";
4
+ import { loadedPlugin, loadedPlugins } from "../plugins/registry.js";
5
+ import { ENFORCED } from "./rwx.js";
6
+ /**
7
+ * Where a rule is set. A place that shows a rule also replaces it, so the rule's own shape tells,
8
+ * whoever wrote the row:
9
+ *
10
+ * - `mount`: any rule on a mount. Its form in Dateien writes them all (mounts/mounts.ts), and the
11
+ * rules routes refuse one.
12
+ * - `start`: a role's or the guests' rule on every resource of an enforced kind: the seed
13
+ * (`created_by` `seed`), and what Rechte sets for a role on top of it.
14
+ * - `folder`: on a page of Wissen, what „Wer sieht diesen Ordner“ writes and reads back
15
+ * (`folderRules`): closed to the team or to guests, open to clients. Wissen offers it on every
16
+ * page, a folder or not.
17
+ * - `clients`: „Für Kund:innen sichtbar“ on a document, a table or a wizard
18
+ * (`setOpenToClients`): the clients read it, and run a wizard. On a page of Wissen it is the
19
+ * rule the folder's dialog shows.
20
+ * - `rights`: every other rule. Rechte set it, and removes it.
21
+ */
22
+ export function originOf(rule, page) {
23
+ if (rule.resourceKind === "mount") {
24
+ return "mount";
25
+ }
26
+ const group = rule.subjectKind === "guest" || rule.subjectKind === "role";
27
+ if (rule.resourceId === RWX_ALL) {
28
+ return group && ENFORCED.includes(rule.resourceKind) ? "start" : "rights";
29
+ }
30
+ const role = rule.subjectKind === "role" ? rule.subjectId : null;
31
+ const opensToClients = role === "client" &&
32
+ rule.r === "allow" &&
33
+ rule.w === null &&
34
+ rule.x === (rule.resourceKind === "wizard" ? "allow" : null);
35
+ if (rule.resourceKind === "page" && page?.wissen) {
36
+ const closesToTeam = role === "member" && rule.r === "deny" && rule.w !== "allow" && !rule.x;
37
+ const closesToGuests = rule.subjectKind === "guest" && rule.r === "deny" && !rule.w && !rule.x;
38
+ if (closesToTeam || closesToGuests || opensToClients) {
39
+ return "folder";
40
+ }
41
+ }
42
+ if (opensToClients && ["document", "table", "page", "wizard"].includes(rule.resourceKind)) {
43
+ return "clients";
44
+ }
45
+ return "rights";
46
+ }
47
+ /** The ids the rules name for one kind of resource or subject. */
48
+ const idsOf = (rules, pick) => [
49
+ ...new Set(rules.map(pick).filter((id) => Boolean(id) && id !== RWX_ALL)),
50
+ ];
51
+ /**
52
+ * The rules with where each is set and with their names: a person's, a wizard's, a plugin's; a
53
+ * document's, a page's, a table's, a wizard's, a skill's, a mount's. A name is null where there is
54
+ * nothing to name (a role, guests, every resource of a kind, the setup) or what it named is gone.
55
+ */
56
+ export async function describeRules(spaceId, rules, people) {
57
+ const of = (kind) => idsOf(rules, (r) => (r.resourceKind === kind ? r.resourceId : null));
58
+ const wizardIds = [
59
+ ...new Set([
60
+ ...of("wizard"),
61
+ ...idsOf(rules, (r) => (r.subjectKind === "wizard" ? r.subjectId : null)),
62
+ ]),
63
+ ];
64
+ const [pages, files, tables, wizards, skills, mounts] = await Promise.all([
65
+ of("page").length
66
+ ? db
67
+ .select({
68
+ id: schema.spacePage.id,
69
+ title: schema.spacePage.title,
70
+ wizardId: schema.spacePage.wizardId,
71
+ blank: sql `length(trim(${schema.spacePage.markdown})) = 0`,
72
+ })
73
+ .from(schema.spacePage)
74
+ .where(and(eq(schema.spacePage.spaceId, spaceId), inArray(schema.spacePage.id, of("page"))))
75
+ : [],
76
+ of("document").length
77
+ ? db
78
+ .select({ id: schema.spaceFile.id, name: schema.spaceFile.name })
79
+ .from(schema.spaceFile)
80
+ .where(and(eq(schema.spaceFile.spaceId, spaceId), inArray(schema.spaceFile.id, of("document"))))
81
+ : [],
82
+ of("table").length
83
+ ? db
84
+ .select({ id: schema.spaceTable.id, name: schema.spaceTable.title })
85
+ .from(schema.spaceTable)
86
+ .where(and(eq(schema.spaceTable.spaceId, spaceId), inArray(schema.spaceTable.id, of("table"))))
87
+ : [],
88
+ wizardIds.length
89
+ ? db
90
+ .select({ id: schema.wizard.id, name: schema.wizard.title })
91
+ .from(schema.wizard)
92
+ .where(and(eq(schema.wizard.spaceId, spaceId), inArray(schema.wizard.id, wizardIds)))
93
+ : [],
94
+ of("skill").length
95
+ ? db
96
+ .select({ id: schema.spaceSkill.id, name: schema.spaceSkill.name })
97
+ .from(schema.spaceSkill)
98
+ .where(and(eq(schema.spaceSkill.spaceId, spaceId), inArray(schema.spaceSkill.id, of("skill"))))
99
+ : [],
100
+ of("mount").length
101
+ ? db
102
+ .select({ id: schema.spaceMount.id, name: schema.spaceMount.name })
103
+ .from(schema.spaceMount)
104
+ .where(and(eq(schema.spaceMount.spaceId, spaceId), inArray(schema.spaceMount.id, of("mount"))))
105
+ : [],
106
+ ]);
107
+ const pageOf = new Map(pages.map((p) => [
108
+ p.id,
109
+ { title: p.title, wissen: !p.wizardId, folder: !p.wizardId && Boolean(p.blank) },
110
+ ]));
111
+ const named = (rows) => new Map(rows.map((r) => [r.id, r.name]));
112
+ const names = {
113
+ document: named(files),
114
+ table: named(tables),
115
+ wizard: named(wizards),
116
+ skill: named(skills),
117
+ mount: named(mounts),
118
+ };
119
+ const person = new Map(people.map((p) => [p.id, p.name]));
120
+ const subjectName = (r) => {
121
+ switch (r.subjectKind) {
122
+ case "person":
123
+ case "goose":
124
+ return person.get(r.subjectId ?? "") ?? null;
125
+ case "wizard":
126
+ return names.wizard?.get(r.subjectId ?? "") ?? null;
127
+ case "plugin":
128
+ return loadedPlugin(r.subjectId ?? "")?.source.manifest.name ?? null;
129
+ default:
130
+ return null;
131
+ }
132
+ };
133
+ return rules.map((r) => {
134
+ const page = r.resourceKind === "page" ? pageOf.get(r.resourceId) : undefined;
135
+ return {
136
+ ...r,
137
+ origin: originOf(r, page),
138
+ subjectName: subjectName(r),
139
+ resourceName: page?.title ?? names[r.resourceKind]?.get(r.resourceId) ?? null,
140
+ ...(page?.folder ? { folder: true } : {}),
141
+ };
142
+ });
143
+ }
144
+ /**
145
+ * What Rechte picks from, for a rule and for „Was darf …?“: the organization's people, and the
146
+ * space's wizards, plugins, documents, pages of Wissen, tables and skills. All of them, whatever
147
+ * the admin asking may read: a rule is written about what it closes too.
148
+ */
149
+ export async function ruleChoices(spaceId, people) {
150
+ const [wizards, documents, pages, tables, skills] = await Promise.all([
151
+ db
152
+ .select({ id: schema.wizard.id, name: schema.wizard.title })
153
+ .from(schema.wizard)
154
+ .where(eq(schema.wizard.spaceId, spaceId))
155
+ .orderBy(asc(schema.wizard.title)),
156
+ db
157
+ .select({ id: schema.spaceFile.id, name: schema.spaceFile.name })
158
+ .from(schema.spaceFile)
159
+ .where(and(eq(schema.spaceFile.spaceId, spaceId), eq(schema.spaceFile.kind, "document")))
160
+ .orderBy(asc(schema.spaceFile.name)),
161
+ db
162
+ .select({
163
+ id: schema.spacePage.id,
164
+ name: schema.spacePage.title,
165
+ blank: sql `length(trim(${schema.spacePage.markdown})) = 0`,
166
+ })
167
+ .from(schema.spacePage)
168
+ .where(and(eq(schema.spacePage.spaceId, spaceId), isNull(schema.spacePage.wizardId)))
169
+ .orderBy(asc(schema.spacePage.title)),
170
+ db
171
+ .select({ id: schema.spaceTable.id, name: schema.spaceTable.title })
172
+ .from(schema.spaceTable)
173
+ .where(and(eq(schema.spaceTable.spaceId, spaceId), isNull(schema.spaceTable.wizardId)))
174
+ .orderBy(asc(schema.spaceTable.title)),
175
+ db
176
+ .select({ id: schema.spaceSkill.id, name: schema.spaceSkill.name })
177
+ .from(schema.spaceSkill)
178
+ .where(eq(schema.spaceSkill.spaceId, spaceId))
179
+ .orderBy(asc(schema.spaceSkill.name)),
180
+ ]);
181
+ return {
182
+ people: people.map((p) => ({ id: p.id, name: p.name, role: p.role })),
183
+ wizards,
184
+ plugins: loadedPlugins()
185
+ .filter((p) => !p.error && p.source.entry)
186
+ .map((p) => ({ id: p.source.id, name: p.source.manifest.name })),
187
+ documents,
188
+ pages: pages.map((p) => ({ id: p.id, name: p.name, folder: Boolean(p.blank) })),
189
+ tables,
190
+ skills,
191
+ };
192
+ }
@@ -1,7 +1,7 @@
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 { AUDIENCES, RWX_ALL, RWX_LIMITS, RWX_ROLES, } from "@engenty/wizards-shared/rwx";
4
+ import { AUDIENCES, RWX_ALL, RWX_ASKED, RWX_LIMITS, RWX_PERMS, RWX_ROLES, rwxAsked, } from "@engenty/wizards-shared/rwx";
5
5
  import { and, eq, inArray, isNull } from "drizzle-orm";
6
6
  import { nanoid } from "nanoid";
7
7
  import { db, schema } from "../db/client.js";
@@ -45,6 +45,14 @@ export const subjectsOfPerson = (userId, role) => [
45
45
  { kind: "person", id: userId },
46
46
  { kind: "role", id: role },
47
47
  ];
48
+ /**
49
+ * An AI working for a person: what the person may, and what the space lets agents do. An agent's
50
+ * rows name no one: they hold for every person's AI.
51
+ */
52
+ export const subjectsOfAgent = (userId, role) => [
53
+ ...subjectsOfPerson(userId, role),
54
+ AGENT,
55
+ ];
48
56
  /** Goose for a person: its own rows for them, and the person's. */
49
57
  export const subjectsOfGoose = (userId, role) => [
50
58
  { kind: "goose", id: userId },
@@ -461,94 +469,330 @@ function requireRuleAdmin() {
461
469
  throw new ServiceError("forbidden", MEMBERS_EDIT_ONLY);
462
470
  }
463
471
  }
464
- const key = (r) => [r.subjectKind, r.subjectId ?? "", r.resourceKind, r.resourceId].join("\u0000");
465
- /** A rule as a person wrote it, checked for what the schema cannot say. */
466
- function checkRule(r) {
467
- const refuse = (what) => new ServiceError("invalid", what);
472
+ const PERM_WORD = { r: "read", w: "change", x: "run" };
473
+ const KIND_WORD = {
474
+ document: "a document",
475
+ table: "a table",
476
+ page: "a page",
477
+ connection: "a connection",
478
+ mail: "mail",
479
+ host: "a host",
480
+ sandbox: "the sandbox",
481
+ wizard: "a wizard",
482
+ skill: "a skill",
483
+ setup: "the setup",
484
+ mount: "a mounted folder",
485
+ };
486
+ const SUBJECT_WORD = {
487
+ guest: "a guest",
488
+ person: "a person",
489
+ role: "a role",
490
+ goose: "Goose",
491
+ wizard: "a wizard",
492
+ plugin: "a plugin",
493
+ agent: "an AI working for a person",
494
+ };
495
+ /**
496
+ * Why nothing asks `perm` on a resource of `kind` for a subject of `subject` (a role by its id),
497
+ * or null where a reader does.
498
+ */
499
+ function unasked(subject, kind, perm, subjectId) {
500
+ if (rwxAsked(subject, kind, perm, subjectId)) {
501
+ return null;
502
+ }
503
+ if (kind === "connection") {
504
+ return "A connection has its own audience and rules, set on its page: no rule here is asked for it.";
505
+ }
506
+ if (!Object.keys(RWX_ASKED[kind]).length) {
507
+ return `Nothing asks a rule about ${KIND_WORD[kind]}: a connection's rules and a run's grant decide it.`;
508
+ }
509
+ if (!RWX_ASKED[kind][perm]) {
510
+ return `Nothing asks who may ${PERM_WORD[perm]} ${KIND_WORD[kind]}.`;
511
+ }
512
+ if (rwxAsked(subject, kind, perm)) {
513
+ return `Nothing asks whether a client may ${PERM_WORD[perm]} ${KIND_WORD[kind]}: only Goose does, and a client reaches no studio.`;
514
+ }
515
+ return `Nothing asks whether ${SUBJECT_WORD[subject]} may ${PERM_WORD[perm]} ${KIND_WORD[kind]}.`;
516
+ }
517
+ /**
518
+ * Why the runtime refuses a rule, or null where it takes it: what the schema cannot say about its
519
+ * subject and resource, then every flag in `flags` (all three, unless only some are being set)
520
+ * that no reader asks (`RWX_ASKED`). The sentence says why.
521
+ */
522
+ export function refusalOf(spaceId, r, flags = RWX_PERMS) {
468
523
  if (r.subjectKind === "guest" && r.subjectId !== null) {
469
- throw refuse("A guest rule has no subject id.");
524
+ return "A guest rule has no subject id.";
525
+ }
526
+ if (r.subjectKind === "agent" && r.subjectId !== null) {
527
+ return "A rule for the AI working for a person has no subject id: it holds for every person's.";
470
528
  }
471
529
  if (r.subjectKind === "role" && !RWX_ROLES.includes(r.subjectId ?? "")) {
472
- throw refuse("A role is member, admin or owner.");
530
+ return "A role is member, admin, owner or client.";
473
531
  }
474
- if (r.subjectKind !== "guest" && !r.subjectId) {
475
- throw refuse(`A ${r.subjectKind} rule names the ${r.subjectKind}'s id.`);
532
+ if (r.subjectKind !== "guest" && r.subjectKind !== "agent" && !r.subjectId) {
533
+ return `A ${r.subjectKind} rule names the ${r.subjectKind}'s id.`;
476
534
  }
477
535
  if (!r.resourceId.trim()) {
478
- throw refuse("A rule names the resource's id, or * for all of the kind.");
536
+ return "A rule names the resource's id, or * for all of the kind.";
537
+ }
538
+ if (r.resourceKind === "setup" && r.resourceId !== RWX_ALL && r.resourceId !== spaceId) {
539
+ return "A space has one setup: its rule names the space's id, or *.";
540
+ }
541
+ for (const perm of flags) {
542
+ const why = r[perm] === null ? null : unasked(r.subjectKind, r.resourceKind, perm, r.subjectId);
543
+ if (why) {
544
+ return `${why} The rule would be stored and never asked.`;
545
+ }
479
546
  }
480
- if (r.r === null && r.w === null && r.x === null) {
481
- throw refuse("A rule sets at least one of r, w and x.");
547
+ return null;
548
+ }
549
+ /** A mount's rules are its form's: it reads them back as its switches and replaces them whole. */
550
+ const MOUNT_RULES = "A mounted folder's rules are written with it: who sees it, which wizards use it and what the AI may do are set on the folder in Dateien.";
551
+ const NO_FLAG = "A rule sets at least one of r, w and x.";
552
+ /** What a rule names by its id, in its space: with the document behind a page or a table. */
553
+ async function resourceIn(spaceId, kind, id) {
554
+ const here = (row) => row?.spaceId === spaceId ? row : null;
555
+ switch (kind) {
556
+ case "document": {
557
+ const file = here(await db.query.spaceFile.findFirst({
558
+ columns: { spaceId: true },
559
+ where: eq(schema.spaceFile.id, id),
560
+ }));
561
+ return file && { kind, id };
562
+ }
563
+ case "page": {
564
+ const page = here(await db.query.spacePage.findFirst({
565
+ columns: { spaceId: true, fileId: true },
566
+ where: eq(schema.spacePage.id, id),
567
+ }));
568
+ return page && { kind, id, fileId: page.fileId };
569
+ }
570
+ case "table": {
571
+ const table = here(await db.query.spaceTable.findFirst({
572
+ columns: { spaceId: true, fileId: true },
573
+ where: eq(schema.spaceTable.id, id),
574
+ }));
575
+ return table && { kind, id, fileId: table.fileId };
576
+ }
577
+ case "wizard": {
578
+ const wizard = here(await db.query.wizard.findFirst({
579
+ columns: { spaceId: true },
580
+ where: eq(schema.wizard.id, id),
581
+ }));
582
+ return wizard && { kind, id };
583
+ }
584
+ case "skill": {
585
+ const skill = here(await db.query.spaceSkill.findFirst({
586
+ columns: { spaceId: true },
587
+ where: eq(schema.spaceSkill.id, id),
588
+ }));
589
+ return skill && { kind, id };
590
+ }
591
+ case "setup":
592
+ return id === spaceId ? { kind, id } : null;
593
+ default:
594
+ return null;
482
595
  }
483
596
  }
484
- export async function listRules(userId, spaceId) {
597
+ /** The rule of a space about one subject and one resource: there is at most one. */
598
+ const ruleAbout = (spaceId, r) => db.query.rwxRule.findFirst({
599
+ where: and(eq(schema.rwxRule.spaceId, spaceId), eq(schema.rwxRule.subjectKind, r.subjectKind), r.subjectId === null
600
+ ? isNull(schema.rwxRule.subjectId)
601
+ : eq(schema.rwxRule.subjectId, r.subjectId), eq(schema.rwxRule.resourceKind, r.resourceKind), eq(schema.rwxRule.resourceId, r.resourceId)),
602
+ });
603
+ /** A rule in a few words, for the log: who, what, and each flag it sets. */
604
+ const said = (r) => `${r.subjectKind}${r.subjectId ? ` ${r.subjectId}` : ""} on ${r.resourceKind} ${r.resourceId}: ${RWX_PERMS.filter((p) => r[p])
605
+ .map((p) => `${p} ${r[p]}`)
606
+ .join(", ") || "nothing"}`;
607
+ async function ruleOf(spaceId, ruleId) {
608
+ const rule = await db.query.rwxRule.findFirst({
609
+ where: and(eq(schema.rwxRule.spaceId, spaceId), eq(schema.rwxRule.id, ruleId)),
610
+ });
611
+ if (!rule) {
612
+ throw notFound();
613
+ }
614
+ if (rule.resourceKind === "mount") {
615
+ throw new ServiceError("refused", MOUNT_RULES);
616
+ }
617
+ return rule;
618
+ }
619
+ /** The space whose rules `userId` reads and writes: one of theirs, the switch on, an admin. */
620
+ export async function rulesSpace(userId, spaceId) {
485
621
  const space = await ownedSpace(userId, spaceId);
486
622
  await requireBroker();
487
623
  requireRuleAdmin();
624
+ return space;
625
+ }
626
+ export async function listRules(userId, spaceId) {
627
+ const space = await rulesSpace(userId, spaceId);
488
628
  return (await rulesOf(space.id)).map(view);
489
629
  }
490
630
  /**
491
- * The whole list, as the page saves it: what is there is replaced. An empty list brings the seed
492
- * back the next time the space is read.
631
+ * One rule more, and no other rule touched. Refused: a rule no reader would ask (`refusalOf`), one
632
+ * on a mount (its form writes them), one about a resource the space does not have, and a second
633
+ * rule about the same subject and resource, which is changed instead.
493
634
  */
494
- export async function putRules(userId, spaceId, rules) {
495
- const space = await ownedSpace(userId, spaceId);
496
- await requireBroker();
497
- requireRuleAdmin();
498
- if (rules.length > RWX_LIMITS.rules) {
499
- throw new ServiceError("invalid", `A space holds at most ${RWX_LIMITS.rules} rules.`);
500
- }
501
- const seen = new Set();
502
- for (const r of rules) {
503
- checkRule(r);
504
- if (seen.has(key(r))) {
505
- throw new ServiceError("invalid", "Two rules name the same subject and resource.");
506
- }
507
- seen.add(key(r));
508
- }
509
- await db.transaction(async (tx) => {
510
- await tx.delete(schema.rwxRule).where(eq(schema.rwxRule.spaceId, space.id));
511
- if (rules.length) {
512
- await tx.insert(schema.rwxRule).values(rules.map((r) => row(space.id, r, userId)));
513
- }
635
+ export async function addRule(userId, spaceId, rule) {
636
+ const space = await rulesSpace(userId, spaceId);
637
+ const refuse = (what, data) => new ServiceError("invalid", what, data);
638
+ if (rule.resourceKind === "mount") {
639
+ throw new ServiceError("refused", MOUNT_RULES);
640
+ }
641
+ if (rule.r === null && rule.w === null && rule.x === null) {
642
+ throw refuse(NO_FLAG);
643
+ }
644
+ const why = refusalOf(space.id, rule);
645
+ if (why) {
646
+ throw refuse(why);
647
+ }
648
+ if (rule.resourceId !== RWX_ALL &&
649
+ !(await resourceIn(space.id, rule.resourceKind, rule.resourceId))) {
650
+ throw refuse(`This space has no ${rule.resourceKind} "${rule.resourceId}".`);
651
+ }
652
+ // Seeded first: a space's first rule would else leave it without its start set.
653
+ const rules = await rulesOf(space.id);
654
+ if (rules.length >= RWX_LIMITS.rules) {
655
+ throw refuse(`A space holds at most ${RWX_LIMITS.rules} rules.`);
656
+ }
657
+ const there = await ruleAbout(space.id, rule);
658
+ if (there) {
659
+ throw refuse("There is a rule about this subject and resource already: change that one.", {
660
+ rule: there.id,
661
+ });
662
+ }
663
+ const added = row(space.id, rule, userId);
664
+ await db.insert(schema.rwxRule).values(added);
665
+ await logRuleChange({
666
+ userId,
667
+ spaceId: space.id,
668
+ connectionId: "rwx",
669
+ summary: { added: added.id, [rule.resourceKind]: rule.resourceId },
670
+ reason: `An RWX rule was added: ${said(rule)}.`,
514
671
  });
672
+ return view(await ruleOf(space.id, added.id));
673
+ }
674
+ /**
675
+ * One rule's flags changed, and no other rule touched: the flags named are set (null takes one
676
+ * away), the others stay. A flag set here is refused where no reader asks it; one the rule held
677
+ * before stays as it is.
678
+ */
679
+ export async function changeRule(userId, spaceId, ruleId, flags) {
680
+ const space = await rulesSpace(userId, spaceId);
681
+ const rule = await ruleOf(space.id, ruleId);
682
+ const set = RWX_PERMS.filter((p) => flags[p] !== undefined);
683
+ const next = { ...rule, ...Object.fromEntries(set.map((p) => [p, flags[p] ?? null])) };
684
+ if (next.r === null && next.w === null && next.x === null) {
685
+ throw new ServiceError("invalid", `${NO_FLAG} Remove the rule instead.`);
686
+ }
687
+ const why = refusalOf(space.id, next, set);
688
+ if (why) {
689
+ throw new ServiceError("invalid", why);
690
+ }
691
+ await db
692
+ .update(schema.rwxRule)
693
+ .set({ r: next.r, w: next.w, x: next.x })
694
+ .where(and(eq(schema.rwxRule.spaceId, space.id), eq(schema.rwxRule.id, rule.id)));
515
695
  await logRuleChange({
516
696
  userId,
517
697
  spaceId: space.id,
518
698
  connectionId: "rwx",
519
- summary: { rules: rules.length },
520
- reason: `The RWX rules were replaced: ${rules.length} now.`,
699
+ summary: { changed: rule.id, [rule.resourceKind]: rule.resourceId },
700
+ reason: `An RWX rule was changed: ${said(next)}.`,
521
701
  });
522
- return (await rulesOf(space.id)).map(view);
702
+ return view(next);
523
703
  }
704
+ /** One rule removed, and no other rule touched. A mount's rules go with its form. */
524
705
  export async function deleteRule(userId, spaceId, ruleId) {
525
- const space = await ownedSpace(userId, spaceId);
526
- await requireBroker();
527
- requireRuleAdmin();
528
- const gone = await db
706
+ const space = await rulesSpace(userId, spaceId);
707
+ const rule = await ruleOf(space.id, ruleId);
708
+ await db
529
709
  .delete(schema.rwxRule)
530
- .where(and(eq(schema.rwxRule.spaceId, space.id), eq(schema.rwxRule.id, ruleId)))
531
- .returning({ id: schema.rwxRule.id });
532
- if (!gone.length) {
533
- throw notFound();
534
- }
710
+ .where(and(eq(schema.rwxRule.spaceId, space.id), eq(schema.rwxRule.id, rule.id)));
535
711
  await logRuleChange({
536
712
  userId,
537
713
  spaceId: space.id,
538
714
  connectionId: "rwx",
539
715
  summary: { deleted: ruleId },
540
- reason: "An RWX rule was deleted.",
716
+ reason: `An RWX rule was deleted: ${said(rule)}.`,
541
717
  });
542
718
  }
719
+ /**
720
+ * The subjects a reader would ask for: a person and their role, Goose or an AI for them, a guest,
721
+ * a wizard's run with who holds it, and a plugin's job, which reads as the runtime itself with the
722
+ * plugin beside it (a tool of the plugin reads as whom it was called for).
723
+ */
724
+ async function subjectsOfQuestion(q) {
725
+ const person = async (id) => {
726
+ if (!id) {
727
+ throw new ServiceError("invalid", `The question names the person's id.`);
728
+ }
729
+ return { id, role: await roleOf(id) };
730
+ };
731
+ switch (q.who) {
732
+ case "guest":
733
+ return subjectsOfGuest();
734
+ case "person": {
735
+ const p = await person(q.id);
736
+ return subjectsOfPerson(p.id, p.role);
737
+ }
738
+ case "goose": {
739
+ const p = await person(q.id);
740
+ return subjectsOfGoose(p.id, p.role);
741
+ }
742
+ case "agent": {
743
+ const p = await person(q.id);
744
+ return subjectsOfAgent(p.id, p.role);
745
+ }
746
+ case "wizard": {
747
+ if (!q.id) {
748
+ throw new ServiceError("invalid", "The question names the wizard's id.");
749
+ }
750
+ const holder = q.for ? await person(q.for) : null;
751
+ return [
752
+ ...(holder ? subjectsOfPerson(holder.id, holder.role) : subjectsOfGuest()),
753
+ { kind: "wizard", id: q.id },
754
+ ];
755
+ }
756
+ case "plugin": {
757
+ if (!q.id) {
758
+ throw new ServiceError("invalid", "The question names the plugin's id.");
759
+ }
760
+ return [SYSTEM, { kind: "plugin", id: q.id }];
761
+ }
762
+ }
763
+ }
764
+ /**
765
+ * „Was darf …?“ for content: whether who is asked about may read, change or run a document, a
766
+ * page or folder, a table, a wizard, a skill or the setup, with the rule that decides. It is the
767
+ * readers' own decision (`decideWith`, the folders and the document behind a page as they look
768
+ * them up), and nothing is read or run. What no reader asks has no answer: refused in words, as a
769
+ * rule about it is. Admins only.
770
+ */
771
+ export async function askRule(userId, spaceId, q) {
772
+ const space = await rulesSpace(userId, spaceId);
773
+ const why = unasked(q.who, q.resource, q.perm);
774
+ if (why) {
775
+ throw new ServiceError("invalid", why);
776
+ }
777
+ const id = q.resource === "setup" ? space.id : (q.resourceId ?? "");
778
+ const resource = await resourceIn(space.id, q.resource, id);
779
+ if (!resource) {
780
+ throw notFound();
781
+ }
782
+ const subjects = await subjectsOfQuestion(q);
783
+ const rules = await rulesOf(space.id);
784
+ const [item] = await withFolders(space.id, rules, [resource]);
785
+ const decision = decideWith(rules, subjects, item, q.perm);
786
+ const decided = decision.rule ? rules.find((r) => r.id === decision.rule) : undefined;
787
+ return { decision, rule: decided ? view(decided) : null };
788
+ }
543
789
  /**
544
790
  * Opens one item of a space to the clients of its client spaces, or closes it again
545
791
  * (docs/plans/client-spaces.md): a rule for the role `client` on that item, read (and run for a
546
792
  * wizard). Its admins decide; the change is a line of the log.
547
793
  */
548
794
  export async function setOpenToClients(userId, spaceId, resource, open) {
549
- const space = await ownedSpace(userId, spaceId);
550
- await requireBroker();
551
- requireRuleAdmin();
795
+ const space = await rulesSpace(userId, spaceId);
552
796
  await rulesOf(space.id);
553
797
  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));
554
798
  await db.delete(schema.rwxRule).where(where);