@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
@@ -26,6 +26,7 @@ import { openCommand } from "./open-command.js";
26
26
  import { PLUGIN_NAME, pluginArchive, pluginMarketplace } from "./plugin.js";
27
27
  import { apiRoutes } from "./routes/api.js";
28
28
  import { brokerRoutes } from "./routes/broker.js";
29
+ import { bundleRoutes } from "./routes/bundles.js";
29
30
  import { clientContractRoutes } from "./routes/client-contract.js";
30
31
  import { clientSpaceRoutes } from "./routes/client-spaces.js";
31
32
  import { connectionRoutes } from "./routes/connections.js";
@@ -348,6 +349,7 @@ if (serves.studio) {
348
349
  app.route("/api/studio", ruleRoutes);
349
350
  app.route("/api/studio", clientSpaceRoutes);
350
351
  app.route("/api/studio", connectionRoutes);
352
+ app.route("/api/studio", bundleRoutes);
351
353
  app.route("/api/studio", brokerRoutes);
352
354
  app.route("/api/studio", dateienRoutes);
353
355
  app.route("/api/studio/runtime", runtimeSettingsRoutes);
@@ -153,12 +153,31 @@ export async function spaceAccount(row, connector, who) {
153
153
  };
154
154
  return { connector, ctx, label };
155
155
  }
156
- /** „Letzte Nutzung“: the connection was just used. */
156
+ /**
157
+ * What a connection of the space says of a call now: whether it pauses, its limits, and whether
158
+ * it was used before. Read on every call, so a pause or a limit binds a step or a chat turn that
159
+ * read the row before it, and only the first call of all is a first use. Null where the
160
+ * connection is gone.
161
+ */
162
+ export async function stateOf(id) {
163
+ const row = await db.query.spaceConnection.findFirst({
164
+ where: eq(schema.spaceConnection.id, id),
165
+ columns: {
166
+ pausedAt: true,
167
+ pausedBy: true,
168
+ callsPerRun: true,
169
+ callsPerDay: true,
170
+ lastUsedAt: true,
171
+ },
172
+ });
173
+ return row ?? null;
174
+ }
157
175
  /** The rights the provider granted a connection of the space at its sign-in; none for keys. */
158
176
  export function grantedScopes(row) {
159
177
  const data = row.secret ? unseal(row.secret) : null;
160
178
  return data?.scopes ?? [];
161
179
  }
180
+ /** „Letzte Nutzung“: the connection was just used. */
162
181
  export async function markUsed(row) {
163
182
  await db
164
183
  .update(schema.spaceConnection)
@@ -1,6 +1,7 @@
1
- import { keptSecret, markUsed, spaceAccount, wizardAccount } from "./account.js";
1
+ import { keptSecret, markUsed, spaceAccount, stateOf, wizardAccount, } from "./account.js";
2
2
  import { inGrant, runGrant } from "./grant.js";
3
- import { SIGN_IN_FAILED, summarizeInput, writeLog } from "./log.js";
3
+ import { CALLS_PER_DAY, CALLS_PER_RUN, closeLine, limitHeard, SIGN_IN_FAILED, summarizeInput, takePlace, writeLog, } from "./log.js";
4
+ import { runOver } from "./over.js";
4
5
  import { channelOf, guestSendCheck, postsToChannel, recipientsOf } from "./send.js";
5
6
  /**
6
7
  * A wizard's step calls as the person running it: the store's holder says who that is, their
@@ -22,6 +23,7 @@ export function whereOf(ctx) {
22
23
  return {
23
24
  ...whereOfRun({ id: ctx.runId, wizardId: ctx.store.wizardId, mode: ctx.test ? "test" : "live" }, ctx.store.holder, ctx.space.id),
24
25
  stepId: ctx.stepId,
26
+ ...(ctx.share ? { share: true } : {}),
25
27
  };
26
28
  }
27
29
  /** Where a call about a run is made (a share job, a step). */
@@ -35,7 +37,10 @@ export function whereOfRun(run, holder, spaceId) {
35
37
  guest: mode === "live" && !holder.startsWith("u:"),
36
38
  };
37
39
  }
