@engenty/wizards-runtime 0.16.2 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +13 -6
  2. package/apps/runtime/dist/app.js +2 -0
  3. package/apps/runtime/dist/assistant/knows.js +15 -2
  4. package/apps/runtime/dist/broker/account.js +20 -1
  5. package/apps/runtime/dist/broker/call.js +131 -22
  6. package/apps/runtime/dist/broker/grant.js +25 -1
  7. package/apps/runtime/dist/broker/host.js +8 -2
  8. package/apps/runtime/dist/broker/index.js +5 -4
  9. package/apps/runtime/dist/broker/log.js +178 -24
  10. package/apps/runtime/dist/broker/over.js +38 -0
  11. package/apps/runtime/dist/broker/rights.js +192 -0
  12. package/apps/runtime/dist/broker/rwx.js +309 -53
  13. package/apps/runtime/dist/broker/send.js +109 -44
  14. package/apps/runtime/dist/bundles/fetch.js +119 -0
  15. package/apps/runtime/dist/bundles/index.js +621 -0
  16. package/apps/runtime/dist/bundles/read.js +607 -0
  17. package/apps/runtime/dist/connectors/external.js +532 -61
  18. package/apps/runtime/dist/connectors/person-sign-ins.js +1 -0
  19. package/apps/runtime/dist/connectors/reload.js +73 -0
  20. package/apps/runtime/dist/connectors/space-connections.js +118 -6
  21. package/apps/runtime/dist/db/migrations/tenant/0058_mcp_state_across_roles.sql +26 -0
  22. package/apps/runtime/dist/db/migrations/tenant/0059_space_connection_paused.sql +2 -0
  23. package/apps/runtime/dist/db/migrations/tenant/0060_space_bundle.sql +21 -0
  24. package/apps/runtime/dist/db/migrations/tenant/0061_space_connection_limits.sql +2 -0
  25. package/apps/runtime/dist/db/migrations/tenant/meta/0058_snapshot.json +6696 -0
  26. package/apps/runtime/dist/db/migrations/tenant/meta/0059_snapshot.json +6710 -0
  27. package/apps/runtime/dist/db/migrations/tenant/meta/0060_snapshot.json +6857 -0
  28. package/apps/runtime/dist/db/migrations/tenant/meta/0061_snapshot.json +6871 -0
  29. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +28 -0
  30. package/apps/runtime/dist/db/schema.js +81 -3
  31. package/apps/runtime/dist/docs/dev/broker.md +316 -50
  32. package/apps/runtime/dist/docs/dev/plugins/space.md +13 -2
  33. package/apps/runtime/dist/docs/user-guide/capabilities.md +172 -10
  34. package/apps/runtime/dist/docs/user-guide/connectors.md +57 -7
  35. package/apps/runtime/dist/docs/user-guide/protocol.md +44 -7
  36. package/apps/runtime/dist/docs/user-guide/test-and-share.md +1 -1
  37. package/apps/runtime/dist/docs/user-guide/together.md +4 -4
  38. package/apps/runtime/dist/elements/caller.js +2 -2
  39. package/apps/runtime/dist/elements/knowledge.js +16 -12
  40. package/apps/runtime/dist/engenty/connections-external/build-connector.js +23 -8
  41. package/apps/runtime/dist/engenty/connections-external/import-service.js +18 -9
  42. package/apps/runtime/dist/engenty/connections-external/importer/classify.js +12 -0
  43. package/apps/runtime/dist/engenty/connections-external/invoke/http-invoker.js +1 -0
  44. package/apps/runtime/dist/engenty/connections-external/net/guarded-fetch.js +6 -3
  45. package/apps/runtime/dist/engenty/connections-sdk/oauth2.js +2 -2
  46. package/apps/runtime/dist/engenty/shims/web-ingest.js +64 -0
  47. package/apps/runtime/dist/engine/resources.js +15 -6
  48. package/apps/runtime/dist/engine/runner.js +2 -1
  49. package/apps/runtime/dist/engine/steps.js +3 -2
  50. package/apps/runtime/dist/env.js +2 -0
  51. package/apps/runtime/dist/index.js +19 -2
  52. package/apps/runtime/dist/live/hub.js +17 -3
  53. package/apps/runtime/dist/live/origin.js +6 -4
  54. package/apps/runtime/dist/live/views.js +38 -7
  55. package/apps/runtime/dist/mcp/handler.js +2 -2
  56. package/apps/runtime/dist/mcp/seen.js +71 -51
  57. package/apps/runtime/dist/mcp/tools.js +5 -1
  58. package/apps/runtime/dist/models.js +18 -0
  59. package/apps/runtime/dist/prompts/mcp.md +1 -1
  60. package/apps/runtime/dist/prompts/tools.md +17 -1
  61. package/apps/runtime/dist/routes/api.js +2 -2
  62. package/apps/runtime/dist/routes/broker.js +59 -20
  63. package/apps/runtime/dist/routes/bundles.js +91 -0
  64. package/apps/runtime/dist/routes/connections.js +14 -3
  65. package/apps/runtime/dist/routes/live.js +4 -2
  66. package/apps/runtime/dist/routes/rules.js +53 -9
  67. package/apps/runtime/dist/routes/studio.js +36 -20
  68. package/apps/runtime/dist/services/api.js +4 -2
  69. package/apps/runtime/dist/services/cloud.js +2 -0
  70. package/apps/runtime/dist/services/draft-events.js +79 -6
  71. package/apps/runtime/dist/services/errors.js +1 -0
  72. package/apps/runtime/dist/services/files.js +2 -2
  73. package/apps/runtime/dist/services/knowledge.js +93 -27
  74. package/apps/runtime/dist/services/members-studio.js +22 -2
  75. package/apps/runtime/dist/services/skills.js +61 -5
  76. package/apps/runtime/dist/services/space-categories.js +83 -5
  77. package/apps/runtime/dist/services/space-index.js +173 -25
  78. package/apps/runtime/dist/services/space-origin.js +28 -11
  79. package/apps/runtime/dist/services/synced-spaces.js +5 -1
  80. package/apps/runtime/dist/services/wizards.js +48 -2
  81. package/apps/runtime/dist/services/work-ai.js +15 -5
  82. package/apps/runtime/dist/sharing/jobs.js +8 -2
  83. package/apps/runtime/dist/sync/hub.js +17 -3
  84. package/apps/runtime/dist/sync/records.js +6 -1
  85. package/apps/runtime/dist/texts.js +42 -5
  86. package/apps/runtime/dist/tools/connections.js +8 -0
  87. package/apps/runtime/dist/tools/connector.js +13 -1
  88. package/apps/runtime/dist/tools/index.js +21 -10
  89. package/apps/runtime/dist/tools/skills.js +11 -1
  90. package/apps/runtime/dist/tools/web-search.js +36 -0
  91. package/apps/web/dist/assets/{AboutDialog-BCcD8hKm.js → AboutDialog-mZCBU7KF.js} +1 -1
  92. package/apps/web/dist/assets/{BlockEditor-DgaUm2pR.js → BlockEditor-Dk0QwLSU.js} +1 -1
  93. package/apps/web/dist/assets/CapabilitiesPage-GkpgF-wZ.js +2 -0
  94. package/apps/web/dist/assets/{ChangelogDialog-B08elwyr.js → ChangelogDialog-BhyilZWA.js} +1 -1
  95. package/apps/web/dist/assets/{CodeEditor-BiyOk_SC.js → CodeEditor-DULYZbuE.js} +1 -1
  96. package/apps/web/dist/assets/EditorPage-D_mCdYdZ.js +3 -0
  97. package/apps/web/dist/assets/{FlowPreview-DF_6TvZ0.js → FlowPreview-ykxZxWnk.js} +1 -1
  98. package/apps/web/dist/assets/{LangSwitch-Ba4OWLzJ.js → LangSwitch-iO54w9AP.js} +1 -1
  99. package/apps/web/dist/assets/{Marketplace-DqziLf66.js → Marketplace-C97fH7UC.js} +2 -2
  100. package/apps/web/dist/assets/{NewWizardChannels-CsIGp0nZ.js → NewWizardChannels-CsSV7sm2.js} +1 -1
  101. package/apps/web/dist/assets/{NewWizardPage-CzQAkKMy.js → NewWizardPage-Ebgw-Vf_.js} +1 -1
  102. package/apps/web/dist/assets/{OnboardingPage-B9gr2OX5.js → OnboardingPage-BZlloT7v.js} +1 -1
  103. package/apps/web/dist/assets/PreviewPane-CJuqY5uA.js +7 -0
  104. package/apps/web/dist/assets/ProtocolSection-CPaDKVpZ.js +1 -0
  105. package/apps/web/dist/assets/{PublicRunner-BVs8-Vu3.js → PublicRunner-4Lf4SnwB.js} +1 -1
  106. package/apps/web/dist/assets/{ReadOnly--4CIJCDD.js → ReadOnly-CXQ41R9Q.js} +1 -1
  107. package/apps/web/dist/assets/SettingsPage-C-8BgK9O.js +2 -0
  108. package/apps/web/dist/assets/{SetupPage-9Zk-KUGA.js → SetupPage-4_K083Wl.js} +1 -1
  109. package/apps/web/dist/assets/{SharePage-D_Ab0gjr.js → SharePage-CQjgMcDI.js} +1 -1
  110. package/apps/web/dist/assets/{SkillEditor-DvtameHg.js → SkillEditor-DT5hQwbg.js} +1 -1
  111. package/apps/web/dist/assets/{Skills-Cf1Kl4Fy.js → Skills-D7V_9_xo.js} +1 -1
  112. package/apps/web/dist/assets/SpacePage-D3rYS1bA.js +2 -0
  113. package/apps/web/dist/assets/{UpdateCheck-DweZBVP6.js → UpdateCheck-DVgAJmy8.js} +2 -2
  114. package/apps/web/dist/assets/changelog-DzQCUSsx.js +1 -0
  115. package/apps/web/dist/assets/{code-editor-B1RbFTAZ.js → code-editor-5T7ilBjd.js} +2 -2
  116. package/apps/web/dist/assets/{host-CKS5U5Vg.js → host-CCijW1hj.js} +6 -6
  117. package/apps/web/dist/assets/i18n-DCPDesT-.js +55 -0
  118. package/apps/web/dist/assets/{index-Ckcn5vy7.js → index-C_iWl8iS.js} +3 -3
  119. package/apps/web/dist/assets/index-zcPlodHx.css +1 -0
  120. package/apps/web/dist/assets/minus-BpYkOkYw.js +1 -0
  121. package/apps/web/dist/assets/{read-aloud-Bq88XUHC.js → read-aloud-Qb719not.js} +1 -1
  122. package/apps/web/dist/assets/{runners-DvYVe9Dt.js → runners-BeZ84YH_.js} +1 -1
  123. package/apps/web/dist/assets/{session-D2bjiA3P.js → session-CEJRkSP5.js} +1 -1
  124. package/apps/web/dist/assets/{theme-CNJIC2be.js → theme-y_owNosi.js} +1 -1
  125. package/apps/web/dist/assets/{ui-Mplfhz_Z.js → ui-BacfkQ7Q.js} +1 -1
  126. package/apps/web/dist/assets/{useMutation-8QRM-z4M.js → useMutation-CgzFr4qH.js} +1 -1
  127. package/apps/web/dist/assets/{viewers-CEocUV_2.js → viewers-CkyHAjnk.js} +2 -2
  128. package/apps/web/dist/index.html +12 -12
  129. package/apps/web/dist/mcp/flow.html +2 -2
  130. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +7 -2
  131. package/node_modules/@engenty/wizards-shared/dist/bundles.d.ts +219 -0
  132. package/node_modules/@engenty/wizards-shared/dist/bundles.js +19 -0
  133. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +117 -4
  134. package/node_modules/@engenty/wizards-shared/dist/connectors.js +14 -0
  135. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +12 -0
  136. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +12 -0
  137. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +11 -0
  138. package/node_modules/@engenty/wizards-shared/dist/run.js +22 -0
  139. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +84 -1
  140. package/node_modules/@engenty/wizards-shared/dist/rwx.js +69 -1
  141. package/node_modules/@engenty/wizards-shared/dist/skills.d.ts +20 -3
  142. package/node_modules/@engenty/wizards-shared/dist/skills.js +5 -2
  143. package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +3 -2
  144. package/node_modules/@engenty/wizards-shared/dist/spaces.js +12 -3
  145. package/package.json +1 -1
  146. package/plugin/.claude-plugin/plugin.json +1 -1
  147. package/plugin/plugin.json +1 -1
  148. package/apps/web/dist/assets/CapabilitiesPage-DuJJV1ll.js +0 -2
  149. package/apps/web/dist/assets/EditorPage-EMFTHEYD.js +0 -3
  150. package/apps/web/dist/assets/PreviewPane-DSOV3o-1.js +0 -7
  151. package/apps/web/dist/assets/SettingsPage-z2u8lSe2.js +0 -2
  152. package/apps/web/dist/assets/SpacePage-CyqVzX9b.js +0 -2
  153. package/apps/web/dist/assets/changelog-C85v9OWg.js +0 -1
  154. package/apps/web/dist/assets/connection-sign-in-CaVvh5GQ.js +0 -1
  155. package/apps/web/dist/assets/i18n-Bymk5Ev-.js +0 -55
  156. package/apps/web/dist/assets/index-w-3J3ZJ9.css +0 -1
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { featureOn } from "@engenty/wizards-shared/features";
3
3
  import { byteLength, officialSkill, parseSkillMd, SKILL_LIMITS, SKILL_NAME, SkillMdError, skillMd, skillPathOk, skillTextPath, } from "@engenty/wizards-shared/skills";
