@engenty/wizards-runtime 0.17.0 → 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 (128) hide show
  1. package/apps/runtime/dist/app.js +2 -0
  2. package/apps/runtime/dist/broker/account.js +20 -1
  3. package/apps/runtime/dist/broker/call.js +116 -20
  4. package/apps/runtime/dist/broker/host.js +8 -2
  5. package/apps/runtime/dist/broker/index.js +3 -2
  6. package/apps/runtime/dist/broker/log.js +149 -14
  7. package/apps/runtime/dist/broker/over.js +38 -0
  8. package/apps/runtime/dist/broker/rights.js +192 -0
  9. package/apps/runtime/dist/broker/rwx.js +295 -51
  10. package/apps/runtime/dist/broker/send.js +25 -12
  11. package/apps/runtime/dist/bundles/fetch.js +119 -0
  12. package/apps/runtime/dist/bundles/index.js +621 -0
  13. package/apps/runtime/dist/bundles/read.js +607 -0
  14. package/apps/runtime/dist/connectors/external.js +532 -61
  15. package/apps/runtime/dist/connectors/person-sign-ins.js +1 -0
  16. package/apps/runtime/dist/connectors/reload.js +73 -0
  17. package/apps/runtime/dist/connectors/space-connections.js +73 -6
  18. package/apps/runtime/dist/db/migrations/tenant/0058_mcp_state_across_roles.sql +26 -0
  19. package/apps/runtime/dist/db/migrations/tenant/0059_space_connection_paused.sql +2 -0
  20. package/apps/runtime/dist/db/migrations/tenant/0060_space_bundle.sql +21 -0
  21. package/apps/runtime/dist/db/migrations/tenant/0061_space_connection_limits.sql +2 -0
  22. package/apps/runtime/dist/db/migrations/tenant/meta/0058_snapshot.json +6696 -0
  23. package/apps/runtime/dist/db/migrations/tenant/meta/0059_snapshot.json +6710 -0
  24. package/apps/runtime/dist/db/migrations/tenant/meta/0060_snapshot.json +6857 -0
  25. package/apps/runtime/dist/db/migrations/tenant/meta/0061_snapshot.json +6871 -0
  26. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +28 -0
  27. package/apps/runtime/dist/db/schema.js +81 -3
  28. package/apps/runtime/dist/docs/dev/broker.md +251 -31
  29. package/apps/runtime/dist/docs/user-guide/capabilities.md +123 -5
  30. package/apps/runtime/dist/docs/user-guide/connectors.md +52 -5
  31. package/apps/runtime/dist/docs/user-guide/protocol.md +15 -4
  32. package/apps/runtime/dist/docs/user-guide/test-and-share.md +1 -1
  33. package/apps/runtime/dist/elements/caller.js +2 -2
  34. package/apps/runtime/dist/engenty/connections-external/build-connector.js +23 -8
  35. package/apps/runtime/dist/engenty/connections-external/import-service.js +18 -9
  36. package/apps/runtime/dist/engenty/connections-external/importer/classify.js +12 -0
  37. package/apps/runtime/dist/engenty/connections-external/invoke/http-invoker.js +1 -0
  38. package/apps/runtime/dist/engenty/connections-external/net/guarded-fetch.js +6 -3
  39. package/apps/runtime/dist/engenty/connections-sdk/oauth2.js +2 -2
  40. package/apps/runtime/dist/engenty/shims/web-ingest.js +64 -0
  41. package/apps/runtime/dist/engine/resources.js +15 -6
  42. package/apps/runtime/dist/engine/runner.js +2 -1
  43. package/apps/runtime/dist/env.js +2 -0
  44. package/apps/runtime/dist/index.js +11 -2
  45. package/apps/runtime/dist/mcp/handler.js +2 -2
  46. package/apps/runtime/dist/mcp/seen.js +71 -51
  47. package/apps/runtime/dist/mcp/tools.js +5 -1
  48. package/apps/runtime/dist/prompts/mcp.md +1 -1
  49. package/apps/runtime/dist/prompts/tools.md +16 -0
  50. package/apps/runtime/dist/routes/broker.js +1 -1
  51. package/apps/runtime/dist/routes/bundles.js +91 -0
  52. package/apps/runtime/dist/routes/connections.js +14 -3
  53. package/apps/runtime/dist/routes/rules.js +53 -9
  54. package/apps/runtime/dist/routes/studio.js +23 -18
  55. package/apps/runtime/dist/services/cloud.js +2 -0
  56. package/apps/runtime/dist/services/draft-events.js +79 -6
  57. package/apps/runtime/dist/services/files.js +2 -2
  58. package/apps/runtime/dist/services/skills.js +61 -5
  59. package/apps/runtime/dist/services/space-index.js +102 -10
  60. package/apps/runtime/dist/services/synced-spaces.js +5 -1
  61. package/apps/runtime/dist/services/wizards.js +48 -2
  62. package/apps/runtime/dist/sharing/jobs.js +6 -2
  63. package/apps/runtime/dist/sync/records.js +6 -1
  64. package/apps/runtime/dist/texts.js +36 -1
  65. package/apps/runtime/dist/tools/connections.js +8 -0
  66. package/apps/runtime/dist/tools/connector.js +13 -1
  67. package/apps/runtime/dist/tools/index.js +8 -3
  68. package/apps/runtime/dist/tools/skills.js +11 -1
  69. package/apps/web/dist/assets/{AboutDialog-B2Xmxyj4.js → AboutDialog-mZCBU7KF.js} +1 -1
  70. package/apps/web/dist/assets/{BlockEditor-D0HoUSih.js → BlockEditor-Dk0QwLSU.js} +1 -1
  71. package/apps/web/dist/assets/CapabilitiesPage-GkpgF-wZ.js +2 -0
  72. package/apps/web/dist/assets/{ChangelogDialog-BIrJbAKi.js → ChangelogDialog-BhyilZWA.js} +1 -1
  73. package/apps/web/dist/assets/{CodeEditor-DUVcXI5P.js → CodeEditor-DULYZbuE.js} +1 -1
  74. package/apps/web/dist/assets/EditorPage-D_mCdYdZ.js +3 -0
  75. package/apps/web/dist/assets/{FlowPreview-BIag8_Be.js → FlowPreview-ykxZxWnk.js} +1 -1
  76. package/apps/web/dist/assets/{LangSwitch-CJ00IgaO.js → LangSwitch-iO54w9AP.js} +1 -1
  77. package/apps/web/dist/assets/{Marketplace-D7-ot9Dz.js → Marketplace-C97fH7UC.js} +2 -2
  78. package/apps/web/dist/assets/{NewWizardChannels-DI3SQ4iS.js → NewWizardChannels-CsSV7sm2.js} +1 -1
  79. package/apps/web/dist/assets/{NewWizardPage-CytheHxX.js → NewWizardPage-Ebgw-Vf_.js} +1 -1
  80. package/apps/web/dist/assets/{OnboardingPage-_91Pa8Ad.js → OnboardingPage-BZlloT7v.js} +1 -1
  81. package/apps/web/dist/assets/PreviewPane-CJuqY5uA.js +7 -0
  82. package/apps/web/dist/assets/ProtocolSection-CPaDKVpZ.js +1 -0
  83. package/apps/web/dist/assets/{PublicRunner-CEgXSk3r.js → PublicRunner-4Lf4SnwB.js} +1 -1
  84. package/apps/web/dist/assets/{ReadOnly-CWf5x74a.js → ReadOnly-CXQ41R9Q.js} +1 -1
  85. package/apps/web/dist/assets/{SettingsPage-Dr8SDk-L.js → SettingsPage-C-8BgK9O.js} +2 -2
  86. package/apps/web/dist/assets/{SetupPage-B68n0l4I.js → SetupPage-4_K083Wl.js} +1 -1
  87. package/apps/web/dist/assets/{SharePage-DfznN7ar.js → SharePage-CQjgMcDI.js} +1 -1
  88. package/apps/web/dist/assets/{SkillEditor-BIcIczRc.js → SkillEditor-DT5hQwbg.js} +1 -1
  89. package/apps/web/dist/assets/{Skills-CN4QE7Kx.js → Skills-D7V_9_xo.js} +1 -1
  90. package/apps/web/dist/assets/SpacePage-D3rYS1bA.js +2 -0
  91. package/apps/web/dist/assets/{UpdateCheck-QhBI3rlQ.js → UpdateCheck-DVgAJmy8.js} +2 -2
  92. package/apps/web/dist/assets/changelog-DzQCUSsx.js +1 -0
  93. package/apps/web/dist/assets/{code-editor-DkPo1C-L.js → code-editor-5T7ilBjd.js} +2 -2
  94. package/apps/web/dist/assets/{host-D6H6Z9Jp.js → host-CCijW1hj.js} +6 -6
  95. package/apps/web/dist/assets/i18n-DCPDesT-.js +55 -0
  96. package/apps/web/dist/assets/{index-De0Wb42y.js → index-C_iWl8iS.js} +3 -3
  97. package/apps/web/dist/assets/index-zcPlodHx.css +1 -0
  98. package/apps/web/dist/assets/minus-BpYkOkYw.js +1 -0
  99. package/apps/web/dist/assets/{read-aloud-CnFwDSGD.js → read-aloud-Qb719not.js} +1 -1
  100. package/apps/web/dist/assets/{runners-0sTPbWzr.js → runners-BeZ84YH_.js} +1 -1
  101. package/apps/web/dist/assets/{session-BMiUrqHg.js → session-CEJRkSP5.js} +1 -1
  102. package/apps/web/dist/assets/{theme-CkNTe-_Z.js → theme-y_owNosi.js} +1 -1
  103. package/apps/web/dist/assets/{ui-DAk_vjrL.js → ui-BacfkQ7Q.js} +1 -1
  104. package/apps/web/dist/assets/{useMutation-isHfB33W.js → useMutation-CgzFr4qH.js} +1 -1
  105. package/apps/web/dist/assets/{viewers-ijNZHJFG.js → viewers-CkyHAjnk.js} +2 -2
  106. package/apps/web/dist/index.html +12 -12
  107. package/apps/web/dist/mcp/flow.html +2 -2
  108. package/node_modules/@engenty/wizards-shared/dist/bundles.d.ts +219 -0
  109. package/node_modules/@engenty/wizards-shared/dist/bundles.js +19 -0
  110. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +105 -4
  111. package/node_modules/@engenty/wizards-shared/dist/connectors.js +6 -0
  112. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +8 -0
  113. package/node_modules/@engenty/wizards-shared/dist/run.js +16 -0
  114. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +84 -1
  115. package/node_modules/@engenty/wizards-shared/dist/rwx.js +69 -1
  116. package/node_modules/@engenty/wizards-shared/dist/skills.d.ts +20 -3
  117. package/node_modules/@engenty/wizards-shared/dist/skills.js +5 -2
  118. package/package.json +1 -1
  119. package/plugin/.claude-plugin/plugin.json +1 -1
  120. package/plugin/plugin.json +1 -1
  121. package/apps/web/dist/assets/CapabilitiesPage-C1th2cZE.js +0 -2
  122. package/apps/web/dist/assets/EditorPage-56sIqEfF.js +0 -3
  123. package/apps/web/dist/assets/PreviewPane-BDsYm-_K.js +0 -7
  124. package/apps/web/dist/assets/ProtocolSection-D_zaxHEL.js +0 -1
  125. package/apps/web/dist/assets/SpacePage-DiVTwhnJ.js +0 -2
  126. package/apps/web/dist/assets/changelog-a_CuplMX.js +0 -1
  127. package/apps/web/dist/assets/i18n-BaPKbQ1s.js +0 -55
  128. package/apps/web/dist/assets/index-CCUG6Vnh.css +0 -1
