@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
@@ -1,7 +1,7 @@
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";
@@ -14,6 +14,7 @@ import { pluginIdsOf } from "../plugins/registry.js";
14
14
  import { currentTenant } from "../tenants/tenant.js";
15
15
  import { ServiceError } from "./errors.js";
16
16
  import { filePaths, pageTree, tablePaths } from "./knowledge.js";
17
+ import { queryVector, searchesFirst } from "./query-vectors.js";
17
18
  import { judgeRelevance, MIN_RELEVANCE } from "./relevance.js";
18
19
  import { categoryLines, categoryRows, filterItems, itemCategoriesOf, } from "./space-categories.js";
19
20
  const CHUNK = { mode: "paragraph", max_chunk_length: 1200, overlap: 120 };
@@ -29,12 +30,17 @@ const CANDIDATES = 24;
29
30
  * has it: the nearest units are near even for a question the space knows nothing of.
30
31
  */
31
32
  const MIN_LEAD = 0.08;
33
+ /** The palette's quick ask waits this long for the query's vector, then answers with words. */
34
+ const QUICK_MS = 800;
35
+ /** Any other search waits this long for it: the embedding model may be busy with the index. */
36
+ const VECTOR_MS = 15_000;
32
37
  const vectorBytes = (v) => Buffer.from(new Float32Array(v).buffer);
33
38
  async function embed(texts) {
34
39
  const resolved = await embeddingModel();
35
40
  if (!resolved || !texts.length) {
36
41
  return null;
37
42
  }
43
+ await searchesFirst();
38
44
  const result = await embedMany({ model: resolved.model, values: texts, maxParallelCalls: 4 });
39
45
  return { vectors: result.embeddings.map((e) => Array.from(e)), model: resolved.ref };
40
46
  }
@@ -100,7 +106,7 @@ async function writeUnits(scope, units) {
100
106
  }));
101
107
  }
102
108
  if (units.some((u) => u.kind && !pictures.has(pictureKey(u)))) {
103
- queuePictures();
109
+ queueVectors();
104
110
  }
105
111
  }
106
112
  const SHEET = /^\s*<!--\s*S\.\s*(\d+)\s*-->\s*$/;
@@ -478,30 +484,86 @@ export async function flushIndex() {
478
484
  await working;
479
485
  }
480
486
  await working;
481
- await picturesRunning;
487
+ await vectorsRunning;
482
488
  }
483
- // --- pictures -----------------------------------------------------------------------------
489
+ // --- vectors in the background ------------------------------------------------------------
484
490
  // A picture's vector comes after its unit: a picture of a PDF page takes a second or more to
