@engenty/wizards-runtime 0.16.1 → 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 (139) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +13 -6
  2. package/apps/runtime/dist/assistant/knows.js +18 -3
  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/db/control-schema.js +7 -0
  11. package/apps/runtime/dist/db/migrations/control/0014_run_index_generation.sql +1 -0
  12. package/apps/runtime/dist/db/migrations/control/0015_run_index_wake.sql +3 -0
  13. package/apps/runtime/dist/db/migrations/control/meta/0014_snapshot.json +629 -0
  14. package/apps/runtime/dist/db/migrations/control/meta/0015_snapshot.json +650 -0
  15. package/apps/runtime/dist/db/migrations/control/meta/_journal.json +14 -0
  16. package/apps/runtime/dist/db/migrations/tenant/0056_run_claim_rev.sql +2 -0
  17. package/apps/runtime/dist/db/migrations/tenant/0057_run_wake_at.sql +1 -0
  18. package/apps/runtime/dist/db/migrations/tenant/meta/0056_snapshot.json +6520 -0
  19. package/apps/runtime/dist/db/migrations/tenant/meta/0057_snapshot.json +6527 -0
  20. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +14 -0
  21. package/apps/runtime/dist/db/schema.js +17 -3
  22. package/apps/runtime/dist/docs/dev/broker.md +72 -26
  23. package/apps/runtime/dist/docs/dev/plugins/space.md +13 -2
  24. package/apps/runtime/dist/docs/user-guide/capabilities.md +51 -7
  25. package/apps/runtime/dist/docs/user-guide/connectors.md +6 -3
  26. package/apps/runtime/dist/docs/user-guide/protocol.md +30 -4
  27. package/apps/runtime/dist/docs/user-guide/together.md +4 -4
  28. package/apps/runtime/dist/elements/knowledge.js +17 -12
  29. package/apps/runtime/dist/engine/runner.js +344 -52
  30. package/apps/runtime/dist/engine/steps.js +3 -2
  31. package/apps/runtime/dist/env.js +18 -0
  32. package/apps/runtime/dist/index.js +8 -0
  33. package/apps/runtime/dist/live/hub.js +17 -3
  34. package/apps/runtime/dist/live/origin.js +6 -4
  35. package/apps/runtime/dist/live/views.js +38 -7
  36. package/apps/runtime/dist/models.js +18 -0
  37. package/apps/runtime/dist/mounts/mounts.js +3 -0
  38. package/apps/runtime/dist/plugins/runs.js +3 -0
  39. package/apps/runtime/dist/prompts/mcp.md +3 -0
  40. package/apps/runtime/dist/prompts/tools.md +1 -1
  41. package/apps/runtime/dist/routes/api.js +2 -2
  42. package/apps/runtime/dist/routes/broker.js +59 -20
  43. package/apps/runtime/dist/routes/live.js +4 -2
  44. package/apps/runtime/dist/routes/runs.js +17 -14
  45. package/apps/runtime/dist/routes/studio.js +13 -2
  46. package/apps/runtime/dist/services/api.js +5 -3
  47. package/apps/runtime/dist/services/errors.js +1 -0
  48. package/apps/runtime/dist/services/knowledge.js +95 -28
  49. package/apps/runtime/dist/services/manage-reports.js +2 -0
  50. package/apps/runtime/dist/services/members-studio.js +22 -2
  51. package/apps/runtime/dist/services/query-vectors.js +60 -0
  52. package/apps/runtime/dist/services/relevance.js +12 -0
  53. package/apps/runtime/dist/services/runs.js +16 -2
  54. package/apps/runtime/dist/services/space-categories.js +83 -5
  55. package/apps/runtime/dist/services/space-index.js +99 -27
  56. package/apps/runtime/dist/services/space-origin.js +28 -11
  57. package/apps/runtime/dist/services/work-ai.js +15 -5
  58. package/apps/runtime/dist/sharing/index.js +3 -0
  59. package/apps/runtime/dist/sharing/jobs.js +2 -0
  60. package/apps/runtime/dist/sync/hub.js +17 -3
  61. package/apps/runtime/dist/tenants/control.js +46 -14
  62. package/apps/runtime/dist/texts.js +6 -4
  63. package/apps/runtime/dist/tools/index.js +13 -7
  64. package/apps/runtime/dist/tools/web-search.js +36 -0
  65. package/apps/web/dist/assets/{AboutDialog-C9SnsGno.js → AboutDialog-B2Xmxyj4.js} +1 -1
  66. package/apps/web/dist/assets/{BlockEditor-CUYFH_CU.js → BlockEditor-D0HoUSih.js} +1 -1
  67. package/apps/web/dist/assets/CapabilitiesPage-C1th2cZE.js +2 -0
  68. package/apps/web/dist/assets/{ChangelogDialog-B28TK333.js → ChangelogDialog-BIrJbAKi.js} +1 -1
  69. package/apps/web/dist/assets/{CodeEditor-D-Y16fdk.js → CodeEditor-DUVcXI5P.js} +1 -1
  70. package/apps/web/dist/assets/EditorPage-56sIqEfF.js +3 -0
  71. package/apps/web/dist/assets/{FlowPreview-DXnk7m9P.js → FlowPreview-BIag8_Be.js} +1 -1
  72. package/apps/web/dist/assets/{LangSwitch-Dkd0FBIH.js → LangSwitch-CJ00IgaO.js} +1 -1
  73. package/apps/web/dist/assets/Marketplace-D7-ot9Dz.js +2 -0
  74. package/apps/web/dist/assets/{NewWizardChannels-B12l2_Jh.js → NewWizardChannels-DI3SQ4iS.js} +1 -1
  75. package/apps/web/dist/assets/NewWizardPage-CytheHxX.js +7 -0
  76. package/apps/web/dist/assets/OnboardingPage-_91Pa8Ad.js +1 -0
  77. package/apps/web/dist/assets/PreviewPane-BDsYm-_K.js +7 -0
  78. package/apps/web/dist/assets/ProtocolSection-D_zaxHEL.js +1 -0
  79. package/apps/web/dist/assets/PublicRunner-CEgXSk3r.js +1 -0
  80. package/apps/web/dist/assets/{ReadOnly-DwewuYi8.js → ReadOnly-CWf5x74a.js} +1 -1
  81. package/apps/web/dist/assets/SettingsPage-Dr8SDk-L.js +2 -0
  82. package/apps/web/dist/assets/SetupPage-B68n0l4I.js +1 -0
  83. package/apps/web/dist/assets/{SharePage-CZClatA_.js → SharePage-DfznN7ar.js} +1 -1
  84. package/apps/web/dist/assets/SkillEditor-BIcIczRc.js +1 -0
  85. package/apps/web/dist/assets/{Skills-Bv6XbKxc.js → Skills-CN4QE7Kx.js} +6 -6
  86. package/apps/web/dist/assets/SpacePage-DiVTwhnJ.js +2 -0
  87. package/apps/web/dist/assets/{UpdateCheck-CLPUsKVT.js → UpdateCheck-QhBI3rlQ.js} +2 -2
  88. package/apps/web/dist/assets/changelog-a_CuplMX.js +1 -0
  89. package/apps/web/dist/assets/{code-editor-Ca5EAxmd.js → code-editor-DkPo1C-L.js} +2 -2
  90. package/apps/web/dist/assets/{host-CJdLkzfY.js → host-D6H6Z9Jp.js} +18 -18
  91. package/apps/web/dist/assets/i18n-BaPKbQ1s.js +55 -0
  92. package/apps/web/dist/assets/{index-w-3J3ZJ9.css → index-CCUG6Vnh.css} +1 -1
  93. package/apps/web/dist/assets/{index-CmonJZHC.js → index-De0Wb42y.js} +4 -4
  94. package/apps/web/dist/assets/{read-aloud-Bfp9_bUY.js → read-aloud-CnFwDSGD.js} +1 -1
  95. package/apps/web/dist/assets/{runners-CUpBpSji.js → runners-0sTPbWzr.js} +1 -1
  96. package/apps/web/dist/assets/session-BMiUrqHg.js +2 -0
  97. package/apps/web/dist/assets/theme-CkNTe-_Z.js +12 -0
  98. package/apps/web/dist/assets/ui-DAk_vjrL.js +16 -0
  99. package/apps/web/dist/assets/{useMutation-1fV4Nnxq.js → useMutation-isHfB33W.js} +1 -1
  100. package/apps/web/dist/assets/{viewers-ChriFcRy.js → viewers-ijNZHJFG.js} +2 -2
  101. package/apps/web/dist/index.html +12 -12
  102. package/apps/web/dist/mcp/flow.html +66 -66
  103. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +15 -4
  104. package/node_modules/@engenty/wizards/dist/plugin/thread.js +30 -0
  105. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +13 -1
  106. package/node_modules/@engenty/wizards-shared/dist/connectors.js +8 -0
  107. package/node_modules/@engenty/wizards-shared/dist/definition.d.ts +168 -0
  108. package/node_modules/@engenty/wizards-shared/dist/definition.js +52 -0
  109. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +18 -0
  110. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +18 -0
  111. package/node_modules/@engenty/wizards-shared/dist/fit.d.ts +2 -0
  112. package/node_modules/@engenty/wizards-shared/dist/fit.js +4 -0
  113. package/node_modules/@engenty/wizards-shared/dist/knowledge.d.ts +5 -0
  114. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +11 -1
  115. package/node_modules/@engenty/wizards-shared/dist/run.js +14 -0
  116. package/node_modules/@engenty/wizards-shared/dist/runner-texts.d.ts +7 -1
  117. package/node_modules/@engenty/wizards-shared/dist/runner-texts.js +6 -0
  118. package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +3 -2
  119. package/node_modules/@engenty/wizards-shared/dist/spaces.js +12 -3
  120. package/package.json +1 -1
  121. package/plugin/.claude-plugin/plugin.json +1 -1
  122. package/plugin/plugin.json +1 -1
  123. package/apps/web/dist/assets/CapabilitiesPage-DvSSybt0.js +0 -2
  124. package/apps/web/dist/assets/EditorPage-Duu8swX6.js +0 -3
  125. package/apps/web/dist/assets/Marketplace-Cty40VwG.js +0 -2
  126. package/apps/web/dist/assets/NewWizardPage-B10K8vND.js +0 -7
  127. package/apps/web/dist/assets/OnboardingPage-D3SEpTmt.js +0 -1
  128. package/apps/web/dist/assets/PreviewPane-DhhQ06Ic.js +0 -7
  129. package/apps/web/dist/assets/PublicRunner-B8ncIxIP.js +0 -1
  130. package/apps/web/dist/assets/SettingsPage-C-gGIJLJ.js +0 -2
  131. package/apps/web/dist/assets/SetupPage-CdsrHW-w.js +0 -1
  132. package/apps/web/dist/assets/SkillEditor-BaEiqqXl.js +0 -1
  133. package/apps/web/dist/assets/SpacePage-CYhxcjj0.js +0 -2
  134. package/apps/web/dist/assets/changelog-y5oxYzPd.js +0 -1
  135. package/apps/web/dist/assets/connection-sign-in-DECedzrs.js +0 -1
  136. package/apps/web/dist/assets/i18n-BBzMbGoo.js +0 -55
  137. package/apps/web/dist/assets/session-CMQo8P-G.js +0 -2
  138. package/apps/web/dist/assets/theme-D6KUBJnh.js +0 -11
  139. package/apps/web/dist/assets/ui-BCfu5sia.js +0 -16
