@engenty/wizards-runtime 0.16.2 → 0.17.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 (95) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +13 -6
  2. package/apps/runtime/dist/assistant/knows.js +15 -2
  3. package/apps/runtime/dist/broker/call.js +16 -3
  4. package/apps/runtime/dist/broker/grant.js +25 -1
  5. package/apps/runtime/dist/broker/index.js +2 -2
  6. package/apps/runtime/dist/broker/log.js +30 -11
  7. package/apps/runtime/dist/broker/rwx.js +14 -2
  8. package/apps/runtime/dist/broker/send.js +84 -32
  9. package/apps/runtime/dist/connectors/space-connections.js +47 -2
  10. package/apps/runtime/dist/docs/dev/broker.md +72 -26
  11. package/apps/runtime/dist/docs/dev/plugins/space.md +13 -2
  12. package/apps/runtime/dist/docs/user-guide/capabilities.md +51 -7
  13. package/apps/runtime/dist/docs/user-guide/connectors.md +6 -3
  14. package/apps/runtime/dist/docs/user-guide/protocol.md +30 -4
  15. package/apps/runtime/dist/docs/user-guide/together.md +4 -4
  16. package/apps/runtime/dist/elements/knowledge.js +16 -12
  17. package/apps/runtime/dist/engine/steps.js +3 -2
  18. package/apps/runtime/dist/index.js +8 -0
  19. package/apps/runtime/dist/live/hub.js +17 -3
  20. package/apps/runtime/dist/live/origin.js +6 -4
  21. package/apps/runtime/dist/live/views.js +38 -7
  22. package/apps/runtime/dist/models.js +18 -0
  23. package/apps/runtime/dist/prompts/tools.md +1 -1
  24. package/apps/runtime/dist/routes/api.js +2 -2
  25. package/apps/runtime/dist/routes/broker.js +59 -20
  26. package/apps/runtime/dist/routes/live.js +4 -2
  27. package/apps/runtime/dist/routes/studio.js +13 -2
  28. package/apps/runtime/dist/services/api.js +4 -2
  29. package/apps/runtime/dist/services/errors.js +1 -0
  30. package/apps/runtime/dist/services/knowledge.js +93 -27
  31. package/apps/runtime/dist/services/members-studio.js +22 -2
  32. package/apps/runtime/dist/services/space-categories.js +83 -5
  33. package/apps/runtime/dist/services/space-index.js +77 -21
  34. package/apps/runtime/dist/services/space-origin.js +28 -11
  35. package/apps/runtime/dist/services/work-ai.js +15 -5
  36. package/apps/runtime/dist/sharing/jobs.js +2 -0
  37. package/apps/runtime/dist/sync/hub.js +17 -3
  38. package/apps/runtime/dist/texts.js +6 -4
  39. package/apps/runtime/dist/tools/index.js +13 -7
  40. package/apps/runtime/dist/tools/web-search.js +36 -0
  41. package/apps/web/dist/assets/{AboutDialog-BCcD8hKm.js → AboutDialog-B2Xmxyj4.js} +1 -1
  42. package/apps/web/dist/assets/{BlockEditor-DgaUm2pR.js → BlockEditor-D0HoUSih.js} +1 -1
  43. package/apps/web/dist/assets/CapabilitiesPage-C1th2cZE.js +2 -0
  44. package/apps/web/dist/assets/{ChangelogDialog-B08elwyr.js → ChangelogDialog-BIrJbAKi.js} +1 -1
  45. package/apps/web/dist/assets/{CodeEditor-BiyOk_SC.js → CodeEditor-DUVcXI5P.js} +1 -1
  46. package/apps/web/dist/assets/{EditorPage-EMFTHEYD.js → EditorPage-56sIqEfF.js} +1 -1
  47. package/apps/web/dist/assets/{FlowPreview-DF_6TvZ0.js → FlowPreview-BIag8_Be.js} +1 -1
  48. package/apps/web/dist/assets/{LangSwitch-Ba4OWLzJ.js → LangSwitch-CJ00IgaO.js} +1 -1
  49. package/apps/web/dist/assets/{Marketplace-DqziLf66.js → Marketplace-D7-ot9Dz.js} +2 -2
  50. package/apps/web/dist/assets/{NewWizardChannels-CsIGp0nZ.js → NewWizardChannels-DI3SQ4iS.js} +1 -1
  51. package/apps/web/dist/assets/{NewWizardPage-CzQAkKMy.js → NewWizardPage-CytheHxX.js} +1 -1
  52. package/apps/web/dist/assets/{OnboardingPage-B9gr2OX5.js → OnboardingPage-_91Pa8Ad.js} +1 -1
  53. package/apps/web/dist/assets/{PreviewPane-DSOV3o-1.js → PreviewPane-BDsYm-_K.js} +2 -2
  54. package/apps/web/dist/assets/ProtocolSection-D_zaxHEL.js +1 -0
  55. package/apps/web/dist/assets/{PublicRunner-BVs8-Vu3.js → PublicRunner-CEgXSk3r.js} +1 -1
  56. package/apps/web/dist/assets/{ReadOnly--4CIJCDD.js → ReadOnly-CWf5x74a.js} +1 -1
  57. package/apps/web/dist/assets/SettingsPage-Dr8SDk-L.js +2 -0
  58. package/apps/web/dist/assets/{SetupPage-9Zk-KUGA.js → SetupPage-B68n0l4I.js} +1 -1
  59. package/apps/web/dist/assets/{SharePage-D_Ab0gjr.js → SharePage-DfznN7ar.js} +1 -1
  60. package/apps/web/dist/assets/{SkillEditor-DvtameHg.js → SkillEditor-BIcIczRc.js} +1 -1
  61. package/apps/web/dist/assets/{Skills-Cf1Kl4Fy.js → Skills-CN4QE7Kx.js} +1 -1
  62. package/apps/web/dist/assets/{SpacePage-CyqVzX9b.js → SpacePage-DiVTwhnJ.js} +2 -2
  63. package/apps/web/dist/assets/{UpdateCheck-DweZBVP6.js → UpdateCheck-QhBI3rlQ.js} +2 -2
  64. package/apps/web/dist/assets/changelog-a_CuplMX.js +1 -0
  65. package/apps/web/dist/assets/{code-editor-B1RbFTAZ.js → code-editor-DkPo1C-L.js} +2 -2
  66. package/apps/web/dist/assets/{host-CKS5U5Vg.js → host-D6H6Z9Jp.js} +6 -6
  67. package/apps/web/dist/assets/i18n-BaPKbQ1s.js +55 -0
  68. package/apps/web/dist/assets/{index-w-3J3ZJ9.css → index-CCUG6Vnh.css} +1 -1
  69. package/apps/web/dist/assets/{index-Ckcn5vy7.js → index-De0Wb42y.js} +3 -3
  70. package/apps/web/dist/assets/{read-aloud-Bq88XUHC.js → read-aloud-CnFwDSGD.js} +1 -1
  71. package/apps/web/dist/assets/{runners-DvYVe9Dt.js → runners-0sTPbWzr.js} +1 -1
  72. package/apps/web/dist/assets/{session-D2bjiA3P.js → session-BMiUrqHg.js} +1 -1
  73. package/apps/web/dist/assets/{theme-CNJIC2be.js → theme-CkNTe-_Z.js} +1 -1
  74. package/apps/web/dist/assets/{ui-Mplfhz_Z.js → ui-DAk_vjrL.js} +1 -1
  75. package/apps/web/dist/assets/{useMutation-8QRM-z4M.js → useMutation-isHfB33W.js} +1 -1
  76. package/apps/web/dist/assets/{viewers-CEocUV_2.js → viewers-ijNZHJFG.js} +2 -2
  77. package/apps/web/dist/index.html +12 -12
  78. package/apps/web/dist/mcp/flow.html +2 -2
  79. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +7 -2
  80. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +13 -1
  81. package/node_modules/@engenty/wizards-shared/dist/connectors.js +8 -0
  82. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +12 -0
  83. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +12 -0
  84. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +3 -0
  85. package/node_modules/@engenty/wizards-shared/dist/run.js +6 -0
  86. package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +3 -2
  87. package/node_modules/@engenty/wizards-shared/dist/spaces.js +12 -3
  88. package/package.json +1 -1
  89. package/plugin/.claude-plugin/plugin.json +1 -1
  90. package/plugin/plugin.json +1 -1
  91. package/apps/web/dist/assets/CapabilitiesPage-DuJJV1ll.js +0 -2
  92. package/apps/web/dist/assets/SettingsPage-z2u8lSe2.js +0 -2
  93. package/apps/web/dist/assets/changelog-C85v9OWg.js +0 -1
  94. package/apps/web/dist/assets/connection-sign-in-CaVvh5GQ.js +0 -1
  95. package/apps/web/dist/assets/i18n-Bymk5Ev-.js +0 -55
