@engenty/wizards-runtime 0.16.2 → 0.17.1

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 (156) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +13 -6
  2. package/apps/runtime/dist/app.js +2 -0
  3. package/apps/runtime/dist/assistant/knows.js +15 -2
  4. package/apps/runtime/dist/broker/account.js +20 -1
  5. package/apps/runtime/dist/broker/call.js +131 -22
  6. package/apps/runtime/dist/broker/grant.js +25 -1
  7. package/apps/runtime/dist/broker/host.js +8 -2
  8. package/apps/runtime/dist/broker/index.js +5 -4
  9. package/apps/runtime/dist/broker/log.js +178 -24
  10. package/apps/runtime/dist/broker/over.js +38 -0
  11. package/apps/runtime/dist/broker/rights.js +192 -0
  12. package/apps/runtime/dist/broker/rwx.js +309 -53
  13. package/apps/runtime/dist/broker/send.js +109 -44
  14. package/apps/runtime/dist/bundles/fetch.js +119 -0
  15. package/apps/runtime/dist/bundles/index.js +621 -0
  16. package/apps/runtime/dist/bundles/read.js +607 -0
  17. package/apps/runtime/dist/connectors/external.js +532 -61
  18. package/apps/runtime/dist/connectors/person-sign-ins.js +1 -0
  19. package/apps/runtime/dist/connectors/reload.js +73 -0
  20. package/apps/runtime/dist/connectors/space-connections.js +118 -6
  21. package/apps/runtime/dist/db/migrations/tenant/0058_mcp_state_across_roles.sql +26 -0
  22. package/apps/runtime/dist/db/migrations/tenant/0059_space_connection_paused.sql +2 -0
  23. package/apps/runtime/dist/db/migrations/tenant/0060_space_bundle.sql +21 -0
  24. package/apps/runtime/dist/db/migrations/tenant/0061_space_connection_limits.sql +2 -0
  25. package/apps/runtime/dist/db/migrations/tenant/meta/0058_snapshot.json +6696 -0
  26. package/apps/runtime/dist/db/migrations/tenant/meta/0059_snapshot.json +6710 -0
  27. package/apps/runtime/dist/db/migrations/tenant/meta/0060_snapshot.json +6857 -0
  28. package/apps/runtime/dist/db/migrations/tenant/meta/0061_snapshot.json +6871 -0
  29. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +28 -0
  30. package/apps/runtime/dist/db/schema.js +81 -3
  31. package/apps/runtime/dist/docs/dev/broker.md +316 -50
  32. package/apps/runtime/dist/docs/dev/plugins/space.md +13 -2
  33. package/apps/runtime/dist/docs/user-guide/capabilities.md +172 -10
  34. package/apps/runtime/dist/docs/user-guide/connectors.md +57 -7
  35. package/apps/runtime/dist/docs/user-guide/protocol.md +44 -7
  36. package/apps/runtime/dist/docs/user-guide/test-and-share.md +1 -1
  37. package/apps/runtime/dist/docs/user-guide/together.md +4 -4
  38. package/apps/runtime/dist/elements/caller.js +2 -2
  39. package/apps/runtime/dist/elements/knowledge.js +16 -12
  40. package/apps/runtime/dist/engenty/connections-external/build-connector.js +23 -8
  41. package/apps/runtime/dist/engenty/connections-external/import-service.js +18 -9
  42. package/apps/runtime/dist/engenty/connections-external/importer/classify.js +12 -0
  43. package/apps/runtime/dist/engenty/connections-external/invoke/http-invoker.js +1 -0
  44. package/apps/runtime/dist/engenty/connections-external/net/guarded-fetch.js +6 -3
  45. package/apps/runtime/dist/engenty/connections-sdk/oauth2.js +2 -2
  46. package/apps/runtime/dist/engenty/shims/web-ingest.js +64 -0
  47. package/apps/runtime/dist/engine/resources.js +15 -6
  48. package/apps/runtime/dist/engine/runner.js +2 -1
  49. package/apps/runtime/dist/engine/steps.js +3 -2
  50. package/apps/runtime/dist/env.js +2 -0
  51. package/apps/runtime/dist/index.js +19 -2
  52. package/apps/runtime/dist/live/hub.js +17 -3
  53. package/apps/runtime/dist/live/origin.js +6 -4
  54. package/apps/runtime/dist/live/views.js +38 -7
  55. package/apps/runtime/dist/mcp/handler.js +2 -2
  56. package/apps/runtime/dist/mcp/seen.js +71 -51
  57. package/apps/runtime/dist/mcp/tools.js +5 -1
  58. package/apps/runtime/dist/models.js +18 -0
  59. package/apps/runtime/dist/prompts/mcp.md +1 -1
  60. package/apps/runtime/dist/prompts/tools.md +17 -1
  61. package/apps/runtime/dist/routes/api.js +2 -2
  62. package/apps/runtime/dist/routes/broker.js +59 -20
  63. package/apps/runtime/dist/routes/bundles.js +91 -0
  64. package/apps/runtime/dist/routes/connections.js +14 -3
  65. package/apps/runtime/dist/routes/live.js +4 -2
  66. package/apps/runtime/dist/routes/rules.js +53 -9
  67. package/apps/runtime/dist/routes/studio.js +36 -20
  68. package/apps/runtime/dist/services/api.js +4 -2
  69. package/apps/runtime/dist/services/cloud.js +2 -0
  70. package/apps/runtime/dist/services/draft-events.js +79 -6
  71. package/apps/runtime/dist/services/errors.js +1 -0
  72. package/apps/runtime/dist/services/files.js +2 -2
  73. package/apps/runtime/dist/services/knowledge.js +93 -27
  74. package/apps/runtime/dist/services/members-studio.js +22 -2
  75. package/apps/runtime/dist/services/skills.js +61 -5
  76. package/apps/runtime/dist/services/space-categories.js +83 -5
  77. package/apps/runtime/dist/services/space-index.js +173 -25
  78. package/apps/runtime/dist/services/space-origin.js +28 -11
  79. package/apps/runtime/dist/services/synced-spaces.js +5 -1
  80. package/apps/runtime/dist/services/wizards.js +48 -2
  81. package/apps/runtime/dist/services/work-ai.js +15 -5
  82. package/apps/runtime/dist/sharing/jobs.js +8 -2
  83. package/apps/runtime/dist/sync/hub.js +17 -3
  84. package/apps/runtime/dist/sync/records.js +6 -1
  85. package/apps/runtime/dist/texts.js +42 -5
  86. package/apps/runtime/dist/tools/connections.js +8 -0
  87. package/apps/runtime/dist/tools/connector.js +13 -1
  88. package/apps/runtime/dist/tools/index.js +21 -10
  89. package/apps/runtime/dist/tools/skills.js +11 -1
  90. package/apps/runtime/dist/tools/web-search.js +36 -0
  91. package/apps/web/dist/assets/{AboutDialog-BCcD8hKm.js → AboutDialog-mZCBU7KF.js} +1 -1
  92. package/apps/web/dist/assets/{BlockEditor-DgaUm2pR.js → BlockEditor-Dk0QwLSU.js} +1 -1
  93. package/apps/web/dist/assets/CapabilitiesPage-GkpgF-wZ.js +2 -0
  94. package/apps/web/dist/assets/{ChangelogDialog-B08elwyr.js → ChangelogDialog-BhyilZWA.js} +1 -1
  95. package/apps/web/dist/assets/{CodeEditor-BiyOk_SC.js → CodeEditor-DULYZbuE.js} +1 -1
  96. package/apps/web/dist/assets/EditorPage-D_mCdYdZ.js +3 -0
  97. package/apps/web/dist/assets/{FlowPreview-DF_6TvZ0.js → FlowPreview-ykxZxWnk.js} +1 -1
  98. package/apps/web/dist/assets/{LangSwitch-Ba4OWLzJ.js → LangSwitch-iO54w9AP.js} +1 -1
  99. package/apps/web/dist/assets/{Marketplace-DqziLf66.js → Marketplace-C97fH7UC.js} +2 -2
  100. package/apps/web/dist/assets/{NewWizardChannels-CsIGp0nZ.js → NewWizardChannels-CsSV7sm2.js} +1 -1
  101. package/apps/web/dist/assets/{NewWizardPage-CzQAkKMy.js → NewWizardPage-Ebgw-Vf_.js} +1 -1
  102. package/apps/web/dist/assets/{OnboardingPage-B9gr2OX5.js → OnboardingPage-BZlloT7v.js} +1 -1
  103. package/apps/web/dist/assets/PreviewPane-CJuqY5uA.js +7 -0
  104. package/apps/web/dist/assets/ProtocolSection-CPaDKVpZ.js +1 -0
  105. package/apps/web/dist/assets/{PublicRunner-BVs8-Vu3.js → PublicRunner-4Lf4SnwB.js} +1 -1
  106. package/apps/web/dist/assets/{ReadOnly--4CIJCDD.js → ReadOnly-CXQ41R9Q.js} +1 -1
  107. package/apps/web/dist/assets/SettingsPage-C-8BgK9O.js +2 -0
  108. package/apps/web/dist/assets/{SetupPage-9Zk-KUGA.js → SetupPage-4_K083Wl.js} +1 -1
  109. package/apps/web/dist/assets/{SharePage-D_Ab0gjr.js → SharePage-CQjgMcDI.js} +1 -1
  110. package/apps/web/dist/assets/{SkillEditor-DvtameHg.js → SkillEditor-DT5hQwbg.js} +1 -1
  111. package/apps/web/dist/assets/{Skills-Cf1Kl4Fy.js → Skills-D7V_9_xo.js} +1 -1
  112. package/apps/web/dist/assets/SpacePage-D3rYS1bA.js +2 -0
  113. package/apps/web/dist/assets/{UpdateCheck-DweZBVP6.js → UpdateCheck-DVgAJmy8.js} +2 -2
  114. package/apps/web/dist/assets/changelog-DzQCUSsx.js +1 -0
  115. package/apps/web/dist/assets/{code-editor-B1RbFTAZ.js → code-editor-5T7ilBjd.js} +2 -2
  116. package/apps/web/dist/assets/{host-CKS5U5Vg.js → host-CCijW1hj.js} +6 -6
  117. package/apps/web/dist/assets/i18n-DCPDesT-.js +55 -0
  118. package/apps/web/dist/assets/{index-Ckcn5vy7.js → index-C_iWl8iS.js} +3 -3
  119. package/apps/web/dist/assets/index-zcPlodHx.css +1 -0
  120. package/apps/web/dist/assets/minus-BpYkOkYw.js +1 -0
  121. package/apps/web/dist/assets/{read-aloud-Bq88XUHC.js → read-aloud-Qb719not.js} +1 -1
  122. package/apps/web/dist/assets/{runners-DvYVe9Dt.js → runners-BeZ84YH_.js} +1 -1
  123. package/apps/web/dist/assets/{session-D2bjiA3P.js → session-CEJRkSP5.js} +1 -1
  124. package/apps/web/dist/assets/{theme-CNJIC2be.js → theme-y_owNosi.js} +1 -1
  125. package/apps/web/dist/assets/{ui-Mplfhz_Z.js → ui-BacfkQ7Q.js} +1 -1
  126. package/apps/web/dist/assets/{useMutation-8QRM-z4M.js → useMutation-CgzFr4qH.js} +1 -1
  127. package/apps/web/dist/assets/{viewers-CEocUV_2.js → viewers-CkyHAjnk.js} +2 -2
  128. package/apps/web/dist/index.html +12 -12
  129. package/apps/web/dist/mcp/flow.html +2 -2
  130. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +7 -2
  131. package/node_modules/@engenty/wizards-shared/dist/bundles.d.ts +219 -0
  132. package/node_modules/@engenty/wizards-shared/dist/bundles.js +19 -0
  133. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +117 -4
  134. package/node_modules/@engenty/wizards-shared/dist/connectors.js +14 -0
  135. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +12 -0
  136. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +12 -0
  137. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +11 -0
  138. package/node_modules/@engenty/wizards-shared/dist/run.js +22 -0
  139. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +84 -1
  140. package/node_modules/@engenty/wizards-shared/dist/rwx.js +69 -1
  141. package/node_modules/@engenty/wizards-shared/dist/skills.d.ts +20 -3
  142. package/node_modules/@engenty/wizards-shared/dist/skills.js +5 -2
  143. package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +3 -2
  144. package/node_modules/@engenty/wizards-shared/dist/spaces.js +12 -3
  145. package/package.json +1 -1
  146. package/plugin/.claude-plugin/plugin.json +1 -1
  147. package/plugin/plugin.json +1 -1
  148. package/apps/web/dist/assets/CapabilitiesPage-DuJJV1ll.js +0 -2
  149. package/apps/web/dist/assets/EditorPage-EMFTHEYD.js +0 -3
  150. package/apps/web/dist/assets/PreviewPane-DSOV3o-1.js +0 -7
  151. package/apps/web/dist/assets/SettingsPage-z2u8lSe2.js +0 -2
  152. package/apps/web/dist/assets/SpacePage-CyqVzX9b.js +0 -2
  153. package/apps/web/dist/assets/changelog-C85v9OWg.js +0 -1
  154. package/apps/web/dist/assets/connection-sign-in-CaVvh5GQ.js +0 -1
  155. package/apps/web/dist/assets/i18n-Bymk5Ev-.js +0 -55
  156. package/apps/web/dist/assets/index-w-3J3ZJ9.css +0 -1
