@engenty/wizards-runtime 0.19.1 → 0.20.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 (162) hide show
  1. package/apps/runtime/dist/agents/architect.js +4 -4
  2. package/apps/runtime/dist/agents/studio-assistant.js +2 -31
  3. package/apps/runtime/dist/app.js +4 -4
  4. package/apps/runtime/dist/assistant/knows.js +2 -2
  5. package/apps/runtime/dist/auth/index.js +1 -1
  6. package/apps/runtime/dist/authoring/example.js +1 -1
  7. package/apps/runtime/dist/authoring/guide.js +35 -6
  8. package/apps/runtime/dist/broker/account.js +85 -16
  9. package/apps/runtime/dist/broker/call.js +137 -37
  10. package/apps/runtime/dist/broker/log.js +19 -5
  11. package/apps/runtime/dist/broker/rwx.js +12 -9
  12. package/apps/runtime/dist/connectors/index.js +52 -11
  13. package/apps/runtime/dist/connectors/person-connections.js +279 -0
  14. package/apps/runtime/dist/connectors/person-sign-ins.js +74 -3
  15. package/apps/runtime/dist/connectors/same-service.js +14 -0
  16. package/apps/runtime/dist/connectors/space-choice.js +116 -0
  17. package/apps/runtime/dist/connectors/space-connections.js +40 -2
  18. package/apps/runtime/dist/db/client.js +8 -0
  19. package/apps/runtime/dist/db/kept-accounts.js +88 -0
  20. package/apps/runtime/dist/db/migrations/tenant/0075_person_connection.sql +25 -0
  21. package/apps/runtime/dist/db/migrations/tenant/0076_clients_in_spaces.sql +28 -0
  22. package/apps/runtime/dist/db/migrations/tenant/0077_client_spaces_at_root.sql +21 -0
  23. package/apps/runtime/dist/db/migrations/tenant/meta/0075_snapshot.json +7859 -0
  24. package/apps/runtime/dist/db/migrations/tenant/meta/0076_snapshot.json +7859 -0
  25. package/apps/runtime/dist/db/migrations/tenant/meta/0077_snapshot.json +7859 -0
  26. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +21 -0
  27. package/apps/runtime/dist/db/schema.js +67 -16
  28. package/apps/runtime/dist/docs/dev/api.md +8 -8
  29. package/apps/runtime/dist/docs/dev/wizard-format/index.md +3 -1
  30. package/apps/runtime/dist/elements/caller.js +1 -1
  31. package/apps/runtime/dist/elements/knowledge.js +5 -5
  32. package/apps/runtime/dist/elements/wizards.js +7 -11
  33. package/apps/runtime/dist/engine/notices.js +13 -1
  34. package/apps/runtime/dist/engine/requirements.js +116 -3
  35. package/apps/runtime/dist/engine/run-needs.js +58 -0
  36. package/apps/runtime/dist/engine/runner.js +209 -16
  37. package/apps/runtime/dist/engine/starts.js +9 -0
  38. package/apps/runtime/dist/engine/types.js +5 -1
  39. package/apps/runtime/dist/harness/claude.js +3 -1
  40. package/apps/runtime/dist/manage.js +1 -1
  41. package/apps/runtime/dist/mcp/tools.js +3 -3
  42. package/apps/runtime/dist/plugins/runs.js +2 -1
  43. package/apps/runtime/dist/prompts/authoring.md +13 -3
  44. package/apps/runtime/dist/prompts/goose.md +0 -5
  45. package/apps/runtime/dist/routes/api.js +9 -4
  46. package/apps/runtime/dist/routes/client-contract.js +2 -2
  47. package/apps/runtime/dist/routes/client-spaces.js +1 -16
  48. package/apps/runtime/dist/routes/connections.js +6 -1
  49. package/apps/runtime/dist/routes/marketplace.js +27 -7
  50. package/apps/runtime/dist/routes/plugins.js +1 -1
  51. package/apps/runtime/dist/routes/runs.js +157 -11
  52. package/apps/runtime/dist/routes/studio.js +42 -5
  53. package/apps/runtime/dist/services/client-portal.js +58 -49
  54. package/apps/runtime/dist/services/client-spaces.js +57 -125
  55. package/apps/runtime/dist/services/links.js +3 -3
  56. package/apps/runtime/dist/services/marketplace.js +6 -2
  57. package/apps/runtime/dist/services/members-studio.js +1 -1
  58. package/apps/runtime/dist/services/query-vectors.js +1 -1
  59. package/apps/runtime/dist/services/runs.js +19 -20
  60. package/apps/runtime/dist/services/space-parent.js +4 -11
  61. package/apps/runtime/dist/services/spaces.js +56 -47
  62. package/apps/runtime/dist/services/work-ai.js +3 -3
  63. package/apps/runtime/dist/store/index.js +28 -8
  64. package/apps/runtime/dist/store/shared-lists.js +2 -2
  65. package/apps/runtime/dist/sync/hub.js +9 -5
  66. package/apps/runtime/dist/tools/connector.js +4 -2
  67. package/apps/web/dist/assets/{AboutDialog-BUWu36Mb.js → AboutDialog-QWzpEK8M.js} +1 -1
  68. package/apps/web/dist/assets/{BlockEditor-1-EvUIta.js → BlockEditor-C44bI_ih.js} +1 -1
  69. package/apps/web/dist/assets/{Bundle-RNkjBwAL.js → Bundle-DZyQ1FP7.js} +1 -1
  70. package/apps/web/dist/assets/CapabilitiesPage-DAr0-gN1.js +2 -0
  71. package/apps/web/dist/assets/{ChangelogDialog-C_ZZLRZT.js → ChangelogDialog-CdHqJV2P.js} +1 -1
  72. package/apps/web/dist/assets/{CodeEditor-BEJKIMd0.js → CodeEditor-BRufUwu0.js} +1 -1
  73. package/apps/web/dist/assets/ConnectorsSection-BO6jHrYU.js +1 -0
  74. package/apps/web/dist/assets/EditorPage-Bx-fKnsY.js +3 -0
  75. package/apps/web/dist/assets/{FlowPreview-ptI86Ogs.js → FlowPreview-aj58c-gH.js} +1 -1
  76. package/apps/web/dist/assets/{LangSwitch-BNa_H8AR.js → LangSwitch-BNkytlus.js} +1 -1
  77. package/apps/web/dist/assets/Marketplace-D3hdvrkz.js +2 -0
  78. package/apps/web/dist/assets/NewWizardChannels-fveQcQlY.js +1 -0
  79. package/apps/web/dist/assets/NewWizardPage-BTX1g2t1.js +7 -0
  80. package/apps/web/dist/assets/OnboardingPage-DwF6KdQy.js +1 -0
  81. package/apps/web/dist/assets/ProtocolSection-YnJcMN9E.js +1 -0
  82. package/apps/web/dist/assets/PublicRunner-Bp4DxTrD.js +1 -0
  83. package/apps/web/dist/assets/{ReadOnly-YF0RkR7P.js → ReadOnly-C6qmTD35.js} +1 -1
  84. package/apps/web/dist/assets/{Results-DJRLiVo0.js → Results-BNuuBiwU.js} +1 -1
  85. package/apps/web/dist/assets/{RunDrawer-CSpTNJp-.js → RunDrawer-CMgN-XTB.js} +1 -1
  86. package/apps/web/dist/assets/SettingsPage-CuUB26YJ.js +2 -0
  87. package/apps/web/dist/assets/SetupPage-llGzMVeH.js +1 -0
  88. package/apps/web/dist/assets/{SharePage-OiKEnmL1.js → SharePage-CgQp_PT6.js} +1 -1
  89. package/apps/web/dist/assets/SkillEditor-ARx8QPGp.js +1 -0
  90. package/apps/web/dist/assets/Skills-frfXXEcF.js +9 -0
  91. package/apps/web/dist/assets/SpacePage-Dv6ocsc_.js +2 -0
  92. package/apps/web/dist/assets/StudioHome-B0bZRm1L.js +1 -0
  93. package/apps/web/dist/assets/TableEditor-CfzTLmJF.js +7 -0
  94. package/apps/web/dist/assets/{UpdateCheck-BpdsLIOc.js → UpdateCheck-D3QhfI5c.js} +2 -2
  95. package/apps/web/dist/assets/{brand-ByQY-UcL.js → brand-DKuVyYhH.js} +1 -1
  96. package/apps/web/dist/assets/changelog-Db3nvWao.js +1 -0
  97. package/apps/web/dist/assets/{code-editor-B8zG80PA.js → code-editor-BLwDuQLI.js} +2 -2
  98. package/apps/web/dist/assets/host-C-AAp8Bz.js +69 -0
  99. package/apps/web/dist/assets/i18n-Dyi0kvaA.js +55 -0
  100. package/apps/web/dist/assets/{index-D18zQ05f.css → index-CduFlFCp.css} +1 -1
  101. package/apps/web/dist/assets/index-CtE0rJEL.js +102 -0
  102. package/apps/web/dist/assets/{read-aloud-spC7eEBp.js → read-aloud-DGS8mWgC.js} +1 -1
  103. package/apps/web/dist/assets/session-EIDP3Wzc.js +1 -0
  104. package/apps/web/dist/assets/theme-B46aPLtX.js +14 -0
  105. package/apps/web/dist/assets/ui-DSgksc1H.js +16 -0
  106. package/apps/web/dist/assets/{useMutation-CoEdB_9_.js → useMutation-fT44ij_b.js} +1 -1
  107. package/apps/web/dist/assets/{viewers-BmcrgvXX.js → viewers-DvA5VsXw.js} +2 -2
  108. package/apps/web/dist/index.html +18 -13
  109. package/apps/web/dist/mcp/flow.html +62 -62
  110. package/node_modules/@engenty/wizards-shared/dist/catalog-prompt.js +2 -2
  111. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +67 -0
  112. package/node_modules/@engenty/wizards-shared/dist/definition.d.ts +10324 -7
  113. package/node_modules/@engenty/wizards-shared/dist/definition.js +32 -6
  114. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +17 -23
  115. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +17 -23
  116. package/node_modules/@engenty/wizards-shared/dist/json-schema.js +3 -3
  117. package/node_modules/@engenty/wizards-shared/dist/marketplace-search.js +7 -1
  118. package/node_modules/@engenty/wizards-shared/dist/marketplace.d.ts +9 -2
  119. package/node_modules/@engenty/wizards-shared/dist/page-data.d.ts +72 -0
  120. package/node_modules/@engenty/wizards-shared/dist/page-data.js +5 -0
  121. package/node_modules/@engenty/wizards-shared/dist/page-look.d.ts +17 -0
  122. package/node_modules/@engenty/wizards-shared/dist/page-look.js +118 -0
  123. package/node_modules/@engenty/wizards-shared/dist/page-styles.d.ts +6 -0
  124. package/node_modules/@engenty/wizards-shared/dist/page-styles.js +98 -0
  125. package/node_modules/@engenty/wizards-shared/dist/page-texts.d.ts +36 -0
  126. package/node_modules/@engenty/wizards-shared/dist/page-texts.js +119 -0
  127. package/node_modules/@engenty/wizards-shared/dist/requires.js +2 -0
  128. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +54 -1
  129. package/node_modules/@engenty/wizards-shared/dist/run.js +23 -0
  130. package/node_modules/@engenty/wizards-shared/dist/runner-texts.d.ts +27 -1
  131. package/node_modules/@engenty/wizards-shared/dist/runner-texts.js +26 -0
  132. package/node_modules/@engenty/wizards-shared/dist/store.d.ts +24 -1
  133. package/node_modules/@engenty/wizards-shared/dist/transition.d.ts +2 -1
  134. package/node_modules/@engenty/wizards-shared/dist/transition.js +5 -1
  135. package/node_modules/@engenty/wizards-shared/dist/wizard-text.js +1 -1
  136. package/package.json +1 -1
  137. package/plugin/.claude-plugin/plugin.json +1 -1
  138. package/plugin/plugin.json +1 -1
  139. package/apps/web/dist/assets/CapabilitiesPage-fgTP28Mn.js +0 -2
  140. package/apps/web/dist/assets/ConnectorsSection-iLrduYak.js +0 -1
  141. package/apps/web/dist/assets/EditorPage-CRZte0O1.js +0 -3
  142. package/apps/web/dist/assets/Marketplace-9aGWG2pJ.js +0 -2
  143. package/apps/web/dist/assets/NewWizardChannels-BFDm9vCT.js +0 -1
  144. package/apps/web/dist/assets/NewWizardPage-ueGFlLDo.js +0 -7
  145. package/apps/web/dist/assets/OnboardingPage-DtDd7k_O.js +0 -1
  146. package/apps/web/dist/assets/PreviewPane-CEltrf_-.js +0 -7
  147. package/apps/web/dist/assets/ProtocolSection-Bb3c44Te.js +0 -1
  148. package/apps/web/dist/assets/PublicRunner-BaTg24s3.js +0 -1
  149. package/apps/web/dist/assets/SettingsPage--_ap3omw.js +0 -2
  150. package/apps/web/dist/assets/SetupPage-ELKHbmnE.js +0 -1
  151. package/apps/web/dist/assets/SkillEditor-C1_zwNOQ.js +0 -1
  152. package/apps/web/dist/assets/Skills-_pLGtOjH.js +0 -9
  153. package/apps/web/dist/assets/SpacePage-r4EbxEJe.js +0 -2
  154. package/apps/web/dist/assets/StudioHome-CwvxI29m.js +0 -1
  155. package/apps/web/dist/assets/changelog-Dt-V-BKp.js +0 -1
  156. package/apps/web/dist/assets/host-Ckjz94Ea.js +0 -69
  157. package/apps/web/dist/assets/i18n-ClCOlfx2.js +0 -55
  158. package/apps/web/dist/assets/index-BHKh0A9F.js +0 -10
  159. package/apps/web/dist/assets/runners-DNqzwMQ0.js +0 -1
  160. package/apps/web/dist/assets/session-Dd9duhPc.js +0 -1
  161. package/apps/web/dist/assets/theme-DumM6FI_.js +0 -14
  162. package/apps/web/dist/assets/ui-BjhZhw8x.js +0 -16