@@ -31,6 +31,11 @@ const num = (key, fallback) => {
31
31
  const v = Number(process.env[key]);
32
32
  return Number.isFinite(v) && v > 0 ? v : fallback;
33
33
  };
34
+ /** `a=1,b=2.5`: positive numbers by name; anything else is left out. */
35
+ const minutesByName = (key) => Object.fromEntries(list(key)
36
+ .map((item) => item.split("="))
37
+ .map(([name, value]) => [name?.trim(), Number(value)])
38
+ .filter(([name, value]) => name && Number.isFinite(value) && value > 0));
34
39
  const dataDir = resolve(str("DATA_DIR", "data"));
35
40
  /**
36
41
  * Signs cookies and links and derives the store's encryption key. A runtime that runs alone
@@ -97,6 +102,19 @@ export const env = {
97
102
  * nothing knows the runner stopped taking runs. Empty = no ping.
98
103
  */
99
104
  heartbeatUrl: str("HEARTBEAT_URL"),
105
+ /** The runs one process drives at once; the rest stay in line for its next free slot. */
106
+ maxRuns: num("RUNNER_MAX_RUNS", 16),
107
+ /** How often the clock looks for runs whose wait is over. */
108
+ clockMs: num("RUNNER_CLOCK_MS", 60_000),
109
+ /**
110
+ * The longest a step may work, in minutes. `RUNNER_STEP_DEADLINES=default=480,agent=240`: per
111
+ * step type, `default` for the rest. Generous until real step lengths are in.
112
+ */
113
+ stepDeadlines: {
114
+ default: 8 * 60,
115
+ "motion-graphics": 12 * 60,
116
+ ...minutesByName("RUNNER_STEP_DEADLINES"),
117
+ },
100
118
  },