4
- import { and, asc, count, eq, ne } from "drizzle-orm";
4
+ import { and, asc, count, eq, isNotNull, ne } from "drizzle-orm";
5
5
  import { unzipSync, zipSync } from "fflate";
6
6
  import { nanoid } from "nanoid";
7
7
  import { db, schema } from "../db/client.js";
@@ -128,7 +128,49 @@ export async function checkAlways(spaceId, id, mode, body) {
128
128
  }
129
129
  }
130
130
  // --- views ----------------------------------------------------------------------------------
131
- function summaryOf(row) {
131
+ /**
132
+ * What the space's skills came with, by the record's id: the plugin's name and the connectors
133
+ * that came with it.
134
+ */
135
+ export async function skillBundles(spaceId) {
136
+ const bundles = await db
137
+ .select({ id: schema.spaceBundle.id, name: schema.spaceBundle.name })
138
+ .from(schema.spaceBundle)
139
+ .where(eq(schema.spaceBundle.spaceId, spaceId));
140
+ if (!bundles.length) {
141
+ return new Map();
142
+ }
143
+ const connectors = await db.query.spaceConnector.findMany({
144
+ where: and(eq(schema.spaceConnector.spaceId, spaceId), isNotNull(schema.spaceConnector.bundleId)),
145
+ orderBy: [asc(schema.spaceConnector.createdAt)],
146
+ });
147
+ return new Map(bundles.map((b) => [
148
+ b.id,
149
+ {
150
+ id: b.id,
151
+ name: b.name,
152
+ connectors: connectors
153
+ .filter((c) => c.bundleId === b.id)
154
+ .map((c) => ({ id: c.id, name: c.record.name }))
155
+ .sort((x, y) => x.name.localeCompare(y.name)),
156
+ },
157
+ ]));
158
+ }
159
+ /**
160
+ * The connectors a skill came with, as a step names them: by name and by what their tools'
161
+ * names start with.
162
+ */
163
+ export async function skillConnectors(row) {
164
+ if (!row.bundleId) {
165
+ return [];
166
+ }
167
+ const connectors = await db.query.spaceConnector.findMany({
168
+ where: and(eq(schema.spaceConnector.spaceId, row.spaceId), eq(schema.spaceConnector.bundleId, row.bundleId)),
169
+ orderBy: [asc(schema.spaceConnector.createdAt)],
170
+ });
171
+ return connectors.map((c) => ({ name: c.record.name, toolPrefix: c.record.tool_prefix }));
172
+ }
173
+ function summaryOf(row, bundles) {
132
174
  return {
133
175
  id: row.id,
134
176
  name: row.name,
@@ -137,6 +179,7 @@ function summaryOf(row) {
137
179
  source: row.source,
138
180
  origin: row.origin,
139
181
  official: row.source === "skills.sh" && officialSkill(row.origin),
182
+ bundle: (row.bundleId ? bundles.get(row.bundleId) : null) ?? null,
140
183
  runScripts: row.runScripts,
141
184
  files: row.files.length + row.blobFiles.length,
142
185
  chars: row.body.length,
@@ -159,14 +202,18 @@ export async function listSkills(userId, spaceId) {
159
202
  where: eq(schema.spaceSkill.spaceId, space.id),
160
203
  orderBy: [asc(schema.spaceSkill.name)],
161
204
  });
162
- return { skills: rows.map(summaryOf), readOnly: !(await spaceWritable(space)) };
205
+ const bundles = rows.some((r) => r.bundleId) ? await skillBundles(space.id) : new Map();
206
+ return {
207
+ skills: rows.map((r) => summaryOf(r, bundles)),
208
+ readOnly: !(await spaceWritable(space)),
209
+ };
163
210
  }
164
211
  export async function getSkill(userId, id) {
165
212
  await requireSkills();
166
213
  const row = await skillRow(id);
167
214
  const space = await ownedSpace(userId, row.spaceId);
168
215
  return {
169
- ...summaryOf(row),
216
+ ...summaryOf(row, row.bundleId ? await skillBundles(row.spaceId) : new Map()),
170
217
  spaceId: row.spaceId,
171
218
  body: row.body,
172
219
  meta: row.meta,
@@ -226,6 +273,7 @@ export async function insertSkill(spaceId, content, options) {
226
273
  source: options.source,
227
274
  origin: options.origin ?? null,
228
275
  originHash: options.originHash ?? null,
276
+ bundleId: options.bundleId ?? null,
229
277
  });
230
278
  return { id, name };
231
279
  }
@@ -245,7 +293,8 @@ export async function createSkill(userId, spaceId, input) {
245
293
  }
246
294
  /**
247
295
  * Changes a skill: when it counts and whether its scripts run, always; its content only when it
248
- * is the space's own, since one from skills.sh stays as it came (an update replaces it whole).
296
+ * is the space's own, since one from skills.sh or one a plugin brought stays as it came (an
297
+ * update replaces it whole).
249
298
  */
250
299
  export async function updateSkill(userId, id, patch) {
251
300
  await requireSkills();
@@ -260,6 +309,9 @@ export async function updateSkill(userId, id, patch) {
260
309
  if (touches && row.source === "skills.sh") {
261
310
  throw refuse("skillReadOnly");
262
311
  }
312
+ if (touches && row.bundleId) {
313
+ throw refuse("skillOfBundleReadOnly");
314
+ }
263
315
  const next = checkContent({
264
316
  name: content.name ?? row.name,
265
317
  description: content.description ?? row.description,
@@ -284,6 +336,10 @@ export async function deleteSkill(userId, id) {
284
336
  const row = await skillRow(id);
285
337
  await ownedSpace(userId, row.spaceId);
286
338
  await requireWritableSpace(row.spaceId);
339
+ // What a plugin brought goes with it, all at once (`bundles/`): until then it is switched off.
340
+ if (row.bundleId) {
341
+ throw refuse("skillOfBundleStays");
342
+ }
287
343
  await db.delete(schema.spaceSkill).where(eq(schema.spaceSkill.id, row.id));
288
344
  }
289
345
  /**
@@ -232,17 +232,95 @@ export async function listCategories(spaceId) {
232
232
  count: v.n,
233
233
  summary: Boolean(v.summary),
234
234
  })),
235
- range: c.type === "number" && range?.minNum !== null && range?.minNum !== undefined
236
- ? { min: range.minNum, max: range.maxNum ?? range.minNum }
237
- : c.type === "date" && range?.minAt !== null && range?.minAt !== undefined
238
- ? { min: dateText(range.minAt), max: dateText(range.maxAt ?? range.minAt) }
239
- : null,
235
+ range: rangeOf(c.type, range),
240
236
  alike: [],
241
237
  };
242
238
  category.alike = alikeValues(category.values);
243
239
  return category;
244
240
  });
245
241
  }
242
+ /** A number's or a date's lowest and highest value, as a category shows them. */
243
+ function rangeOf(type, of) {
244
+ if (type === "number" && of?.minNum !== null && of?.minNum !== undefined) {
245
+ return { min: of.minNum, max: of.maxNum ?? of.minNum };
246
+ }
247
+ if (type === "date" && of?.minAt !== null && of?.minAt !== undefined) {
248
+ return { min: dateText(of.minAt), max: dateText(of.maxAt ?? of.minAt) };
249
+ }
250
+ return null;
251
+ }
252
+ /** The use of the space's categories by place, for a reader who may not read every place. */
253
+ export async function categoryUse(spaceId) {
254
+ const ids = (await categoryRows(spaceId)).map((c) => c.id);
255
+ if (!ids.length) {
256
+ return { items: [], values: [] };
257
+ }
258
+ const t = schema.spaceItemCategory;
259
+ const row = schema.spaceTableRow;
260
+ const file = schema.spaceMountFile;
261
+ // A row lies in its table, a mounted file in its mount.
262
+ const tableId = sql `coalesce(${t.tableId}, ${row.tableId})`;
263
+ const place = { pageId: t.pageId, tableId, fileId: t.fileId, mountId: file.mountId };
264
+ const [items, values] = await Promise.all([
265
+ db
266
+ .select({
267
+ ...place,
268
+ categoryId: t.categoryId,
269
+ n: sql `count(DISTINCT coalesce(${t.pageId}, ${t.rowId}, ${t.tableId}, ${t.fileId}, ${t.mountFileId}))`,
270
+ minNum: sql `min(${t.num})`,
271
+ maxNum: sql `max(${t.num})`,
272
+ minAt: sql `min(${t.at})`,
273
+ maxAt: sql `max(${t.at})`,
274
+ })
275
+ .from(t)
276
+ .leftJoin(row, eq(row.id, t.rowId))
277
+ .leftJoin(file, eq(file.id, t.mountFileId))
278
+ .where(inArray(t.categoryId, ids))
279
+ .groupBy(t.categoryId, t.pageId, tableId, t.fileId, file.mountId),
280
+ db
281
+ .select({ ...place, valueId: t.valueId, n: sql `count(*)` })
282
+ .from(t)
283
+ .leftJoin(row, eq(row.id, t.rowId))
284
+ .leftJoin(file, eq(file.id, t.mountFileId))
285
+ .where(and(inArray(t.categoryId, ids), isNotNull(t.valueId)))
286
+ .groupBy(t.valueId, t.pageId, tableId, t.fileId, file.mountId),
287
+ ]);
288
+ return { items, values };
289
+ }
290
+ /**
291
+ * The categories counted over a part of their use: how many items have each, a choice's values
292
+ * and the ranges, from `use` alone. A value that only items outside it have is left out; one no
293
+ * item has stays, as the category's own.
294
+ */
295
+ export function categoriesOver(all, use) {
296
+ const byValue = new Map();
297
+ for (const u of use.values) {
298
+ if (u.valueId) {
299
+ byValue.set(u.valueId, (byValue.get(u.valueId) ?? 0) + u.n);
300
+ }
301
+ }
302
+ const least = (list) => list.reduce((m, x) => (x === null ? m : m === null ? x : Math.min(m, x)), null);
303
+ const most = (list) => list.reduce((m, x) => (x === null ? m : m === null ? x : Math.max(m, x)), null);
304
+ return all.map((c) => {
305
+ const mine = use.items.filter((u) => u.categoryId === c.id);
306
+ const values = c.values
307
+ .filter((v) => byValue.has(v.id) || v.count === 0)
308
+ .map((v) => ({ ...v, count: byValue.get(v.id) ?? 0 }));
309
+ const kept = new Set(values.map((v) => v.id));
310
+ return {
311
+ ...c,
312
+ count: mine.reduce((sum, u) => sum + u.n, 0),
313
+ values,
314
+ range: rangeOf(c.type, {
315
+ minNum: least(mine.map((u) => u.minNum)),
316
+ maxNum: most(mine.map((u) => u.maxNum)),
317
+ minAt: least(mine.map((u) => u.minAt)),
318
+ maxAt: most(mine.map((u) => u.maxAt)),
319
+ }),
320
+ alike: c.alike.filter(([a, b]) => kept.has(a) && kept.has(b)),
321
+ };
322
+ });
323
+ }
246
324
  /** Pairs of a choice's values that look like one value written two ways, to offer merging. */
247
325
  function alikeValues(list) {
248
326
  const pairs = [];
@@ -1,10 +1,11 @@
1
1
  import { formatTableCell } from "@engenty/wizards-shared/engenty/data-tables";
2
2
  import { featureOn } from "@engenty/wizards-shared/features";
3
3
  import { embedMany } from "ai";
4
- import { and, eq, inArray, isNotNull, isNull, ne, notInArray, or, sql, } from "drizzle-orm";
4
+ import { and, asc, eq, gt, inArray, isNotNull, isNull, ne, notInArray, or, sql, } from "drizzle-orm";
5
5
  import { brokerOn, forbidden, pageResources, readable, readsEverything, tableResources, } from "../broker/rwx.js";
6
6
  import { db, schema, withTenant } from "../db/client.js";
7
7
  import { createSearchChunks } from "../engenty/search-index/chunks.js";
8
+ import { env } from "../env.js";
8
9
  import { currentFeatures } from "../features.js";
9
10
  import { getBlob, putBlob } from "../files/blobs.js";
10
11
  import { jpegOf, MAX_PAGE_PICTURES, pdfPages } from "../files/pictures.js";
@@ -35,13 +36,18 @@ const QUICK_MS = 800;
35
36
  /** Any other search waits this long for it: the embedding model may be busy with the index. */
36
37
  const VECTOR_MS = 15_000;
37
38
  const vectorBytes = (v) => Buffer.from(new Float32Array(v).buffer);
38
- async function embed(texts) {
39
+ async function embed(texts, maxRetries) {
39
40
  const resolved = await embeddingModel();
40
41
  if (!resolved || !texts.length) {
41
42
  return null;
42
43
  }
43
44
  await searchesFirst();
44
- const result = await embedMany({ model: resolved.model, values: texts, maxParallelCalls: 4 });
45
+ const result = await embedMany({
46
+ model: resolved.model,
47
+ values: texts,
48
+ maxParallelCalls: 4,
49
+ maxRetries,
50
+ });
45
51
  return { vectors: result.embeddings.map((e) => Array.from(e)), model: resolved.ref };
46
52
  }
47
53
  export async function dropIndex(fileId) {
@@ -106,7 +112,7 @@ async function writeUnits(scope, units) {
106
112
  }));
107
113
  }
108
114
  if (units.some((u) => u.kind && !pictures.has(pictureKey(u)))) {
109
- queuePictures();
115
+ queueVectors();
110
116
  }
111
117
  }
112
118
  const SHEET = /^\s*<!--\s*S\.\s*(\d+)\s*-->\s*$/;
@@ -484,30 +490,126 @@ export async function flushIndex() {
484
490
  await working;
485
491
  }
486
492
  await working;
487
- await picturesRunning;
493
+ await vectorsRunning;
488
494
  }
489
- // --- pictures -----------------------------------------------------------------------------
495
+ // --- vectors in the background ------------------------------------------------------------
490
496
  // A picture's vector comes after its unit: a picture of a PDF page takes a second or more to
491
- // make and embed, and the index of a page someone types in must not wait for it. Tenant after
492
- // tenant, file after file, units without a vector of the embedding model at hand.
493
- const picturesWaiting = new Set();
494
- let picturesRunning = null;
495
- /** Gives the pictures of the tenant at hand their vectors, soon. */
496
- export function queuePictures() {
497
- picturesWaiting.add(currentTenant());
498
- if (picturesRunning) {
497
+ // make and embed, and the index of a page someone types in must not wait for it. A text's comes
498
+ // with its unit, unless the model failed, none was set up then, or another one is now: on a
499
+ // Manage-App's runtime the binding changes without a word to the runtime. Tenant after tenant,
500
+ // units without a vector of the embedding model at hand. Only one process of a runtime does the
501
+ // texts: two would embed, and book, every batch twice.
502
+ const vectorsWaiting = new Set();
503
+ let vectorsRunning = null;
504
+ /** After a round the model failed in: twice as long each time, up to the longest. */
505
+ const VECTORS_PAUSE_MS = 20 * 60_000;
506
+ const VECTORS_PAUSE_LONGEST_MS = 2 * 60 * 60_000;
507
+ let vectorsFailedRounds = 0;
508
+ let vectorsPausedUntil = 0;
509
+ /** No tenant's round until later: they all share the model, and a failing call holds it busy. */
510
+ function pauseVectors(what, err) {
511
+ const pause = Math.min(VECTORS_PAUSE_MS * 2 ** vectorsFailedRounds, VECTORS_PAUSE_LONGEST_MS);
512
+ vectorsFailedRounds++;
513
+ vectorsPausedUntil = Date.now() + pause;
514
+ console.error(`[space-index] embedding ${what} failed, again in ${pause / 60_000} min:`, err.message);
515
+ }
516
+ /** Gives the units of the tenant at hand the vectors they lack, soon. */
517
+ export function queueVectors() {
518
+ vectorsWaiting.add(currentTenant());
519
+ if (vectorsRunning) {
499
520
  return;
500
521
  }
501
- picturesRunning = (async () => {
502
- while (picturesWaiting.size) {
503
- const [tenant] = picturesWaiting;
504
- picturesWaiting.delete(tenant);
505
- await withTenant(tenant, embedPictures).catch((err) => console.error("[space-index] pictures", err));
522
+ vectorsRunning = (async () => {
523
+ while (vectorsWaiting.size) {
524
+ const [tenant] = vectorsWaiting;
525
+ vectorsWaiting.delete(tenant);
526
+ await withTenant(tenant, async () => {
527
+ await embedTexts();
528
+ await embedPictures();
529
+ }).catch((err) => console.error("[space-index] vectors", err));
506
530
  }
507
531
  })().finally(() => {
508
- picturesRunning = null;
532
+ vectorsRunning = null;
509
533
  });
510
534
  }
535
+ /** Texts sent at once: a search's question waits behind them in a busy Ollama. */
536
+ const TEXT_BATCH = 32;
537
+ /**
538
+ * And their characters: 32 long units are about 60,000 tokens, while the gateway's Ollama on four
539
+ * cores makes some 400 a second and gives a call up after 120 s.
540
+ */
541
+ const TEXT_BATCH_CHARS = 16_000;
542
+ /** As many of `units` as go in one call: one at least, however long. */
543
+ function textBatch(units) {
544
+ let chars = 0;
545
+ const batch = units.filter((u) => {
546
+ chars += u.text.length;
547
+ return chars <= TEXT_BATCH_CHARS;
548
+ });
549
+ return batch.length ? batch : units.slice(0, 1);
550
+ }
551
+ /** The vectors of the text units that lack one of the model at hand. */
552
+ async function embedTexts() {
553
+ if (!env.serves.vectors || Date.now() < vectorsPausedUntil) {
554
+ return;
555
+ }
556
+ const resolved = await embeddingModel().catch(() => null);
557
+ if (!resolved) {
558
+ return;
559
+ }
560
+ // Past a batch that failed: the next round tries it again.
561
+ let after = 0;
562
+ let inRow = 0;
563
+ let failure = null;
564
+ const started = Date.now();
565
+ let done = 0;
566
+ for (;;) {
567
+ const units = await db
568
+ .select({ id: schema.spaceChunk.id, text: schema.spaceChunk.text })
569
+ .from(schema.spaceChunk)
570
+ .where(and(isNull(schema.spaceChunk.kind), gt(schema.spaceChunk.id, after), or(isNull(schema.spaceChunk.model), ne(schema.spaceChunk.model, resolved.ref))))
571
+ .orderBy(asc(schema.spaceChunk.id))
572
+ .limit(TEXT_BATCH);
573
+ if (!units.length) {
574
+ break;
575
+ }
576
+ const todo = textBatch(units);
577
+ after = todo[todo.length - 1].id;
578
+ try {
579
+ // No retries: a call that timed out still holds the model, and the next round comes anyway.
580
+ const embedded = await embed(todo.map((u) => u.text), 0);
581
+ if (!embedded) {
582
+ break;
583
+ }
584
+ // A unit written again in the meantime has a new id, and its vector already.
585
+ for (const [i, u] of todo.entries()) {
586
+ await db
587
+ .update(schema.spaceChunk)
588
+ .set({ embedding: vectorBytes(embedded.vectors[i]), model: embedded.model })
589
+ .where(eq(schema.spaceChunk.id, u.id));
590
+ }
591
+ done += todo.length;
592
+ inRow = 0;
593
+ }
594
+ catch (err) {
595
+ // The model is not there or not working: a later round tries again.
596
+ failure = err;
597
+ if (++inRow >= 3) {
598
+ break;
599
+ }
600
+ }
601
+ }
602
+ if (failure) {
603
+ pauseVectors("texts", failure);
604
+ }
605
+ else if (done) {
606
+ vectorsFailedRounds = 0;
607
+ vectorsPausedUntil = 0;
608
+ }
609
+ if (done) {
610
+ console.log(`[space-index] embedded ${done} texts with ${resolved.ref} in ${Math.round((Date.now() - started) / 1000)} s`);
611
+ }
612
+ }
511
613
  /** The pictures of the bytes `hash`, by page (0: a picture file itself), made when asked for. */
512
614
  async function picturesOf(hash, pdf) {
513
615
  const data = hash ? await getBlob(hash).catch(() => null) : null;
@@ -519,6 +621,9 @@ async function picturesOf(hash, pdf) {
519
621
  : new Map([[0, await jpegOf(data)]]);
520
622
  }
521
623
  async function embedPictures() {
624
+ if (Date.now() < vectorsPausedUntil) {
625
+ return;
626
+ }
522
627
  const resolved = await embeddingModel().catch(() => null);
523
628
  const embedImage = resolved?.embedImage;
524
629
  if (!(resolved && embedImage)) {
@@ -570,6 +675,7 @@ async function embedPictures() {
570
675
  failed.add(fileId);
571
676
  // The model is not there or not working: the next start, or the next picture, tries again.
572
677
  if (++inRow >= 3) {
678
+ pauseVectors("pictures", err);
573
679
  break;
574
680
  }
575
681
  }
@@ -725,6 +831,47 @@ async function readableUnits(spaceId, who, units) {
725
831
  return Boolean(u.plugin);
726
832
  };
727
833
  }
834
+ /**
835
+ * How many of a filter's items `who` may read: a page or a file by its own rule, a table and its
836
+ * rows by the table's, a mounted file where they may use its mount. What a search says its
837
+ * `where` left, so the number never counts what its caller cannot see.
838
+ */
839
+ async function readableSize(spaceId, who, filter, mounts) {
840
+ if (!(await brokerOn())) {
841
+ return filter.size;
842
+ }
843
+ const rowsOf = new Map();
844
+ const rows = [...filter.rows];
845
+ for (let i = 0; i < rows.length; i += 500) {
846
+ for (const r of await db.query.spaceTableRow.findMany({
847
+ where: inArray(schema.spaceTableRow.id, rows.slice(i, i + 500)),
848
+ columns: { tableId: true },
849
+ })) {
850
+ rowsOf.set(r.tableId, (rowsOf.get(r.tableId) ?? 0) + 1);
851
+ }
852
+ }
853
+ const [pages, files, tables] = await Promise.all([
854
+ pageResources([...filter.pages]).then((r) => readable(spaceId, who, r)),
855
+ readable(spaceId, who, [...filter.files].map((id) => ({ kind: "document", id }))),
856
+ tableResources([...new Set([...filter.tables, ...rowsOf.keys()])]).then((r) => readable(spaceId, who, r)),
857
+ ]);
858
+ const usable = new Set(mounts.map((m) => m.id));
859
+ let mounted = 0;
860
+ const inMounts = [...filter.mounted];
861
+ for (let i = 0; usable.size && i < inMounts.length; i += 500) {
862
+ for (const f of await db.query.spaceMountFile.findMany({
863
+ where: inArray(schema.spaceMountFile.id, inMounts.slice(i, i + 500)),
864
+ columns: { mountId: true },
865
+ })) {
866
+ mounted += usable.has(f.mountId) ? 1 : 0;
867
+ }
868
+ }
869
+ return ([...filter.pages].filter((id) => pages.has(id)).length +
870
+ [...filter.files].filter((id) => files.has(id)).length +
871
+ [...filter.tables].filter((id) => tables.has(id)).length +
872
+ [...rowsOf].reduce((n, [table, count]) => n + (tables.has(table) ? count : 0), 0) +
873
+ mounted);
874
+ }
728
875
  /**
729
876
  * Searches Knowledge for `who`: items whose categories pass `where` and that they may read, then
730
877
  * the units the keywords, the trigrams and the vectors rank best, merged by rank (RRF), then the
@@ -780,6 +927,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
780
927
  }
781
928
  // The mounts of Dateien the caller may use: their words and their vectors, beside Knowledge's.
782
929
  const mounts = await usableMounts(spaceId, opts.who ?? []);
930
+ const left = filter ? await readableSize(spaceId, opts.who ?? [], filter, mounts) : null;
783
931
  const mounted = filter ? [...filter.mounted] : null;
784
932
  if (mounts.length && !(mounted && !mounted.length)) {
785
933
  const inMounts = and(sql `u.mount_id IN (${sql.join(mounts.map((m) => sql `${m.id}`), sql `, `)})`, mounted && mounted.length <= IN_LIMIT
@@ -822,7 +970,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
822
970
  hits: [],
823
971
  candidates: 0,
824
972
  checked: false,
825
- filtered: filter?.size ?? null,
973
+ filtered: left,
826
974
  hidden: [],
827
975
  late: embedded === undefined,
828
976
  };
@@ -887,7 +1035,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
887
1035
  hits,
888
1036
  candidates: candidates.length,
889
1037
  checked: judged !== null,
890
- filtered: filter?.size ?? null,
1038
+ filtered: left,
891
1039
  hidden,
892
1040
  late: embedded === undefined,
893
1041
  };
@@ -1126,8 +1274,8 @@ export async function reindexAll() {
1126
1274
  }
1127
1275
  /**
1128
1276
  * What the index lacks, added at start: image, video and sound assets it does not hold yet; where
1129
- * the embedding model takes pictures, the picture files and PDFs without picture units, and the
1130
- * pictures without a vector of the model at hand.
1277
+ * the embedding model takes pictures, the picture files and PDFs without picture units; and the
1278
+ * units without a vector of the model at hand.
1131
1279
  */
1132
1280
  export async function indexMissingAssets() {
1133
1281
  const rows = await db.all(sql `
@@ -1137,6 +1285,7 @@ export async function indexMissingAssets() {
1137
1285
  for (const row of rows.filter(indexedFile)) {
1138
1286
  queueIndex(`f:${row.id}`);
1139
1287
  }
1288
+ queueVectors();
1140
1289
  if (!(await embeddingModel().catch(() => null))?.embedImage) {
1141
1290
  return;
1142
1291
  }
@@ -1148,5 +1297,4 @@ export async function indexMissingAssets() {
1148
1297
  for (const row of unseen.filter(indexedFile)) {
1149
1298
  queueIndex(`f:${row.id}`);
1150
1299
  }
1151
- queuePictures();
1152
1300
  }
@@ -1,6 +1,6 @@
1
1
  import { and, desc, eq, isNull } from "drizzle-orm";
2
2
  import { currentCaller } from "../broker/caller.js";
3
- import { currentReader, subjectsOfCaller } from "../broker/rwx.js";
3
+ import { currentReader, readable, subjectsOfCaller } from "../broker/rwx.js";
4
4
  import { db, schema } from "../db/client.js";
5
5
  import { UnreadableDocument } from "../documents/parse.js";
6
6
  import { ServiceError } from "./errors.js";
@@ -11,9 +11,21 @@ import { putCategory, setItemCategories } from "./space-categories.js";
11
11
  import { listOrigin, putOriginPage, putOriginTable, removeOrigin } from "./space-data.js";
12
12
  import { putOriginFile, spaceFileContent } from "./space-files.js";
13
13
  import { queueIndex } from "./space-index.js";
14
+ /**
15
+ * As whom a plugin reads the space's Knowledge: as whom it was called for, and as itself. A tool
16
+ * in a step or a Work chat reads as its caller, an HTTP route as the person it answers, a job as
17
+ * the runtime itself (readingAs). Anything else reads as the plugin alone, which no seed allows.
18
+ * A deny for the plugin always wins.
19
+ */
20
+ async function readerOf(origin) {
21
+ const caller = currentCaller();
22
+ const plugin = { kind: "plugin", id: origin };
23
+ return [...(caller ? await subjectsOfCaller(caller) : currentReader()), plugin];
24
+ }
14
25
  /**
15
26
  * `server.spaceData` of a plugin: Knowledge it writes under keys of its own, with categories. The
16
- * plugin's id is the origin of everything it writes; a person who changes an item keeps it.
27
+ * plugin's id is the origin of everything it writes; a person who changes an item keeps it. What
28
+ * it reads of the space (`readPages`, `files`, `readFile`), it reads as `readerOf` says.
17
29
  */
18
30
  export function originData(origin) {
19
31
  return {
@@ -176,7 +188,11 @@ export function originData(origin) {
176
188
  where: and(eq(schema.spacePage.spaceId, space), isNull(schema.spacePage.wizardId), opts?.parent ? eq(schema.spacePage.parentId, opts.parent) : undefined),
177
189
  orderBy: [schema.spacePage.position, schema.spacePage.title],
178
190
  });
179
- return rows.map((r) => ({
191
+ // Only the pages its reader may read: a page, the document behind it, the folders it lies in.
192
+ const ok = await readable(space, await readerOf(origin), rows.map((r) => ({ kind: "page", id: r.id, fileId: r.fileId })));
193
+ return rows
194
+ .filter((r) => ok.has(r.id))
195
+ .map((r) => ({
180
196
  id: r.id,
181
197
  title: r.title,
182
198
  path: tree.get(r.id)?.path ?? `pages/${r.slug ?? r.id}`,
@@ -192,7 +208,14 @@ export function originData(origin) {
192
208
  where: and(eq(schema.spaceFile.spaceId, space), eq(schema.spaceFile.kind, kind), eq(schema.spaceFile.status, "ready")),
193
209
  orderBy: [desc(schema.spaceFile.updatedAt)],
194
210
  });
195
- return rows.map((r) => ({
211
+ // A document is listed to whom may read it; a logo, pattern or asset is the brand's, not
212
+ // Knowledge, and asks nobody (space-files.ts).
213
+ const ok = kind === "document"
214
+ ? await readable(space, await readerOf(origin), rows.map((r) => ({ kind: "document", id: r.id })))
215
+ : null;
216
+ return rows
217
+ .filter((r) => !ok || ok.has(r.id))
218
+ .map((r) => ({
196
219
  id: r.id,
197
220
  name: r.name,
198
221
  mime: r.mime,
@@ -202,13 +225,7 @@ export function originData(origin) {
202
225
  }));
203
226
  },
204
227
  async readFile(space, fileId) {
205
- // As whom the plugin was called for, and as itself: a tool in a step or a Work chat as its
206
- // caller, an HTTP route as the person it answers, a job as the runtime itself (readingAs).
207
- // Anything else reads as the plugin alone, which no seed allows. A deny for it always wins.
208
- const caller = currentCaller();
209
- const plugin = { kind: "plugin", id: origin };
210
- const who = [...(caller ? await subjectsOfCaller(caller) : currentReader()), plugin];
211
- const { row, data } = await spaceFileContent(space, fileId, who);
228
+ const { row, data } = await spaceFileContent(space, fileId, await readerOf(origin));
212
229
  return {
213
230
  id: row.id,
214
231
  name: row.name,
@@ -69,6 +69,8 @@ export const syncWizardSchema = z.object({
69
69
  .default([]),
70
70
  shareEnabled: z.boolean().default(true),
71
71
  dailyRunLimit: z.number().int().min(1).max(10_000).optional(),
72
+ /** The mails and posts its guests' runs send per day; left out by an install from before it sent one. */
73
+ dailyMailLimit: z.number().int().min(0).max(10_000).optional(),
72
74
  /** The install's themes the wizard names; the cloud keeps them as the install has them. */
73
75
  themes: z.array(themeSchema).max(MAX_WIZARD_THEMES).default([]),
74
76
  });
@@ -76,6 +78,7 @@ export const syncSettingsSchema = z.object({
76
78
  shareEnabled: z.boolean().optional(),
77
79
  translate: z.boolean().optional(),
78
80
  dailyRunLimit: z.number().int().min(1).max(10_000).optional(),
81
+ dailyMailLimit: z.number().int().min(0).max(10_000).optional(),
79
82
  });
80
83
  export const checkSchema = z.object({
81
84
  definition: z.unknown(),
@@ -271,6 +274,7 @@ export async function syncWizard(rawSpaceId, rawWizardId, input) {
271
274
  draft,
272
275
  shareEnabled: input.shareEnabled,
273
276
  ...(input.dailyRunLimit ? { dailyRunLimit: input.dailyRunLimit } : {}),
277
+ ...(input.dailyMailLimit !== undefined ? { dailyMailLimit: input.dailyMailLimit } : {}),
274
278
  };
275
279
  if (!existing) {
276
280
  await requireWizardRoom(spaceId);
@@ -323,7 +327,7 @@ export async function syncWizard(rawSpaceId, rawWizardId, input) {
323
327
  // The public link lives in the control database, outside the transaction: set on every
324
328
  // sync, so one that failed to get there once is there after the next.
325
329
  await putLink(row.shareToken, "wizard", wizardId);
326
- emitDraftChanged({
330
+ await emitDraftChanged({
327
331
  wizardId,
328
332
  kind: "draft",
329
333
  revision: row.revision,