@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,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { and, desc, eq, 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}`);
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();
101
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) {
@@ -140,10 +275,25 @@ const REFUSED_BY_PERSON = ["declined"];
140
275
  function likeOf(text) {
141
276
  return `%${text.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
142
277
  }
278
+ /**
279
+ * A person's own lines: the calls they made themselves (an AI step of their run calls as them)
280
+ * and the ones Goose made for them, and the fixed steps of a run held for them, which call as
281
+ * the step. Part of the query, so a page, a cursor and a search count nobody else's lines.
282
+ */
283
+ function ownLines(userId) {
284
+ const log = schema.brokerLog;
285
+ return or(and(inArray(log.whoKind, ["person", "goose"]), eq(log.whoId, userId)), and(eq(log.whoKind, "step"), exists(db
286
+ .select({ one: sql `1` })
287
+ .from(schema.run)
288
+ .where(and(eq(schema.run.id, log.runId), eq(schema.run.userId, userId))))));
289
+ }
143
290
  /** A space's log, newest first, filtered. */
144
291
  export async function logOfSpace(spaceId, query = {}) {
145
292
  const log = schema.brokerLog;
146
293
  const where = [eq(log.spaceId, spaceId)];
294
+ if (query.own) {
295
+ where.push(ownLines(query.own));
296
+ }
147
297
  if (query.connection) {
148
298
  where.push(eq(log.connectionId, query.connection));
149
299
  }
@@ -196,17 +346,21 @@ export async function logOfSpace(spaceId, query = {}) {
196
346
  if (query.before) {
197
347
  where.push(or(lt(log.at, query.before.at), and(eq(log.at, query.before.at), lt(log.id, query.before.id))));
198
348
  }
199
- return db.query.brokerLog.findMany({
200
- where: and(...where),
201
- orderBy: [desc(log.at), desc(log.id)],
202
- limit: Math.min(Math.max(query.limit ?? LOG_PAGE, 1), LOG_PAGE),
203
- });
349
+ return db
350
+ .select()
351
+ .from(log)
352
+ .where(and(...where))
353
+ .orderBy(desc(log.at), desc(log.id))
354
+ .limit(Math.min(Math.max(query.limit ?? LOG_PAGE, 1), LOG_PAGE));
204
355
  }
205
- /** One line of a space's log. */
206
- export async function logLine(spaceId, id) {
207
- const row = await db.query.brokerLog.findFirst({
208
- where: and(eq(schema.brokerLog.spaceId, spaceId), eq(schema.brokerLog.id, id)),
209
- });
356
+ /** One line of a space's log; with `own`, only where it is that person's own. */
357
+ export async function logLine(spaceId, id, own) {
358
+ const log = schema.brokerLog;
359
+ const [row] = await db
360
+ .select()
361
+ .from(log)
362
+ .where(and(eq(log.spaceId, spaceId), eq(log.id, id), ...(own ? [ownLines(own)] : [])))
363
+ .limit(1);
210
364
  return row ?? null;
211
365
  }
212
366
  /** The critical rows of these spaces since a time, newest first. */
@@ -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
+ }
@@ -0,0 +1,192 @@
1
+ import { RWX_ALL, } from "@engenty/wizards-shared/rwx";
2
+ import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";
3
+ import { db, schema } from "../db/client.js";
4
+ import { loadedPlugin, loadedPlugins } from "../plugins/registry.js";
5
+ import { ENFORCED } from "./rwx.js";
6
+ /**
7
+ * Where a rule is set. A place that shows a rule also replaces it, so the rule's own shape tells,
8
+ * whoever wrote the row:
9
+ *
10
+ * - `mount`: any rule on a mount. Its form in Dateien writes them all (mounts/mounts.ts), and the
11
+ * rules routes refuse one.
12
+ * - `start`: a role's or the guests' rule on every resource of an enforced kind: the seed
13
+ * (`created_by` `seed`), and what Rechte sets for a role on top of it.
14
+ * - `folder`: on a page of Wissen, what „Wer sieht diesen Ordner“ writes and reads back
15
+ * (`folderRules`): closed to the team or to guests, open to clients. Wissen offers it on every
16
+ * page, a folder or not.
17
+ * - `clients`: „Für Kund:innen sichtbar“ on a document, a table or a wizard
18
+ * (`setOpenToClients`): the clients read it, and run a wizard. On a page of Wissen it is the
19
+ * rule the folder's dialog shows.
20
+ * - `rights`: every other rule. Rechte set it, and removes it.
21
+ */
22
+ export function originOf(rule, page) {
23
+ if (rule.resourceKind === "mount") {
24
+ return "mount";
25
+ }
26
+ const group = rule.subjectKind === "guest" || rule.subjectKind === "role";
27
+ if (rule.resourceId === RWX_ALL) {
28
+ return group && ENFORCED.includes(rule.resourceKind) ? "start" : "rights";
29
+ }
30
+ const role = rule.subjectKind === "role" ? rule.subjectId : null;
31
+ const opensToClients = role === "client" &&
32
+ rule.r === "allow" &&
33
+ rule.w === null &&
34
+ rule.x === (rule.resourceKind === "wizard" ? "allow" : null);
35
+ if (rule.resourceKind === "page" && page?.wissen) {
36
+ const closesToTeam = role === "member" && rule.r === "deny" && rule.w !== "allow" && !rule.x;
37
+ const closesToGuests = rule.subjectKind === "guest" && rule.r === "deny" && !rule.w && !rule.x;
38
+ if (closesToTeam || closesToGuests || opensToClients) {
39
+ return "folder";
40
+ }
41
+ }
42
+ if (opensToClients && ["document", "table", "page", "wizard"].includes(rule.resourceKind)) {
43
+ return "clients";
44
+ }
45
+ return "rights";
46
+ }
47
+ /** The ids the rules name for one kind of resource or subject. */
48
+ const idsOf = (rules, pick) => [
49
+ ...new Set(rules.map(pick).filter((id) => Boolean(id) && id !== RWX_ALL)),
50
+ ];
51
+ /**
52
+ * The rules with where each is set and with their names: a person's, a wizard's, a plugin's; a
53
+ * document's, a page's, a table's, a wizard's, a skill's, a mount's. A name is null where there is
54
+ * nothing to name (a role, guests, every resource of a kind, the setup) or what it named is gone.
55
+ */
56
+ export async function describeRules(spaceId, rules, people) {
57
+ const of = (kind) => idsOf(rules, (r) => (r.resourceKind === kind ? r.resourceId : null));
58
+ const wizardIds = [
59
+ ...new Set([
60
+ ...of("wizard"),
61
+ ...idsOf(rules, (r) => (r.subjectKind === "wizard" ? r.subjectId : null)),
62
+ ]),
63
+ ];
64
+ const [pages, files, tables, wizards, skills, mounts] = await Promise.all([
65
+ of("page").length
66
+ ? db
67
+ .select({
68
+ id: schema.spacePage.id,
69
+ title: schema.spacePage.title,
70
+ wizardId: schema.spacePage.wizardId,
71
+ blank: sql `length(trim(${schema.spacePage.markdown})) = 0`,
72
+ })
73
+ .from(schema.spacePage)
74
+ .where(and(eq(schema.spacePage.spaceId, spaceId), inArray(schema.spacePage.id, of("page"))))
75
+ : [],
76
+ of("document").length
77
+ ? db
78
+ .select({ id: schema.spaceFile.id, name: schema.spaceFile.name })
79
+ .from(schema.spaceFile)
80
+ .where(and(eq(schema.spaceFile.spaceId, spaceId), inArray(schema.spaceFile.id, of("document"))))
81
+ : [],
82
+ of("table").length
83
+ ? db
84
+ .select({ id: schema.spaceTable.id, name: schema.spaceTable.title })
85
+ .from(schema.spaceTable)
86
+ .where(and(eq(schema.spaceTable.spaceId, spaceId), inArray(schema.spaceTable.id, of("table"))))
87
+ : [],
88
+ wizardIds.length
89
+ ? db
90
+ .select({ id: schema.wizard.id, name: schema.wizard.title })
91
+ .from(schema.wizard)
92
+ .where(and(eq(schema.wizard.spaceId, spaceId), inArray(schema.wizard.id, wizardIds)))
93
+ : [],
94
+ of("skill").length
95
+ ? db
96
+ .select({ id: schema.spaceSkill.id, name: schema.spaceSkill.name })
97
+ .from(schema.spaceSkill)
98
+ .where(and(eq(schema.spaceSkill.spaceId, spaceId), inArray(schema.spaceSkill.id, of("skill"))))
99
+ : [],
100
+ of("mount").length
101
+ ? db
102
+ .select({ id: schema.spaceMount.id, name: schema.spaceMount.name })
103
+ .from(schema.spaceMount)
104
+ .where(and(eq(schema.spaceMount.spaceId, spaceId), inArray(schema.spaceMount.id, of("mount"))))
105
+ : [],
106
+ ]);
107
+ const pageOf = new Map(pages.map((p) => [
108
+ p.id,
109
+ { title: p.title, wissen: !p.wizardId, folder: !p.wizardId && Boolean(p.blank) },
110
+ ]));
111
+ const named = (rows) => new Map(rows.map((r) => [r.id, r.name]));
112
+ const names = {
113
+ document: named(files),
114
+ table: named(tables),
115
+ wizard: named(wizards),
116
+ skill: named(skills),
117
+ mount: named(mounts),
118
+ };
119
+ const person = new Map(people.map((p) => [p.id, p.name]));
120
+ const subjectName = (r) => {
121
+ switch (r.subjectKind) {
122
+ case "person":
123
+ case "goose":
124
+ return person.get(r.subjectId ?? "") ?? null;
125
+ case "wizard":
126
+ return names.wizard?.get(r.subjectId ?? "") ?? null;
127
+ case "plugin":
128
+ return loadedPlugin(r.subjectId ?? "")?.source.manifest.name ?? null;
129
+ default:
130
+ return null;
131
+ }
132
+ };
133
+ return rules.map((r) => {
134
+ const page = r.resourceKind === "page" ? pageOf.get(r.resourceId) : undefined;
135
+ return {
136
+ ...r,
137
+ origin: originOf(r, page),
138
+ subjectName: subjectName(r),
139
+ resourceName: page?.title ?? names[r.resourceKind]?.get(r.resourceId) ?? null,
140
+ ...(page?.folder ? { folder: true } : {}),
141
+ };
142
+ });
143
+ }
144
+ /**
145
+ * What Rechte picks from, for a rule and for „Was darf …?“: the organization's people, and the
146
+ * space's wizards, plugins, documents, pages of Wissen, tables and skills. All of them, whatever
147
+ * the admin asking may read: a rule is written about what it closes too.
148
+ */
149
+ export async function ruleChoices(spaceId, people) {
150
+ const [wizards, documents, pages, tables, skills] = await Promise.all([
151
+ db
152
+ .select({ id: schema.wizard.id, name: schema.wizard.title })
153
+ .from(schema.wizard)
154
+ .where(eq(schema.wizard.spaceId, spaceId))
155
+ .orderBy(asc(schema.wizard.title)),
156
+ db
157
+ .select({ id: schema.spaceFile.id, name: schema.spaceFile.name })
158
+ .from(schema.spaceFile)
159
+ .where(and(eq(schema.spaceFile.spaceId, spaceId), eq(schema.spaceFile.kind, "document")))
160
+ .orderBy(asc(schema.spaceFile.name)),
161
+ db
162
+ .select({
163
+ id: schema.spacePage.id,
164
+ name: schema.spacePage.title,
165
+ blank: sql `length(trim(${schema.spacePage.markdown})) = 0`,
166
+ })
167
+ .from(schema.spacePage)
168
+ .where(and(eq(schema.spacePage.spaceId, spaceId), isNull(schema.spacePage.wizardId)))
169
+ .orderBy(asc(schema.spacePage.title)),
170
+ db
171
+ .select({ id: schema.spaceTable.id, name: schema.spaceTable.title })
172
+ .from(schema.spaceTable)
173
+ .where(and(eq(schema.spaceTable.spaceId, spaceId), isNull(schema.spaceTable.wizardId)))
174
+ .orderBy(asc(schema.spaceTable.title)),
175
+ db
176
+ .select({ id: schema.spaceSkill.id, name: schema.spaceSkill.name })
177
+ .from(schema.spaceSkill)
178
+ .where(eq(schema.spaceSkill.spaceId, spaceId))
179
+ .orderBy(asc(schema.spaceSkill.name)),
180
+ ]);
181
+ return {
182
+ people: people.map((p) => ({ id: p.id, name: p.name, role: p.role })),
183
+ wizards,
184
+ plugins: loadedPlugins()
185
+ .filter((p) => !p.error && p.source.entry)
186
+ .map((p) => ({ id: p.source.id, name: p.source.manifest.name })),
187
+ documents,
188
+ pages: pages.map((p) => ({ id: p.id, name: p.name, folder: Boolean(p.blank) })),
189
+ tables,
190
+ skills,
191
+ };
192
+ }