@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
@@ -7,7 +7,7 @@ import { embeddingModel } from "../models.js";
7
7
  import { mayBuild, spaceWritable } from "../services/access.js";
8
8
  import { cloudLinked, cloudState } from "../services/cloud.js";
9
9
  import { ServiceError } from "../services/errors.js";
10
- import { closedToMe, studioOpen } from "../services/members-studio.js";
10
+ import { spaceOfItem, studioOpen, studioSpaces } from "../services/members-studio.js";
11
11
  import { presentIn } from "../services/presence.js";
12
12
  import { getPage, getRow, getTableHeader } from "../services/space-data.js";
13
13
  import { fileView, spaceFiles } from "../services/space-files.js";
@@ -137,27 +137,58 @@ const ITEM_VIEWS = {
137
137
  },
138
138
  };
139
139
  /**
140
- * What the Studio alone shows of a space: a member whose Studio the space is closed to gets no view
141
- * of these, and the browser asks the studio API, which refuses it (services/members-studio.ts).
142
- * The space itself, its files and connectors are what Work reads in every space.
140
+ * What the Studio alone shows of a space: its wizards with their translations and build chats,
141
+ * its pages, tables, rows and categories, its skills, and who is in an item. The space itself,
142
+ * its files and connectors are what Work reads in every space.
143
143
  */
144
144
  const STUDIO_KINDS = new Set([
145
145
  "wizard",
146
146
  "translation",
147
+ "message",
147
148
  "page",
148
149
  "table",
149
150
  "row",
151
+ "category",
152
+ "skill",
150
153
  "presence",
151
154
  ]);