485
- // make and embed, and the index of a page someone types in must not wait for it. Tenant after
486
- // tenant, file after file, units without a vector of the embedding model at hand.
487
- const picturesWaiting = new Set();
488
- let picturesRunning = null;
489
- /** Gives the pictures of the tenant at hand their vectors, soon. */
490
- export function queuePictures() {
491
- picturesWaiting.add(currentTenant());
492
- if (picturesRunning) {
491
+ // make and embed, and the index of a page someone types in must not wait for it. A text's comes
492
+ // with its unit, unless the model failed, none was set up then, or another one is now: on a
493
+ // 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.
495
+ const vectorsWaiting = new Set();
496
+ let vectorsRunning = null;
497
+ /** Gives the units of the tenant at hand the vectors they lack, soon. */
498
+ export function queueVectors() {
499
+ vectorsWaiting.add(currentTenant());
500
+ if (vectorsRunning) {
493
501
  return;
494
502
  }
495
- picturesRunning = (async () => {
496
- while (picturesWaiting.size) {
497
- const [tenant] = picturesWaiting;
498
- picturesWaiting.delete(tenant);
499
- await withTenant(tenant, embedPictures).catch((err) => console.error("[space-index] pictures", err));
503
+ vectorsRunning = (async () => {
504
+ while (vectorsWaiting.size) {
505
+ const [tenant] = vectorsWaiting;
506
+ vectorsWaiting.delete(tenant);
507
+ await withTenant(tenant, async () => {
508
+ await embedTexts();
509
+ await embedPictures();
510
+ }).catch((err) => console.error("[space-index] vectors", err));
500
511
  }
501
512
  })().finally(() => {
502
- picturesRunning = null;
513
+ vectorsRunning = null;
503
514
  });
504
515
  }
516
+ /** Texts sent at once: a search's question waits behind them in a busy Ollama. */
517
+ const TEXT_BATCH = 32;
518
+ /** The vectors of the text units that lack one of the model at hand. */
519
+ async function embedTexts() {
520
+ const resolved = await embeddingModel().catch(() => null);
521
+ if (!resolved) {
522
+ return;
523
+ }
524
+ // Past a batch that failed: the next round tries it again.
525
+ let after = 0;
526
+ let inRow = 0;
527
+ const started = Date.now();
528
+ let done = 0;
529
+ for (;;) {
530
+ const todo = await db
531
+ .select({ id: schema.spaceChunk.id, text: schema.spaceChunk.text })
532
+ .from(schema.spaceChunk)
533
+ .where(and(isNull(schema.spaceChunk.kind), gt(schema.spaceChunk.id, after), or(isNull(schema.spaceChunk.model), ne(schema.spaceChunk.model, resolved.ref))))
534
+ .orderBy(asc(schema.spaceChunk.id))
535
+ .limit(TEXT_BATCH);
536
+ if (!todo.length) {
537
+ break;
538
+ }
539
+ after = todo[todo.length - 1].id;
540
+ try {
541
+ const embedded = await embed(todo.map((u) => u.text));
542
+ if (!embedded) {
543
+ break;
544
+ }
545
+ // A unit written again in the meantime has a new id, and its vector already.
546
+ for (const [i, u] of todo.entries()) {
547
+ await db
548
+ .update(schema.spaceChunk)
549
+ .set({ embedding: vectorBytes(embedded.vectors[i]), model: embedded.model })
550
+ .where(eq(schema.spaceChunk.id, u.id));
551
+ }
552
+ done += todo.length;
553
+ inRow = 0;
554
+ }
555
+ catch (err) {
556
+ // The model is not there or not working: the next round tries again.
557
+ if (++inRow >= 3) {
558
+ console.error("[space-index] embedding texts failed", err.message);
559
+ break;
560
+ }
561
+ }
562
+ }
563
+ if (done) {
564
+ console.log(`[space-index] embedded ${done} texts with ${resolved.ref} in ${Math.round((Date.now() - started) / 1000)} s`);
565
+ }
566
+ }
505
567
  /** The pictures of the bytes `hash`, by page (0: a picture file itself), made when asked for. */
506
568
  async function picturesOf(hash, pdf) {
507
569
  const data = hash ? await getBlob(hash).catch(() => null) : null;
@@ -549,6 +611,7 @@ async function embedPictures() {
549
611
  await db.delete(schema.spaceChunk).where(which);
550
612
  continue;
551
613
  }
614
+ await searchesFirst();
552
615
  const vector = await embedImage(jpeg);
553
616
  await db
554
617
  .update(schema.spaceChunk)
@@ -722,7 +785,8 @@ async function readableUnits(spaceId, who, units) {
722
785
  * Searches Knowledge for `who`: items whose categories pass `where` and that they may read, then
723
786
  * the units the keywords, the trigrams and the vectors rank best, merged by rank (RRF), then the
724
787
  * classifier's judgement of each of the CANDIDATES best. Gives up to `limit` items with their
725
- * best section. `check: false` leaves the classifier out. While the `broker` switch is on, a call
788
+ * best section. `check: false` is the palette's quick ask: no classifier, and the query's vector
789
+ * only if it comes within QUICK_MS (`late` says it did not). While the `broker` switch is on, a call
726
790
  * without `who` is refused, and an item they may not read is in no hit, candidate or count.
727
791
  */
728
792
  export async function searchKnowledge(spaceId, query, opts = {}) {
@@ -733,7 +797,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
733
797
  }
734
798
  const filter = await filterItems(spaceId, opts.where);
735
799
  if (filter && !filter.size) {
736
- return { hits: [], candidates: 0, checked: false, filtered: 0, hidden: [] };
800
+ return { hits: [], candidates: 0, checked: false, filtered: 0, hidden: [], late: false };
737
801
  }
738
802
  const plugins = [...(await pluginIdsOf(currentTenant()))];
739
803
  const inFilter = filter ? filtered(filter) : null;
@@ -760,9 +824,9 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
760
824
  ORDER BY bm25(space_chunk_tri) LIMIT ${take}`)
761
825
  .catch(() => []));
762
826
  }
763
- const embedded = await embed([query]).catch(() => null);
827
+ const embedded = await queryVector(query, opts.check === false ? QUICK_MS : VECTOR_MS);
764
828
  if (embedded) {
765
- const question = vectorBytes(embedded.vectors[0]);
829
+ const question = vectorBytes(embedded.vector);
766
830
  lists.push(featureOn(await currentFeatures(), "knowledgeMedia")
767
831
  ? await byMeaning(CHUNKS, where, embedded.model, question, take)
768
832
  : await db.all(sql `
@@ -791,7 +855,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
791
855
  }
792
856
  }
793
857
  if (embedded) {
794
- lists.push(await byMeaning(MOUNT_UNITS, inMounts, embedded.model, vectorBytes(embedded.vectors[0]), take));
858
+ lists.push(await byMeaning(MOUNT_UNITS, inMounts, embedded.model, vectorBytes(embedded.vector), take));
795
859
  }
796
860
  }
797
861
  const allowed = await readableUnits(spaceId, opts.who ?? [], lists.flat());
@@ -810,7 +874,14 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
810
874
  }
811
875
  const candidates = [...scored.values()].sort((a, b) => b.score - a.score).slice(0, CANDIDATES);
812
876
  if (!candidates.length) {
813
- return { hits: [], candidates: 0, checked: false, filtered: filter?.size ?? null, hidden: [] };
877
+ return {
878
+ hits: [],
879
+ candidates: 0,
880
+ checked: false,
881
+ filtered: filter?.size ?? null,
882
+ hidden: [],
883
+ late: embedded === undefined,
884
+ };
814
885
  }
815
886
  const described = await describe(spaceId, candidates.map((c) => c.unit), mounts);
816
887
  // The classifier reads text; a picture, found by what it shows, keeps its place.
@@ -874,6 +945,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
874
945
  checked: judged !== null,
875
946
  filtered: filter?.size ?? null,
876
947
  hidden,
948
+ late: embedded === undefined,
877
949
  };
878
950
  }
879
951
  /** Where `byMeaning` looks: Knowledge's units, or the mounts'. */
@@ -1110,8 +1182,8 @@ export async function reindexAll() {
1110
1182
  }
1111
1183
  /**
1112
1184
  * What the index lacks, added at start: image, video and sound assets it does not hold yet; where
1113
- * the embedding model takes pictures, the picture files and PDFs without picture units, and the
1114
- * pictures without a vector of the model at hand.
1185
+ * the embedding model takes pictures, the picture files and PDFs without picture units; and the
1186
+ * units without a vector of the model at hand.
1115
1187
  */
1116
1188
  export async function indexMissingAssets() {
1117
1189
  const rows = await db.all(sql `
@@ -1121,6 +1193,7 @@ export async function indexMissingAssets() {
1121
1193
  for (const row of rows.filter(indexedFile)) {
1122
1194
  queueIndex(`f:${row.id}`);
1123
1195
  }
1196
+ queueVectors();
1124
1197
  if (!(await embeddingModel().catch(() => null))?.embedImage) {
1125
1198
  return;
1126
1199
  }
@@ -1132,5 +1205,4 @@ export async function indexMissingAssets() {
1132
1205
  for (const row of unseen.filter(indexedFile)) {
1133
1206
  queueIndex(`f:${row.id}`);
1134
1207
  }
1135
- queuePictures();
1136
1208
  }
@@ -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,
@@ -9,7 +9,7 @@ import { elementTools } from "../elements/catalogue.js";
9
9
  import { currentFeatures } from "../features.js";
10
10
  import { HarnessModel } from "../harness/index.js";
11
11
  import { managed } from "../manage.js";
12
- import { attachTools, chatModel, gatewayTools } from "../models.js";
12
+ import { attachTools, chatModel, gatewayTools, toolAccess, } from "../models.js";
13
13
  import { pluginsOf } from "../plugins/registry.js";
14
14
  import { prompt } from "../prompts.js";
15
15
  import { sandboxCapabilities, shellToolDescription } from "../sandbox/index.js";
@@ -17,6 +17,7 @@ import { currentTenant } from "../tenants/tenant.js";
17
17
  import { assistantToolPlugin, assistantToolRisk, assistantToolsOf } from "../tools/plugin.js";
18
18
  import { clip } from "../tools/shared.js";
19
19
  import { skillsBlock } from "../tools/skills.js";
20
+ import { gatewayWebSearch } from "../tools/web-search.js";
20
21
  import { roleOf } from "./access.js";
21
22
  import { ClientSteps } from "./client-steps.js";
22
23
  import { activeSkills } from "./skills.js";
@@ -137,7 +138,7 @@ async function clientTools(space, userId, signal, chatId) {
137
138
  * and the web the person turned off (`choice`) left out. A client gets `clientTools` alone.
138
139
  * `role`: the person's, where the session knows it; else the organization's list says.
139
140
  */
140
- async function toolsFor(resolved, space, userId, signal, choice = {}, chatId = null, approved = null, known = null) {
141
+ async function toolsFor(resolved, space, userId, signal, choice = {}, chatId = null, approved = null, known = null, web = null) {
141
142
  const role = known ?? (await roleOf(userId));
142
143
  if (role === "client") {
143
144
  return clientTools(space, userId, signal, chatId ?? approved?.chatId ?? null);
@@ -184,7 +185,12 @@ async function toolsFor(resolved, space, userId, signal, choice = {}, chatId = n
184
185
  delete tools[name];
185
186
  }
186
187
  }
187
- if (choice.web !== false && resolved?.vendor === "anthropic") {
188
+ // The gateway's search where the gateway is reached, for every model; else the model's own.
189
+ const access = choice.web !== false ? web : null;
190
+ if (access) {
191
+ tools.web_search = gatewayWebSearch(access);
192
+ }
193
+ else if (choice.web !== false && resolved?.vendor === "anthropic") {
188
194
  tools.web_search = anthropic.tools.webSearch_20250305({ maxUses: 5 });
189
195
  }
190
196
  else if (choice.web !== false && resolved?.gateway) {
@@ -253,9 +259,13 @@ export async function toolToRun(space, userId, name, signal, approved) {
253
259
  * composer.
254
260
  */
255
261
  export async function workTurn(turn, signal, steps, choice = {}) {
256
- const resolved = await chatModel(await chatTurnWay(managed), choice.extra ? "high" : "standard");
262
+ // The gateway's way for web search, asked beside the model rather than after it.
263
+ const [resolved, web] = await Promise.all([
264
+ chatTurnWay(managed).then((way) => chatModel(way, choice.extra ? "high" : "standard")),
265
+ choice.web !== false ? toolAccess() : null,
266
+ ]);
257
267
  const client = turn.role === "client";
258
- const made = gated(await toolsFor(resolved, turn.space, turn.userId, signal, choice, turn.chatId, null, turn.role ?? null), turn);
268
+ const made = gated(await toolsFor(resolved, turn.space, turn.userId, signal, choice, turn.chatId, null, turn.role ?? null, web), turn);
259
269
  const tools = resolved.model instanceof HarnessModel ? steps.wrap(made) : made;
260
270
  attachTools(resolved, tools);
261
271
  const skills = client ? null : await spaceSkills(turn.space.id);
@@ -225,6 +225,9 @@ function standIn(wizard, userId) {
225
225
  origin: null,
226
226
  client: null,
227
227
  status: "done",
228
+ wakeAt: null,
229
+ claim: 0,
230
+ rev: 0,
228
231
  cursor: null,
229
232
  state: { values: {}, outputs: {}, history: [], notes: {} },
230
233
  error: null,
@@ -100,6 +100,8 @@ function refusalLine(refused) {
100
100
  switch (refused) {
101
101
  case "not_allowed_recipient":
102
102
  return line("shareGuestRecipient");
103
+ case "channel_not_fixed":
104
+ return line("shareGuestChannel");
103
105
  case "run_limit":
104
106
  return line("shareGuestRunMails", { mails: GUEST_MAILS_PER_RUN });
105
107
  case "day_limit":
@@ -5,6 +5,7 @@ import { getBlob, hasBlob, putBlobOf } from "../files/blobs.js";
5
5
  import { managed, tenantInfo } from "../manage.js";
6
6
  import { currentRole, isAdminRole, MEMBERS_EDIT_ONLY, mayBuild } from "../services/access.js";
7
7
  import { ServiceError } from "../services/errors.js";
8
+ import { studioSpaces } from "../services/members-studio.js";
8
9
  import { spaceLimit } from "../services/spaces.js";
9
10
  import { publishWizard, rotateShareLink, shareUrl } from "../services/wizards.js";
10
11
  import { codeOf } from "../tenants/control.js";
@@ -26,13 +27,18 @@ function requireSchema(theirs) {
26
27
  throw new ServiceError("refused", order(theirs) < order(tenantSchemaVersion) ? note("syncUpdateHere") : note("syncUpdateCloud"), { reason: "schema_mismatch", schema: tenantSchemaVersion });
27
28
  }
28
29
  }
29
- /** The organization as an install meets it: its schema, its number of spaces, its spaces. */
30
+ /**
31
+ * The organization as an install meets it: its schema, its number of spaces, its spaces. The
32
+ * install of a member meets the spaces whose Studio is open to members; the others refuse its
33
+ * pulls and pushes (services/members-studio.ts), so they are not offered to it.
34
+ */
30
35
  export async function syncOverview() {
31
- const spaces = await db.query.space.findMany({
36
+ const open = await studioSpaces();
37
+ const spaces = (await db.query.space.findMany({
32
38
  where: eq(schema.space.tenantId, currentTenant()),
33
39
  columns: { id: true, name: true, origin: true },
34
40
  orderBy: [schema.space.createdAt],
35
- });
41
+ })).filter((s) => !open || open.has(s.id));
36
42
  const info = managed ? await tenantInfo(currentTenant()).catch(() => null) : null;
37
43
  const limit = await spaceLimit();
38
44
  return {
@@ -45,6 +51,14 @@ export async function syncOverview() {
45
51
  spaces: await Promise.all(spaces.map(async (s) => ({ id: s.id, name: s.name, seq: await spaceSeq(s.id) }))),
46
52
  };
47
53
  }
54
+ /**
55
+ * What of the feed's changes an install hears as spaces to pull (`GET /sync/live`): for a
56
+ * member's install, none of a space whose Studio is closed to members.
57
+ */
58
+ export async function syncHears(changes) {
59
+ const open = await studioSpaces();
60
+ return open ? changes.filter((x) => !x.spaceId || open.has(x.spaceId)) : changes;
61
+ }
48
62
  /**
49
63
  * What changed in a space after `since`. From 0 it is every item of the space, a page at a
50
64
  * time (`cursor`); `next` then is the number the log stood at when the listing began.
@@ -1,4 +1,4 @@
1
- import { and, count, eq, gte, inArray, isNull, lt, or, sql } from "drizzle-orm";
1
+ import { and, count, eq, gte, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
2
2
  import { control, controlDb } from "../db/client.js";
3
3
  import { env } from "../env.js";
4
4
  import { currentTenant } from "./tenant.js";
@@ -116,32 +116,62 @@ export const RUNNER_STALE_MS = 30_000;
116
116
  export async function wakeRun(runId) {
117
117
  await controlDb
118
118
  .update(control.runIndex)
119
- .set({ active: true, owner: null, seen: null })
119
+ .set({ active: true, owner: null, seen: null, wokenAt: new Date() })
120
120
  .where(eq(control.runIndex.runId, runId));
121
121
  }
122
- /** The run is done with runners for now: a page, a review or the end. */
122
+ /**
123
+ * When a run that sleeps wakes, in the copy the clock reads; null: nothing due. Written before the
124
+ * run's own row: a crash in between gives one extra wake, which finds the run as it is, never a
125
+ * lost one.
126
+ */
127
+ export async function setWake(runId, wakeAt) {
128
+ await controlDb.update(control.runIndex).set({ wakeAt }).where(eq(control.runIndex.runId, runId));
129
+ }
130
+ /**
131
+ * The clock: what came due goes in line, in one statement over every tenant, so several runners
132
+ * running it are harmless. The run ages from the time it was due. A run that turns out not to be
133
+ * due puts its time back from its own row.
134
+ */
135
+ export async function wakeDue(now = new Date()) {
136
+ const result = await controlDb
137
+ .update(control.runIndex)
138
+ .set({
139
+ active: true,
140
+ owner: null,
141
+ seen: null,
142
+ wakeAt: null,
143
+ wokenAt: sql `${control.runIndex.wakeAt}`,
144
+ })
145
+ .where(and(eq(control.runIndex.active, false), lte(control.runIndex.wakeAt, now)));
146
+ return result.rowsAffected;
147
+ }
148
+ /**
149
+ * The run is done with runners for now: a page, a review or the end. Only its owner rests it: a
150
+ * wake meanwhile cleared the owner, and the run stays in line.
151
+ */
123
152
  export async function restRun(runId) {
124
153
  await controlDb
125
154
  .update(control.runIndex)
126
155
  .set({ active: false, owner: null, seen: null })
127
- .where(eq(control.runIndex.runId, runId));
156
+ .where(and(eq(control.runIndex.runId, runId), eq(control.runIndex.owner, env.runner.id)));
128
157
  }
129
158
  /**
130
159
  * Takes a run for this runner, in one statement: only while nobody (alive) holds it and the
131
- * tenant's owned runs stay under its limit. False: someone else has it, or the tenant is at its
132
- * limit — the run stays in line.
160
+ * tenant's owned runs stay under its limit. Answers the claim's number, higher than any before.
161
+ * Null: someone else has it, or the tenant is at its limit — the run stays in line.
133
162
  */
134
163
  export async function claimRun(runId, tenantId, limit) {
135
164
  const now = Date.now();
136
165
  const stale = now - RUNNER_STALE_MS;
137
166
  const result = await controlDb.run(sql `
138
- UPDATE run_index SET owner = ${env.runner.id}, seen = ${now}
167
+ UPDATE run_index SET owner = ${env.runner.id}, seen = ${now}, generation = generation + 1
139
168
  WHERE run_id = ${runId} AND active = 1
140
169
  AND (owner IS NULL OR seen IS NULL OR seen < ${stale})
141
170
  AND (SELECT count(*) FROM run_index
142
171
  WHERE tenant_id = ${tenantId} AND owner IS NOT NULL AND seen >= ${stale}
143
- AND run_id != ${runId}) < ${limit}`);
144
- return result.rowsAffected > 0;
172
+ AND run_id != ${runId}) < ${limit}
173
+ RETURNING generation`);
174
+ return result.rows.length ? Number(result.rows[0].generation) : null;
145
175
  }
146
176
  /** This runner still works on these runs. */
147
177
  export async function heartbeatRuns(runIds) {
@@ -159,14 +189,16 @@ export async function disownRuns() {
159
189
  .set({ owner: null, seen: null })
160
190
  .where(eq(control.runIndex.owner, env.runner.id));
161
191
  }
162
- /** The runs in line: unowned, or whose owner fell silent. */
192
+ /** How long a run has been in line for: since it last woke, else since it was made. */
193
+ const inLineSince = sql `coalesce(${control.runIndex.wokenAt}, ${control.runIndex.createdAt})`;
194
+ /** The runs in line, longest in line first: unowned, or whose owner fell silent. */
163
195
  export async function waitingRuns() {
164
196
  const stale = new Date(Date.now() - RUNNER_STALE_MS);
165
197
  return controlDb
166
198
  .select({ runId: control.runIndex.runId, tenantId: control.runIndex.tenantId })
167
199
  .from(control.runIndex)
168
200
  .where(and(eq(control.runIndex.active, true), or(isNull(control.runIndex.owner), isNull(control.runIndex.seen), lt(control.runIndex.seen, stale))))
169
- .orderBy(control.runIndex.createdAt);
201
+ .orderBy(inLineSince);
170
202
  }
171
203
  /** Where the runner holding a run is reached; null when none holds it or it named no address. */
172
204
  export async function ownerUrl(runId) {
@@ -207,12 +239,12 @@ export async function lineState() {
207
239
  .select({ id: control.runner.id, seen: control.runner.seen, lineAt: control.runner.lineAt })
208
240
  .from(control.runner);
209
241
  const [oldest] = await controlDb
210
- .select({ createdAt: control.runIndex.createdAt })
242
+ .select({ createdAt: control.runIndex.createdAt, wokenAt: control.runIndex.wokenAt })
211
243
  .from(control.runIndex)
212
244
  .where(and(eq(control.runIndex.active, true), or(isNull(control.runIndex.owner), isNull(control.runIndex.seen), lt(control.runIndex.seen, new Date(Date.now() - RUNNER_STALE_MS)))))
213
- .orderBy(control.runIndex.createdAt)
245
+ .orderBy(inLineSince)
214
246
  .limit(1);
215
- return { runners, oldestWaiting: oldest?.createdAt ?? null };
247
+ return { runners, oldestWaiting: oldest ? (oldest.wokenAt ?? oldest.createdAt) : null };
216
248
  }
217
249
  export async function forgetRunner() {
218
250
  await controlDb.delete(control.runner).where(eq(control.runner.id, env.runner.id));
@@ -152,8 +152,9 @@ const EN = {
152
152
  shareMailboxLimit: "The attachments are too large for this mailbox (at most 3 MB). Choose fewer files or share the link.",
153
153
  shareVisitorRecipients: "From here, an email goes to at most {recipients} addresses.",
154
154
  shareGuestRecipient: "From here, an email goes only to the address you gave in the wizard or to the team’s own addresses.",
155
- shareGuestRunMails: "This run has sent its {mails} emails.",
156
- shareGuestDayMails: "This wizard has sent its emails for today. Try again tomorrow.",
155
+ shareGuestChannel: "From here, no message goes to a Slack channel.",
156
+ shareGuestRunMails: "This run has sent its {mails} emails and messages.",
157
+ shareGuestDayMails: "This wizard has sent its emails and messages for today. Try again tomorrow.",
157
158
  shareConnectMailbox: "Connect a mailbox first.",
158
159
  shareSendingFrom: "Sending from {account}",
159
160
  shareSentTo: "Sent to {to}",
@@ -378,8 +379,9 @@ const DE = {
378
379
  shareMailboxLimit: "Die Anhänge sind zu groß für dieses Postfach (höchstens 3 MB). Wähle weniger Dateien oder teile den Link.",
379
380
  shareVisitorRecipients: "Von hier geht eine E-Mail an höchstens {recipients} Adressen.",
380
381
  shareGuestRecipient: "Von hier geht eine E-Mail nur an die Adresse, die du im Wizard angegeben hast, oder an Adressen des Teams.",
381
- shareGuestRunMails: "Dieser Lauf hat seine {mails} E-Mails gesendet.",
382
- shareGuestDayMails: "Dieser Wizard hat seine E-Mails für heute gesendet. Versuch es morgen wieder.",
382
+ shareGuestChannel: "Von hier geht keine Nachricht in einen Slack-Kanal.",
383
+ shareGuestRunMails: "Dieser Lauf hat seine {mails} E-Mails und Nachrichten gesendet.",
384
+ shareGuestDayMails: "Dieser Wizard hat seine E-Mails und Nachrichten für heute gesendet. Versuch es morgen wieder.",
383
385
  shareConnectMailbox: "Verbinde zuerst ein Postfach.",
384
386
  shareSendingFrom: "Sendet von {account}",
385
387
  shareSentTo: "Gesendet an {to}",
@@ -8,7 +8,7 @@ import { stepCaller } from "../elements/caller.js";
8
8
  import { elementTools } from "../elements/catalogue.js";
9
9
  import { generateImageMedia } from "../media/generate.js";
10
10
  import { markMedia } from "../media/marking.js";
11
- import { gatewayTools, isHarnessVendor, searchAllowed } from "../models.js";
11
+ import { gatewayTools, isHarnessVendor, searchAllowed, toolAccess, } from "../models.js";
12
12
  import { prompt } from "../prompts.js";
13
13
  import { htmlToMarkdown } from "../render/convert.js";
14
14
  import { shellToolDescription } from "../sandbox/index.js";
@@ -24,6 +24,7 @@ import { pluginTools, spaceContextOf } from "./plugin.js";
24
24
  import { clip, FileKeeper } from "./shared.js";
25
25
  import { skillsOf } from "./skills.js";
26
26
  import { storeTools } from "./store.js";
27
+ import { gatewayWebSearch } from "./web-search.js";
27
28
  // A request to a host is a send to that host; the broker holds a guest's run to the hosts in its grant.
28
29
  reachesOutside("http_request", { connection: "host", action: "http_request", kind: "send" });
29
30
  /**
@@ -65,12 +66,11 @@ export async function buildStepTools(step, ctx, resolved, uploads) {
65
66
  const allowed = new Set(step.tools);
66
67
  // A tier without web search leaves the tool out; the builder says so before a run.
67
68
  if (allowed.has("web_search") && (await searchAllowed())) {
68
- // Anthropic models search natively; other models search through the AI Gateway's tool.
69
- if (resolved.vendor === "anthropic") {
70
- tools.web_search = anthropic.tools.webSearch_20250305({ maxUses: 8 });
71
- }
72
- else if (isHarnessVendor(resolved.vendor)) {
73
- // An installed client searches with its own tool; naming it here switches it on.
69
+ // An installed client searches with its own tool; naming it here switches it on. Else the
70
+ // gateway's search where it is reached, for every model alike; else Anthropic models search
71
+ // natively, other models through the AI Gateway's tool.
72
+ const access = isHarnessVendor(resolved.vendor) ? null : await toolAccess();
73
+ if (isHarnessVendor(resolved.vendor)) {
74
74
  tools.web_search = createTool({
75
75
  id: "web_search",
76
76
  description: prompt("tools", "tool.web_search"),
@@ -78,6 +78,12 @@ export async function buildStepTools(step, ctx, resolved, uploads) {
78
78
  execute: async () => ({ error: "The client searches itself." }),
79
79
  });
80
80
  }
81
+ else if (access) {
82
+ tools.web_search = gatewayWebSearch(access, { runId: ctx.runId });
83
+ }
84
+ else if (resolved.vendor === "anthropic") {
85
+ tools.web_search = anthropic.tools.webSearch_20250305({ maxUses: 8 });
86
+ }
81
87
  else if (resolved.gateway) {
82
88
  tools.web_search = gatewayTools.perplexitySearch({ maxResults: 8 });
83
89
  }