@@ -25,7 +25,8 @@ import { createLocalKey, deleteLocalKey, listLocalKeys } from "../auth/keys.js";
25
25
  import { assertRwx, folderAudience, setFolderAudience, subjectsOfPerson } from "../broker/rwx.js";
26
26
  import { appStates, connectApps } from "../cli/connect.js";
27
27
  import { layout } from "../cli/home.js";
28
- import { connectorImportSchema, importConnector, previewSource, refreshConnector, registryService, removeConnector, searchRegistry, } from "../connectors/external.js";
28
+ import { actionKindsPatchSchema, connectorImportSchema, connectorPreviewSchema, importConnector, previewSource, registryService, removeConnector, searchRegistry, setActionKinds, } from "../connectors/external.js";
29
+ import { reloadConnector } from "../connectors/reload.js";
29
30
  import { balanceCredits, canSpend } from "../credits/credits.js";
30
31
  import { estimateRun } from "../credits/estimate.js";
31
32
  import { missingModels, stepsWithoutModel } from "../engine/requirements.js";
@@ -833,15 +834,10 @@ export const studio = new Hono()
833
834
  return c.json(await searchRegistry(query));
834
835
  })
835
836
  .get("/connectors/registry/:domain", async (c) => c.json(await registryService(c.req.param("domain"))))