101
119
  appUrl,
102
120
  /**
@@ -121,6 +121,14 @@ if (env.serves.studio) {
121
121
  for (const id of await knownTenants()) {
122
122
  void withTenant(id, () => indexMissingAssets()).catch((err) => console.error(`[space-index ${id}]`, err));
123
123
  }
124
+ // The embedding model can change at any time on a Manage-App: vectors of another don't compare.
125
+ const { queueVectors } = await import("./services/space-index.js");
126
+ const vectors = async () => {
127
+ for (const id of await knownTenants()) {
128
+ await withTenant(id, () => queueVectors());
129
+ }
130
+ };
131
+ setInterval(() => void vectors().catch((err) => console.error("[space-index]", err)), 600_000).unref();
124
132
  }
125
133
  // Dateien: the folders of this computer mounted in a space, watched and listed again.
126
134
  if (env.serves.studio) {
@@ -18,7 +18,7 @@ const feeds = new Map();
18
18
  * Starts sending the tenant's changes after `since` (null: from now on). Answers `hello`, or
19
19
  * `reset` when the changes after `since` are no longer kept or `since` is of another database.
20
20
  */
21
- export async function subscribe(tenantId, since, send, views) {
21
+ export async function subscribe(tenantId, since, send, views, hears) {
22
22
  const { newest, gap } = await withTenant(tenantId, async () => {
23
23
  const newest = await newestSeq();
24
24
  if (since === null || since === newest) {
@@ -30,7 +30,7 @@ export async function subscribe(tenantId, since, send, views) {
30
30
  const oldest = await oldestSeq();
31
31
  return { newest, gap: oldest === null || oldest > since + 1 };
32
32
  });
33
- const sub = { since: since === null || gap ? newest : since, send, views };
33
+ const sub = { since: since === null || gap ? newest : since, send, views, hears };
34
34
  send(gap ? { event: "reset", seq: newest } : { event: "hello", seq: newest });
35
35
  let feed = feeds.get(tenantId);
36
36
  if (!feed) {
@@ -137,9 +137,23 @@ async function read(feed) {
137
137
  if (!mine.length) {
138
138
  continue;
139
139
  }
140
+ let heard = mine;
141
+ if (sub.hears) {
142
+ try {
143
+ heard = await sub.hears(mine);
144
+ }
145
+ catch (err) {
146
+ // Not known what this reader may hear: nothing is sent, and the next tick asks again.
147
+ console.error(`[live ${feed.id}] what a reader hears:`, err);
148
+ continue;
149
+ }
150
+ }
140
151
  const seq = mine[mine.length - 1].seq;
141
152
  sub.since = seq;
142
- sub.send({ event: "changes", seq, items: await withViews(dedupe(mine), sub.views, read) });
153
+ if (heard.length) {
154
+ const items = await withViews(dedupe(heard), sub.views, read);
155
+ sub.send({ event: "changes", seq, items });
156
+ }
143
157
  }
144
158
  }
145
159
  if (Date.now() - feed.prunedAt > PRUNE_EVERY_MS) {
@@ -32,10 +32,11 @@ export function pushedBy(tenant, install, seq) {
32
32
  }
33
33
  /**
34
34
  * The cloud's live call for one install: the spaces with changes, without what the install
35
- * pushed itself. `hear` gets hello, reset and changes; the answer stops it.
35
+ * pushed itself, and without what `hears` leaves out for its caller. `hear` gets hello, reset and
36
+ * changes; the answer stops it.
36
37
  */
37
- export async function followFor(tenantId, install, since, hear) {
38
- return subscribe(tenantId, since, (e) => {
38
+ export async function followFor(tenantId, install, since, hear, hears) {
39
+ const send = (e) => {
39
40
  if (e.event === "changes") {
40
41
  const spaces = new Set();
41
42
  for (const x of e.items) {
@@ -49,5 +50,6 @@ export async function followFor(tenantId, install, since, hear) {
49
50
  else if (e.event === "hello" || e.event === "reset") {
50
51
  hear(e);
51
52
  }
52
- });
53
+ };
54
+ return subscribe(tenantId, since, send, undefined, hears);
53
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]) ||
@@ -20,6 +20,7 @@ import { embeddingModel } from "../models.js";
20
20
  import { onPluginChange, pluginsOf } from "../plugins/registry.js";
21
21
  import { currentRole, isAdminRole, MEMBERS_EDIT_ONLY } from "../services/access.js";
22
22
  import { notFound, ServiceError } from "../services/errors.js";
23
+ import { searchesFirst } from "../services/query-vectors.js";
23
24
  import { itemCategoriesOf, putCategory, setItemCategories } from "../services/space-categories.js";
24
25
  import { currentTenant } from "../tenants/tenant.js";
25
26
  import { cachedText, keptText } from "./cache.js";
@@ -690,6 +691,7 @@ async function embedTexts() {
690
691
  return unitText(texts.get(file.id) ?? "", unit);
691
692
  });
692
693
  try {
694
+ await searchesFirst();
693
695
  const result = await embedMany({
694
696
  model: resolved.model,
695
697
  values: values.map((v) => v || " "),
@@ -754,6 +756,7 @@ async function embedPictures() {
754
756
  await db.delete(u).where(eq(u.id, unit.id));
755
757
  continue;
756
758
  }
759
+ await searchesFirst();
757
760
  await db
758
761
  .update(u)
759
762
  .set({ embedding: vectorBytes(await embedImage(jpeg)), model: resolved.ref })
@@ -196,6 +196,9 @@ export function runsApiFor(pluginId) {
196
196
  if (run.status === "done" || run.status === "cancelled" || run.status === "failed") {
197
197
  throw new ServiceError("refused", noteText({ code: "runOver" }, wizardLang(run.definition)));
198
198
  }
199
+ if (run.status === "sleeping") {
200
+ throw new ServiceError("refused", noteText({ code: "runSleeps" }, wizardLang(run.definition)));
201
+ }
199
202
  const bytes = file.data instanceof Uint8Array ? file.data : new Uint8Array(file.data);
200
203
  if (!bytes.length || bytes.length > 10_000_000) {
201
204
  throw new ServiceError("invalid", noteText({ code: "recordingTooLarge" }, wizardLang(run.definition)));
@@ -149,6 +149,9 @@ Ask the person, then answer_ask with allow or skip.
149
149
  <!-- section: hint.sign_in -->
150
150
  A sign-in: the person types it on the run page (browserUrl).
151
151
 
152
+ <!-- section: hint.sleeping -->
153
+ The run waits until `until` and goes on by itself. Nothing is needed from the person meanwhile.
154
+
152
155
  <!-- section: hint.page -->
153
156
  Ask the fields in order; skip a field whose `when` does not hold on the answers so far (a hidden one is not required and not kept).
154
157
 
@@ -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;
@@ -25,7 +25,7 @@ import { fieldErrorsIn } from "../engine/input.js";
25
25
  import { fromOwner } from "../engine/owner.js";
26
26
  import { pushAvailable, setPushDevice } from "../engine/push.js";
27
27
  import { liveResources } from "../engine/resources.js";
28
- import { cancel, createRun, editOutput, GuestBudgetError, goBack, NoCreditsError, RunConflict, RunInputError, retry, reviewStep, runView, spaceIdOf, submitPage, talkAllowed, } from "../engine/runner.js";
28
+ import { cancel, createRun, editOutput, GuestBudgetError, goBack, NoCreditsError, RunConflict, RunInputError, retry, reviewStep, runView, spaceIdOf, submitPage, talkAllowed, writeRunState, } from "../engine/runner.js";
29
29
  import { basePath, env } from "../env.js";
30
30
  import { loadAsset, saveAsset } from "../files/storage.js";
31
31
  import { checkUpload } from "../files/upload-check.js";
@@ -712,16 +712,11 @@ export const runRoutes = new Hono()
712
712
  if (JSON.stringify(state).length > MAX_VIEW_STATE) {
713
713
  return c.json({ error: "too large" }, 413);
714
714
  }
715
- await db
716
- .update(schema.run)
717
- .set({
718
- state: {
719
- ...run.state,
720
- outputs: { ...run.state.outputs, [stepId]: { ...output, view: state } },
721
- },
722
- })
723
- .where(eq(schema.run.id, run.id));
724
- return c.json({ ok: true });
715
+ const kept = await writeRunState(run, {
716
+ ...run.state,
717
+ outputs: { ...run.state.outputs, [stepId]: { ...output, view: state } },
718
+ });
719
+ return kept ? c.json({ ok: true }) : c.json({ error: "busy" }, 409);
725
720
  })
726
721
  // A json step's data, edited in the studio by someone of the organization the run belongs to.
727
722
  .put("/:id/outputs/:stepId", async (c) => {
@@ -861,13 +856,15 @@ export const runRoutes = new Hono()
861
856
  }
862
857
  throw err;
863
858
  }
864
- const fresh = await db.query.run.findFirst({ where: eq(schema.run.id, run.id) });
865
- const state = fresh?.state ?? run.state;
859
+ const fresh = (await db.query.run.findFirst({ where: eq(schema.run.id, run.id) })) ?? run;
860
+ const state = fresh.state;
866
861
  state.translated = {
867
862
  ...state.translated,
868
863
  [run.lang]: { ...state.translated?.[run.lang], [stepId]: translated },
869
864
  };
870
- await db.update(schema.run).set({ state }).where(eq(schema.run.id, run.id));
865
+ if (!(await writeRunState(fresh, state))) {
866
+ return refuse(c, { code: "runBusy" }, 409);
867
+ }
871
868
  signalChanged(run.id);
872
869
  }
873
870
  return c.json({ ok: true });
@@ -881,6 +878,9 @@ export const runRoutes = new Hono()
881
878
  if (run.status === "done" || run.status === "cancelled" || run.status === "failed") {
882
879
  return refuse(c, { code: "runOver" }, 409);
883
880
  }
881
+ if (run.status === "sleeping") {
882
+ return refuse(c, { code: "runSleeps" }, 409);
883
+ }
884
884
  if (!(await talkAllowed(run))) {
885
885
  return refuse(c, { code: "talkOff" }, 403);
886
886
  }
@@ -908,6 +908,9 @@ export const runRoutes = new Hono()
908
908
  if (run.status === "done" || run.status === "cancelled" || run.status === "failed") {
909
909
  return refuse(c, { code: "runOver" }, 409);
910
910
  }
911
+ if (run.status === "sleeping") {
912
+ return refuse(c, { code: "runSleeps" }, 409);
913
+ }
911
914
  if (!allowed(`transcribe:${run.id}`, 60, 3600_000)) {
912
915
  return refuse(c, { code: "tryLater" }, 429);
913
916
  }
@@ -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
  };
@@ -200,7 +202,7 @@ export async function apiRuns(userId, filter = {}) {
200
202
  const where = and(inArray(schema.run.wizardId, ids), eq(schema.run.mode, "live"), status === "done"
201
203
  ? eq(schema.run.status, "done")
202
204
  : status === "open"
203
- ? inArray(schema.run.status, ["waiting_input", "running"])
205
+ ? inArray(schema.run.status, ["waiting_input", "sleeping", "running"])
204
206
  : undefined, filter.days
205
207
  ? gte(schema.run.createdAt, new Date(Date.now() - filter.days * 86_400_000))
206
208
  : undefined, like
@@ -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;