@@ -15,7 +15,7 @@ import { elementTools } from "../elements/catalogue.js";
15
15
  import { brokered, elementCall } from "../elements/gate.js";
16
16
  import { currentFeatures } from "../features.js";
17
17
  import { managed } from "../manage.js";
18
- import { chatModel, contextWindowOf, costOf, currentTier, gatewayTools, searchAllowed, textModel, totalUsage, usageOf, } from "../models.js";
18
+ import { chatModel, contextWindowOf, costOf, currentTier, gatewayTools, searchAllowed, textModel, toolAccess, totalUsage, usageOf, } from "../models.js";
19
19
  import { mountsOf } from "../mounts/source.js";
20
20
  import { prompt } from "../prompts.js";
21
21
  import { contentPolicy } from "../safety.js";
@@ -31,6 +31,7 @@ import { currentTenant } from "../tenants/tenant.js";
31
31
  import { serverText } from "../texts.js";
32
32
  import { assistantPageOf, assistantToolsOf } from "../tools/plugin.js";
33
33
  import { attempt as attemptTool, imageOutput } from "../tools/shared.js";
34
+ import { gatewayWebSearch } from "../tools/web-search.js";
34
35
  import { gooseConnectionTools } from "./goose-connections.js";
35
36
  import { spaceAgent } from "./space-agent.js";
36
37
  import { chatTurnWay } from "./subscription.js";
@@ -98,13 +99,14 @@ function activity(tool, args, lang) {
98
99
  }
99
100
  /** A tool failure the model can read and fix, instead of a crashed turn: the whole message. */
100
101
  const attempt = (run) => attemptTool(run, { limit: Number.POSITIVE_INFINITY });