836
- .post("/connectors/preview", async (c) => {
837
- const body = z
838
- .object({
839
- domain: z.string().min(1).max(253).optional(),
840
- sourceKind: z.enum(["openapi", "mcp"]),
841
- sourceUrl: z.string().url(),
842
- })
843
- .parse(await c.req.json());
844
- return c.json(await previewSource(body));
837
+ // Reads an address before it is imported: for admins of a space that can be changed here.
838
+ .post("/spaces/:id/connectors/preview", async (c) => {
839
+ const space = await ownedSpace(c.get("user").id, c.req.param("id"));
840
+ return c.json(await previewSource(space.id, connectorPreviewSchema.parse(await c.req.json())));
845
841
  })
846
842
  .get("/spaces/:id/connectors", async (c) => c.json(await connectorsView(reader(c), c.req.param("id"))))
847
843
  .post("/spaces/:id/connectors", async (c) => {
@@ -850,8 +846,16 @@ export const studio = new Hono()
850
846
  return c.json(await importConnector(user.id, space.id, connectorImportSchema.parse(await c.req.json())));
851
847
  })
852
848
  .post("/spaces/:id/connectors/:connectorId/refresh", async (c) => {
853
- const space = await ownedSpace(c.get("user").id, c.req.param("id"));
854
- return c.json(await refreshConnector(space.id, c.req.param("connectorId"), null));
849
+ const user = c.get("user");
850
+ const space = await ownedSpace(user.id, c.req.param("id"));
851
+ return c.json(await reloadConnector(user.id, space.id, c.req.param("connectorId")));
852
+ })
853
+ // What single actions of an imported connector do, as an admin says it.
854
+ .patch("/spaces/:id/connectors/:connectorId/actions", async (c) => {
855
+ const user = c.get("user");
856
+ const space = await ownedSpace(user.id, c.req.param("id"));
857
+ const { actions } = actionKindsPatchSchema.parse(await c.req.json());
858
+ return c.json(await setActionKinds(user.id, space.id, c.req.param("connectorId"), actions));
855
859
  })
856
860
  .delete("/spaces/:id/connectors/:connectorId", async (c) => {
857
861
  const space = await ownedSpace(c.get("user").id, c.req.param("id"));
@@ -1258,8 +1262,8 @@ export const studio = new Hono()
1258
1262
  const body = z
1259
1263
  .object({ definition: z.unknown(), baseRevision: z.number().int().min(0) })
1260
1264
  .parse(await c.req.json());
1261
- const { revision, issues } = await writeDraft(c.get("user").id, c.req.param("id"), body);
1262
- return c.json({ ok: true, revision, issues });
1265
+ const { revision, issues, warnings } = await writeDraft(c.get("user").id, c.req.param("id"), body);
1266
+ return c.json({ ok: true, revision, issues, warnings });
1263
1267
  })
1264
1268
  .patch("/wizards/:id", async (c) => {
1265
1269
  const patch = z
@@ -1276,6 +1280,7 @@ export const studio = new Hono()
1276
1280
  // The copy in the cloud of a linked account is shared the same way.
1277
1281
  if (patch.shareEnabled !== undefined ||
1278
1282
  patch.dailyRunLimit !== undefined ||
1283
+ patch.dailyMailLimit !== undefined ||
1279
1284
  patch.runners !== undefined ||
1280
1285
  patch.translate !== undefined) {
1281
1286
  await pushSharing(c.get("user").id, c.req.param("id"));
@@ -1602,16 +1607,16 @@ export const studio = new Hono()
1602
1607
  // Not done is an answer too: the app's file is no plain JSON, here is what to paste.
1603
1608
  return c.json(done.outcome);
1604
1609
  })
1605
- // What each AI client did with the MCP server since the start: the test on "Integrate".
1606
- .get("/integrations/seen", (c) => c.json(seenApps(c.get("user").tenantId)))
1610
+ // What each AI client did with the MCP server: the test on "Integrate".
1611
+ .get("/integrations/seen", async (c) => c.json(await seenApps(c.get("user").tenantId)))
1607
1612
  // The apps members used on the spaces, allowed or refused by the organization's model policy.
1608
1613
  // Who used which app is for the organization's owners and admins.
1609
- .get("/model-policy/apps", (c) => {
1614
+ .get("/model-policy/apps", async (c) => {
1610
1615
  const user = c.get("user");
1611
1616
  if (!mayChangeModels(user)) {
1612
1617
  return c.json({ error: say(c, "onlyOrganizationAdminsChange"), code: "forbidden" }, 403);
1613
1618
  }
1614
- return c.json({ apps: checkedApps(user.tenantId) });
1619
+ return c.json({ apps: await checkedApps(user.tenantId) });
1615
1620
  })
1616
1621
  .get("/local/models", (c) => (managed ? c.notFound() : c.json(localModelSettings())))
1617
1622
  .put("/local/models", async (c) => {
@@ -255,6 +255,7 @@ export async function syncToCloud(userId, wizardId) {
255
255
  files,
256
256
  shareEnabled: w.shareEnabled,
257
257
  dailyRunLimit: w.dailyRunLimit,
258
+ dailyMailLimit: w.dailyMailLimit,
258
259
  themes: themesOf(version.definition.themes, (await ownedSpace(userId, w.spaceId)).themes),
259
260
  }, 120_000);
260
261
  if (!answer.ok || !answer.body.shareUrl) {
@@ -323,6 +324,7 @@ export async function pushSharing(userId, wizardId) {
323
324
  await call("PATCH", `/spaces/${w.spaceId}/wizards/${w.id}`, {
324
325
  shareEnabled: w.shareEnabled,
325
326
  dailyRunLimit: w.dailyRunLimit,
327
+ dailyMailLimit: w.dailyMailLimit,
326
328
  translate: w.translate,
327
329
  ...(w.runners ? { runners: w.runners } : {}),
328
330
  }).catch((err) => console.error("[cloud] sharing not sent:", err.message));
@@ -1,12 +1,85 @@
1
+ import { AsyncResource } from "node:async_hooks";
1
2
  import { EventEmitter } from "node:events";
2
- const bus = new EventEmitter();
3
- bus.setMaxListeners(0);
4
- export function emitDraftChanged(change) {
5
- bus.emit(change.wizardId, change);
3
+ import { and, asc, eq, gt, lt, max } from "drizzle-orm";
4
+ import { db } from "../db/client.js";
5
+ import * as schema from "../db/schema.js";
6
+ /** How often a subscriber looks for what another process wrote. */
7
+ const LOOK_MS = 2000;
8
+ /** A subscriber reads a change within seconds; a reconnect catches up on the revision. */
9
+ const KEEP_MS = 3600_000;
10
+ /** Wakes this process's subscribers at once; those of another process find the row on their look. */
11
+ const wake = new EventEmitter();
12
+ wake.setMaxListeners(0);
13
+ /**
14
+ * In the tenant's database, so the studio hears what the process answering MCP wrote
15
+ * (RUNTIME_ROLE). A notice lost is a notice lost: the write it tells of stands.
16
+ */
17
+ export async function emitDraftChanged(change) {
18
+ try {
19
+ await db.insert(schema.draftChange).values({ wizardId: change.wizardId, change });
20
+ wake.emit(change.wizardId);
21
+ }
22
+ catch (err) {
23
+ console.error("[draft-events]", err.message);
24
+ }
6
25
  }
26
+ /** Hears the changes to a wizard from now on, in the current tenant's context. */
7
27
  export function subscribeDraft(wizardId, listener) {
8
- bus.on(wizardId, listener);
9
- return () => bus.off(wizardId, listener);
28
+ const t = schema.draftChange;
29
+ let stopped = false;
30
+ let reading = false;
31
+ let again = false;
32
+ let seen = null;
33
+ // The tenant's context stays with the reader, whoever wakes it: ids are unique per tenant only.
34
+ const read = AsyncResource.bind(async () => {
35
+ if (reading) {
36
+ again = true;
37
+ return;
38
+ }
39
+ reading = true;
40
+ try {
41
+ if (seen === null) {
42
+ const [newest] = await db.select({ id: max(t.id) }).from(t);
43
+ seen = newest?.id ?? 0;
44
+ }
45
+ do {
46
+ again = false;
47
+ const after = seen ?? 0;
48
+ const rows = await db
49
+ .select()
50
+ .from(t)
51
+ .where(and(eq(t.wizardId, wizardId), gt(t.id, after)))
52
+ .orderBy(asc(t.id));
53
+ for (const row of rows) {
54
+ seen = row.id;
55
+ if (!stopped) {
56
+ listener(row.change);
57
+ }
58
+ }
59
+ } while (again && !stopped);
60
+ }
61
+ catch (err) {
62
+ console.error("[draft-events]", err.message);
63
+ }
64
+ finally {
65
+ reading = false;
66
+ }
67
+ });
68
+ const timer = setInterval(() => void read(), LOOK_MS);
69
+ timer.unref();
70
+ wake.on(wizardId, read);
71
+ void read();
72
+ return () => {
73
+ stopped = true;
74
+ clearInterval(timer);
75
+ wake.off(wizardId, read);
76
+ };
77
+ }
78
+ /** Deletes notices nobody needs any more, in the current tenant's context. */
79
+ export async function pruneDraftChanges(now = Date.now()) {
80
+ await db
81
+ .delete(schema.draftChange)
82
+ .where(lt(schema.draftChange.createdAt, new Date(now - KEEP_MS)));
10
83
  }
11
84
  /** Steps that are new or differ in `after`. */
12
85
  export function changedSteps(before, after) {
@@ -73,7 +73,7 @@ export async function writeFile(userId, wizardId, rawPath, content, mime) {
73
73
  set: { hash: file.hash, mime: file.mime, size: file.size, updatedAt: new Date() },
74
74
  });
75
75
  await touch(w.id);
76
- emitDraftChanged(filesChanged(w, path));
76
+ await emitDraftChanged(filesChanged(w, path));
77
77
  return file;
78
78
  }
79
79
  /**
@@ -136,7 +136,7 @@ export async function deleteFile(userId, wizardId, rawPath) {
136
136
  throw notFound();
137
137
  }
138
138
  await touch(w.id);
139
- emitDraftChanged(filesChanged(w, path));
139
+ await emitDraftChanged(filesChanged(w, path));
140
140
  }
141
141
  /** Copies a workspace onto another wizard (duplicate). Blobs are shared, only rows are new. */
142
142
  export async function copyFiles(fromWizardId, toWizardId) {
@@ -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
  /**
@@ -5,6 +5,7 @@ import { and, asc, eq, gt, inArray, isNotNull, isNull, ne, notInArray, or, sql,
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) {
@@ -491,9 +497,22 @@ export async function flushIndex() {
491
497
  // make and embed, and the index of a page someone types in must not wait for it. A text's comes
492
498
  // with its unit, unless the model failed, none was set up then, or another one is now: on a
493
499
  // Manage-App's runtime the binding changes without a word to the runtime. Tenant after tenant,
494
- // units without a vector of the embedding model at hand.
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.
495
502
  const vectorsWaiting = new Set();
496
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
+ }
497
516
  /** Gives the units of the tenant at hand the vectors they lack, soon. */
498
517
  export function queueVectors() {
499
518
  vectorsWaiting.add(currentTenant());
@@ -515,8 +534,25 @@ export function queueVectors() {
515
534
  }
516
535
  /** Texts sent at once: a search's question waits behind them in a busy Ollama. */
517
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
+ }
518
551
  /** The vectors of the text units that lack one of the model at hand. */
519
552
  async function embedTexts() {
553
+ if (!env.serves.vectors || Date.now() < vectorsPausedUntil) {
554
+ return;
555
+ }
520
556
  const resolved = await embeddingModel().catch(() => null);
521
557
  if (!resolved) {
522
558
  return;
@@ -524,21 +560,24 @@ async function embedTexts() {
524
560
  // Past a batch that failed: the next round tries it again.
525
561
  let after = 0;
526
562
  let inRow = 0;
563
+ let failure = null;
527
564
  const started = Date.now();
528
565
  let done = 0;
529
566
  for (;;) {
530
- const todo = await db
567
+ const units = await db
531
568
  .select({ id: schema.spaceChunk.id, text: schema.spaceChunk.text })
532
569
  .from(schema.spaceChunk)
533
570
  .where(and(isNull(schema.spaceChunk.kind), gt(schema.spaceChunk.id, after), or(isNull(schema.spaceChunk.model), ne(schema.spaceChunk.model, resolved.ref))))
534
571
  .orderBy(asc(schema.spaceChunk.id))
535
572
  .limit(TEXT_BATCH);
536
- if (!todo.length) {
573
+ if (!units.length) {
537
574
  break;
538
575
  }
576
+ const todo = textBatch(units);
539
577
  after = todo[todo.length - 1].id;
540
578
  try {
541
- const embedded = await embed(todo.map((u) => u.text));
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);
542
581
  if (!embedded) {
543
582
  break;
544
583
  }
@@ -553,13 +592,20 @@ async function embedTexts() {
553
592
  inRow = 0;
554
593
  }
555
594
  catch (err) {
556
- // The model is not there or not working: the next round tries again.
595
+ // The model is not there or not working: a later round tries again.
596
+ failure = err;
557
597
  if (++inRow >= 3) {
558
- console.error("[space-index] embedding texts failed", err.message);
559
598
  break;
560
599
  }
561
600
  }
562
601
  }
602
+ if (failure) {
603
+ pauseVectors("texts", failure);
604
+ }
605
+ else if (done) {
606
+ vectorsFailedRounds = 0;
607
+ vectorsPausedUntil = 0;
608
+ }
563
609
  if (done) {
564
610
  console.log(`[space-index] embedded ${done} texts with ${resolved.ref} in ${Math.round((Date.now() - started) / 1000)} s`);
565
611
  }
@@ -575,6 +621,9 @@ async function picturesOf(hash, pdf) {
575
621
  : new Map([[0, await jpegOf(data)]]);
576
622
  }
577
623
  async function embedPictures() {
624
+ if (Date.now() < vectorsPausedUntil) {
625
+ return;
626
+ }
578
627
  const resolved = await embeddingModel().catch(() => null);
579
628
  const embedImage = resolved?.embedImage;
580
629
  if (!(resolved && embedImage)) {
@@ -626,6 +675,7 @@ async function embedPictures() {
626
675
  failed.add(fileId);
627
676
  // The model is not there or not working: the next start, or the next picture, tries again.
628
677
  if (++inRow >= 3) {
678
+ pauseVectors("pictures", err);
629
679
  break;
630
680
  }
631
681
  }
@@ -781,6 +831,47 @@ async function readableUnits(spaceId, who, units) {
781
831
  return Boolean(u.plugin);
782
832
  };
783
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
+ }
784
875
  /**
785
876
  * Searches Knowledge for `who`: items whose categories pass `where` and that they may read, then
786
877
  * the units the keywords, the trigrams and the vectors rank best, merged by rank (RRF), then the
@@ -836,6 +927,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
836
927
  }
837
928
  // The mounts of Dateien the caller may use: their words and their vectors, beside Knowledge's.
838
929
  const mounts = await usableMounts(spaceId, opts.who ?? []);
930
+ const left = filter ? await readableSize(spaceId, opts.who ?? [], filter, mounts) : null;
839
931
  const mounted = filter ? [...filter.mounted] : null;
840
932
  if (mounts.length && !(mounted && !mounted.length)) {
841
933
  const inMounts = and(sql `u.mount_id IN (${sql.join(mounts.map((m) => sql `${m.id}`), sql `, `)})`, mounted && mounted.length <= IN_LIMIT
@@ -878,7 +970,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
878
970
  hits: [],
879
971
  candidates: 0,
880
972
  checked: false,
881
- filtered: filter?.size ?? null,
973
+ filtered: left,
882
974
  hidden: [],
883
975
  late: embedded === undefined,
884
976
  };
@@ -943,7 +1035,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
943
1035
  hits,
944
1036
  candidates: candidates.length,
945
1037
  checked: judged !== null,
946
- filtered: filter?.size ?? null,
1038
+ filtered: left,
947
1039
  hidden,
948
1040
  late: embedded === undefined,
949
1041
  };
@@ -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,