@@ -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 },
@@ -198,13 +206,25 @@ export function decideWith(rules, subjects, resource, perm) {
198
206
  const behind = decideOne(rules, subjects, { kind: "document", id: resource.fileId }, perm);
199
207
  return behind.ok ? own : behind;
200
208
  }
201
- /** The rules of a space, seeded first where it has none yet. */
209
+ /** The spaces being seeded right now, by tenant and space: each once. */
210
+ const seeding = new Map();
211
+ /**
212
+ * The rules of a space, seeded first where it has none yet. Readers that ask at once (a search's
213
+ * three, a plugin listing files and pages together) wait for one seed: a guest's rows have no
214
+ * subject id, so the table's unique key does not keep a second seed's rows out.
215
+ */
202
216
  async function rulesOf(spaceId) {
203
217
  const rows = await db.query.rwxRule.findMany({ where: eq(schema.rwxRule.spaceId, spaceId) });
204
218
  if (rows.length) {
205
219
  return rows;
206
220
  }
207
- await seedRwx(spaceId);
221
+ const key = `${currentTenant()}/${spaceId}`;
222
+ let seed = seeding.get(key);
223
+ if (!seed) {
224
+ seed = seedRwx(spaceId).finally(() => seeding.delete(key));
225
+ seeding.set(key, seed);
226
+ }
227
+ await seed;
208
228
  return db.query.rwxRule.findMany({ where: eq(schema.rwxRule.spaceId, spaceId) });
209
229
  }