38
- /** The rules' view of a connector action's group. */
40
+ /**
41
+ * The rules' view of a connector action's group. An imported connector's group is what an admin
42
+ * said the action does, where one did, before the importer's guess (`groupIn`, importer/classify.ts).
43
+ */
39
44
  export function kindOf(group) {
40
45
  return group === "destructive" || group === "write" || group === "send" ? group : "read";
41
46
  }
@@ -56,8 +61,9 @@ export function inAudience(audience, who) {
56
61
  * comes first: a wizard's connection outside it, or an action the grant does not name, is denied
57
62
  * whatever the rules say.
58
63
  *
59
- * A connection of the space: outside its audience nothing runs, nor an action the connection is
60
- * not for. Its rules say per kind of action Erlaubt, Mit Freigabe or Nie. On a connection that
64
+ * A connection of the space: a pause is asked first, for every caller and before a plugin's own
65
+ * job: nobody reaches a connection an admin paused. Outside its audience nothing runs, nor an
66
+ * action the connection is not for. Its rules say per kind of action Erlaubt, Mit Freigabe or Nie. On a connection that
61
67
  * signs in as the space an AI step only reads: a write there comes from a fixed `call` step (the
62
68
  * wizard's fields, no model) or a Work chat's confirmed action, and never asks the person running;
63
69
  * „Mit Freigabe“ there asks the space's admins (`admins`). Where each person signs in, „Mit
@@ -79,6 +85,10 @@ export function decide(call) {
79
85
  }
80
86
  if (connection.kind === "space_connection") {
81
87
  const { row } = connection;
88
+ const paused = pausedDecision(row);
89
+ if (paused) {
90
+ return paused;
91
+ }
82
92
  const ownJob = who.kind === "plugin" && row.plugin === who.id && !call.where.runId && !call.where.chatId;
83
93
  if (ownJob) {
84
94
  return { outcome: "allow", rule: "own_job", reason: "The plugin's own connection." };
@@ -154,6 +164,14 @@ export function decide(call) {
154
164
  reason: kind === "read" ? "Reading is allowed." : "The wizard allows this action.",
155
165
  };
156
166
  }
167
+ /** What the log and „Was darf …?“ say of a connection that pauses. */
168
+ export const CONNECTION_PAUSED = "The connection is paused: nobody reaches it until an admin resumes it.";
169
+ /** The decision for a connection of the space that pauses, whoever calls; null where it does not. */
170
+ function pausedDecision(row) {
171
+ return row.pausedAt
172
+ ? { outcome: "deny", rule: "paused", refused: "paused", reason: CONNECTION_PAUSED }
173
+ : null;
174
+ }
157
175
  /**
158
176
  * Whether a call in a run comes from an AI step: a model's tool call, made as the person running
159
177
  * (a guest, a person, an admin), or a plugin tool it called. A fixed step calls as `step`; a
@@ -209,13 +227,12 @@ const ASK_INPUT = 4000;
209
227
  */
210
228
  export async function brokerCall(call) {
211
229
  const started = Date.now();
212
- const { who, where, connection, ctx = {} } = call;
230
+ const { who, where, ctx = {} } = call;
231
+ let { connection } = call;
213
232
  const connectionId = connectionIdOf(connection);
214
- // A connection of the space used for the first time is heard of (log.ts, `first_use`).
215
- const firstUse = connection.kind === "space_connection" && !connection.row.lastUsedAt;
216
- const line = (kind, outcome, rule, reason, result, size = null, context = {}) => writeLog({
233
+ /** What every line of this call says, whatever came of it. */
234
+ const lineOf = (kind, outcome, rule, reason) => ({
217
235
  at: new Date(started),
218
- durationMs: Date.now() - started,
219
236
  whoKind: who.kind,
220
237
  whoId: who.id ?? null,
221
238
  runId: where.runId ?? null,
@@ -231,9 +248,37 @@ export async function brokerCall(call) {
231
248
  outcome,
232
249
  rule,
233
250
  reason,
251
+ });
252
+ const line = (kind, outcome, rule, reason, result, size = null, context = {}) => writeLog({
253
+ ...lineOf(kind, outcome, rule, reason),
254
+ durationMs: Date.now() - started,
234
255
  result,
235
256
  resultSize: size,
236
257
  }, context);
258
+ // Before anything else: a run that is over calls nothing more, whatever the connection.
259
+ const over = await runOver(where);
260
+ if (over) {
261
+ await line(kindBefore(call), "deny", over.rule, over.reason, "run_ended");
262
+ return { ok: false, refused: "run_ended", reason: over.reason };
263
+ }
264
+ // A connection of the space: whether it pauses, and its limits, are read now, not taken from the
265
+ // row a step or a chat turn read when it started; one that was removed since is gone for them too.
266
+ if (connection.kind === "space_connection") {
267
+ const now = await stateOf(connection.row.id);
268
+ if (!now) {
269
+ const reason = "The connection was removed.";
270
+ await line(kindBefore(call), "deny", null, reason, "not_connected");
271
+ return { ok: false, refused: "not_connected", reason };
272
+ }
273
+ connection = { ...connection, row: { ...connection.row, ...now } };
274
+ const paused = pausedDecision(connection.row);
275
+ if (paused) {
276
+ await line(kindBefore(call), "deny", paused.rule, paused.reason, "paused");
277
+ return { ok: false, refused: "paused", reason: paused.reason };
278
+ }
279
+ }
280
+ // A connection of the space used for the first time is heard of (log.ts, `first_use`).
281
+ const firstUse = connection.kind === "space_connection" && !connection.row.lastUsedAt;
237
282
  // The account says what kind the action is; its secret stays inside the broker. A sign-in
238
283
  // that ran out and cannot be renewed, or that the service refuses, is heard of.
239
284
  let account;
@@ -285,7 +330,7 @@ export async function brokerCall(call) {
285
330
  // channel its fixed step is fixed to, a few per run and day.
286
331
  if (kind === "send" && where.guest) {
287
332
  const sent = await guestSendCheck(where, {
288
- recipients: recipientsOf(call.input),
333
+ recipients: recipientsOf(call.input, found?.recipientField),
289
334
  ...(postsToChannel(account.connector.id, call.action.id)
290
335
  ? {
291
336
  post: {
@@ -349,11 +394,38 @@ export async function brokerCall(call) {
349
394
  }
350
395
  }
351
396
  }
397
+ // The call would run. Through a connection of the space with a limit it takes its place first:
398
+ // its line is written now, if the limits leave room, and its end is filled in after.
399
+ let open = null;
400
+ if (connection.kind === "space_connection") {
401
+ const { callsPerRun: perRun, callsPerDay: perDay } = connection.row;
402
+ if (perRun !== null || perDay !== null) {
403
+ const place = await takePlace(lineOf(kind, decision.outcome, rule, decision.reason), {
404
+ perRun,
405
+ perDay,
406
+ });
407
+ if ("full" in place) {
408
+ const refused = place.full === "run" ? CALLS_PER_RUN : CALLS_PER_DAY;
409
+ const reason = place.full === "run"
410
+ ? `The connection takes ${perRun} calls from one run, and this run has made them.`
411
+ : `The connection takes ${perDay} calls a day, and today's are made.`;
412
+ await line(kind, "deny", `limits.${place.full}`, reason, refused, null, {
413
+ limitHeard: await limitHeard(connectionId, place.full, where.runId ?? null),
414
+ });
415
+ return { ok: false, refused, reason };
416
+ }
417
+ open = place;
418
+ }
419
+ }
420
+ /** The call's end: on the line that took its place, else as a line of its own. */
421
+ const end = (result, size = null, context = {}) => open
422
+ ? closeLine(open, { durationMs: Date.now() - started, result, resultSize: size }, context)
423
+ : line(kind, decision.outcome, rule, decision.reason, result, size, context);
352
424
  try {
353
425
  const result = call.handler
354
426
  ? await call.handler(account)
355
427
  : (await found.handler(call.input ?? {}, account.ctx));
356
- await line(kind, decision.outcome, rule, decision.reason, "ok", sizeOf(result), { firstUse });
428
+ await end("ok", sizeOf(result), { firstUse });
357
429
  if (connection.kind === "space_connection") {
358
430
  await markUsed(connection.row);
359
431
  }
@@ -366,10 +438,25 @@ export async function brokerCall(call) {
366
438
  : err instanceof Error
367
439
  ? err.constructor.name || "Error"
368
440
  : "Error";
369
- await line(kind, decision.outcome, rule, decision.reason, result);
441
+ await end(result);
370
442
  throw err;
371
443
  }
372
444
  }
445
+ /**
446
+ * An action's kind before the account is read: what the caller says, else what the connector of
447
+ * a connection of the space says; a wizard's own connection names its connector only once its
448
+ * account is read, so an action of unknown kind counts as a write there.
449
+ */
450
+ function kindBefore(call) {
451
+ if (call.action.kind) {
452
+ return call.action.kind;
453
+ }
454
+ const { connection } = call;
455
+ const found = connection.kind === "space_connection"
456
+ ? connection.connector.actions.find((a) => a.id === call.action.id)
457
+ : undefined;
458
+ return found ? kindOf(found.group) : "write";
459
+ }
373
460
  /** Whether the service answered a call with "who are you?": its 401, or an OAuth grant gone. */
374
461
  export function signInRefused(err) {
375
462
  const text = err instanceof Error ? err.message : String(err);
@@ -377,12 +464,16 @@ export function signInRefused(err) {
377
464
  }
378
465
  /**
379
466
  * A secret of a run's store that is no connection (the browser's kept sign-ins), read through
380
- * the broker as a `read`: the handler alone sees it, and the call is logged like any other.
467
+ * the broker as a `read`: the handler alone sees it, and the call is logged like any other. A run
468
+ * that is over reads none.
381
469
  */
382
470
  export async function brokerSecret(call) {
383
471
  const started = Date.now();
384
- const kept = await keptSecret(call.scope, call.slot);
385
- const line = (result) => writeLog({
472
+ const line = (result, decided = {
473
+ outcome: "allow",
474
+ rule: "read",
475
+ reason: "Reading is allowed.",
476
+ }) => writeLog({
386
477
  at: new Date(started),
387
478
  durationMs: Date.now() - started,
388
479
  whoKind: call.who.kind,
@@ -397,16 +488,21 @@ export async function brokerSecret(call) {
397
488
  actionId: "read_secret",
398
489
  kind: "read",
399
490
  inputSummary: summarizeInput({}),
400
- outcome: "allow",
401
- rule: "read",
402
- reason: "Reading is allowed.",
491
+ ...decided,
403
492
  result,
404
493
  resultSize: null,
405
494
  });
495
+ // A run that is over reads no secret: the handler does not run.
496
+ const over = await runOver(call.where);
497
+ if (over) {
498
+ await line("run_ended", { outcome: "deny", ...over });
499
+ return { ok: false, refused: "run_ended", reason: over.reason };
500
+ }
501
+ const kept = await keptSecret(call.scope, call.slot);
406
502
  try {
407
503
  const result = await call.handler(kept?.data ?? null);
408
504
  await line(kept ? "ok" : "not_connected");
409
- return result;
505
+ return { ok: true, result };
410
506
  }
411
507
  catch (err) {
412
508
  await line(err instanceof Error ? err.constructor.name || "Error" : "Error");
@@ -1,11 +1,12 @@
1
1
  import { hostInGrant, runGrant } from "./grant.js";
2
2
  import { summarizeInput, writeLog } from "./log.js";
3
+ import { runOver } from "./over.js";
3
4
  import { brokerOn } from "./rwx.js";
4
5
  export async function brokerHost(call) {
5
6
  const started = Date.now();
6
7
  const { who, where, url } = call;
7
8
  const host = url.hostname.toLowerCase();
8
- const line = (outcome, reason, result) => writeLog({
9
+ const line = (outcome, reason, result, rule = "grant") => writeLog({
9
10
  at: new Date(started),
10
11
  durationMs: Date.now() - started,
11
12
  whoKind: who.kind,
@@ -22,11 +23,16 @@ export async function brokerHost(call) {
22
23
  // The path without its query: a query may carry a key.
23
24
  inputSummary: summarizeInput({ method: call.method, host, path: url.pathname }),
24
25
  outcome,
25
- rule: "grant",
26
+ rule,
26
27
  reason,
27
28
  result,
28
29
  resultSize: null,
29
30
  });
31
+ const over = await runOver(where);
32
+ if (over) {
33
+ await line("deny", over.reason, "run_ended", over.rule);
34
+ return { ok: false, refused: "run_ended", reason: over.reason };
35
+ }
30
36
  const bound = where.guest || (await brokerOn());
31
37
  let reason = "Members reach every public host.";
32
38
  if (bound) {
@@ -3,11 +3,12 @@
3
3
  * targets, plugins and the run's browser import from here; `account.ts` stays the broker's own.
4
4
  */
5
5
  export { grantedScopes } from "./account.js";
6
- export { brokerCall, brokerConnected, brokerSecret, decide, grantBinds, inAudience, kindOf, signInRefused, whereOf, whereOfRun, whoOf, } from "./call.js";
6
+ export { brokerCall, brokerConnected, brokerSecret, CONNECTION_PAUSED, decide, grantBinds, inAudience, kindOf, signInRefused, whereOf, whereOfRun, whoOf, } from "./call.js";
7
7
  export { currentCaller, withCaller } from "./caller.js";
8
8
  export { channelInGrant, grantNote, grantOf, hostInGrant, inGrant, runGrant, } from "./grant.js";
9
9
  export { brokerHost } from "./host.js";
10
10
  export { keptStepIds } from "./kept.js";
11
- export { CRITICAL_KINDS, criticalOf, criticalSince, cursorOf, LOG_PAGE, lastUseOf, logLine, logOfSpace, logRuleChange, onCritical, RULE_CHANGE_ACTION, readCursor, SIGN_IN_FAILED, summarizeInput, } from "./log.js";
11
+ export { CALLS_PER_DAY, CALLS_PER_RUN, CRITICAL_KINDS, callsToday, criticalOf, criticalSince, cursorOf, LOG_PAGE, lastUseOf, logLine, logOfSpace, logRuleChange, onCritical, RULE_CHANGE_ACTION, readCursor, SIGN_IN_FAILED, summarizeInput, } from "./log.js";
12
+ export { runOver } from "./over.js";
12
13
  export { outsideReaches, reachesOutside } from "./registry.js";
13
14
  export { brokerSend, channelOf, FIXED_CHANNEL_ONLY, GUEST_MAILS_PER_RUN, guestPostCheck, guestSendCheck, postsToChannel, recipientsOf, runAddresses, } from "./send.js";
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { and, desc, eq, exists, gt, inArray, lt, not, or, sql } from "drizzle-orm";
2
+ import { BROKER_REFUSALS } from "@engenty/wizards-shared/connectors";
3
+ import { and, count, desc, eq, exists, gt, gte, inArray, isNull, lt, ne, not, notInArray, or, sql, } from "drizzle-orm";
3
4
  import { nanoid } from "nanoid";
4
5
  import { db, schema } from "../db/client.js";
5
6
  /**
@@ -7,19 +8,27 @@ import { db, schema } from "../db/client.js";
7
8
  * `CRITICAL_KINDS` (shared/connectors): `refused_write` – a *Nie*, the grant or the AI-step rule
8
9
  * stopped a write, a delete or a send; `outside_audience` – a guest's run reached a connection
9
10
  * that is for the space's members or admins; `host_not_in_grant`; `limit_reached` – a guest's run
10
- * or a wizard's guests have sent their mails for the run or the day; `sign_in_failed` – a sign-in
11
- * ran out or the service refused it; `first_use` of a connection of the space; `rule_changed` –
12
- * RWX, or a connection's rules or audience.
11
+ * or a wizard's guests have sent their mails for the run or the day, or a connection of the space
12
+ * has taken its calls for a run or the day; `sign_in_failed` – a sign-in ran out or the service
13
+ * refused it; `first_use` of a connection of the space; `rule_changed` – RWX, a connection's
14
+ * rules, audience or limits, or a connection paused or resumed.
13
15
  */
14
16
  export { CRITICAL_KINDS } from "@engenty/wizards-shared/connectors";
15
17
  /** The action under which a changed rule is logged; the connection is the one changed, or `rwx`. */
16
18
  export const RULE_CHANGE_ACTION = "change_rules";
17
19
  /** The result under which a sign-in that ran out or was refused is logged. */
18
20
  export const SIGN_IN_FAILED = "sign_in_failed";
21
+ /** The refusals of a connection's own limits (`takePlace`): its calls per run, its calls per day. */
22
+ export const CALLS_PER_RUN = "calls_per_run";
23
+ export const CALLS_PER_DAY = "calls_per_day";
19
24
  /**
20
25
  * Which critical kind a row is, if any: the one place that decides. Every refusal of a write, a
21
26
  * delete or a send is critical; a refused read only where a guest reached outside a connection's
22
27
  * audience. A connection's first use and a changed rule are critical though nothing was refused.
28
+ * What a paused connection refuses is not: the admins paused it themselves and heard of that
29
+ * (`rule_changed`), and the mail that tells them of critical lines may go through that connection.
30
+ * A connection's limit is heard of once per run or day, at the first call it refuses: the ones
31
+ * after are refused and logged, and that mail may be one of them.
23
32
  */
24
33
  export function criticalOf(row, context = {}) {
25
34
  if (row.actionId === RULE_CHANGE_ACTION) {
@@ -29,9 +38,15 @@ export function criticalOf(row, context = {}) {
29
38
  return "sign_in_failed";
30
39
  }
31
40
  if (row.outcome === "deny") {
41
+ if (row.result === "paused") {
42
+ return null;
43
+ }
32
44
  if (row.result === "run_limit" || row.result === "day_limit") {
33
45
  return "limit_reached";
34
46
  }
47
+ if (row.result === CALLS_PER_RUN || row.result === CALLS_PER_DAY) {
48
+ return context.limitHeard ? null : "limit_reached";
49
+ }
35
50
  if (row.connectionId.startsWith("host:") && row.result === "not_in_grant") {
36
51
  return "host_not_in_grant";
37
52
  }
@@ -72,6 +87,18 @@ export function onCritical(listener) {
72
87
  listeners.add(listener);
73
88
  return () => listeners.delete(listener);
74
89
  }
90
+ /** A critical row is a line of the runtime's own log too, and goes to whoever listens. */
91
+ function hear(row) {
92
+ console.warn(`[broker] ${row.criticalKind}: ${row.whoKind}${row.whoId ? ` ${row.whoId}` : ""} → ${row.connectionId} ${row.actionId} (${row.kind}): ${row.outcome}, ${row.result ?? ""}${row.reason ? ` – ${row.reason}` : ""}`);
93
+ for (const listener of listeners) {
94
+ try {
95
+ listener(row);
96
+ }
97
+ catch (err) {
98
+ console.error("[broker] a listener failed:", err);
99
+ }
100
+ }
101
+ }
75
102
  /**
76
103
  * Writes one row, deciding whether it is critical; a log that cannot be written never stops the
77
104
  * call. A critical row is also a line of the runtime's own log, so the log ring and „wizards
@@ -88,17 +115,125 @@ export async function writeLog(row, context = {}) {
88
115
  return;
89
116
  }
90
117
  if (criticalKind) {
91
- console.warn(`[broker] ${criticalKind}: ${row.whoKind}${row.whoId ? ` ${row.whoId}` : ""} → ${row.connectionId} ${row.actionId} (${row.kind}): ${row.outcome}, ${row.result ?? ""}${row.reason ? ` – ${row.reason}` : ""}`);
92
- const full = written;
93
- for (const listener of listeners) {
94
- try {
95
- listener(full);
96
- }
97
- catch (err) {
98
- console.error("[broker] a listener failed:", err);
99
- }
100
- }
118
+ hear(written);
119
+ }
120
+ }
121
+ // --- a connection's limits (docs/plans/capabilities-next.md, 2b) -----------------------------
122
+ /** Today's first moment (UTC), as every per-day count sees it. */
123
+ export function startOfToday() {
124
+ const now = new Date();
125
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
126
+ }
127
+ /**
128
+ * The lines that count under a connection's limits: the calls the broker let through to the
129
+ * service, whatever came of them. One that failed counts, and one still under way (`result` is
130
+ * null). A refused call, one held for an approval and a changed rule count for nothing.
131
+ */
132
+ function counted() {
133
+ const log = schema.brokerLog;
134
+ return and(ne(log.outcome, "deny"), ne(log.actionId, RULE_CHANGE_ACTION), or(isNull(log.result), notInArray(log.result, [...BROKER_REFUSALS])));
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());
138
+ /**
139
+ * Takes a call's place under its connection's limits by writing its line: the count and the line
140
+ * are one statement, so of two calls at once only one gets the last free place, in whichever
141
+ * process they run. A call with no run counts for the day only. Answers the open line, or which
142
+ * limit is reached; then nothing was written.
143
+ */
144
+ export async function takePlace(row, limits) {
145
+ const log = schema.brokerLog;
146
+ const places = [];
147
+ if (limits.perRun !== null && row.runId) {
148
+ places.push(sql `(select count(*) from ${log} where ${inRun(row.connectionId, row.runId)}) < ${limits.perRun}`);
149
+ }
150
+ if (limits.perDay !== null) {
151
+ places.push(sql `(select count(*) from ${log} where ${today(row.connectionId)}) < ${limits.perDay}`);
101
152
  }
153
+ const id = nanoid(14);
154
+ // The columns as the table has them: a time is its milliseconds, a flag 0 or 1.
155
+ const values = [
156
+ ["id", id],
157
+ ["at", row.at.getTime()],
158
+ ["duration_ms", 0],
159
+ ["who_kind", row.whoKind],
160
+ ["who_id", row.whoId ?? null],
161
+ ["run_id", row.runId ?? null],
162
+ ["step_id", row.stepId ?? null],
163
+ ["client", row.client ?? null],
164
+ ["chat_id", row.chatId ?? null],
165
+ ["wizard_id", row.wizardId ?? null],
166
+ ["space_id", row.spaceId ?? null],
167
+ ["connection_id", row.connectionId],
168
+ ["action_id", row.actionId],
169
+ ["kind", row.kind],
170
+ ["input_summary", row.inputSummary],
171
+ ["outcome", row.outcome],
172
+ ["rule", row.rule ?? null],
173
+ ["reason", row.reason ?? null],
174
+ ["critical", 0],
175
+ ];
176
+ const taken = await db.run(sql `insert into broker_log (${sql.raw(values.map(([column]) => column).join(", "))}) select ${sql.join(values.map(([, value]) => sql `${value}`), sql `, `)} where ${and(...places) ?? sql `1`}`);
177
+ if (taken.rowsAffected > 0) {
178
+ return { id, row: { ...row, durationMs: 0 } };
179
+ }
180
+ // Which one: the run's where the run has made its calls, else the day's.
181
+ const full = limits.perRun !== null &&
182
+ row.runId &&
183
+ (await db.$count(log, inRun(row.connectionId, row.runId))) >= limits.perRun
184
+ ? "run"
185
+ : "day";
186
+ return { full };
187
+ }
188
+ /**
189
+ * Writes the end of a call that took a place: what came of it, how long it took, how much came
190
+ * back, and whether the line is critical now (a connection's first use). A line whose end cannot
191
+ * be written keeps its place and never stops the call.
192
+ */
193
+ export async function closeLine(open, end, context = {}) {
194
+ const row = { ...open.row, ...end, resultSize: end.resultSize ?? null };
195
+ const criticalKind = criticalOf(row, context);
196
+ try {
197
+ await db
198
+ .update(schema.brokerLog)
199
+ .set({
200
+ durationMs: row.durationMs,
201
+ result: row.result,
202
+ resultSize: row.resultSize,
203
+ critical: criticalKind !== null,
204
+ criticalKind,
205
+ })
206
+ .where(eq(schema.brokerLog.id, open.id));
207
+ }
208
+ catch (err) {
209
+ console.error("[broker] the log could not be written:", err);
210
+ return;
211
+ }
212
+ if (criticalKind) {
213
+ hear({ ...row, id: open.id, critical: true, criticalKind });
214
+ }
215
+ }
216
+ /** Whether this connection's limit refused a call before, in this run or today: it was heard of then. */
217
+ export async function limitHeard(connectionId, full, runId) {
218
+ const log = schema.brokerLog;
219
+ const refused = and(eq(log.connectionId, connectionId), eq(log.critical, true));
220
+ const before = full === "run" && runId
221
+ ? and(refused, eq(log.result, CALLS_PER_RUN), eq(log.runId, runId))
222
+ : and(refused, eq(log.result, CALLS_PER_DAY), gte(log.at, startOfToday()));
223
+ return (await db.$count(log, before)) > 0;
224
+ }
225
+ /** The calls each of these connections took today, as the limit per day counts them. */
226
+ export async function callsToday(connectionIds) {
227
+ if (!connectionIds.length) {
228
+ return new Map();
229
+ }
230
+ const log = schema.brokerLog;
231
+ const rows = await db
232
+ .select({ id: log.connectionId, calls: count() })
233
+ .from(log)
234
+ .where(and(inArray(log.connectionId, connectionIds), gte(log.at, startOfToday()), counted()))
235
+ .groupBy(log.connectionId);
236
+ return new Map(rows.map((row) => [row.id, row.calls]));
102
237
  }
103
238
  /** A rule changed by an admin: RWX (`connectionId` "rwx") or a connection's rules or audience. */
104
239
  export function logRuleChange(change) {
@@ -0,0 +1,38 @@
1
+ import { eq } from "drizzle-orm";
2
+ import { db, schema } from "../db/client.js";
3
+ /*
4
+ * A stop that holds (docs/plans/capabilities-next.md, 2a): stopping a run is the revoke, there is
5
+ * no other. Every path of the broker (`brokerCall`, `brokerHost`, `brokerSend`, `brokerSecret`)
6
+ * asks here before anything else, whatever the connection: a run that was stopped, is done or
7
+ * failed calls nothing more. The status is read on every call, so a step that is still under way
8
+ * when its run is stopped is refused at its next call. A call already under way finishes: the
9
+ * broker does not take back what has left.
10
+ *
11
+ * A share job is the one caller of a run that is done (`where.share`): the person sends the
12
+ * finished result on. It is refused like any other once the run was stopped or failed.
13
+ */
14
+ /** Why a call of a run that is over does not run, by the run's status. */
15
+ const OVER = {
16
+ cancelled: "The run was stopped.",
17
+ done: "The run is done.",
18
+ failed: "The run failed.",
19
+ };
20
+ /**
21
+ * Why this call's run takes no more calls, or null where it may go on: no run, a run under way
22
+ * (`running`, `waiting_input`, `sleeping`), or a share job of a run that is done. A run this
23
+ * tenant does not have is the grant's to refuse (call.ts, host.ts), not asked here.
24
+ */
25
+ export async function runOver(where) {
26
+ if (!where.runId) {
27
+ return null;
28
+ }
29
+ const run = await db.query.run.findFirst({
30
+ where: eq(schema.run.id, where.runId),
31
+ columns: { status: true },
32
+ });
33
+ if (!run || (run.status === "done" && where.share)) {
34
+ return null;
35
+ }
36
+ const reason = OVER[run.status];
37
+ return reason ? { rule: `run.${run.status}`, reason } : null;
38
+ }