@@ -1,5 +1,6 @@
1
+ import { CONNECTION_ACTION_KINDS, } from "@engenty/wizards-shared/connectors";
1
2
  import { effectUnsure } from "../engine/events.js";
2
- import { keptSecret, markUsed, spaceAccount, stateOf, wizardAccount, } from "./account.js";
3
+ import { heldConnection, keptSecret, markUsed, spaceAccount, spaceRulesFor, stateOf, wizardAccount, } from "./account.js";
3
4
  import { askAgain, effectDone, effectIdOf, effectThrew, findEffect, startEffect, } from "./effect.js";
4
5
  import { inGrant, runGrant } from "./grant.js";
5
6
  import { CALLS_PER_DAY, CALLS_PER_RUN, closeLine, limitHeard, SIGN_IN_FAILED, summarizeInput, takePlace, writeLog, } from "./log.js";
@@ -71,20 +72,23 @@ export function inAudience(audience, who) {
71
72
  * „Mit Freigabe“ there asks the space's admins (`admins`). Where each person signs in, „Mit
72
73
  * Freigabe“ asks that person. A plugin's own job on a connection it set up runs as before.
73
74
  *
74
- * A wizard's own connection: reads run, writes and sends ask the person running, deleting always
75
- * asks; the wizard's author may settle an action's ask per `connection.policy`.
75
+ * A wizard's need on a person's own account, in a space that has connections of its service: the
76
+ * space's rules, pause and limits count (`space`), not its audience. Else reads run, writes and
77
+ * sends ask the person running, deleting always asks; the wizard's author may settle an action's
78
+ * ask per `connection.policy`.
76
79
  */
77
80
  export function decide(call) {
78
81
  const { connection, kind, who } = call;
79
82
  if (who.kind === "runtime") {
80
83
  return decideRuntime(connection, kind);
81
84
  }
82
- if (call.grant && connection.kind === "store_secret") {
83
- if (!inGrant(call.grant, connection.def.id, call.actionId, kind)) {
85
+ const need = needOf(connection);
86
+ if (call.grant && need) {
87
+ if (!inGrant(call.grant, need.id, call.actionId, kind)) {
84
88
  return {
85
89
  outcome: "deny",
86
90
  rule: "grant",
87
- reason: `The run's grant does not include "${call.actionId}" through ${connection.def.id}.`,
91
+ reason: `The run's grant does not include "${call.actionId}" through ${need.id}.`,
88
92
  };
89
93
  }
90
94
  }
@@ -98,7 +102,8 @@ export function decide(call) {
98
102
  if (ownJob) {
99
103
  return { outcome: "allow", rule: "own_job", reason: "The plugin's own connection." };
100
104
  }
101
- if (!inAudience(row.audience, who)) {
105
+ const chosen = connection.chosenForUnwatched === true && row.audience !== "admins";
106
+ if (!chosen && !inAudience(row.audience, who)) {
102
107
  return {
103
108
  outcome: "deny",
104
109
  rule: "audience",
@@ -150,6 +155,9 @@ export function decide(call) {
150
155
  reason: `The connection's rule: ${VERB[kind]} asks the space's admins.`,
151
156
  };
152
157
  }
158
+ if (call.space) {
159
+ return decideBySpace(call.space, kind);
160
+ }
153
161
  if (kind === "destructive") {
154
162
  return { outcome: "ask", rule: "destructive", reason: "Deleting always asks the person." };
155
163
  }
@@ -169,6 +177,69 @@ export function decide(call) {
169
177
  reason: kind === "read" ? "Reading is allowed." : "The wizard allows this action.",
170
178
  };
171
179
  }
180
+ /**
181
+ * A person's own account under the space's rules: a pause first, then the rule for the kind. The
182
+ * rule names the connection of the space that decided (`rules.send@<id>`); „Mit Freigabe“ asks the
183
+ * person running, whose account it is.
184
+ */
185
+ function decideBySpace(space, kind) {
186
+ if (space.paused) {
187
+ return {
188
+ outcome: "deny",
189
+ rule: `paused@${space.paused.id}`,
190
+ refused: "paused",
191
+ reason: `The space's connection „${space.paused.name}“ is paused: nobody reaches the service until an admin resumes it.`,
192
+ };
193
+ }
194
+ const { outcome, by } = space.rules[kind];
195
+ const rule = `rules.${kind}@${by.id}`;
196
+ const said = `The space's rule (${by.name})`;
197
+ if (outcome === "deny") {
198
+ return { outcome: "deny", rule, reason: `${said}: ${VERB[kind]} never.` };
199
+ }
200
+ if (outcome === "allow") {
201
+ return { outcome: "allow", rule, reason: `${said}: ${VERB[kind]} allowed.` };
202
+ }
203
+ return { outcome: "ask", rule, reason: `${said}: ${VERB[kind]} asks the person.` };
204
+ }
205
+ /** How strict an outcome is: the strictest of several connections' rules counts. */
206
+ const STRICT = { allow: 0, ask: 1, deny: 2 };
207
+ /**
208
+ * The space's rules a person's own account is used under: those of `rows`, the space's
209
+ * connections of the account's service. Null where the space has none: the wizard's `policy`
210
+ * counts then. Pure; `rows` in the order they were set up, so of two as strict the first decides.
211
+ */
212
+ export function spaceRulesOf(rows) {
213
+ const [first] = rows;
214
+ if (!first) {
215
+ return null;
216
+ }
217
+ const named = (row) => ({ id: row.id, name: row.name });
218
+ const rules = Object.fromEntries(CONNECTION_ACTION_KINDS.map((kind) => {
219
+ let pick = { outcome: first.rules[kind] ?? "deny", by: named(first) };
220
+ for (const row of rows) {
221
+ const outcome = row.rules[kind] ?? "deny";
222
+ if (STRICT[outcome] > STRICT[pick.outcome]) {
223
+ pick = { outcome, by: named(row) };
224
+ }
225
+ }
226
+ return [kind, pick];
227
+ }));
228
+ const lowest = (of) => rows.reduce((low, row) => {
229
+ const calls = row[of];
230
+ return calls !== null && (low === null || calls < low.calls)
231
+ ? { calls, by: named(row) }
232
+ : low;
233
+ }, null);
234
+ const paused = rows.find((row) => row.pausedAt);
235
+ return {
236
+ rules,
237
+ paused: paused ? named(paused) : null,
238
+ callsPerRun: lowest("callsPerRun"),
239
+ callsPerDay: lowest("callsPerDay"),
240
+ ids: rows.map((row) => row.id),
241
+ };
242
+ }
172
243
  /** What the log and „Was darf …?“ say of a connection that pauses. */
173
244
  export const CONNECTION_PAUSED = "The connection is paused: nobody reaches it until an admin resumes it.";
174
245
  /** The decision for a connection of the space that pauses, whoever calls; null where it does not. */
@@ -208,12 +279,22 @@ function aiStep(who, where) {
208
279
  return !!where.runId && who.kind !== "step";
209
280
  }
210
281
  /**
211
- * Whether a run's grant binds this call: a wizard's own connection, called in a run. A plugin's
212
- * connection is the space's, under its own rules (A4, A5); a share target's connection
213
- * (`def.target`) is the person's own request after the run, never in the definition.
282
+ * The wizard's need a connection serves: the wizard's own connection, or the one a connection of
283
+ * the space is used for (`heldConnection`). None for a plugin's connection or one of the space a
284
+ * definition names by its id.
285
+ */
286
+ function needOf(connection) {
287
+ return connection.kind === "store_secret" ? connection.def : (connection.need ?? null);
288
+ }
289
+ /**
290
+ * Whether a run's grant binds this call: a wizard's need, called in a run, through its own
291
+ * connection or one of the space the run uses for it. A plugin's connection is the space's, under
292
+ * its own rules (A4, A5); a share target's connection (`def.target`) is the person's own request
293
+ * after the run, never in the definition.
214
294
  */
215
295
  export function grantBinds(where, connection) {
216
- return !!where.runId && connection.kind === "store_secret" && !connection.def.target;
296
+ const need = needOf(connection);
297
+ return !!where.runId && !!need && !need.target;
217
298
  }
218
299
  const AUDIENCE = {
219
300
  admins: "the space's admins",
@@ -242,7 +323,7 @@ const NOBODY = { kind: "guest" };
242
323
  * connection in which each person signs in needs the caller to say whose.
243
324
  */
244
325
  export async function brokerConnected(connection, who = NOBODY) {
245
- const account = await accountOf(connection, who);
326
+ const account = await accountOf(await heldConnection(connection), who);
246
327
  return account ? { connector: account.connector, label: account.label } : null;
247
328
  }
248
329
  /** The widest the person sees of an input they are asked about. */
@@ -258,7 +339,8 @@ const MAY_HAVE_HAPPENED = "It was interrupted before and may have happened alrea
258
339
  export async function brokerCall(call) {
259
340
  const started = Date.now();
260
341
  const { who, where, ctx = {} } = call;
261
- let { connection } = call;
342
+ // The run may use a connection of the space for a wizard's need: its rules count then.
343
+ let connection = await heldConnection(call.connection);
262
344
  const connectionId = connectionIdOf(connection);
263
345
  /** What every line of this call says, whatever came of it. */
264
346
  const lineOf = (kind, outcome, rule, reason) => ({
@@ -324,14 +406,15 @@ export async function brokerCall(call) {
324
406
  const kind = call.action.kind ?? (found ? kindOf(found.group) : "write");
325
407
  // The grant first: what the run's definition gave it, fixed when it started.
326
408
  let grant;
327
- if (grantBinds(where, connection)) {
409
+ const need = needOf(connection);
410
+ if (need && grantBinds(where, connection)) {
328
411
  grant = await runGrant(where.runId);
329
412
  if (!grant) {
330
413
  const reason = "The run is not known here.";
331
414
  await line(kind, "deny", "grant", reason, "not_in_grant");
332
415
  return { ok: false, refused: "not_in_grant", reason };
333
416
  }
334
- if (!inGrant(grant, connectionId, call.action.id, kind)) {
417
+ if (!inGrant(grant, need.id, call.action.id, kind)) {
335
418
  const decision = decide({ who, where, connection, actionId: call.action.id, kind, grant });
336
419
  await line(kind, "deny", decision.rule, decision.reason, "not_in_grant");
337
420
  return { ok: false, refused: "not_in_grant", reason: decision.reason };
@@ -349,7 +432,11 @@ export async function brokerCall(call) {
349
432
  await line(kind, "deny", null, reason, "no_action");
350
433
  return { ok: false, refused: "no_action", reason };
351
434
  }
352
- const decision = decide({ who, where, connection, actionId: call.action.id, kind, grant });
435
+ // A person's own account in a space with rules for its service: those rules count (decided 4).
436
+ const space = connection.kind === "store_secret" && account.person
437
+ ? await spaceRulesFor(connection.scope.clientSpaceId ?? connection.spaceId, account.connector.id)
438
+ : null;
439
+ const decision = decide({ who, where, connection, actionId: call.action.id, kind, grant, space });
353
440
  const { rule } = decision;
354
441
  if (decision.outcome === "deny") {
355
442
  const refused = decision.refused ?? "denied";
@@ -376,7 +463,8 @@ export async function brokerCall(call) {
376
463
  ? {
377
464
  post: {
378
465
  who,
379
- connectionId,
466
+ // The grant fixes a held connection's channel under the wizard's need.
467
+ connectionId: connection.kind === "space_connection" && need ? need.id : connectionId,
380
468
  actionId: call.action.id,
381
469
  channel: channelOf(call.input),
382
470
  },
@@ -465,28 +553,24 @@ export async function brokerCall(call) {
465
553
  }
466
554
  }
467
555
  }
468
- // The call would run. Through a connection of the space with a limit it takes its place first:
469
- // its line is written now, if the limits leave room, and its end is filled in after.
556
+ // The call would run. Through a connection of the space with a limit, or a person's account
557
+ // under the space's, it takes its place first: its line is written now, if the limits leave
558
+ // room, and its end is filled in after.
470
559
  let open = null;
471
- if (connection.kind === "space_connection") {
472
- const { callsPerRun: perRun, callsPerDay: perDay } = connection.row;
473
- if (perRun !== null || perDay !== null) {
474
- const place = await takePlace(lineOf(kind, decision.outcome, rule, decision.reason), {
475
- perRun,
476
- perDay,
477
- });
478
- if ("full" in place) {
479
- const refused = place.full === "run" ? CALLS_PER_RUN : CALLS_PER_DAY;
480
- const reason = place.full === "run"
481
- ? `The connection takes ${perRun} calls from one run, and this run has made them.`
482
- : `The connection takes ${perDay} calls a day, and today's are made.`;
483
- await line(kind, "deny", `limits.${place.full}`, reason, refused, null, {
484
- limitHeard: await limitHeard(connectionId, place.full, where.runId ?? null),
485
- });
486
- return { ok: false, refused, reason };
487
- }
488
- open = place;
560
+ const limits = limitsOf(connection, space);
561
+ if (limits) {
562
+ const { perRun, perDay } = limits;
563
+ const place = await takePlace(lineOf(kind, decision.outcome, rule, decision.reason), limits);
564
+ if ("full" in place) {
565
+ const refused = place.full === "run" ? CALLS_PER_RUN : CALLS_PER_DAY;
566
+ const reason = place.full === "run"
567
+ ? `The connection takes ${perRun} calls from one run, and this run has made them.`
568
+ : `The connection takes ${perDay} calls a day, and today's are made.`;
569
+ const by = space ? (place.full === "run" ? space.callsPerRun : space.callsPerDay)?.by : null;
570
+ await line(kind, "deny", `limits.${place.full}${by ? `@${by.id}` : ""}`, reason, refused, null, { limitHeard: await limitHeard(connectionId, place.full, where.runId ?? null) });
571
+ return { ok: false, refused, reason };
489
572
  }
573
+ open = place;
490
574
  }
491
575
  /** The call's end: on the line that took its place, else as a line of its own. */
492
576
  const end = (result, size = null, context = {}) => open
@@ -541,6 +625,22 @@ export async function brokerCall(call) {
541
625
  throw err;
542
626
  }
543
627
  }
628
+ /**
629
+ * The limits a call takes its place under: a connection of the space's own, or the space's for a
630
+ * person's account (`of`: the connections whose calls count together). Null where there are none.
631
+ */
632
+ function limitsOf(connection, space) {
633
+ const limits = connection.kind === "space_connection"
634
+ ? { perRun: connection.row.callsPerRun, perDay: connection.row.callsPerDay }
635
+ : space
636
+ ? {
637
+ perRun: space.callsPerRun?.calls ?? null,
638
+ perDay: space.callsPerDay?.calls ?? null,
639
+ of: space.ids,
640
+ }
641
+ : null;
642
+ return limits && (limits.perRun !== null || limits.perDay !== null) ? limits : null;
643
+ }
544
644
  /**
545
645
  * An action's kind before the account is read: what the caller says, else what the connector of
546
646
  * a connection of the space says; a wizard's own connection names its connector only once its
@@ -133,8 +133,21 @@ function counted() {
133
133
  const log = schema.brokerLog;
134
134
  return and(ne(log.outcome, "deny"), ne(log.actionId, RULE_CHANGE_ACTION), or(isNull(log.result), notInArray(log.result, [...BROKER_REFUSALS])));
135
135
  }
136
- const inRun = (connectionId, runId) => and(eq(schema.brokerLog.connectionId, connectionId), eq(schema.brokerLog.runId, runId), counted());
137
- const today = (connectionId) => and(eq(schema.brokerLog.connectionId, connectionId), gte(schema.brokerLog.at, startOfToday()), counted());
136
+ /**
137
+ * The lines a connection's limits count: its own, and those of people's own accounts its rules
138
+ * decided (`rules.<kind>@<id>`, call.ts `decideBySpace`), which the run or the space finds.
139
+ */
140
+ const ruledBy = (ids) => or(...ids.map((id) => sql `substr(${schema.brokerLog.rule}, ${-(id.length + 1)}) = ${`@${id}`}`));
141
+ const inRun = (ids, runId) => and(eq(schema.brokerLog.runId, runId), or(inArray(schema.brokerLog.connectionId, [...ids]), ruledBy(ids)), counted());
142
+ /** Today's: through the connections by their index, and in the space where people's own accounts are. */
143
+ const today = (ids, spaceId) => {
144
+ const log = schema.brokerLog;
145
+ const since = gte(log.at, startOfToday());
146
+ const own = sql `(select count(*) from ${log} where ${and(inArray(log.connectionId, [...ids]), since, counted())})`;
147
+ return spaceId
148
+ ? sql `(${own} + (select count(*) from ${log} where ${and(eq(log.spaceId, spaceId), since, ruledBy(ids), counted())}))`
149
+ : own;
150
+ };
138
151
  /**
139
152
  * Takes a call's place under its connection's limits by writing its line: the count and the line
140
153
  * are one statement, so of two calls at once only one gets the last free place, in whichever
@@ -143,12 +156,13 @@ const today = (connectionId) => and(eq(schema.brokerLog.connectionId, connection
143
156
  */
144
157
  export async function takePlace(row, limits) {
145
158
  const log = schema.brokerLog;
159
+ const ids = limits.of ?? [row.connectionId];
146
160
  const places = [];
147
161
  if (limits.perRun !== null && row.runId) {
148
- places.push(sql `(select count(*) from ${log} where ${inRun(row.connectionId, row.runId)}) < ${limits.perRun}`);
162
+ places.push(sql `(select count(*) from ${log} where ${inRun(ids, row.runId)}) < ${limits.perRun}`);
149
163
  }
150
164
  if (limits.perDay !== null) {
151
- places.push(sql `(select count(*) from ${log} where ${today(row.connectionId)}) < ${limits.perDay}`);
165
+ places.push(sql `${today(ids, row.spaceId)} < ${limits.perDay}`);
152
166
  }
153
167
  const id = nanoid(14);
154
168
  // The columns as the table has them: a time is its milliseconds, a flag 0 or 1.
@@ -180,7 +194,7 @@ export async function takePlace(row, limits) {
180
194
  // Which one: the run's where the run has made its calls, else the day's.
181
195
  const full = limits.perRun !== null &&
182
196
  row.runId &&
183
- (await db.$count(log, inRun(row.connectionId, row.runId))) >= limits.perRun
197
+ (await db.$count(log, inRun(ids, row.runId))) >= limits.perRun
184
198
  ? "run"
185
199
  : "day";
186
200
  return { full };
@@ -401,8 +401,8 @@ export async function seedRwx(spaceId) {
401
401
  if (guest) {
402
402
  seeded.push(rule("guest", null, kind, guest));
403
403
  }
404
- // A client space's clients work with their own data, and run what the space lets them. A
405
- // space gets no rule for clients: what of it a client reads, a rule opens item by item.
404
+ // A client space's clients work with its data and run its wizards. Any other space has no rule
405
+ // for clients: what of it a client reads, a rule opens item by item.
406
406
  const client = space?.kind === "client" ? CLIENT_SEED[kind] : undefined;
407
407
  if (client) {
408
408
  seeded.push(rule("role", "client", kind, client));
@@ -414,10 +414,12 @@ export async function seedRwx(spaceId) {
414
414
  .onConflictDoNothing();
415
415
  }
416
416
  /**
417
- * Opens a space to its Kund:innen as a client space is (docs/plans/org-spaces.md): with
418
- * `orgSpaces` any space may be shared with clients; the first one shared writes these rules.
417
+ * Writes a client space's rules for its clients where they are missing: a client space seeded
418
+ * before it had clients, or made one by migration. The space's own seed first.
419
419
  */
420
420
  export async function seedClientRules(spaceId) {
421
+ // The space's own seed first: rules for clients alone would keep it from ever being written.
422
+ await rulesOf(spaceId);
421
423
  const seeded = [];
422
424
  for (const kind of ENFORCED) {
423
425
  const client = CLIENT_SEED[kind];
@@ -441,8 +443,9 @@ const MEMBER_SEED = {
441
443
  skill: { r: "allow", w: null, x: "allow" },
442
444
  };
443
445
  /**
444
- * A client's seed in their client space (docs/plans/client-spaces.md): its data read and written,
445
- * wizards and skills read and run; never its setup.
446
+ * A client's seed in their client space (docs/plans/org-spaces.md): its data read and written,
447
+ * its wizards and skills read and run; never its setup. What of the organization's root a client
448
+ * reaches, the root opens item by item (`setOpenToClients`).
446
449
  */
447
450
  const CLIENT_SEED = {
448
451
  document: { r: "allow", w: "allow", x: null },
@@ -816,9 +819,9 @@ export async function askRule(userId, spaceId, q) {
816
819
  return { decision, rule: decided ? view(decided) : null };
817
820
  }
818
821
  /**
819
- * Opens one item of a space to the clients of its client spaces, or closes it again
820
- * (docs/plans/client-spaces.md): a rule for the role `client` on that item, read (and run for a
821
- * wizard). Its admins decide; the change is a line of the log.
822
+ * Opens one item of a space to its clients, or closes it again (docs/plans/org-spaces.md): a rule
823
+ * for the role `client` on that item, read (and run for a wizard). Its admins decide; the change
824
+ * is a line of the log.
822
825
  */
823
826
  export async function setOpenToClients(userId, spaceId, resource, open) {
824
827
  const space = await rulesSpace(userId, spaceId);
@@ -7,10 +7,10 @@ import { scopesForGroups } from "../engenty/connections-sdk/types.js";
7
7
  import { env } from "../env.js";
8
8
  import { NotedError } from "../model-errors.js";
9
9
  import { seal, unseal } from "../secrets/crypto.js";
10
- import { deleteSecret, peekSecret, putSecret } from "../store/index.js";
11
10
  import { serverText } from "../texts.js";
12
11
  import { connectorFetch, MAIL_CONNECTORS, resolveEnv, signInFetch, usable, viaAccount, } from "./builtin.js";
13
12
  import { resolveConnector } from "./external.js";
13
+ import { connectionsFor, forget, remember, saveConnection, } from "./person-connections.js";
14
14
  import { standInUrl } from "./stand-ins.js";
15
15
  import { AccountConnectError, redeemTicket, startThroughAccount } from "./via-account.js";
16
16
  /** The connectors a person can pick for each kind of connection. */
@@ -69,8 +69,6 @@ export async function findConnection(run, connectionId, spaceId) {
69
69
  export function connectRedirectUri() {
70
70
  return env.connectRedirectUrl || `${env.appUrl}/api/connect/callback`;
71
71
  }
72
- /** The store slot of a connection's account. */
73
- export const slot = (connectionId) => `connection:${connectionId}`;
74
72
  /** A connector that needs no credential: there is nothing for the person to connect. */
75
73
  export const open = (connector) => connector.auth.kind === "api_key" && connector.auth.apiKey.fields.length === 0;
76
74
  /**
@@ -116,11 +114,15 @@ export async function connectorFor(connection, connectorId, spaceId) {
116
114
  }
117
115
  return connector;
118
116
  }
117
+ /**
118
+ * What each need of a run shows: the account the run uses for it (`connectionsFor`), or none
119
+ * where it has none or several and no choice.
120
+ */
119
121
  export async function connectionViews(connections, scope, spaceId,
120
122
  /** The language the person reads the connectors' fields in. */
121
123
  lang = "en") {
122
124
  return Promise.all(connections.map(async (c) => {
123
- const stored = await peekSecret(scope, slot(c.id));
125
+ const { chosen, candidates: found } = await connectionsFor(scope, spaceId, c);
124
126
  const only = c.connector ? (await candidates(c, spaceId))[0] : undefined;
125
127
  return {
126
128
  id: c.id,
@@ -128,19 +130,54 @@ lang = "en") {
128
130
  connector: c.connector ?? null,
129
131
  title: c.title ?? only?.name ?? null,
130
132
  description: c.description ?? null,
131
- account: stored
133
+ account: chosen
132
134
  ? {
133
- connector: stored.provider,
134
- label: stored.label,
135
- connectedAt: stored.createdAt.toISOString(),
135
+ connector: chosen.connector.id,
136
+ label: chosen.kind === "person" ? chosen.row.label : (chosen.row.label ?? chosen.row.name),
137
+ connectedAt: (chosen.kind === "person"
138
+ ? chosen.row.createdAt
139
+ : chosen.row.setUpAt).toISOString(),
136
140
  }
137
141
  : only && open(only)
138
142
  ? { connector: only.id, label: only.name, connectedAt: new Date(0).toISOString() }
139
143
  : null,
144
+ candidates: found.map((u) => candidateOf(u, u === chosen)),
140
145
  connectors: await connectorOptions(c, spaceId, lang),
141
146
  };
142
147
  }));
143
148
  }
149
+ /** An account a run may use, as the connect card lists it. */
150
+ function candidateOf(u, chosen) {
151
+ return {
152
+ id: u.row.id,
153
+ owner: u.kind,
154
+ label: u.kind === "person" ? u.row.label : (u.row.label ?? u.row.name),
155
+ name: u.kind === "space" ? u.row.name : null,
156
+ connector: u.row.connectorId,
157
+ chosen,
158
+ };
159
+ }
160
+ /**
161
+ * The person picks which of the accounts the run may use the wizard uses for a need, from the
162
+ * card or under „Was dieser Wizard sich merkt“. False: it is none the run may use.
163
+ */
164
+ export async function choose(scope, spaceId, connection, pick) {
165
+ const { candidates: found } = await connectionsFor(scope, spaceId, connection);
166
+ const usable = found.find((u) => u.kind === pick.owner && u.row.id === pick.id);
167
+ if (!usable) {
168
+ return false;
169
+ }
170
+ await remember(scope.wizardId, connection.id, scope.holder, usable);
171
+ return true;
172
+ }
173
+ /**
174
+ * Keeps an account connected from a run as the holder's own connection, and remembers it as the
175
+ * one this wizard uses for the need.
176
+ */
177
+ export async function keepAccount(scope, connectionId, connectorId, label, stored) {
178
+ const row = await saveConnection(scope.holder, connectorId, label, stored);
179
+ await remember(scope.wizardId, connectionId, scope.holder, { kind: "person", row });
180
+ }
144
181
  export async function startOAuth(scope, spaceId, runId, connection, connectorId, lang) {
145
182
  const connector = await connectorFor(connection, connectorId, spaceId);
146
183
  if (connector.auth.kind !== "oauth2") {
@@ -235,7 +272,7 @@ export async function finishOAuth(answer, rawState) {
235
272
  scopes: tokens.grantedScopes,
236
273
  ...("ticket" in answer ? { via: "account" } : {}),
237
274
  };
238
- await putSecret(state.scope, slot(connection.id), connector.id, account.label, stored);
275
+ await keepAccount(state.scope, connection.id, connector.id, account.label, stored);
239
276
  return state;
240
277
  }
241
278
  /** Connects an `api_key` connector with what the person typed; the connector checks it first. */
@@ -267,7 +304,7 @@ export async function connectWithCredentials(scope, spaceId, connection, connect
267
304
  expiresAt: null,
268
305
  scopes: [],
269
306
  };
270
- await putSecret(scope, slot(connection.id), connector.id, account.label, stored);
307
+ await keepAccount(scope, connection.id, connector.id, account.label, stored);
271
308
  return account.label;
272
309
  }
273
310
  /** A connect attempt the person can fix (wrong password, unknown server). */
@@ -289,8 +326,12 @@ function connectFailure(err) {
289
326
  const detail = String(e.message ?? err).slice(0, 200);
290
327
  return note("connectingNotWork", { host, detail });
291
328
  }
329
+ /**
330
+ * The person disconnects an account from a run: the wizard forgets its choice. The account goes
331
+ * too unless another wizard uses it.
332
+ */
292
333
  export function disconnect(scope, connectionId) {
293
- return deleteSecret(scope, slot(connectionId));
334
+ return forget(scope.wizardId, scope.holder, connectionId);
294
335
  }
295
336
  // --- using ---------------------------------------------------------------------
296
337
  // An account is read by the broker alone (`broker/account.ts`): a connector call goes through