210
230
  /** Whether the subjects may do `perm` on the resource. With the switch off: yes. */
@@ -449,94 +469,330 @@ function requireRuleAdmin() {
449
469
  throw new ServiceError("forbidden", MEMBERS_EDIT_ONLY);
450
470
  }
451
471
  }
452
- const key = (r) => [r.subjectKind, r.subjectId ?? "", r.resourceKind, r.resourceId].join("\u0000");
453
- /** A rule as a person wrote it, checked for what the schema cannot say. */
454
- function checkRule(r) {
455
- 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) {
456
523
  if (r.subjectKind === "guest" && r.subjectId !== null) {
457
- 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.";
458
528
  }
459
529
  if (r.subjectKind === "role" && !RWX_ROLES.includes(r.subjectId ?? "")) {
460
- throw refuse("A role is member, admin or owner.");
530
+ return "A role is member, admin, owner or client.";
461
531
  }
462
- if (r.subjectKind !== "guest" && !r.subjectId) {
463
- 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.`;
464
534
  }
465
535
  if (!r.resourceId.trim()) {
466
- 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.";
467
537
  }
468
- if (r.r === null && r.w === null && r.x === null) {
469
- throw refuse("A rule sets at least one of r, w and x.");
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
+ }
546
+ }
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;
470
595
  }
471
596
  }
472
- 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) {
473
621
  const space = await ownedSpace(userId, spaceId);
474
622
  await requireBroker();
475
623
  requireRuleAdmin();
624
+ return space;
625
+ }
626
+ export async function listRules(userId, spaceId) {
627
+ const space = await rulesSpace(userId, spaceId);
476
628
  return (await rulesOf(space.id)).map(view);
477
629
  }
478
630
  /**
479
- * The whole list, as the page saves it: what is there is replaced. An empty list brings the seed
480
- * 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.
481
634
  */
482
- export async function putRules(userId, spaceId, rules) {
483
- const space = await ownedSpace(userId, spaceId);
484
- await requireBroker();
485
- requireRuleAdmin();
486
- if (rules.length > RWX_LIMITS.rules) {
487
- throw new ServiceError("invalid", `A space holds at most ${RWX_LIMITS.rules} rules.`);
488
- }
489
- const seen = new Set();
490
- for (const r of rules) {
491
- checkRule(r);
492
- if (seen.has(key(r))) {
493
- throw new ServiceError("invalid", "Two rules name the same subject and resource.");
494
- }
495
- seen.add(key(r));
496
- }
497
- await db.transaction(async (tx) => {
498
- await tx.delete(schema.rwxRule).where(eq(schema.rwxRule.spaceId, space.id));
499
- if (rules.length) {
500
- await tx.insert(schema.rwxRule).values(rules.map((r) => row(space.id, r, userId)));
501
- }
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)}.`,
502
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)));
503
695
  await logRuleChange({
504
696
  userId,
505
697
  spaceId: space.id,
506
698
  connectionId: "rwx",
507
- summary: { rules: rules.length },
508
- 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)}.`,
509
701
  });
510
- return (await rulesOf(space.id)).map(view);
702
+ return view(next);
511
703
  }
704
+ /** One rule removed, and no other rule touched. A mount's rules go with its form. */
512
705
  export async function deleteRule(userId, spaceId, ruleId) {
513
- const space = await ownedSpace(userId, spaceId);
514
- await requireBroker();
515
- requireRuleAdmin();
516
- const gone = await db
706
+ const space = await rulesSpace(userId, spaceId);
707
+ const rule = await ruleOf(space.id, ruleId);
708
+ await db
517
709
  .delete(schema.rwxRule)
518
- .where(and(eq(schema.rwxRule.spaceId, space.id), eq(schema.rwxRule.id, ruleId)))
519
- .returning({ id: schema.rwxRule.id });
520
- if (!gone.length) {
521
- throw notFound();
522
- }
710
+ .where(and(eq(schema.rwxRule.spaceId, space.id), eq(schema.rwxRule.id, rule.id)));
523
711
  await logRuleChange({
524
712
  userId,
525
713
  spaceId: space.id,
526
714
  connectionId: "rwx",
527
715
  summary: { deleted: ruleId },
528
- reason: "An RWX rule was deleted.",
716
+ reason: `An RWX rule was deleted: ${said(rule)}.`,
529
717
  });
530
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
+ }
531
789
  /**
532
790
  * Opens one item of a space to the clients of its client spaces, or closes it again
533
791
  * (docs/plans/client-spaces.md): a rule for the role `client` on that item, read (and run for a
534
792
  * wizard). Its admins decide; the change is a line of the log.
535
793
  */
536
794
  export async function setOpenToClients(userId, spaceId, resource, open) {
537
- const space = await ownedSpace(userId, spaceId);
538
- await requireBroker();
539
- requireRuleAdmin();
795
+ const space = await rulesSpace(userId, spaceId);
540
796
  await rulesOf(space.id);
541
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));
542
798
  await db.delete(schema.rwxRule).where(where);