101
- async function spaceState(userId, spaceId) {
102
+ async function spaceState(userId, role, spaceId) {
102
103
  const p = await ownedSpace(userId, spaceId);
103
104
  const files = await spaceFiles(spaceId);
104
105
  const categories = await categoryRows(spaceId);
105
106
  return {
106
107
  knowledge: {
107
- ...(await knowledgeCounts(spaceId)),
108
+ // How much of it Goose may read for the person.
109
+ ...(await knowledgeCounts(spaceId, subjectsOfGoose(userId, role))),
108
110
  categories: categories.map((c) => `${c.name} (${c.type}${c.proposed ? ", proposed" : ""})`),
109
111
  },
110
112
  title: p.brand.name ?? "",
@@ -806,7 +808,8 @@ export async function runStudioAssistant(input) {
806
808
  let changes = 0;
807
809
  // The way the settings chose for the studio's chats: on a client, its tools reach it over MCP.
808
810
  const way = await chatTurnWay(managed);
809
- const resolved = await assistantModel(way, input);
811
+ // The gateway's way for web search, asked beside the model rather than after it.
812
+ const [resolved, webAccess] = await Promise.all([assistantModel(way, input), toolAccess()]);
810
813
  const wrote = () => {
811
814
  changes++;
812
815
  input.onChanged?.();
@@ -972,7 +975,11 @@ export async function runStudioAssistant(input) {
972
975
  traced(tools, input, toolCalls);
973
976
  // The organization's tier may allow no web search.
974
977
  const search = await searchAllowed();
975
- if (search && resolved.vendor === "anthropic") {
978
+ const access = search ? webAccess : null;
979
+ if (access) {
980
+ tools.web_search = gatewayWebSearch(access);
981
+ }
982
+ else if (search && resolved.vendor === "anthropic") {
976
983
  tools.web_search = anthropic.tools.webSearch_20250305({ maxUses: 5 });
977
984
  }
978
985
  else if (search && resolved.gateway) {
@@ -1018,7 +1025,7 @@ export async function runStudioAssistant(input) {
1018
1025
  ].join("\n\n")
1019
1026
  : "",
1020
1027
  writable
1021
- ? `The space now:\n\`\`\`json\n${JSON.stringify(await spaceState(input.user.id, writable.id))}\n\`\`\``
1028
+ ? `The space now:\n\`\`\`json\n${JSON.stringify(await spaceState(input.user.id, input.user.role, writable.id))}\n\`\`\``
1022
1029
  : space
1023
1030
  ? prompt("goose", "turn.space_read_only", { name: space.name })
1024
1031
  : "No space is open.",
@@ -14,6 +14,7 @@ import { pluginToolsOf } from "../plugins/registry.js";
14
14
  import { prompt } from "../prompts.js";
15
15
  import { earlierChats, readChat, searchChats } from "../services/assistant-chats.js";
16
16
  import { asLang, marketplaceDetail, searchMarketplace } from "../services/marketplace.js";
17
+ import { studioSpaces } from "../services/members-studio.js";
17
18
  import { listWizards } from "../services/wizards.js";
18
19
  import { serverText } from "../texts.js";
19
20
  import { attempt } from "../tools/shared.js";
@@ -207,17 +208,29 @@ export function knowsTools(ctx) {
207
208
  const runIds = [...new Set(usage.months.flatMap((m) => m.runs.map((r) => r.runId)))];
208
209
  const runs = runIds.length
209
210
  ? await db
210
- .select({ id: schema.run.id, wizard: schema.wizard.title, mode: schema.run.mode })
211
+ .select({
212
+ id: schema.run.id,
213
+ wizard: schema.wizard.title,
214
+ spaceId: schema.wizard.spaceId,
215
+ mode: schema.run.mode,
216
+ })
211
217
  .from(schema.run)
212
218
  .innerJoin(schema.wizard, eq(schema.wizard.id, schema.run.wizardId))
213
219
  .where(inArray(schema.run.id, runIds))
214
220
  : [];
215
221
  const byRun = new Map(runs.map((r) => [r.id, r]));
222
+ // A member reads no wizard's use in a space whose Studio is closed to them.
223
+ const open = await studioSpaces();
216
224
  return {
217
225
  months: usage.months.map((m) => {
218
226
  const perWizard = new Map();
219
227
  for (const r of m.runs) {
220
- const title = byRun.get(r.runId)?.wizard ?? "(a run of another install)";
228
+ const run = byRun.get(r.runId);
229
+ const title = !run
230
+ ? "(a run of another install)"
231
+ : open && !open.has(run.spaceId)
232
+ ? "(wizards of spaces whose Studio is closed to you)"
233
+ : run.wizard;
221
234
  perWizard.set(title, (perWizard.get(title) ?? 0) + r.credits);
222
235
  }
223
236
  return {
@@ -1,7 +1,7 @@
1
1
  import { keptSecret, markUsed, spaceAccount, wizardAccount } from "./account.js";
2
2
  import { inGrant, runGrant } from "./grant.js";
3
3
  import { SIGN_IN_FAILED, summarizeInput, writeLog } from "./log.js";
4
- import { guestSendCheck, recipientsOf } from "./send.js";
4
+ import { channelOf, guestSendCheck, postsToChannel, recipientsOf } from "./send.js";
5
5
  /**
6
6
  * A wizard's step calls as the person running it: the store's holder says who that is, their
7
7
  * role in the organization whether they count as an admin.
@@ -281,9 +281,22 @@ export async function brokerCall(call) {
281
281
  await line(kind, "deny", rule, decision.reason, refused);
282
282
  return { ok: false, refused, reason: decision.reason };
283
283
  }
284
- // A guest's send goes only to the run's own address or the space's domains, a few per run and day.
284
+ // A guest's send goes only to the run's own address or the space's domains, a post only to the
285
+ // channel its fixed step is fixed to, a few per run and day.
285
286
  if (kind === "send" && where.guest) {
286
- const sent = await guestSendCheck(where, recipientsOf(call.input));
287
+ const sent = await guestSendCheck(where, {
288
+ recipients: recipientsOf(call.input),
289
+ ...(postsToChannel(account.connector.id, call.action.id)
290
+ ? {
291
+ post: {
292
+ who,
293
+ connectionId,
294
+ actionId: call.action.id,
295
+ channel: channelOf(call.input),
296
+ },
297
+ }
298
+ : {}),
299
+ });
287
300
  if (!sent.ok) {
288
301
  await line(kind, "deny", "guest_send", sent.reason, sent.refused);
289
302
  return { ok: false, refused: sent.refused, reason: sent.reason };
@@ -1,9 +1,14 @@
1
1
  import { note } from "@engenty/wizards-shared/run";
2
2
  import { eq } from "drizzle-orm";
3
3
  import { db, schema } from "../db/client.js";
4
+ /** A value of a call's input as the definition fixes it: a text with no template; else null. */
5
+ function literal(value) {
6
+ return typeof value === "string" && !value.includes("{{") && value.trim() ? value.trim() : null;
7
+ }
4
8
  /** The grant a definition gives its runs. Pure: the same definition, the same grant. */
5
9
  export function grantOf(definition) {
6
10
  const connections = {};
11
+ const channels = {};
7
12
  const tools = new Set();
8
13
  const hosts = new Set();
9
14
  const defs = new Map((definition.connections ?? []).map((c) => [c.id, c]));
@@ -18,6 +23,14 @@ export function grantOf(definition) {
18
23
  const have = new Set(connections[step.call.connection] ?? []);
19
24
  have.add(step.call.action);
20
25
  connections[step.call.connection] = [...have].sort();
26
+ const channel = literal(step.call.input.channel);
27
+ if (channel) {
28
+ channels[step.id] = {
29
+ connection: defs.get(step.call.connection)?.spaceConnection ?? step.call.connection,
30
+ action: step.call.action,
31
+ channel,
32
+ };
33
+ }
21
34
  }
22
35
  for (const host of step.hosts ?? []) {
23
36
  hosts.add(host.trim().toLowerCase());
@@ -34,7 +47,18 @@ export function grantOf(definition) {
34
47
  connections[id] = [...have].sort();
35
48
  }
36
49
  }
37
- return { connections, hosts: [...hosts].sort(), tools: [...tools].sort() };
50
+ return { connections, hosts: [...hosts].sort(), tools: [...tools].sort(), channels };
51
+ }
52
+ /**
53
+ * Whether the grant fixes this step's post to this channel: the step's own connection and action,
54
+ * and the channel its definition names as a literal.
55
+ */
56
+ export function channelInGrant(grant, stepId, post) {
57
+ const fixed = grant.channels?.[stepId];
58
+ return (!!fixed &&
59
+ fixed.connection === post.connectionId &&
60
+ fixed.action === post.actionId &&
61
+ fixed.channel === post.channel);
38
62
  }
39
63
  /**
40
64
  * Whether the grant lets `http_request` reach this host: named as it is, or below a `*.` entry
@@ -5,9 +5,9 @@
5
5
  export { grantedScopes } from "./account.js";
6
6
  export { brokerCall, brokerConnected, brokerSecret, decide, grantBinds, inAudience, kindOf, signInRefused, whereOf, whereOfRun, whoOf, } from "./call.js";
7
7
  export { currentCaller, withCaller } from "./caller.js";
8
- export { grantNote, grantOf, hostInGrant, inGrant, runGrant, } from "./grant.js";
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
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";
12
12
  export { outsideReaches, reachesOutside } from "./registry.js";
13
- export { brokerSend, GUEST_MAILS_PER_RUN, guestSendCheck, recipientsOf, runAddresses, } from "./send.js";
13
+ export { brokerSend, channelOf, FIXED_CHANNEL_ONLY, GUEST_MAILS_PER_RUN, guestPostCheck, guestSendCheck, postsToChannel, recipientsOf, runAddresses, } from "./send.js";
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { and, desc, eq, gt, inArray, lt, not, or, sql } from "drizzle-orm";
2
+ import { and, desc, eq, exists, gt, inArray, lt, not, or, sql } from "drizzle-orm";
3
3
  import { nanoid } from "nanoid";
4
4
  import { db, schema } from "../db/client.js";
5
5
  /**
@@ -140,10 +140,25 @@ const REFUSED_BY_PERSON = ["declined"];
140
140
  function likeOf(text) {
141
141
  return `%${text.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
142
142
  }
143
+ /**
144
+ * A person's own lines: the calls they made themselves (an AI step of their run calls as them)
145
+ * and the ones Goose made for them, and the fixed steps of a run held for them, which call as
146
+ * the step. Part of the query, so a page, a cursor and a search count nobody else's lines.
147
+ */
148
+ function ownLines(userId) {
149
+ const log = schema.brokerLog;
150
+ return or(and(inArray(log.whoKind, ["person", "goose"]), eq(log.whoId, userId)), and(eq(log.whoKind, "step"), exists(db
151
+ .select({ one: sql `1` })
152
+ .from(schema.run)
153
+ .where(and(eq(schema.run.id, log.runId), eq(schema.run.userId, userId))))));
154
+ }
143
155
  /** A space's log, newest first, filtered. */
144
156
  export async function logOfSpace(spaceId, query = {}) {
145
157
  const log = schema.brokerLog;
146
158
  const where = [eq(log.spaceId, spaceId)];
159
+ if (query.own) {
160
+ where.push(ownLines(query.own));
161
+ }
147
162
  if (query.connection) {
148
163
  where.push(eq(log.connectionId, query.connection));
149
164
  }
@@ -196,17 +211,21 @@ export async function logOfSpace(spaceId, query = {}) {
196
211
  if (query.before) {
197
212
  where.push(or(lt(log.at, query.before.at), and(eq(log.at, query.before.at), lt(log.id, query.before.id))));
198
213
  }
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
- });
214
+ return db
215
+ .select()
216
+ .from(log)
217
+ .where(and(...where))
218
+ .orderBy(desc(log.at), desc(log.id))
219
+ .limit(Math.min(Math.max(query.limit ?? LOG_PAGE, 1), LOG_PAGE));
204
220
  }
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
- });
221
+ /** One line of a space's log; with `own`, only where it is that person's own. */
222
+ export async function logLine(spaceId, id, own) {
223
+ const log = schema.brokerLog;
224
+ const [row] = await db
225
+ .select()
226
+ .from(log)
227
+ .where(and(eq(log.spaceId, spaceId), eq(log.id, id), ...(own ? [ownLines(own)] : [])))
228
+ .limit(1);
210
229
  return row ?? null;
211
230
  }
212
231
  /** The critical rows of these spaces since a time, newest first. */
@@ -198,13 +198,25 @@ export function decideWith(rules, subjects, resource, perm) {
198
198
  const behind = decideOne(rules, subjects, { kind: "document", id: resource.fileId }, perm);
199
199
  return behind.ok ? own : behind;
200
200
  }
201
- /** The rules of a space, seeded first where it has none yet. */
201
+ /** The spaces being seeded right now, by tenant and space: each once. */
202
+ const seeding = new Map();
203
+ /**
204
+ * The rules of a space, seeded first where it has none yet. Readers that ask at once (a search's
205
+ * three, a plugin listing files and pages together) wait for one seed: a guest's rows have no
206
+ * subject id, so the table's unique key does not keep a second seed's rows out.
207
+ */
202
208
  async function rulesOf(spaceId) {
203
209
  const rows = await db.query.rwxRule.findMany({ where: eq(schema.rwxRule.spaceId, spaceId) });
204
210
  if (rows.length) {
205
211
  return rows;
206
212
  }
207
- await seedRwx(spaceId);
213
+ const key = `${currentTenant()}/${spaceId}`;
214
+ let seed = seeding.get(key);
215
+ if (!seed) {
216
+ seed = seedRwx(spaceId).finally(() => seeding.delete(key));
217
+ seeding.set(key, seed);
218
+ }
219
+ await seed;
208
220
  return db.query.rwxRule.findMany({ where: eq(schema.rwxRule.spaceId, spaceId) });
209
221
  }
210
222
  /** Whether the subjects may do `perm` on the resource. With the switch off: yes. */
@@ -1,15 +1,49 @@
1
- import { and, eq, gte, notLike } from "drizzle-orm";
1
+ import { and, eq, gte, inArray, isNull, notLike, or } from "drizzle-orm";
2
2
  import { db, schema } from "../db/client.js";
3
+ import { channelInGrant, grantOf } from "./grant.js";
3
4
  import { summarizeInput, writeLog } from "./log.js";
4
5
  /*
5
6
  * Sends from a guest's run (docs/plans/capabilities.md, A6; rule 7 of the connections plan): a
6
7
  * mail leaves only for an address the run itself collected — what the person typed into a page
7
- * field of kind `email` — or for an address in one of the space's own mail domains. A run sends a
8
- * few, a wizard's guests a number per day the wizard sets. Everything beyond is refused and
9
- * logged as critical. Members' runs are not bound: they send as they always did.
8
+ * field of kind `email` — or for an address in one of the space's own mail domains. A post to a
9
+ * channel (Slack) leaves only from a fixed step, for the channel the published definition fixes
10
+ * (the run's grant). A run sends a few, a wizard's guests a number per day the wizard sets, mails
11
+ * and posts together. Everything beyond is refused and logged as critical. Members' runs are not
12
+ * bound: they send as they always did.
10
13
  */
11
- /** Mails one guest's run sends, from any address. */
14
+ /** Mails and posts one guest's run sends, from any address. */
12
15
  export const GUEST_MAILS_PER_RUN = 3;
16
+ /**
17
+ * The sends that go to a channel and name no address, by connector: the actions whose input
18
+ * names the channel as `channel`. Slack's post is the one.
19
+ */
20
+ const CHANNEL_POSTS = { slack: ["post_message"] };
21
+ /** Whether this action of this connector posts to a channel. */
22
+ export function postsToChannel(connectorId, actionId) {
23
+ return CHANNEL_POSTS[connectorId]?.includes(actionId) ?? false;
24
+ }
25
+ /** The channel a post's input names; null where it names none. */
26
+ export function channelOf(input) {
27
+ const channel = input && typeof input === "object" ? input.channel : null;
28
+ return typeof channel === "string" && channel.trim() ? channel.trim() : null;
29
+ }
30
+ /** A guest's post, as the log and „Was darf …?“ say it. */
31
+ export const FIXED_CHANNEL_ONLY = "A guest's run posts only from a fixed step, to the channel its published step fixes.";
32
+ /**
33
+ * Whether a guest's run may post to this channel, with no side effect: only its fixed step
34
+ * posts, and only to the channel the grant fixes for that step. The grant comes from the
35
+ * published definition, so nothing the guest typed decides it.
36
+ */
37
+ export function guestPostCheck(post) {
38
+ const { where, connectionId, actionId, channel } = post;
39
+ const fixed = post.who.kind === "step" &&
40
+ !!where.stepId &&
41
+ !!channel &&
42
+ channelInGrant(post.grant, where.stepId, { connectionId, actionId, channel });
43
+ return fixed
44
+ ? { ok: true }
45
+ : { ok: false, refused: "channel_not_fixed", reason: FIXED_CHANNEL_ONLY };
46
+ }
13
47
  const ADDRESS = /^[^\s@<>,;]+@[^\s@<>,;]+\.[^\s@<>,;]+$/;
14
48
  /** The addresses a send's input names: `to`, `cc`, `bcc`, `recipients`, as strings, lists or objects. */
15
49
  export function recipientsOf(input) {
@@ -77,66 +111,84 @@ const startOfToday = () => {
77
111
  const now = new Date();
78
112
  return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
79
113
  };
80
- /** How many mails guests sent through this run, and through this wizard today. */
81
- async function guestMailsSent(where) {
82
- // Mails only: a request to a host is a send too, counted nowhere here.
83
- const sent = and(eq(schema.brokerLog.whoKind, "guest"), eq(schema.brokerLog.kind, "send"), eq(schema.brokerLog.result, "ok"), notLike(schema.brokerLog.connectionId, "host:%"));
114
+ /**
115
+ * How often guests sent through this run, and through this wizard today: mails and posts, a
116
+ * guest's own and those of the fixed steps of guests' runs.
117
+ */
118
+ async function guestSends(where) {
119
+ // A request to a host is a send too, counted nowhere here.
120
+ const sent = and(eq(schema.brokerLog.kind, "send"), eq(schema.brokerLog.result, "ok"), notLike(schema.brokerLog.connectionId, "host:%"));
121
+ // A fixed step is logged as `step`: it counts where its run is a guest's.
122
+ const guestRuns = (wizardId) => db
123
+ .select({ id: schema.run.id })
124
+ .from(schema.run)
125
+ .where(and(eq(schema.run.wizardId, wizardId), eq(schema.run.mode, "live"), isNull(schema.run.userId)));
84
126
  const [inRun, today] = await Promise.all([
85
127
  where.runId
86
- ? db.$count(schema.brokerLog, and(sent, eq(schema.brokerLog.runId, where.runId)))
128
+ ? db.$count(schema.brokerLog, and(sent, eq(schema.brokerLog.runId, where.runId), inArray(schema.brokerLog.whoKind, ["guest", "step"])))
87
129
  : 0,
88
130
  where.wizardId
89
- ? db.$count(schema.brokerLog, and(sent, eq(schema.brokerLog.wizardId, where.wizardId), gte(schema.brokerLog.at, startOfToday())))
131
+ ? db.$count(schema.brokerLog, and(sent, eq(schema.brokerLog.wizardId, where.wizardId), gte(schema.brokerLog.at, startOfToday()), or(eq(schema.brokerLog.whoKind, "guest"), and(eq(schema.brokerLog.whoKind, "step"), inArray(schema.brokerLog.runId, guestRuns(where.wizardId))))))
90
132
  : 0,
91
133
  ]);
92
134
  return { run: inRun, day: today };
93
135
  }
94
136
  /**
95
- * Whether a guest's run may send to these addresses now: each one the run's own or in the space's
96
- * domains, and the run and the wizard under their caps. The run, the wizard and the space are
97
- * read here; a run or wizard not known refuses.
137
+ * Whether a guest's run may send this now: each address the run's own or in the space's domains,
138
+ * a post only to the channel its fixed step is fixed to, and the run and the wizard under their
139
+ * caps. The run, the wizard and the space are read here; a run or wizard not known refuses.
98
140
  */
99
- export async function guestSendCheck(where, recipients) {
141
+ export async function guestSendCheck(where, send) {
142
+ const { recipients, post } = send;
100
143
  const refuse = (refused, reason) => ({
101
144
  ok: false,
102
145
  refused,
103
146
  reason,
104
147
  });
105
- if (!recipients.length) {
148
+ if (!(recipients.length || post)) {
106
149
  return refuse("not_allowed_recipient", "The send names no recipient.");
107
150
  }
108
151
  const run = where.runId
109
152
  ? await db.query.run.findFirst({
110
153
  where: eq(schema.run.id, where.runId),
111
- columns: { definition: true, state: true, wizardId: true },
154
+ columns: { definition: true, state: true, wizardId: true, grant: true },
112
155
  })
113
156
  : null;
114
157
  if (!run) {
115
158
  return refuse("not_allowed_recipient", "The run is not known here.");
116
159
  }
160
+ if (post) {
161
+ // A run from before grants were kept: the grant its definition gives (grant.ts, `runGrant`).
162
+ const fixed = guestPostCheck({ ...post, where, grant: run.grant ?? grantOf(run.definition) });
163
+ if (!fixed.ok) {
164
+ return fixed;
165
+ }
166
+ }
117
167
  const wizard = await db.query.wizard.findFirst({
118
168
  where: eq(schema.wizard.id, run.wizardId),
119
169
  columns: { spaceId: true, dailyMailLimit: true },
120
170
  });
121
- const space = wizard
122
- ? await db.query.space.findFirst({
123
- where: eq(schema.space.id, wizard.spaceId),
124
- columns: { mailDomains: true },
125
- })
126
- : null;
127
- const own = runAddresses(run);
128
- const domains = space?.mailDomains ?? [];
129
- const foreign = recipients.find((address) => !(own.includes(address.toLowerCase()) || inMailDomains(address, domains)));
130
- if (foreign) {
131
- return refuse("not_allowed_recipient", `A guest's run sends only to its own address or the space's domains, not to ${foreign}.`);
171
+ if (recipients.length) {
172
+ const space = wizard
173
+ ? await db.query.space.findFirst({
174
+ where: eq(schema.space.id, wizard.spaceId),
175
+ columns: { mailDomains: true },
176
+ })
177
+ : null;
178
+ const own = runAddresses(run);
179
+ const domains = space?.mailDomains ?? [];
180
+ const foreign = recipients.find((address) => !(own.includes(address.toLowerCase()) || inMailDomains(address, domains)));
181
+ if (foreign) {
182
+ return refuse("not_allowed_recipient", `A guest's run sends only to its own address or the space's domains, not to ${foreign}.`);
183
+ }
132
184
  }
133
- const sent = await guestMailsSent({ ...where, wizardId: where.wizardId ?? run.wizardId });
185
+ const sent = await guestSends({ ...where, wizardId: where.wizardId ?? run.wizardId });
134
186
  if (sent.run >= GUEST_MAILS_PER_RUN) {
135
- return refuse("run_limit", `This run has sent its ${GUEST_MAILS_PER_RUN} mails.`);
187
+ return refuse("run_limit", `This run has sent its ${GUEST_MAILS_PER_RUN} mails and posts.`);
136
188
  }
137
189
  const perDay = wizard?.dailyMailLimit ?? 50;
138
190
  if (sent.day >= perDay) {
139
- return refuse("day_limit", `This wizard's guests have sent today's ${perDay} mails.`);
191
+ return refuse("day_limit", `This wizard's guests have sent today's ${perDay} mails and posts.`);
140
192
  }
141
193
  return { ok: true };
142
194
  }
@@ -170,7 +222,7 @@ export async function brokerSend(call) {
170
222
  });
171
223
  let reason = "The server's address sends for members.";
172
224
  if (where.guest) {
173
- const check = await guestSendCheck(where, call.recipients);
225
+ const check = await guestSendCheck(where, { recipients: call.recipients });
174
226
  if (!check.ok) {
175
227
  await line("deny", check.reason, check.refused);
176
228
  return check;
@@ -1,4 +1,5 @@
1
1
  import { CONNECTION_ACTION_KINDS, CONNECTION_AUDIENCES, CONNECTION_LIMITS, CONNECTION_OUTCOMES, CONNECTION_SIGN_INS, DEFAULT_CONNECTION_RULES, } from "@engenty/wizards-shared/connectors";
2
+ import { featureOn } from "@engenty/wizards-shared/features";
2
3
  import { note } from "@engenty/wizards-shared/run";
3
4
  import { and, asc, eq, inArray } from "drizzle-orm";
4
5
  import { nanoid } from "nanoid";
@@ -6,6 +7,9 @@ import { z } from "zod";
6
7
  import { inAudience, logRuleChange } from "../broker/index.js";
7
8
  import { db, schema } from "../db/client.js";
8
9
  import { buildAuthorizationUrl, createOAuth2Pkce, exchangeAuthorizationCode, } from "../engenty/connections-sdk/oauth2.js";
10
+ import { currentFeatures } from "../features.js";
11
+ import { managed, tenantInfo } from "../manage.js";
12
+ import { loadedPlugin } from "../plugins/registry.js";
9
13
  import { seal, unseal } from "../secrets/crypto.js";
10
14
  import { isAdminRole, requireAdmin, requireWritableSpace } from "../services/access.js";
11
15
  import { notFound, ServiceError } from "../services/errors.js";
@@ -27,6 +31,8 @@ export const newConnectionSchema = z.object({
27
31
  });
28
32
  export const connectionPatchSchema = z.object({
29
33
  name: z.string().trim().min(1).max(CONNECTION_LIMITS.name).optional(),
34
+ /** How it signs in: a change forgets the sign-ins of the way it leaves. */
35
+ signIn: z.enum(CONNECTION_SIGN_INS).optional(),
30
36
  audience: z.enum(CONNECTION_AUDIENCES).optional(),
31
37
  rules: rulesSchema.optional(),
32
38
  actions: z.array(z.string().max(200)).max(200).optional(),
@@ -127,6 +133,9 @@ export async function spaceConnectionViews(spaceId, userId) {
127
133
  rules: row.rules,
128
134
  actions: row.actions,
129
135
  plugin: row.plugin,
136
+ pluginName: row.plugin
137
+ ? (loadedPlugin(row.plugin)?.source.manifest.name ?? row.plugin)
138
+ : null,
130
139
  account: row.signIn === "space" && row.secret
131
140
  ? {
132
141
  label: row.label ?? connector?.name ?? row.name,
@@ -153,12 +162,27 @@ function knownActions(connector, actions) {
153
162
  }
154
163
  return [...new Set(actions)];
155
164
  }
165
+ /** Whether a connection here may have each person sign in. A computer of one's own has no plan. */
166
+ export async function personSignInAllowed() {
167
+ return !managed || featureOn(await currentFeatures(), "personSignIn");
168
+ }
169
+ /** Refuses each person signing in where the organization's plan leaves it out, naming the plan. */
170
+ async function requirePersonSignIn() {
171
+ if (await personSignInAllowed()) {
172
+ return;
173
+ }
174
+ const plan = (await tenantInfo(currentTenant()).catch(() => null))?.plan?.name;
175
+ throw new ServiceError("plan", plan ? note("personSignInNotInPlan", { plan }) : note("personSignInNotInOrganizationPlan"));
176
+ }
156
177
  export async function createSpaceConnection(userId, spaceId, input,
157
178
  /** The plugin that sets it up through `server.connections`, where one does. */
158
179
  plugin = null) {
159
180
  await ownedSpace(userId ?? "", spaceId);
160
181
  await requireWritableSpace(spaceId);
161
182
  await requireAdmin();
183
+ if (input.signIn === "person") {
184
+ await requirePersonSignIn();
185
+ }
162
186
  const found = await resolveConnector(spaceId, input.connectorId);
163
187
  if (!found || found.connector.auth.kind === "browser") {
164
188
  throw new ServiceError("invalid", note("connectorGone", { id: input.connectorId }));
@@ -189,6 +213,14 @@ export async function updateSpaceConnection(userId, id, patch) {
189
213
  await ownedSpace(userId, row.spaceId);
190
214
  await requireWritableSpace(row.spaceId);
191
215
  await requireAdmin();
216
+ const signInChanged = patch.signIn !== undefined && patch.signIn !== row.signIn;
217
+ if (signInChanged && patch.signIn === "person") {
218
+ // A plugin calls with no person: its connection stays the space's.
219
+ if (row.plugin) {
220
+ throw new ServiceError("invalid", note("pluginConnectionSignsInAsSpace"));
221
+ }
222
+ await requirePersonSignIn();
223
+ }
192
224
  const actions = patch.actions !== undefined
193
225
  ? knownActions(await connectorOfRow(row), patch.actions)
194
226
  : undefined;
@@ -196,6 +228,8 @@ export async function updateSpaceConnection(userId, id, patch) {
196
228
  .update(schema.spaceConnection)
197
229
  .set({
198
230
  ...(patch.name !== undefined ? { name: patch.name } : {}),
231
+ // The space's own sign-in goes with the way it leaves; a person's has none on the row.
232
+ ...(signInChanged ? { signIn: patch.signIn, secret: null, label: null } : {}),
199
233
  ...(patch.audience !== undefined ? { audience: patch.audience } : {}),
200
234
  ...(patch.rules !== undefined ? { rules: patch.rules } : {}),
201
235
  ...(actions !== undefined ? { actions } : {}),
@@ -203,19 +237,30 @@ export async function updateSpaceConnection(userId, id, patch) {
203
237
  })
204
238
  .where(eq(schema.spaceConnection.id, row.id))
205
239
  .returning();
206
- // Who may use it, and what each kind of action may do: a change there is heard of.
240
+ if (signInChanged && updated.signIn === "space") {
241
+ await db
242
+ .delete(schema.spaceConnectionSignIn)
243
+ .where(eq(schema.spaceConnectionSignIn.connectionId, row.id));
244
+ }
245
+ // How it signs in, who may use it, and what each kind of action may do: a change there is heard of.
207
246
  const rulesChanged = patch.rules !== undefined && JSON.stringify(patch.rules) !== JSON.stringify(row.rules);
208
247
  const audienceChanged = patch.audience !== undefined && patch.audience !== row.audience;
209
- if (rulesChanged || audienceChanged) {
248
+ if (rulesChanged || audienceChanged || signInChanged) {
210
249
  await logRuleChange({
211
250
  userId,
212
251
  spaceId: row.spaceId,
213
252
  connectionId: row.id,
214
253
  summary: {
254
+ ...(signInChanged ? { signIn: `${row.signIn} → ${updated.signIn}` } : {}),
215
255
  ...(audienceChanged ? { audience: `${row.audience} → ${updated.audience}` } : {}),
216
256
  ...(rulesChanged ? { rules: changedRules(row.rules, updated.rules) } : {}),
217
257
  },
218
258
  reason: [
259
+ signInChanged
260
+ ? updated.signIn === "space"
261
+ ? "It now signs in as the space."
262
+ : "Each person now signs in."
263
+ : "",
219
264
  audienceChanged ? `The audience is now ${updated.audience}.` : "",
220
265
  rulesChanged ? `The rules changed: ${changedRules(row.rules, updated.rules)}.` : "",
221
266
  ]