155
+ /** The space a change is in. Who is in an item (`presence`) is in the item's space. */
156
+ async function spaceOfChange(x) {
157
+ if (x.spaceId || x.kind !== "presence" || !x.parent) {
158
+ return x.spaceId;
159
+ }
160
+ return spaceOfItem("presence", x.parent, x.item.slice(x.parent.length + 1));
161
+ }
162
+ /**
163
+ * What of the feed's changes the person at hand hears. A member hears nothing of what the Studio
164
+ * alone shows of a space closed to them (services/members-studio.ts): not that it changed, not
165
+ * its kind or id. A change that names no space still there (a row that went with its table)
166
+ * says nothing of whose it was, so a member does not hear it either; the item it went with says
167
+ * so in its own space.
168
+ */
169
+ export async function heardChanges(changes) {
170
+ if (!changes.some((x) => STUDIO_KINDS.has(x.kind))) {
171
+ return changes;
172
+ }
173
+ const open = await studioSpaces();
174
+ if (!open) {
175
+ return changes;
176
+ }
177
+ const heard = [];
178
+ for (const x of changes) {
179
+ if (!STUDIO_KINDS.has(x.kind) || open.has((await spaceOfChange(x)) ?? "")) {
180
+ heard.push(x);
181
+ }
182
+ }
183
+ return heard;
184
+ }
185
+ /** The view of a change the reader hears (`heardChanges` comes first, in the hub). */
152
186
  export async function itemView(r, x) {
153
187
  const read = ITEM_VIEWS[x.kind];
154
188
  if (!read) {
155
189
  return undefined;
156
190
  }
157
191
  try {
158
- if (x.spaceId && STUDIO_KINDS.has(x.kind) && (await closedToMe(x.spaceId))) {
159
- return undefined;
160
- }
161
192
  return await read(r, x);
162
193
  }
163
194
  catch (err) {
@@ -367,6 +367,24 @@ async function creditAccess(cfg, chosen) {
367
367
  }
368
368
  return { baseUrl: env.local.gatewayUrl, token, tenant: null };
369
369
  }
370
+ /**
371
+ * Where the gateway's own tools (web search) are reached, behind `gatewaySearch`: a Manage-App's
372
+ * runtime always; alone, through the linked account. None: the model's own search, where it has one.
373
+ */
374
+ export async function toolAccess() {
375
+ if (!feature("gatewaySearch", await remoteFeatures().catch(() => null))) {
376
+ return null;
377
+ }
378
+ if (managed) {
379
+ return {
380
+ baseUrl: env.manage.gatewayUrl,
381
+ token: env.manage.serviceKey,
382
+ tenant: currentTenantOrNull(),
383
+ };
384
+ }
385
+ const token = (await linkedAccount()) ? await accountToken() : null;
386
+ return token ? { baseUrl: env.local.gatewayUrl, token, tenant: null } : null;
387
+ }
370
388
  /** A class goes to the credits on purpose: text on the account, or a binding that says so. */
371
389
  function creditsChosen(cfg, cls) {
372
390
  return (isCreditsRef(cfg.settings.bindings[cls]) ||
@@ -11,7 +11,7 @@ returns and when to use it.
11
11
  <!-- Web: search, fetch, HTTP (tools/index.ts) -->
12
12
 
13
13
  <!-- section: tool.web_search -->
14
- Search the web.
14
+ Search the web. Each result has its address, title and the sentences that fit the query; read a page in full with web_fetch. Name the pages you used.
15
15
 
16
16
  <!-- section: tool.web_fetch -->
17
17
  Fetch a public web page or file and return its readable text (Markdown).
@@ -26,7 +26,7 @@ import { exportWizard } from "../services/package.js";
26
26
  import { siteJob, siteSchema, startSiteJob } from "../services/site.js";
27
27
  import { checkOnServer, checkSchema, listSyncedSpaces, patchSyncedWizard, removeSyncedSpace, removeSyncedWizard, rotateSyncedLink, syncDataSchema, syncSettingsSchema, syncSpaceData, syncWizard, syncWizardSchema, } from "../services/synced-spaces.js";
28
28
  import { createWizard, ownedWizard, publishWizard, writeDraft } from "../services/wizards.js";
29
- import { adoptSpace, blobBytes, missingBlobs, publishSynced, pullChanges, pushChanges, rotateSynced, syncOverview, takeBlob, } from "../sync/hub.js";
29
+ import { adoptSpace, blobBytes, missingBlobs, publishSynced, pullChanges, pushChanges, rotateSynced, syncHears, syncOverview, takeBlob, } from "../sync/hub.js";
30
30
  import { codeOf, tenantStatus } from "../tenants/control.js";
31
31
  import { notFoundAnswer, say } from "./lang.js";
32
32
  import { dispatchAs } from "./plugins.js";
@@ -466,7 +466,7 @@ export const apiRoutes = new Hono()
466
466
  const stop = await followFor(who.tenantId, install, since, (e) => {
467
467
  const { event, ...data } = e;
468
468
  write(event, data, e.seq);
469
- });
469
+ }, (changes) => asRole(who.role, () => syncHears(changes)));
470
470
  stream.onAbort(() => {
471
471
  closed = true;
472
472
  stop();
@@ -1,12 +1,12 @@
1
1
  import { eq, inArray } from "drizzle-orm";
2
2
  import { Hono } from "hono";
3
3
  import { z } from "zod";
4
- import { cursorOf, decide, kindOf, LOG_PAGE, logLine, logOfSpace, readCursor, } from "../broker/index.js";
4
+ import { cursorOf, decide, FIXED_CHANNEL_ONLY, inAudience, kindOf, LOG_PAGE, logLine, logOfSpace, postsToChannel, readCursor, } from "../broker/index.js";
5
5
  import { resolveConnector } from "../connectors/external.js";
6
6
  import { connectorOfRow, listSpaceConnections, spaceConnectionById, } from "../connectors/space-connections.js";
7
7
  import { db, schema } from "../db/client.js";
8
8
  import { managed, tenantMembers } from "../manage.js";
9
- import { isAdminRole, requireAdmin } from "../services/access.js";
9
+ import { currentRole, isAdminRole, requireAdmin } from "../services/access.js";
10
10
  import { notFound } from "../services/errors.js";
11
11
  import { userProfile } from "../services/profile.js";
12
12
  import { ownedSpace } from "../services/spaces.js";
@@ -83,13 +83,22 @@ export function logView(row) {
83
83
  criticalKind: row.criticalKind,
84
84
  };
85
85
  }
86
- /** The organization's people by id, with their role; alone, the one person. */
87
- async function peopleOf(user) {
86
+ /** The person whose own lines are all they read of the log: a member. Undefined for an admin. */
87
+ const memberOf = (user) => managed && !isAdminRole(currentRole()) ? user.id : undefined;
88
+ /** The organization's people by id, with their role; alone, the one person; for a member, themselves. */
89
+ async function peopleOf(user, own) {
88
90
  if (!managed) {
89
91
  return [{ id: user.id, name: (await userProfile(user)).name, role: "owner" }];
90
92
  }
91
93
  const people = await tenantMembers(currentTenant()).catch(() => null);
92
- return (people?.members ?? []).map((m) => ({ id: m.userId, name: m.name, role: m.role }));
94
+ return (people?.members ?? [])
95
+ .filter((m) => !own || m.userId === own)
96
+ .map((m) => ({ id: m.userId, name: m.name, role: m.role }));
97
+ }
98
+ /** The space's connections the lines are named by: for a member, the ones open to them. */
99
+ async function connectionsOf(spaceId, own) {
100
+ const all = await listSpaceConnections(spaceId);
101
+ return own ? all.filter((c) => inAudience(c.audience, { kind: "person", id: own })) : all;
93
102
  }
94
103
  /** A connector, looked up once per request. */
95
104
  function connectorCache(spaceId) {
@@ -109,9 +118,9 @@ function connectorCache(spaceId) {
109
118
  * The lines with the names the page shows: who by name (a fixed step: whom its run is held for),
110
119
  * the connection and the action by theirs, the wizard of a run, the title of a chat.
111
120
  */
112
- async function describeLines(rows, spaceId, people) {
121
+ async function describeLines(rows, spaceId, people, own) {
113
122
  const named = new Map(people.map((p) => [p.id, p]));
114
- const connections = new Map((await listSpaceConnections(spaceId)).map((c) => [c.id, c]));
123
+ const connections = new Map((await connectionsOf(spaceId, own)).map((c) => [c.id, c]));
115
124
  const connector = connectorCache(spaceId);
116
125
  const ids = (pick) => [
117
126
  ...new Set(rows.map(pick).filter((id) => !!id)),
@@ -186,7 +195,7 @@ async function describeLines(rows, spaceId, people) {
186
195
  }));
187
196
  }
188
197
  /** The ids whose names hold the search text: people, the space's connections, its wizards. */
189
- async function matchesOf(q, spaceId, people) {
198
+ async function matchesOf(q, spaceId, people, own) {
190
199
  const text = q.trim().toLowerCase();
191
200
  if (!text) {
192
201
  return undefined;
@@ -198,7 +207,7 @@ async function matchesOf(q, spaceId, people) {
198
207
  .where(eq(schema.wizard.spaceId, spaceId));
199
208
  return {
200
209
  who: people.filter((p) => has(p.name)).map((p) => p.id),
201
- connections: (await listSpaceConnections(spaceId)).filter((c) => has(c.name)).map((c) => c.id),
210
+ connections: (await connectionsOf(spaceId, own)).filter((c) => has(c.name)).map((c) => c.id),
202
211
  wizards: wizards.filter((w) => has(w.title)).map((w) => w.id),
203
212
  };
204
213
  }
@@ -222,7 +231,25 @@ export const brokerRoutes = new Hono()
222
231
  ...(ask.in === "run" ? { runId: "ask", mode: "live" } : {}),
223
232
  ...(ask.in === "chat" ? { chatId: "ask" } : {}),
224
233
  };
225
- const decision = decide({ who, where, connection, actionId: ask.action, kind });
234
+ let decision = decide({ who, where, connection, actionId: ask.action, kind });
235
+ // A guest's post (broker/send.ts): only a fixed step posts, to the channel its published
236
+ // step fixes. No step is named here, so a fixed step's answer says the condition.
237
+ const post = where.guest &&
238
+ kind === "send" &&
239
+ decision.outcome !== "deny" &&
240
+ postsToChannel(connector.id, ask.action);
241
+ const fixedChannel = post && who.kind === "step";
242
+ if (fixedChannel) {
243
+ decision = { ...decision, reason: `${decision.reason} ${FIXED_CHANNEL_ONLY}` };
244
+ }
245
+ else if (post) {
246
+ decision = {
247
+ outcome: "deny",
248
+ rule: "guest_send",
249
+ refused: "channel_not_fixed",
250
+ reason: FIXED_CHANNEL_ONLY,
251
+ };
252
+ }
226
253
  return c.json({
227
254
  who,
228
255
  connection: { id: row.id, name: row.name, connector: connector.id },
@@ -232,6 +259,7 @@ export const brokerRoutes = new Hono()
232
259
  reason: decision.reason,
233
260
  ...(decision.refused ? { refused: decision.refused } : {}),
234
261
  ...(decision.admins ? { admins: true } : {}),
262
+ ...(fixedChannel ? { fixedChannel: true } : {}),
235
263
  });
236
264
  })
237
265
  // What „Was darf …?“ picks from: the organization's people, the space's connections and their actions.
@@ -260,40 +288,51 @@ export const brokerRoutes = new Hono()
260
288
  .get("/spaces/:id/broker/log", async (c) => {
261
289
  const user = c.get("user");
262
290
  const space = await ownedSpace(user.id, c.req.param("id"));
263
- await requireAdmin();
291
+ const own = memberOf(user);
264
292
  const { cursor, q, ...query } = logSchema.parse(c.req.query());
265
293
  const before = cursor ? readCursor(cursor) : null;
266
294
  const limit = query.limit ?? LOG_PAGE;
267
- const people = await peopleOf(user);
295
+ const people = await peopleOf(user, own);
268
296
  const rows = await logOfSpace(space.id, {
269
297
  ...query,
270
298
  limit,
299
+ ...(own ? { own } : {}),
271
300
  ...(before ? { before } : {}),
272
- ...(q?.trim() ? { q, matches: await matchesOf(q, space.id, people) } : {}),
301
+ ...(q?.trim() ? { q, matches: await matchesOf(q, space.id, people, own) } : {}),
273
302
  });
274
303
  const last = rows.at(-1);
275
304
  return c.json({
276
- lines: await describeLines(rows, space.id, people),
305
+ lines: await describeLines(rows, space.id, people, own),
277
306
  // A full page may have more behind it.
278
307
  next: last && rows.length === limit ? cursorOf(last) : null,
279
308
  });
280
309
  })
281
- // One line, with what its run was allowed through that connection or to that host.
310
+ // One line, with what its run was allowed through that connection or to that host. A member's
311
+ // own line; another person's is not there for them.
282
312
  .get("/spaces/:id/broker/log/:line", async (c) => {
283
313
  const user = c.get("user");
284
314
  const space = await ownedSpace(user.id, c.req.param("id"));
285
- await requireAdmin();
286
- const row = await logLine(space.id, c.req.param("line"));
315
+ const own = memberOf(user);
316
+ const row = await logLine(space.id, c.req.param("line"), own);
287
317
  if (!row) {
288
318
  throw notFound();
289
319
  }
290
- const [line] = await describeLines([row], space.id, await peopleOf(user));
291
- const run = row.runId
320
+ const [line] = await describeLines([row], space.id, await peopleOf(user, own), own);
321
+ const found = row.runId
292
322
  ? await db.query.run.findFirst({
293
323
  where: (t, { eq }) => eq(t.id, row.runId),
294
- columns: { id: true, wizardId: true, mode: true, status: true, grant: true },
324
+ columns: {
325
+ id: true,
326
+ wizardId: true,
327
+ mode: true,
328
+ status: true,
329
+ grant: true,
330
+ userId: true,
331
+ },
295
332
  })
296
333
  : undefined;
334
+ // A member reads what a run was allowed only of a run held for them.
335
+ const run = found && (!own || found.userId === own) ? found : undefined;
297
336
  const host = row.connectionId.startsWith("host:") ? row.connectionId.slice(5) : null;
298
337
  return c.json({
299
338
  line,
@@ -3,7 +3,7 @@ import { streamSSE } from "hono/streaming";
3
3
  import { subjectsOfPerson } from "../broker/rwx.js";
4
4
  import { feature, remoteFeatures } from "../features.js";
5
5
  import { openStreams, subscribe } from "../live/hub.js";
6
- import { itemView } from "../live/views.js";
6
+ import { heardChanges, itemView } from "../live/views.js";
7
7
  import { asRole } from "../services/access.js";
8
8
  import { chatChangesFor } from "../services/work-chats.js";
9
9
  import { requestLang, say } from "./lang.js";
@@ -66,7 +66,9 @@ export const liveRoutes = new Hono().get("/", async (c) => {
66
66
  const unsubscribe = await subscribe(user.tenantId, since, send, {
67
67
  key: `${user.role}|${reader.lang}`,
68
68
  read: (x) => asRole(user.role, () => itemView(reader, x)),
69
- });
69
+ },
70
+ // A member hears nothing of the Studio of a space closed to them.
71
+ (changes) => asRole(user.role, () => heardChanges(changes)));
70
72
  const end = () => {
71
73
  if (closed) {
72
74
  return;
@@ -55,7 +55,7 @@ import { notFound, ServiceError } from "../services/errors.js";
55
55
  import { deleteFile, listFiles, readFile, writeFile } from "../services/files.js";
56
56
  import { categoryContents, listKnowledge, resolvePath, valueContents, } from "../services/knowledge.js";
57
57
  import { writeSummary } from "../services/knowledge-model.js";
58
- import { closedToMe } from "../services/members-studio.js";
58
+ import { closedToMe, spaceOfItem, studioSpaces } from "../services/members-studio.js";
59
59
  import { applyAddresses, finishOnboarding, onboardingFor, startingName, } from "../services/onboarding.js";
60
60
  import { findAddresses, siteOfEmail } from "../services/onboarding-find.js";
61
61
  import { setOrganizationContext } from "../services/organization-context.js";
@@ -1379,7 +1379,18 @@ export const studio = new Hono()
1379
1379
  })
1380
1380
  // --- the two-way sync of the spaces with the account's organization (sync/client.ts) ---
1381
1381
  // --- who is in a wizard, page or table: a signal, never a lock (docs/plans/live-changes.md, 8) ---
1382
- .get("/presence/:kind", async (c) => c.json(await presentByItem(z.enum(PRESENCE_KINDS).parse(c.req.param("kind")))))
1382
+ .get("/presence/:kind", async (c) => {
1383
+ const kind = z.enum(PRESENCE_KINDS).parse(c.req.param("kind"));
1384
+ const present = await presentByItem(kind);
1385
+ // A member sees who is in the items of the spaces whose Studio is open to them.
1386
+ const open = await studioSpaces();
1387
+ for (const item of open ? Object.keys(present) : []) {
1388
+ if (!open?.has((await spaceOfItem("presence", kind, item)) ?? "")) {
1389
+ delete present[item];
1390
+ }
1391
+ }
1392
+ return c.json(present);
1393
+ })
1383
1394
  .get("/presence/:kind/:item", async (c) => c.json(await presentIn(z.enum(PRESENCE_KINDS).parse(c.req.param("kind")), c.req.param("item"))))
1384
1395
  .put("/presence", async (c) => {
1385
1396
  const user = c.get("user");
@@ -3,6 +3,7 @@ import { standaloneEntry } from "@engenty/wizards-shared/fit";
3
3
  import { pluginsOf } from "@engenty/wizards-shared/marketplace";
4
4
  import { noteText } from "@engenty/wizards-shared/run";
5
5
  import { and, count, desc, eq, gte, inArray, isNotNull, or, sql } from "drizzle-orm";
6
+ import { subjectsOfPerson } from "../broker/rwx.js";
6
7
  import { MICROS_PER_CREDIT } from "../credits/credits.js";
7
8
  import { db, schema } from "../db/client.js";
8
9
  import { env } from "../env.js";
@@ -10,7 +11,7 @@ import { wizardUnavailable } from "../limits.js";
10
11
  import { codeOf } from "../tenants/control.js";
11
12
  import { currentTenant } from "../tenants/tenant.js";
12
13
  import { serverText } from "../texts.js";
13
- import { mayBuild, READ_ONLY_TENANT, spaceWritable } from "./access.js";
14
+ import { mayBuild, READ_ONLY_TENANT, roleOf, spaceWritable } from "./access.js";
14
15
  import { mainLogoId } from "./brand.js";
15
16
  import { notFound, ServiceError } from "./errors.js";
16
17
  import { knowledgeCounts } from "./knowledge.js";
@@ -70,7 +71,8 @@ export async function apiSpaceDetails(userId, spaceId) {
70
71
  colors: p.brand.colors ?? [],
71
72
  facts: p.facts.map(({ label, value }) => ({ label, value })),
72
73
  logoUrl: logo ? `${env.publicUrl}/api/public/logos/${logo}` : null,
73
- knowledge: await knowledgeCounts(p.id),
74
+ // How much of it the caller may read.
75
+ knowledge: await knowledgeCounts(p.id, subjectsOfPerson(userId, await roleOf(userId))),
74
76
  writable: await spaceWritable(p),
75
77
  studioUrl: `${env.appUrl}/studio/space`,
76
78
  };
@@ -10,6 +10,7 @@ const STATUS = {
10
10
  page_taken: 409,
11
11
  read_only: 403,
12
12
  forbidden: 403,
13
+ plan: 403,
13
14
  };
14
15
  export class ServiceError extends NotedError {
15
16
  code;
@@ -1,12 +1,12 @@
1
1
  import { formatTableCell } from "@engenty/wizards-shared/engenty/data-tables";
2
2
  import { slugOf, } from "@engenty/wizards-shared/knowledge";
3
3
  import { and, asc, count, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm";
4
- import { assertRwx, pageResources, readable, tableResources } from "../broker/rwx.js";
4
+ import { assertRwx, brokerOn, pageResources, readable, readableMounts, tableResources, } from "../broker/rwx.js";
5
5
  import { db, schema } from "../db/client.js";
6
6
  import { embeddingModel, systemOneAccess } from "../models.js";
7
7
  import { prompt } from "../prompts.js";
8
8
  import { notFound, ServiceError } from "./errors.js";
9
- import { categoryLines, categoryRows, dateOf, filterItems, itemCategoriesOf, listCategories, numberOf, } from "./space-categories.js";
9
+ import { categoriesOver, categoryLines, categoryRows, categoryUse, dateOf, filterItems, itemCategoriesOf, listCategories, numberOf, } from "./space-categories.js";
10
10
  import { ownedSpace } from "./spaces.js";
11
11
  /** Gives each item without a slug one, unique among its siblings, and keeps it. */
12
12
  async function slugsFor(rows, siblingsOf, save) {
@@ -519,8 +519,11 @@ export async function readPage(spaceId, path, opts, who) {
519
519
  const node = tree.get(page.id);
520
520
  const categories = await categoryRows(spaceId);
521
521
  const lines = categoryLines(categories, (await itemCategoriesOf([{ pageId: page.id }])).get(`p:${page.id}`));
522
- const children = [...tree.values()]
523
- .filter((n) => n.parentId === page.id)
522
+ // Its sub-pages, as far as `who` may read them: one closed to them is not named.
523
+ const under = [...tree.values()].filter((n) => n.parentId === page.id);
524
+ const okUnder = await readable(spaceId, who, await pageResources(under.map((n) => n.id)));
525
+ const children = under
526
+ .filter((n) => okUnder.has(n.id))
524
527
  .sort((a, b) => a.position - b.position)
525
528
  .map((n) => n.path);
526
529
  const original = page.fileId ? (await filePaths(spaceId)).get(page.fileId) : undefined;
@@ -650,11 +653,10 @@ export async function readTable(spaceId, path, opts, who) {
650
653
  * has; with one, the items it leaves that `who` may read, with their paths and categories.
651
654
  */
652
655
  export async function listForStep(spaceId, where, who) {
653
- const categories = await listCategories(spaceId);
654
- const taken = categories.filter((c) => !c.proposed);
655
656
  if (!Object.keys(where ?? {}).length) {
657
+ const categories = (await categoriesFor(spaceId, who)).filter((c) => !c.proposed);
656
658
  return {
657
- categories: taken.map((c) => ({
659
+ categories: categories.map((c) => ({
658
660
  name: c.name,
659
661
  type: c.type,
660
662
  ...(c.unit ? { unit: c.unit } : {}),
@@ -667,6 +669,7 @@ export async function listForStep(spaceId, where, who) {
667
669
  hint: 'Pass `where` to list the items of values, e.g. { "Baustelle": "Graz Süd" }.',
668
670
  };
669
671
  }
672
+ const taken = (await categoryRows(spaceId)).filter((c) => !c.proposed);
670
673
  const filtered = await filterItems(spaceId, where);
671
674
  const [tree, tPaths, fPaths] = await Promise.all([
672
675
  pageTree(spaceId),
@@ -729,34 +732,97 @@ export async function listForStep(spaceId, where, who) {
729
732
  ];
730
733
  return { items: items.slice(0, 200), total: items.length };
731
734
  }
732
- /** How much Knowledge a space holds: what the block of the steps' instructions says. */
733
- export async function knowledgeCounts(spaceId) {
735
+ /**
736
+ * The space's categories as `who` sees them: how many items have each, a choice's values and the
737
+ * ranges, counted over the pages, tables, files and mounts they may read. Whoever may read all of
738
+ * it gets them as the space has them.
739
+ */
740
+ export async function categoriesFor(spaceId, who) {
741
+ const all = await listCategories(spaceId);
742
+ if (!(all.length && (await brokerOn()))) {
743
+ return all;
744
+ }
745
+ const use = await categoryUse(spaceId);
746
+ const places = [...use.items, ...use.values];
747
+ const ids = (key) => [
748
+ ...new Set(places.flatMap((p) => (p[key] ? [p[key]] : []))),
749
+ ];
750
+ const pages = await readable(spaceId, who, await pageResources(ids("pageId")));
751
+ const tables = await readable(spaceId, who, await tableResources(ids("tableId")));
752
+ const files = await readable(spaceId, who, ids("fileId").map((id) => ({ kind: "document", id })));
753
+ const mounts = await readableMounts(spaceId, who, ids("mountId"));
754
+ const open = (p) => p.pageId
755
+ ? pages.has(p.pageId)
756
+ : p.tableId
757
+ ? tables.has(p.tableId)
758
+ : p.fileId
759
+ ? files.has(p.fileId)
760
+ : p.mountId
761
+ ? mounts.has(p.mountId)
762
+ : false;
763
+ if (places.every(open)) {
764
+ return all;
765
+ }
766
+ return categoriesOver(all, { items: use.items.filter(open), values: use.values.filter(open) });
767
+ }
768
+ /**
769
+ * Which kinds of Knowledge a space holds at all: which tools a caller is offered. It says nothing
770
+ * of what they may read: each read of a tool is the broker's, and a refusal names the item.
771
+ */
772
+ export async function knowledgeKinds(spaceId) {
773
+ const [page, table, file] = await Promise.all([
774
+ db.query.spacePage.findFirst({
775
+ where: and(eq(schema.spacePage.spaceId, spaceId), isNull(schema.spacePage.wizardId)),
776
+ columns: { id: true },
777
+ }),
778
+ db.query.spaceTable.findFirst({
779
+ where: and(eq(schema.spaceTable.spaceId, spaceId), isNull(schema.spaceTable.wizardId)),
780
+ columns: { id: true },
781
+ }),
782
+ db.query.spaceFile.findFirst({
783
+ where: and(eq(schema.spaceFile.spaceId, spaceId), eq(schema.spaceFile.kind, "document")),
784
+ columns: { id: true },
785
+ }),
786
+ ]);
787
+ return { pages: Boolean(page), tables: Boolean(table), files: Boolean(file) };
788
+ }
789
+ /**
790
+ * How much Knowledge a space holds for `who`: the pages, tables and documents they may read. What
791
+ * a step's instructions, Goose and the space's details say counts nothing else.
792
+ */
793
+ export async function knowledgeCounts(spaceId, who) {
734
794
  const [pages, tables, files] = await Promise.all([
735
- db
736
- .select({ n: count() })
737
- .from(schema.spacePage)
738
- .where(and(eq(schema.spacePage.spaceId, spaceId), isNull(schema.spacePage.wizardId))),
739
- db
740
- .select({ n: count() })
741
- .from(schema.spaceTable)
742
- .where(and(eq(schema.spaceTable.spaceId, spaceId), isNull(schema.spaceTable.wizardId))),
743
- db
744
- .select({ n: count() })
745
- .from(schema.spaceFile)
746
- .where(and(eq(schema.spaceFile.spaceId, spaceId), eq(schema.spaceFile.kind, "document"))),
795
+ db.query.spacePage.findMany({
796
+ where: and(eq(schema.spacePage.spaceId, spaceId), isNull(schema.spacePage.wizardId)),
797
+ columns: { id: true, fileId: true },
798
+ }),
799
+ db.query.spaceTable.findMany({
800
+ where: and(eq(schema.spaceTable.spaceId, spaceId), isNull(schema.spaceTable.wizardId)),
801
+ columns: { id: true, fileId: true },
802
+ }),
803
+ db.query.spaceFile.findMany({
804
+ where: and(eq(schema.spaceFile.spaceId, spaceId), eq(schema.spaceFile.kind, "document")),
805
+ columns: { id: true },
806
+ }),
807
+ ]);
808
+ const ok = await readable(spaceId, who, [
809
+ ...pages.map((p) => ({ kind: "page", id: p.id, fileId: p.fileId })),
810
+ ...tables.map((t) => ({ kind: "table", id: t.id, fileId: t.fileId })),
811
+ ...files.map((f) => ({ kind: "document", id: f.id })),
747
812
  ]);
748
- return { pages: pages[0].n, tables: tables[0].n, files: files[0].n };
813
+ const read = (rows) => rows.filter((r) => ok.has(r.id)).length;
814
+ return { pages: read(pages), tables: read(tables), files: read(files) };
749
815
  }
750
816
  /**
751
- * What every step of the space is told about Knowledge: how much there is, the categories to filter
752
- * by, the tools to find and read. Empty when Knowledge is.
817
+ * What a step of the space is told about Knowledge: how much of it `who` may read, the categories
818
+ * to filter by as they see them, the tools to find and read. Empty when that is nothing.
753
819
  */
754
- export async function knowledgeBlock(spaceId) {
755
- const counts = await knowledgeCounts(spaceId);
820
+ export async function knowledgeBlock(spaceId, who) {
821
+ const counts = await knowledgeCounts(spaceId, who);
756
822
  if (!(counts.pages || counts.tables || counts.files)) {
757
823
  return "";
758
824
  }
759
- const categories = (await listCategories(spaceId)).filter((c) => !c.proposed && c.count);
825
+ const categories = (await categoriesFor(spaceId, who)).filter((c) => !c.proposed && c.count);
760
826
  const what = [
761
827
  counts.pages ? `${counts.pages} pages` : "",
762
828
  counts.tables ? `${counts.tables} tables` : "",
@@ -61,9 +61,10 @@ const PUBLISHING = [
61
61
  ];
62
62
  /**
63
63
  * The space of an item, by the kind and id the studio's addresses name it with
64
- * (`/spaces/:id`, `/wizards/:id`, …; `runs` for a run's wizard), and what follows them.
64
+ * (`/spaces/:id`, `/wizards/:id`, …; `runs` for a run's wizard), and what follows them. `null`
65
+ * for what is in no space, or in none that is still there.
65
66
  */
66
- async function spaceOfItem(kind, id, sub) {
67
+ export async function spaceOfItem(kind, id, sub) {
67
68
  const one = async (found) => (await found)?.spaceId ?? null;
68
69
  const tenant = currentTenant();
69
70
  switch (kind) {
@@ -120,6 +121,9 @@ async function spaceOfItem(kind, id, sub) {
120
121
  where: eq(schema.spaceConnection.id, id),
121
122
  columns: { spaceId: true },
122
123
  }));
124
+ case "presence":
125
+ // Who is in a wizard, page or table (`/presence/:kind/:item`) is in that item's space.
126
+ return sub ? spaceOfItem(`${id}s`, sub) : null;
123
127
  default:
124
128
  return null;
125
129
  }
@@ -131,6 +135,22 @@ async function spaceOfItem(kind, id, sub) {
131
135
  export async function closedToMe(spaceId) {
132
136
  return (await ruledMember()) && !(await openToMembers(spaceId));
133
137
  }
138
+ /**
139
+ * The spaces whose Studio the person at hand reaches, where the rule narrows them: the ones open
140
+ * to members. `null` for everyone the rule does not count for, who reaches every space. For what
141
+ * is sent unasked (the live stream, the sync's listing): a space that is not among them, closed
142
+ * or gone, is not named.
143
+ */
144
+ export async function studioSpaces() {
145
+ if (!(await ruledMember())) {
146
+ return null;
147
+ }
148
+ const open = await db.query.space.findMany({
149
+ where: and(eq(schema.space.tenantId, currentTenant()), eq(schema.space.membersStudio, true)),
150
+ columns: { id: true },
151
+ });
152
+ return new Set(open.map((s) => s.id));
153
+ }
134
154
  /**
135
155
  * The studio's „closed“ answer for an item of a space closed to the person at hand: the same 403
136
156
  * through every door (the studio API, MCP, `/api/v1`, Goose). `kind` as the studio's addresses