@engenty/wizards-runtime 0.14.2 → 0.16.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.
- package/apps/runtime/dist/agents/studio-assistant.js +180 -4
- package/apps/runtime/dist/agents/website.js +10 -5
- package/apps/runtime/dist/app.js +27 -2
- package/apps/runtime/dist/auth/index.js +5 -0
- package/apps/runtime/dist/broker/account.js +5 -0
- package/apps/runtime/dist/broker/call.js +2 -0
- package/apps/runtime/dist/broker/host.js +1 -0
- package/apps/runtime/dist/broker/index.js +5 -0
- package/apps/runtime/dist/broker/rwx.js +293 -11
- package/apps/runtime/dist/cli/main.js +7 -0
- package/apps/runtime/dist/cli/move-files.js +68 -0
- package/apps/runtime/dist/cli/move-folder-sources.js +120 -0
- package/apps/runtime/dist/connectors/plugin-connections.js +74 -4
- package/apps/runtime/dist/db/migrations/tenant/0040_rwx_elements.sql +21 -0
- package/apps/runtime/dist/db/migrations/tenant/0041_broker_log_client.sql +1 -0
- package/apps/runtime/dist/db/migrations/tenant/0042_client_spaces.sql +16 -0
- package/apps/runtime/dist/db/migrations/tenant/0043_space_member_invite.sql +19 -0
- package/apps/runtime/dist/db/migrations/tenant/0044_client_portal.sql +8 -0
- package/apps/runtime/dist/db/migrations/tenant/0045_client_portal_no_slug.sql +2 -0
- package/apps/runtime/dist/db/migrations/tenant/0046_space_file_hash.sql +2 -0
- package/apps/runtime/dist/db/migrations/tenant/0047_knowledge_folders.sql +3 -0
- package/apps/runtime/dist/db/migrations/tenant/0048_space_chunk_kind.sql +1 -0
- package/apps/runtime/dist/db/migrations/tenant/0049_knowledge_sources.sql +57 -0
- package/apps/runtime/dist/db/migrations/tenant/0050_dateien.sql +71 -0
- package/apps/runtime/dist/db/migrations/tenant/0051_dateien_drafts.sql +23 -0
- package/apps/runtime/dist/db/migrations/tenant/0052_dateien_plugin_kinds.sql +5 -0
- package/apps/runtime/dist/db/migrations/tenant/0053_dateien_file_title.sql +3 -0
- package/apps/runtime/dist/db/migrations/tenant/0054_dateien_ocr.sql +14 -0
- package/apps/runtime/dist/db/migrations/tenant/0055_dateien_doc_reread.sql +3 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0040_snapshot.json +5153 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0041_snapshot.json +5160 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0042_snapshot.json +5286 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0043_snapshot.json +5293 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0044_snapshot.json +5344 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0045_snapshot.json +5329 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0046_snapshot.json +5343 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0047_snapshot.json +5391 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0048_snapshot.json +5398 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0049_snapshot.json +5793 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0050_snapshot.json +6288 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0051_snapshot.json +6461 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0052_snapshot.json +6497 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0053_snapshot.json +6504 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0054_snapshot.json +6504 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0055_snapshot.json +6504 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +112 -0
- package/apps/runtime/dist/db/schema.js +296 -5
- package/apps/runtime/dist/docs/dev/api.md +49 -2
- package/apps/runtime/dist/docs/dev/architecture.md +13 -2
- package/apps/runtime/dist/docs/dev/plugins/connections.md +30 -2
- package/apps/runtime/dist/docs/dev/plugins/index.md +1 -1
- package/apps/runtime/dist/docs/dev/plugins/reference.md +7 -4
- package/apps/runtime/dist/docs/dev/plugins/server.md +11 -5
- package/apps/runtime/dist/docs/dev/plugins/space.md +130 -4
- package/apps/runtime/dist/docs/dev/plugins/studio.md +13 -3
- package/apps/runtime/dist/docs/user-guide/command-line.md +2 -0
- package/apps/runtime/dist/docs/user-guide/plugins.md +1 -1
- package/apps/runtime/dist/docs/user-guide/space.md +6 -6
- package/apps/runtime/dist/docs/user-guide/steps.md +1 -1
- package/apps/runtime/dist/documents/ocr.js +72 -0
- package/apps/runtime/dist/documents/parse.js +81 -12
- package/apps/runtime/dist/elements/caller.js +47 -0
- package/apps/runtime/dist/elements/catalogue.js +14 -0
- package/apps/runtime/dist/elements/connections.js +60 -0
- package/apps/runtime/dist/elements/gate.js +81 -0
- package/apps/runtime/dist/elements/knowledge.js +308 -0
- package/apps/runtime/dist/elements/outside.js +103 -0
- package/apps/runtime/dist/elements/specs.js +102 -0
- package/apps/runtime/dist/elements/wizards.js +72 -0
- package/apps/runtime/dist/engenty/connections-google/connectors/drive.js +3 -0
- package/apps/runtime/dist/engenty/connections-microsoft/onedrive.js +3 -0
- package/apps/runtime/dist/engenty/connections-s3/s3.js +6 -0
- package/apps/runtime/dist/engine/runner.js +19 -2
- package/apps/runtime/dist/engine/steps.js +1 -1
- package/apps/runtime/dist/env.js +11 -2
- package/apps/runtime/dist/files/blobs.js +57 -1
- package/apps/runtime/dist/files/objects.js +1 -0
- package/apps/runtime/dist/files/pictures.js +41 -0
- package/apps/runtime/dist/files/storage.js +14 -26
- package/apps/runtime/dist/files/thumbs.js +77 -0
- package/apps/runtime/dist/files/upload-check.js +2 -2
- package/apps/runtime/dist/index.js +22 -0
- package/apps/runtime/dist/live/views.js +2 -1
- package/apps/runtime/dist/manage.js +4 -1
- package/apps/runtime/dist/mcp/elements.js +88 -0
- package/apps/runtime/dist/mcp/handler.js +2 -0
- package/apps/runtime/dist/mcp/scopes.js +5 -0
- package/apps/runtime/dist/mcp/tools.js +5 -0
- package/apps/runtime/dist/models.js +82 -13
- package/apps/runtime/dist/mounts/cache.js +71 -0
- package/apps/runtime/dist/mounts/drafts.js +367 -0
- package/apps/runtime/dist/mounts/folder.js +148 -0
- package/apps/runtime/dist/mounts/mounts.js +1315 -0
- package/apps/runtime/dist/mounts/source.js +179 -0
- package/apps/runtime/dist/mounts/units.js +97 -0
- package/apps/runtime/dist/move-files.js +4 -0
- package/apps/runtime/dist/plugins/loader.js +73 -1
- package/apps/runtime/dist/plugins/registry.js +2 -0
- package/apps/runtime/dist/prompts/authoring.md +2 -2
- package/apps/runtime/dist/prompts/goose.md +13 -1
- package/apps/runtime/dist/prompts/tools.md +8 -2
- package/apps/runtime/dist/render/convert.js +188 -1
- package/apps/runtime/dist/routes/api.js +7 -2
- package/apps/runtime/dist/routes/client-contract.js +164 -0
- package/apps/runtime/dist/routes/client-spaces.js +58 -0
- package/apps/runtime/dist/routes/dateien.js +173 -0
- package/apps/runtime/dist/routes/elements.js +76 -0
- package/apps/runtime/dist/routes/plugins.js +2 -1
- package/apps/runtime/dist/routes/runs.js +24 -10
- package/apps/runtime/dist/routes/studio.js +168 -8
- package/apps/runtime/dist/secrets/signing.js +16 -0
- package/apps/runtime/dist/services/client-portal.js +439 -0
- package/apps/runtime/dist/services/client-spaces.js +228 -0
- package/apps/runtime/dist/services/cloud.js +2 -0
- package/apps/runtime/dist/services/knowledge-model.js +24 -8
- package/apps/runtime/dist/services/knowledge.js +72 -42
- package/apps/runtime/dist/services/links.js +17 -0
- package/apps/runtime/dist/services/members-studio.js +5 -1
- package/apps/runtime/dist/services/page-pictures.js +162 -0
- package/apps/runtime/dist/services/runs.js +22 -6
- package/apps/runtime/dist/services/space-categories.js +41 -5
- package/apps/runtime/dist/services/space-data.js +165 -8
- package/apps/runtime/dist/services/space-files.js +102 -19
- package/apps/runtime/dist/services/space-index.js +384 -41
- package/apps/runtime/dist/services/space-origin.js +25 -1
- package/apps/runtime/dist/services/space-sources.js +937 -0
- package/apps/runtime/dist/services/spaces.js +60 -12
- package/apps/runtime/dist/services/synced-spaces.js +10 -1
- package/apps/runtime/dist/services/work-ai.js +53 -24
- package/apps/runtime/dist/services/work-chats.js +3 -2
- package/apps/runtime/dist/services/work-connections.js +2 -2
- package/apps/runtime/dist/sharing/index.js +2 -0
- package/apps/runtime/dist/store/index.js +29 -8
- package/apps/runtime/dist/store/shared-lists.js +30 -17
- package/apps/runtime/dist/sync/records.js +22 -27
- package/apps/runtime/dist/texts.js +4 -0
- package/apps/runtime/dist/tools/index.js +5 -4
- package/apps/runtime/dist/tools/pages.js +1 -1
- package/apps/runtime/dist/tools/skills.js +80 -54
- package/apps/runtime/dist/tools/space.js +8 -152
- package/apps/runtime/dist/widgets/step.js +2 -1
- package/apps/web/dist/assets/AboutDialog-0q4P80yv.js +1 -0
- package/apps/web/dist/assets/BlockEditor-CUYFH_CU.js +173 -0
- package/apps/web/dist/assets/BlockEditor-CtW6lw0y.css +1 -0
- package/apps/web/dist/assets/CapabilitiesPage-BlZP8DYb.js +2 -0
- package/apps/web/dist/assets/{ChangelogDialog-D_dQOMIq.js → ChangelogDialog-CDN7kMs1.js} +1 -1
- package/apps/web/dist/assets/{CodeEditor-nxoOt8ge.js → CodeEditor-D-Y16fdk.js} +1 -1
- package/apps/web/dist/assets/EditorPage-CrMVsgUt.js +3 -0
- package/apps/web/dist/assets/{FlowPreview-aMfwcPul.js → FlowPreview-DXnk7m9P.js} +1 -1
- package/apps/web/dist/assets/{LangSwitch-DpD0inR4.js → LangSwitch-Dkd0FBIH.js} +1 -1
- package/apps/web/dist/assets/Marketplace-Cty40VwG.js +2 -0
- package/apps/web/dist/assets/NewWizardChannels-Czool7s1.js +1 -0
- package/apps/web/dist/assets/NewWizardPage-CfVe_4a2.js +7 -0
- package/apps/web/dist/assets/OnboardingPage-D3SEpTmt.js +1 -0
- package/apps/web/dist/assets/PreviewPane-CQDKQO6z.js +7 -0
- package/apps/web/dist/assets/PublicRunner-BDZNnlQw.js +1 -0
- package/apps/web/dist/assets/ReadOnly-B7MUySpC.js +1 -0
- package/apps/web/dist/assets/SettingsPage-Bgurv3l2.js +2 -0
- package/apps/web/dist/assets/SetupPage-C3km8vqv.js +1 -0
- package/apps/web/dist/assets/{SharePage-N80EhoD7.js → SharePage-UwEJBIzq.js} +1 -1
- package/apps/web/dist/assets/SkillEditor-BaEiqqXl.js +1 -0
- package/apps/web/dist/assets/Skills-Bv6XbKxc.js +9 -0
- package/apps/web/dist/assets/SpacePage-D9PXLSU_.js +2 -0
- package/apps/web/dist/assets/UpdateCheck-C7I43zFZ.js +2 -0
- package/apps/web/dist/assets/changelog-DwgWiSZb.js +1 -0
- package/apps/web/dist/assets/circle-check-DDLzlcXP.js +1 -0
- package/apps/web/dist/assets/code-DsnwzN1x.js +1 -0
- package/apps/web/dist/assets/code-editor-Ca5EAxmd.js +2 -0
- package/apps/web/dist/assets/code-xml-S4IFi5Jc.js +1 -0
- package/apps/web/dist/assets/connection-sign-in-hI3HXhq4.js +1 -0
- package/apps/web/dist/assets/{dist-H1UN89OA.js → dist-B3Ray2U5.js} +1 -1
- package/apps/web/dist/assets/dist-CQpLJoQZ.js +10 -0
- package/apps/web/dist/assets/{dist-GlRRx9Xl.js → dist-D1uGQ_tB.js} +1 -1
- package/apps/web/dist/assets/{dist-BdDd1FxP.js → dist-DFI-tsfx.js} +1 -1
- package/apps/web/dist/assets/eye-TJSuiHHO.js +1 -0
- package/apps/web/dist/assets/floating-ui.dom-pwdNGv4b.js +1 -0
- package/apps/web/dist/assets/host-D5hNHbhF.js +125 -0
- package/apps/web/dist/assets/i18n-BBzMbGoo.js +55 -0
- package/apps/web/dist/assets/index-CyBrvupM.js +10 -0
- package/apps/web/dist/assets/index-w-3J3ZJ9.css +1 -0
- package/apps/web/dist/assets/{json-CEsfHdlZ.js → json-Ce3iHrtf.js} +1 -1
- package/apps/web/dist/assets/link-CPL8pB1P.js +1 -0
- package/apps/web/dist/assets/list-checks-DaxmUPqK.js +1 -0
- package/apps/web/dist/assets/{markdown-5-I9_izp.js → markdown-hqKQy2pp.js} +1 -1
- package/apps/web/dist/assets/marked.esm-DQ7XA7AC.js +67 -0
- package/apps/web/dist/assets/oss-credits-BrwV0a4F.js +1 -0
- package/apps/web/dist/assets/pdf-Dg-raaUo.js +54 -0
- package/apps/web/dist/assets/pdf.worker.min-68CMzziE.js +1 -0
- package/apps/web/dist/assets/pdf.worker.min-CjEcRF4W.mjs +28 -0
- package/apps/web/dist/assets/phone-B4uKDBFq.js +1 -0
- package/apps/web/dist/assets/read-aloud-Bfp9_bUY.js +1 -0
- package/apps/web/dist/assets/{runners-CyIvJIHr.js → runners-CUpBpSji.js} +1 -1
- package/apps/web/dist/assets/scroll-text-BEnPzQEi.js +1 -0
- package/apps/web/dist/assets/session-CMQo8P-G.js +2 -0
- package/apps/web/dist/assets/table-5B9G3oA6.js +1 -0
- package/apps/web/dist/assets/theme-CdX0marK.js +11 -0
- package/apps/web/dist/assets/ui-BCfu5sia.js +16 -0
- package/apps/web/dist/assets/upload-CAlHC232.js +1 -0
- package/apps/web/dist/assets/{useMutation-DEkZhp5c.js → useMutation-1fV4Nnxq.js} +1 -1
- package/apps/web/dist/assets/viewers-ChriFcRy.js +2 -0
- package/apps/web/dist/assets/volume-2-BqlBtCIJ.js +1 -0
- package/apps/web/dist/assets/w3c-keyname-BOAvb0qz.js +1 -0
- package/apps/web/dist/assets/xlsx-CuSbHU4R.js +141 -0
- package/apps/web/dist/index.html +19 -14
- package/apps/web/dist/mcp/flow.html +2 -2
- package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +223 -4
- package/node_modules/@engenty/wizards/dist/plugin/mount.d.ts +123 -0
- package/node_modules/@engenty/wizards/dist/plugin/mount.js +7 -0
- package/node_modules/@engenty/wizards/dist/plugin/studio.d.ts +110 -1
- package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +1 -1
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +24 -0
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +24 -0
- package/node_modules/@engenty/wizards-shared/dist/knowledge.d.ts +33 -4
- package/node_modules/@engenty/wizards-shared/dist/run.d.ts +6 -0
- package/node_modules/@engenty/wizards-shared/dist/run.js +12 -0
- package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +21 -4
- package/node_modules/@engenty/wizards-shared/dist/rwx.js +30 -3
- package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +11 -1
- package/node_modules/@engenty/wizards-shared/dist/spaces.js +9 -2
- package/node_modules/@engenty/wizards-shared/dist/text-merge.d.ts +6 -0
- package/node_modules/@engenty/wizards-shared/dist/text-merge.js +25 -0
- package/package.json +3 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/README.md +3 -0
- package/plugin/plugin.json +1 -1
- package/plugin/skills/work-in-space/SKILL.md +16 -0
- package/apps/web/dist/assets/AboutDialog-Cag3RJuT.js +0 -1
- package/apps/web/dist/assets/CapabilitiesPage-BQYiN0gT.js +0 -2
- package/apps/web/dist/assets/EditorPage-C4_8LsQN.js +0 -3
- package/apps/web/dist/assets/Marketplace-CpzD9pNQ.js +0 -2
- package/apps/web/dist/assets/NewWizardChannels-CcE3UMVb.js +0 -1
- package/apps/web/dist/assets/NewWizardPage-BzN7zrQx.js +0 -7
- package/apps/web/dist/assets/OnboardingPage-ztHT01ah.js +0 -1
- package/apps/web/dist/assets/PreviewPane-BabMbBZI.js +0 -9
- package/apps/web/dist/assets/PublicRunner-D-JmtqCi.js +0 -1
- package/apps/web/dist/assets/ReadOnly-GAORKKqV.js +0 -1
- package/apps/web/dist/assets/SettingsPage-BKAiYmXl.js +0 -2
- package/apps/web/dist/assets/SetupPage-C1EZZHIp.js +0 -1
- package/apps/web/dist/assets/SkillEditor-CqQMg2MC.js +0 -1
- package/apps/web/dist/assets/Skills-CnhpgoOA.js +0 -9
- package/apps/web/dist/assets/SpacePage-CRR8JvV1.js +0 -2
- package/apps/web/dist/assets/UpdateCheck-CfXZBQNv.js +0 -2
- package/apps/web/dist/assets/changelog-6MqC8Vy8.js +0 -1
- package/apps/web/dist/assets/circle-alert-C8Ma-bPY.js +0 -1
- package/apps/web/dist/assets/circle-check-Bu9Z3mlJ.js +0 -1
- package/apps/web/dist/assets/code-editor-CfTGqOpp.js +0 -2
- package/apps/web/dist/assets/code-xml-B4kLFZSj.js +0 -1
- package/apps/web/dist/assets/connection-sign-in-B2D0O8W-.js +0 -1
- package/apps/web/dist/assets/dist-EBVTpvRr.js +0 -10
- package/apps/web/dist/assets/eye-BpoKpIdt.js +0 -1
- package/apps/web/dist/assets/host-BlKXX7YK.js +0 -118
- package/apps/web/dist/assets/i18n-BJ7Ld6O6.js +0 -55
- package/apps/web/dist/assets/index-66tE1oti.js +0 -10
- package/apps/web/dist/assets/index-D18DvnxX.css +0 -1
- package/apps/web/dist/assets/oss-credits-IdX5bc71.js +0 -1
- package/apps/web/dist/assets/phone-Ctvf-Am-.js +0 -1
- package/apps/web/dist/assets/read-aloud-Da_RSm2S.js +0 -1
- package/apps/web/dist/assets/scroll-text-ChrjRu9Y.js +0 -1
- package/apps/web/dist/assets/session-SXPtTWRK.js +0 -2
- package/apps/web/dist/assets/theme-Br1S0j5h.js +0 -11
- package/apps/web/dist/assets/ui-Uqnx1UpK.js +0 -82
- package/apps/web/dist/assets/upload-BchUnQGV.js +0 -1
- package/apps/web/dist/assets/volume-2-CU_oy81Z.js +0 -1
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { formatTableCell } from "@engenty/wizards-shared/engenty/data-tables";
|
|
2
|
+
import { featureOn } from "@engenty/wizards-shared/features";
|
|
2
3
|
import { embedMany } from "ai";
|
|
3
|
-
import { and, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm";
|
|
4
|
+
import { and, eq, inArray, isNotNull, isNull, ne, notInArray, or, sql, } from "drizzle-orm";
|
|
4
5
|
import { brokerOn, forbidden, pageResources, readable, readsEverything, tableResources, } from "../broker/rwx.js";
|
|
5
6
|
import { db, schema, withTenant } from "../db/client.js";
|
|
6
7
|
import { createSearchChunks } from "../engenty/search-index/chunks.js";
|
|
8
|
+
import { currentFeatures } from "../features.js";
|
|
7
9
|
import { getBlob, putBlob } from "../files/blobs.js";
|
|
10
|
+
import { jpegOf, MAX_PAGE_PICTURES, pdfPages } from "../files/pictures.js";
|
|
8
11
|
import { embeddingModel } from "../models.js";
|
|
12
|
+
import { unitTexts, usableMounts } from "../mounts/mounts.js";
|
|
9
13
|
import { pluginIdsOf } from "../plugins/registry.js";
|
|
10
14
|
import { currentTenant } from "../tenants/tenant.js";
|
|
11
15
|
import { ServiceError } from "./errors.js";
|
|
@@ -20,6 +24,11 @@ const SECTION_CHARS = 2400;
|
|
|
20
24
|
const PART_CHARS = 1800;
|
|
21
25
|
/** What the keywords and the vectors hand on to the classifier. */
|
|
22
26
|
const CANDIDATES = 24;
|
|
27
|
+
/**
|
|
28
|
+
* How far the nearest unit has to stand out from the median one to count (cosine), as peer-it
|
|
29
|
+
* has it: the nearest units are near even for a question the space knows nothing of.
|
|
30
|
+
*/
|
|
31
|
+
const MIN_LEAD = 0.08;
|
|
23
32
|
const vectorBytes = (v) => Buffer.from(new Float32Array(v).buffer);
|
|
24
33
|
async function embed(texts) {
|
|
25
34
|
const resolved = await embeddingModel();
|
|
@@ -39,9 +48,12 @@ export async function documentText(file) {
|
|
|
39
48
|
export async function keepText(text) {
|
|
40
49
|
return putBlob(Buffer.from(text, "utf8"));
|
|
41
50
|
}
|
|
51
|
+
/** A picture unit is the same picture while its kind, page and fingerprint (`ref`) are. */
|
|
52
|
+
const pictureKey = (u) => `${u.kind}|${u.sheet}|${u.ref}`;
|
|
42
53
|
/**
|
|
43
54
|
* Replaces the units `scope` held with `units`. A unit whose text has not changed keeps its
|
|
44
|
-
* vector: editing one row of a long table embeds one row.
|
|
55
|
+
* vector: editing one row of a long table embeds one row. A picture keeps its vector while it is
|
|
56
|
+
* the same picture; a new one gets it in the background (`queuePictures`).
|
|
45
57
|
*/
|
|
46
58
|
async function writeUnits(scope, units) {
|
|
47
59
|
const before = await db
|
|
@@ -49,14 +61,22 @@ async function writeUnits(scope, units) {
|
|
|
49
61
|
text: schema.spaceChunk.text,
|
|
50
62
|
embedding: schema.spaceChunk.embedding,
|
|
51
63
|
model: schema.spaceChunk.model,
|
|
64
|
+
kind: schema.spaceChunk.kind,
|
|
65
|
+
sheet: schema.spaceChunk.sheet,
|
|
66
|
+
ref: schema.spaceChunk.ref,
|
|
52
67
|
})
|
|
53
68
|
.from(schema.spaceChunk)
|
|
54
69
|
.where(scope);
|
|
55
70
|
const resolved = await embeddingModel().catch(() => null);
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const missing = [
|
|
71
|
+
const current = before.filter((b) => b.embedding && b.model && b.model === resolved?.ref);
|
|
72
|
+
const kept = new Map(current.filter((b) => !b.kind).map((b) => [b.text, b.embedding]));
|
|
73
|
+
const pictures = new Map(current.filter((b) => b.kind).map((b) => [pictureKey(b), b.embedding]));
|
|
74
|
+
const missing = [
|
|
75
|
+
...new Set(units
|
|
76
|
+
.filter((u) => !u.kind)
|
|
77
|
+
.map((u) => u.text)
|
|
78
|
+
.filter((t) => !kept.has(t))),
|
|
79
|
+
];
|
|
60
80
|
// Without an embedding model, or when it fails, the keywords still find the unit.
|
|
61
81
|
const embedded = await embed(missing).catch((err) => {
|
|
62
82
|
console.error("[space-index] embedding failed", err);
|
|
@@ -71,10 +91,17 @@ async function writeUnits(scope, units) {
|
|
|
71
91
|
await db.delete(schema.spaceChunk).where(scope);
|
|
72
92
|
for (let i = 0; i < units.length; i += 100) {
|
|
73
93
|
await db.insert(schema.spaceChunk).values(units.slice(i, i + 100).map((u) => {
|
|
94
|
+
if (u.kind) {
|
|
95
|
+
const vector = pictures.get(pictureKey(u)) ?? null;
|
|
96
|
+
return { ...u, embedding: vector, model: vector ? (resolved?.ref ?? null) : null };
|
|
97
|
+
}
|
|
74
98
|
const vector = kept.get(u.text) ?? null;
|
|
75
99
|
return { ...u, embedding: vector, model: vector ? model : null };
|
|
76
100
|
}));
|
|
77
101
|
}
|
|
102
|
+
if (units.some((u) => u.kind && !pictures.has(pictureKey(u)))) {
|
|
103
|
+
queuePictures();
|
|
104
|
+
}
|
|
78
105
|
}
|
|
79
106
|
const SHEET = /^\s*<!--\s*S\.\s*(\d+)\s*-->\s*$/;
|
|
80
107
|
/** A page's Markdown cut at its headings; the page marks of its original say where each starts. */
|
|
@@ -224,25 +251,85 @@ async function indexRows(tableId, rowIds) {
|
|
|
224
251
|
}
|
|
225
252
|
/** An image, video or sound among a space's assets: found by its name and description. */
|
|
226
253
|
const MEDIA_ASSET = /^(image|video|audio)\//;
|
|
227
|
-
/** Whether the index holds a file: a document,
|
|
254
|
+
/** Whether the index holds a file: a document, an image, video or sound asset, a page's picture. */
|
|
228
255
|
export function indexedFile(file) {
|
|
229
|
-
return file.kind === "document" ||
|
|
256
|
+
return (file.kind === "document" ||
|
|
257
|
+
file.kind === "picture" ||
|
|
258
|
+
(file.kind === "asset" && MEDIA_ASSET.test(file.mime)));
|
|
259
|
+
}
|
|
260
|
+
/** The pictures the embedding model is shown: what @napi-rs/canvas reads. */
|
|
261
|
+
const PICTURE = /^image\/(png|jpeg|webp|gif)$/;
|
|
262
|
+
/** Whether the index embeds a picture of this type as a picture, by what it shows. */
|
|
263
|
+
export async function seenAsPicture(mime) {
|
|
264
|
+
return PICTURE.test(mime) && Boolean((await embeddingModel().catch(() => null))?.embedImage);
|
|
230
265
|
}
|
|
231
|
-
/**
|
|
266
|
+
/**
|
|
267
|
+
* A file's units embedded as pictures, where the embedding model takes them: a picture file as
|
|
268
|
+
* one, a PDF's first MAX_PAGE_PICTURES pages one each. Their words are the file's name, the page
|
|
269
|
+
* and its categories. `ref` is the hash of the file's bytes: other bytes are another picture.
|
|
270
|
+
*/
|
|
271
|
+
async function pictureUnits(file, lines, from) {
|
|
272
|
+
const pdf = file.mime === "application/pdf";
|
|
273
|
+
if (!(file.hash && (PICTURE.test(file.mime) || pdf)) ||
|
|
274
|
+
!(await embeddingModel().catch(() => null))?.embedImage) {
|
|
275
|
+
return [];
|
|
276
|
+
}
|
|
277
|
+
const unit = { spaceId: file.spaceId, fileId: file.id, ref: file.hash };
|
|
278
|
+
if (!pdf) {
|
|
279
|
+
return [
|
|
280
|
+
{
|
|
281
|
+
...unit,
|
|
282
|
+
kind: "image",
|
|
283
|
+
heading: file.name,
|
|
284
|
+
idx: from,
|
|
285
|
+
text: head([file.name], ["picture", ...lines]),
|
|
286
|
+
},
|
|
287
|
+
];
|
|
288
|
+
}
|
|
289
|
+
// Pages the PDF does not have go when their pictures are made.
|
|
290
|
+
const pages = Math.min(file.pages ?? MAX_PAGE_PICTURES, MAX_PAGE_PICTURES);
|
|
291
|
+
return Array.from({ length: pages }, (_, i) => ({
|
|
292
|
+
...unit,
|
|
293
|
+
kind: "page",
|
|
294
|
+
heading: null,
|
|
295
|
+
sheet: i + 1,
|
|
296
|
+
idx: from + i,
|
|
297
|
+
text: head([file.name, `S. ${i + 1}`], lines),
|
|
298
|
+
}));
|
|
299
|
+
}
|
|
300
|
+
/** The page of the space that shows each picture of a page (`asset://ID` in its Markdown). */
|
|
301
|
+
async function pagesShowing(spaceId, fileIds) {
|
|
302
|
+
const out = new Map();
|
|
303
|
+
for (const id of fileIds) {
|
|
304
|
+
const page = await db.query.spacePage.findFirst({
|
|
305
|
+
where: and(eq(schema.spacePage.spaceId, spaceId), isNull(schema.spacePage.wizardId), sql `instr(${schema.spacePage.markdown}, ${`asset://${id}`}) > 0`),
|
|
306
|
+
columns: { id: true, title: true },
|
|
307
|
+
});
|
|
308
|
+
if (page) {
|
|
309
|
+
out.set(id, page);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return out;
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* An asset stands in the index as one unit: its name, its kind, its categories, its description.
|
|
316
|
+
* A page's picture as the picture of that page.
|
|
317
|
+
*/
|
|
232
318
|
async function indexAsset(file) {
|
|
233
319
|
const categories = await categoryRows(file.spaceId);
|
|
234
320
|
const lines = categoryLines(categories, (await itemCategoriesOf([{ fileId: file.id }])).get(`f:${file.id}`));
|
|
235
321
|
const kind = file.mime.split("/")[0];
|
|
322
|
+
const page = file.kind === "picture" ? (await pagesShowing(file.spaceId, [file.id])).get(file.id) : null;
|
|
323
|
+
const what = page ? `picture of the page "${page.title}"` : `${kind} asset`;
|
|
236
324
|
await writeUnits(eq(schema.spaceChunk.fileId, file.id), [
|
|
237
325
|
{
|
|
238
326
|
spaceId: file.spaceId,
|
|
239
327
|
fileId: file.id,
|
|
240
328
|
heading: file.name,
|
|
241
329
|
idx: 0,
|
|
242
|
-
text: [head([file.name], [
|
|
243
|
-
.filter(Boolean)
|
|
244
|
-
.join("\n\n"),
|
|
330
|
+
text: [head([file.name], [what, ...lines]), file.description].filter(Boolean).join("\n\n"),
|
|
245
331
|
},
|
|
332
|
+
...(await pictureUnits(file, lines, 1)),
|
|
246
333
|
]);
|
|
247
334
|
}
|
|
248
335
|
async function indexFile(fileId) {
|
|
@@ -250,7 +337,7 @@ async function indexFile(fileId) {
|
|
|
250
337
|
if (!(file && indexedFile(file) && file.status === "ready")) {
|
|
251
338
|
return;
|
|
252
339
|
}
|
|
253
|
-
if (file.kind === "asset") {
|
|
340
|
+
if (file.kind === "asset" || file.kind === "picture") {
|
|
254
341
|
return indexAsset(file);
|
|
255
342
|
}
|
|
256
343
|
const converted = (await db.query.spacePage.findFirst({
|
|
@@ -262,21 +349,22 @@ async function indexFile(fileId) {
|
|
|
262
349
|
columns: { id: true },
|
|
263
350
|
}));
|
|
264
351
|
const scope = eq(schema.spaceChunk.fileId, file.id);
|
|
352
|
+
const categories = await categoryRows(file.spaceId);
|
|
353
|
+
const lines = categoryLines(categories, (await itemCategoriesOf([{ fileId: file.id }])).get(`f:${file.id}`));
|
|
265
354
|
if (converted) {
|
|
266
|
-
// Its text is the page's now; the file stands behind it as the original
|
|
267
|
-
|
|
355
|
+
// Its text is the page's now; the file stands behind it as the original, found by its
|
|
356
|
+
// pictures where the embedding model takes them.
|
|
357
|
+
await writeUnits(scope, await pictureUnits(file, lines, 0));
|
|
268
358
|
return;
|
|
269
359
|
}
|
|
270
360
|
const passages = await db
|
|
271
|
-
.select({ heading: schema.spaceChunk.heading,
|
|
361
|
+
.select({ heading: schema.spaceChunk.heading, kind: schema.spaceChunk.kind })
|
|
272
362
|
.from(schema.spaceChunk)
|
|
273
363
|
.where(scope);
|
|
274
364
|
// Passages of a document read before Knowledge had pages stay until it is read again.
|
|
275
|
-
if (passages.some((p) => p.heading === null)) {
|
|
365
|
+
if (passages.some((p) => p.heading === null && !p.kind)) {
|
|
276
366
|
return;
|
|
277
367
|
}
|
|
278
|
-
const categories = await categoryRows(file.spaceId);
|
|
279
|
-
const lines = categoryLines(categories, (await itemCategoriesOf([{ fileId: file.id }])).get(`f:${file.id}`));
|
|
280
368
|
await writeUnits(scope, [
|
|
281
369
|
{
|
|
282
370
|
spaceId: file.spaceId,
|
|
@@ -285,6 +373,7 @@ async function indexFile(fileId) {
|
|
|
285
373
|
idx: 0,
|
|
286
374
|
text: [head([file.name], lines), file.description].filter(Boolean).join("\n\n"),
|
|
287
375
|
},
|
|
376
|
+
...(await pictureUnits(file, lines, 1)),
|
|
288
377
|
]);
|
|
289
378
|
}
|
|
290
379
|
async function indexValue(valueId) {
|
|
@@ -378,7 +467,7 @@ export function queueIndex(key) {
|
|
|
378
467
|
timer.unref?.();
|
|
379
468
|
waiting.set(id, { tenant, key, timer });
|
|
380
469
|
}
|
|
381
|
-
/** Indexes what waits now, and resolves when the index has caught up. */
|
|
470
|
+
/** Indexes what waits now, and resolves when the index has caught up, pictures included. */
|
|
382
471
|
export async function flushIndex() {
|
|
383
472
|
while (waiting.size) {
|
|
384
473
|
for (const [id, entry] of [...waiting]) {
|
|
@@ -389,6 +478,98 @@ export async function flushIndex() {
|
|
|
389
478
|
await working;
|
|
390
479
|
}
|
|
391
480
|
await working;
|
|
481
|
+
await picturesRunning;
|
|
482
|
+
}
|
|
483
|
+
// --- pictures -----------------------------------------------------------------------------
|
|
484
|
+
// 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) {
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
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));
|
|
500
|
+
}
|
|
501
|
+
})().finally(() => {
|
|
502
|
+
picturesRunning = null;
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
/** The pictures of the bytes `hash`, by page (0: a picture file itself), made when asked for. */
|
|
506
|
+
async function picturesOf(hash, pdf) {
|
|
507
|
+
const data = hash ? await getBlob(hash).catch(() => null) : null;
|
|
508
|
+
if (!data) {
|
|
509
|
+
return new Map();
|
|
510
|
+
}
|
|
511
|
+
return pdf
|
|
512
|
+
? new Map((await pdfPages(data)).map((p) => [p.page, p.jpeg]))
|
|
513
|
+
: new Map([[0, await jpegOf(data)]]);
|
|
514
|
+
}
|
|
515
|
+
async function embedPictures() {
|
|
516
|
+
const resolved = await embeddingModel().catch(() => null);
|
|
517
|
+
const embedImage = resolved?.embedImage;
|
|
518
|
+
if (!(resolved && embedImage)) {
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
const failed = new Set();
|
|
522
|
+
let inRow = 0;
|
|
523
|
+
const started = Date.now();
|
|
524
|
+
let done = 0;
|
|
525
|
+
for (;;) {
|
|
526
|
+
const todo = await db
|
|
527
|
+
.select({
|
|
528
|
+
id: schema.spaceChunk.id,
|
|
529
|
+
fileId: schema.spaceChunk.fileId,
|
|
530
|
+
kind: schema.spaceChunk.kind,
|
|
531
|
+
sheet: schema.spaceChunk.sheet,
|
|
532
|
+
ref: schema.spaceChunk.ref,
|
|
533
|
+
})
|
|
534
|
+
.from(schema.spaceChunk)
|
|
535
|
+
.where(and(isNotNull(schema.spaceChunk.kind), isNotNull(schema.spaceChunk.fileId), or(isNull(schema.spaceChunk.model), ne(schema.spaceChunk.model, resolved.ref)), failed.size ? notInArray(schema.spaceChunk.fileId, [...failed]) : undefined))
|
|
536
|
+
.limit(MAX_PAGE_PICTURES);
|
|
537
|
+
const fileId = todo[0]?.fileId;
|
|
538
|
+
if (!fileId) {
|
|
539
|
+
break;
|
|
540
|
+
}
|
|
541
|
+
const units = todo.filter((u) => u.fileId === fileId);
|
|
542
|
+
try {
|
|
543
|
+
const pictures = await picturesOf(units[0].ref, units[0].kind === "page");
|
|
544
|
+
for (const u of units) {
|
|
545
|
+
const jpeg = pictures.get(u.kind === "page" ? (u.sheet ?? 0) : 0);
|
|
546
|
+
const which = and(eq(schema.spaceChunk.id, u.id), u.ref === null ? isNull(schema.spaceChunk.ref) : eq(schema.spaceChunk.ref, u.ref));
|
|
547
|
+
if (!jpeg) {
|
|
548
|
+
// A page the PDF does not have, or a file that is gone.
|
|
549
|
+
await db.delete(schema.spaceChunk).where(which);
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
const vector = await embedImage(jpeg);
|
|
553
|
+
await db
|
|
554
|
+
.update(schema.spaceChunk)
|
|
555
|
+
.set({ embedding: vectorBytes(vector), model: resolved.ref })
|
|
556
|
+
.where(which);
|
|
557
|
+
done++;
|
|
558
|
+
}
|
|
559
|
+
inRow = 0;
|
|
560
|
+
}
|
|
561
|
+
catch (err) {
|
|
562
|
+
console.error("[space-index] picture", fileId, err);
|
|
563
|
+
failed.add(fileId);
|
|
564
|
+
// The model is not there or not working: the next start, or the next picture, tries again.
|
|
565
|
+
if (++inRow >= 3) {
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
if (done) {
|
|
571
|
+
console.log(`[space-index] embedded ${done} pictures with ${resolved.ref} in ${Math.round((Date.now() - started) / 1000)} s`);
|
|
572
|
+
}
|
|
392
573
|
}
|
|
393
574
|
// --- plugins' texts ---------------------------------------------------------------------
|
|
394
575
|
/** Puts a plugin's text into the space's index, in the place of what its key held. */
|
|
@@ -449,7 +630,11 @@ export function trigramQuery(query) {
|
|
|
449
630
|
const terms = [...new Set([...codes, ...words])].map((t) => `"${t.replace(/"/g, "")}"`);
|
|
450
631
|
return terms.length ? terms.join(" OR ") : null;
|
|
451
632
|
}
|
|
452
|
-
const COLUMNS = sql.raw(
|
|
633
|
+
const COLUMNS = sql.raw('c.id, c.file_id, c.page_id, c.row_id, c.table_id, c.value_id, c.heading, c.sheet, c.plugin, c.ref, c.title, c.link, c.idx, c.text, c.kind, NULL AS mount_file_id, NULL AS start, NULL AS "end"');
|
|
634
|
+
/** A mounted file's unit as a `Found`: its text is read from the original for the first hits. */
|
|
635
|
+
const MOUNT_COLUMNS = sql.raw("u.id, NULL AS file_id, NULL AS page_id, NULL AS row_id, NULL AS table_id, NULL AS value_id, u.heading, u.sheet, NULL AS plugin, NULL AS ref, NULL AS title, NULL AS link, u.idx, '' AS text, u.kind, u.file_id AS mount_file_id, u.start, u.\"end\"");
|
|
636
|
+
/** Units of the space's index and of its mounts have ids of their own. */
|
|
637
|
+
const unitKey = (u) => (u.mount_file_id ? `m${u.id}` : `c${u.id}`);
|
|
453
638
|
/** A unit of the space's own Knowledge, or of a plugin's text while the tenant has that plugin. */
|
|
454
639
|
function searchable(plugins) {
|
|
455
640
|
return plugins.length
|
|
@@ -472,11 +657,15 @@ function filtered(f) {
|
|
|
472
657
|
.map(([column, s]) => sql `${sql.raw(column)} IN (${sql.join([...s].map((id) => sql `${id}`), sql `, `)})`);
|
|
473
658
|
return parts.length ? sql `(${sql.join(parts, sql ` OR `)})` : sql `0`;
|
|
474
659
|
}
|
|
475
|
-
const leaves = (f, u) => (u.
|
|
660
|
+
const leaves = (f, u) => (u.mount_file_id !== null && f.mounted.has(u.mount_file_id)) ||
|
|
661
|
+
(u.page_id !== null && f.pages.has(u.page_id)) ||
|
|
476
662
|
(u.row_id !== null && f.rows.has(u.row_id)) ||
|
|
477
663
|
(u.file_id !== null && f.files.has(u.file_id));
|
|
478
664
|
/** The key of the item a unit belongs to: hits are grouped by it. */
|
|
479
665
|
function itemOf(u) {
|
|
666
|
+
if (u.mount_file_id) {
|
|
667
|
+
return `m:${u.mount_file_id}`;
|
|
668
|
+
}
|
|
480
669
|
if (u.page_id) {
|
|
481
670
|
return `p:${u.page_id}`;
|
|
482
671
|
}
|
|
@@ -510,6 +699,10 @@ async function readableUnits(spaceId, who, units) {
|
|
|
510
699
|
readsEverything(spaceId, who),
|
|
511
700
|
]);
|
|
512
701
|
return (u) => {
|
|
702
|
+
// A mount's units are searched only where the caller may use the mount.
|
|
703
|
+
if (u.mount_file_id) {
|
|
704
|
+
return true;
|
|
705
|
+
}
|
|
513
706
|
if (u.page_id) {
|
|
514
707
|
return pages.has(u.page_id);
|
|
515
708
|
}
|
|
@@ -540,7 +733,7 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
|
|
|
540
733
|
}
|
|
541
734
|
const filter = await filterItems(spaceId, opts.where);
|
|
542
735
|
if (filter && !filter.size) {
|
|
543
|
-
return { hits: [], candidates: 0, checked: false, filtered: 0 };
|
|
736
|
+
return { hits: [], candidates: 0, checked: false, filtered: 0, hidden: [] };
|
|
544
737
|
}
|
|
545
738
|
const plugins = [...(await pluginIdsOf(currentTenant()))];
|
|
546
739
|
const inFilter = filter ? filtered(filter) : null;
|
|
@@ -569,10 +762,37 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
|
|
|
569
762
|
}
|
|
570
763
|
const embedded = await embed([query]).catch(() => null);
|
|
571
764
|
if (embedded) {
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
765
|
+
const question = vectorBytes(embedded.vectors[0]);
|
|
766
|
+
lists.push(featureOn(await currentFeatures(), "knowledgeMedia")
|
|
767
|
+
? await byMeaning(CHUNKS, where, embedded.model, question, take)
|
|
768
|
+
: await db.all(sql `
|
|
769
|
+
SELECT ${COLUMNS} FROM space_chunk c
|
|
770
|
+
WHERE ${where} AND c.model = ${embedded.model}
|
|
771
|
+
ORDER BY vector_distance_cos(c.embedding, ${question}) LIMIT ${take}`));
|
|
772
|
+
}
|
|
773
|
+
// The mounts of Dateien the caller may use: their words and their vectors, beside Knowledge's.
|
|
774
|
+
const mounts = await usableMounts(spaceId, opts.who ?? []);
|
|
775
|
+
const mounted = filter ? [...filter.mounted] : null;
|
|
776
|
+
if (mounts.length && !(mounted && !mounted.length)) {
|
|
777
|
+
const inMounts = and(sql `u.mount_id IN (${sql.join(mounts.map((m) => sql `${m.id}`), sql `, `)})`, mounted && mounted.length <= IN_LIMIT
|
|
778
|
+
? sql `u.file_id IN (${sql.join(mounted.map((id) => sql `${id}`), sql `, `)})`
|
|
779
|
+
: undefined);
|
|
780
|
+
for (const [table, q] of [
|
|
781
|
+
["space_mount_unit_fts", words],
|
|
782
|
+
["space_mount_unit_tri", grams],
|
|
783
|
+
]) {
|
|
784
|
+
if (q) {
|
|
785
|
+
lists.push(await db
|
|
786
|
+
.all(sql `
|
|
787
|
+
SELECT ${MOUNT_COLUMNS} FROM ${sql.raw(table)} f JOIN space_mount_unit u ON u.id = f.rowid
|
|
788
|
+
WHERE ${sql.raw(table)} MATCH ${q} AND ${inMounts}
|
|
789
|
+
ORDER BY bm25(${sql.raw(table)}) LIMIT ${take}`)
|
|
790
|
+
.catch(() => []));
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
if (embedded) {
|
|
794
|
+
lists.push(await byMeaning(MOUNT_UNITS, inMounts, embedded.model, vectorBytes(embedded.vectors[0]), take));
|
|
795
|
+
}
|
|
576
796
|
}
|
|
577
797
|
const allowed = await readableUnits(spaceId, opts.who ?? [], lists.flat());
|
|
578
798
|
// Reciprocal rank fusion: a unit the lists rank high comes first.
|
|
@@ -583,31 +803,41 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
|
|
|
583
803
|
.filter((u) => !allowed || allowed(u))
|
|
584
804
|
.slice(0, CANDIDATES)
|
|
585
805
|
.forEach((unit, rank) => {
|
|
586
|
-
const entry = scored.get(unit
|
|
806
|
+
const entry = scored.get(unitKey(unit)) ?? { unit, score: 0 };
|
|
587
807
|
entry.score += 1 / (60 + rank);
|
|
588
|
-
scored.set(unit
|
|
808
|
+
scored.set(unitKey(unit), entry);
|
|
589
809
|
});
|
|
590
810
|
}
|
|
591
811
|
const candidates = [...scored.values()].sort((a, b) => b.score - a.score).slice(0, CANDIDATES);
|
|
592
812
|
if (!candidates.length) {
|
|
593
|
-
return { hits: [], candidates: 0, checked: false, filtered: filter?.size ?? null };
|
|
813
|
+
return { hits: [], candidates: 0, checked: false, filtered: filter?.size ?? null, hidden: [] };
|
|
594
814
|
}
|
|
595
|
-
const described = await describe(spaceId, candidates.map((c) => c.unit));
|
|
596
|
-
|
|
815
|
+
const described = await describe(spaceId, candidates.map((c) => c.unit), mounts);
|
|
816
|
+
// The classifier reads text; a picture, found by what it shows, keeps its place.
|
|
817
|
+
const read = described.filter((d) => !d.picture);
|
|
818
|
+
const scores = opts.check === false || !read.length
|
|
597
819
|
? null
|
|
598
|
-
: await judgeRelevance(query,
|
|
820
|
+
: await judgeRelevance(query, read.map((d) => ({
|
|
599
821
|
title: d.title,
|
|
600
822
|
path: d.path,
|
|
601
823
|
categories: d.categories,
|
|
602
824
|
heading: d.heading,
|
|
603
825
|
text: d.text,
|
|
604
826
|
})), opts.signal);
|
|
605
|
-
const
|
|
827
|
+
const judged = scores
|
|
828
|
+
? described.map((d) => (d.picture ? null : (scores[read.indexOf(d)] ?? null)))
|
|
829
|
+
: null;
|
|
830
|
+
const kept = described
|
|
606
831
|
.map((hit, i) => ({ hit: { ...hit, relevance: judged?.[i] ?? null }, rank: i }))
|
|
607
|
-
.filter(({ hit }) => hit.relevance === null || hit.relevance >= MIN_RELEVANCE)
|
|
832
|
+
.filter(({ hit }) => hit.relevance === null || hit.relevance >= MIN_RELEVANCE);
|
|
833
|
+
// The texts in the classifier's order, in the places texts held; pictures stay where they are.
|
|
834
|
+
const texts = kept
|
|
835
|
+
.filter(({ hit }) => !hit.picture)
|
|
608
836
|
.sort((a, b) => judged
|
|
609
837
|
? (b.hit.relevance ?? MIN_RELEVANCE) - (a.hit.relevance ?? MIN_RELEVANCE) || a.rank - b.rank
|
|
610
838
|
: a.rank - b.rank);
|
|
839
|
+
let next = 0;
|
|
840
|
+
const ranked = kept.map((k) => (k.hit.picture ? k : texts[next++]));
|
|
611
841
|
// One hit per item: its best section.
|
|
612
842
|
const seen = new Set();
|
|
613
843
|
const hits = [];
|
|
@@ -621,21 +851,86 @@ export async function searchKnowledge(spaceId, query, opts = {}) {
|
|
|
621
851
|
break;
|
|
622
852
|
}
|
|
623
853
|
}
|
|
854
|
+
// What the classifier put under the bar, best first: one hit per item not among the hits.
|
|
855
|
+
const hidden = [];
|
|
856
|
+
if (judged) {
|
|
857
|
+
const under = described
|
|
858
|
+
.map((hit, i) => ({ ...hit, relevance: judged[i] ?? null }))
|
|
859
|
+
.filter((hit) => hit.relevance !== null && hit.relevance < MIN_RELEVANCE)
|
|
860
|
+
.sort((a, b) => (b.relevance ?? 0) - (a.relevance ?? 0));
|
|
861
|
+
for (const hit of under) {
|
|
862
|
+
if (!seen.has(hit.key)) {
|
|
863
|
+
seen.add(hit.key);
|
|
864
|
+
hidden.push(hit);
|
|
865
|
+
}
|
|
866
|
+
if (hidden.length >= limit) {
|
|
867
|
+
break;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
624
871
|
return {
|
|
625
872
|
hits,
|
|
626
873
|
candidates: candidates.length,
|
|
627
874
|
checked: judged !== null,
|
|
628
875
|
filtered: filter?.size ?? null,
|
|
876
|
+
hidden,
|
|
629
877
|
};
|
|
630
878
|
}
|
|
879
|
+
/** Where `byMeaning` looks: Knowledge's units, or the mounts'. */
|
|
880
|
+
const CHUNKS = { from: sql.raw("space_chunk c"), alias: sql.raw("c"), columns: COLUMNS };
|
|
881
|
+
const MOUNT_UNITS = {
|
|
882
|
+
from: sql.raw("space_mount_unit u"),
|
|
883
|
+
alias: sql.raw("u"),
|
|
884
|
+
columns: MOUNT_COLUMNS,
|
|
885
|
+
};
|
|
886
|
+
/**
|
|
887
|
+
* The units nearest the question by meaning, where the nearest stand out: the best has to lead
|
|
888
|
+
* the median unit by MIN_LEAD, and a unit counts from halfway between them up. Else none.
|
|
889
|
+
*/
|
|
890
|
+
async function byMeaning(of, where, model, question, take) {
|
|
891
|
+
const near = await db.all(sql `
|
|
892
|
+
SELECT ${of.alias}.id, vector_distance_cos(${of.alias}.embedding, ${question}) AS d
|
|
893
|
+
FROM ${of.from} WHERE ${where} AND ${of.alias}.model = ${model} ORDER BY d`);
|
|
894
|
+
// Distances: 1 - cosine.
|
|
895
|
+
const top = 1 - (near[0]?.d ?? 1);
|
|
896
|
+
const median = 1 - (near[Math.floor(near.length / 2)]?.d ?? 1);
|
|
897
|
+
if (top - median < MIN_LEAD) {
|
|
898
|
+
return [];
|
|
899
|
+
}
|
|
900
|
+
const ids = near
|
|
901
|
+
.filter((n) => 1 - n.d >= median + (top - median) / 2)
|
|
902
|
+
.slice(0, take)
|
|
903
|
+
.map((n) => n.id);
|
|
904
|
+
const rows = await db.all(sql `
|
|
905
|
+
SELECT ${of.columns} FROM ${of.from} WHERE ${of.alias}.id IN (${sql.join(ids.map((id) => sql `${id}`), sql `, `)})`);
|
|
906
|
+
const byId = new Map(rows.map((r) => [r.id, r]));
|
|
907
|
+
return ids.flatMap((id) => (byId.has(id) ? [byId.get(id)] : []));
|
|
908
|
+
}
|
|
631
909
|
/** What a step and the studio see of each unit: the item's path, title and categories. */
|
|
632
|
-
async function describe(spaceId, units) {
|
|
910
|
+
async function describe(spaceId, units, mounts = []) {
|
|
633
911
|
const pageIds = [...new Set(units.flatMap((u) => (u.page_id ? [u.page_id] : [])))];
|
|
634
912
|
const rowIds = [...new Set(units.flatMap((u) => (u.row_id ? [u.row_id] : [])))];
|
|
635
913
|
const fileIds = [...new Set(units.flatMap((u) => (u.file_id ? [u.file_id] : [])))];
|
|
636
914
|
const valueIds = [...new Set(units.flatMap((u) => (u.value_id ? [u.value_id] : [])))];
|
|
915
|
+
const mountFileIds = [
|
|
916
|
+
...new Set(units.flatMap((u) => (u.mount_file_id ? [u.mount_file_id] : []))),
|
|
917
|
+
];
|
|
918
|
+
const mountFiles = mountFileIds.length
|
|
919
|
+
? await db.query.spaceMountFile.findMany({
|
|
920
|
+
where: inArray(schema.spaceMountFile.id, mountFileIds),
|
|
921
|
+
columns: { id: true, mountId: true, path: true, name: true },
|
|
922
|
+
})
|
|
923
|
+
: [];
|
|
924
|
+
// A mounted file keeps no text: the passages found are read from the original (cache.ts).
|
|
925
|
+
const mountUnits = units.filter((u) => u.mount_file_id && !u.kind);
|
|
926
|
+
const mountTexts = new Map((await unitTexts(mountUnits.map((u) => ({
|
|
927
|
+
fileId: u.mount_file_id,
|
|
928
|
+
heading: u.heading,
|
|
929
|
+
start: u.start,
|
|
930
|
+
end: u.end,
|
|
931
|
+
})))).map((text, i) => [unitKey(mountUnits[i]), text]));
|
|
637
932
|
const [tree, tPaths, fPaths, categories, rows, files, values] = await Promise.all([
|
|
638
|
-
pageIds.length ? pageTree(spaceId) : new Map(),
|
|
933
|
+
pageIds.length || fileIds.length ? pageTree(spaceId) : new Map(),
|
|
639
934
|
rowIds.length ? tablePaths(spaceId) : new Map(),
|
|
640
935
|
fileIds.length ? filePaths(spaceId) : new Map(),
|
|
641
936
|
categoryRows(spaceId),
|
|
@@ -648,7 +943,7 @@ async function describe(spaceId, units) {
|
|
|
648
943
|
fileIds.length
|
|
649
944
|
? db.query.spaceFile.findMany({
|
|
650
945
|
where: inArray(schema.spaceFile.id, fileIds),
|
|
651
|
-
columns: { id: true, name: true },
|
|
946
|
+
columns: { id: true, name: true, kind: true, description: true },
|
|
652
947
|
})
|
|
653
948
|
: [],
|
|
654
949
|
valueIds.length
|
|
@@ -664,11 +959,13 @@ async function describe(spaceId, units) {
|
|
|
664
959
|
columns: { id: true, title: true },
|
|
665
960
|
})
|
|
666
961
|
: [];
|
|
962
|
+
const showing = await pagesShowing(spaceId, files.filter((f) => f.kind === "picture").map((f) => f.id));
|
|
667
963
|
const cats = await itemCategoriesOf([
|
|
668
964
|
...pageIds.map((pageId) => ({ pageId })),
|
|
669
965
|
...rowIds.map((rowId) => ({ rowId })),
|
|
670
966
|
...tableIds.map((tableId) => ({ tableId })),
|
|
671
967
|
...fileIds.map((fileId) => ({ fileId })),
|
|
968
|
+
...mountFileIds.map((mountFileId) => ({ mountFileId })),
|
|
672
969
|
]);
|
|
673
970
|
// The unit's text without the head it was indexed with: the step gets that as fields.
|
|
674
971
|
const bodyOf = (u) => {
|
|
@@ -689,7 +986,23 @@ async function describe(spaceId, units) {
|
|
|
689
986
|
relevance: null,
|
|
690
987
|
link: u.link,
|
|
691
988
|
plugin: u.plugin,
|
|
989
|
+
...(u.kind ? { picture: u.kind } : {}),
|
|
692
990
|
};
|
|
991
|
+
if (u.mount_file_id) {
|
|
992
|
+
const file = mountFiles.find((f) => f.id === u.mount_file_id);
|
|
993
|
+
const mount = mounts.find((m) => m.id === file?.mountId);
|
|
994
|
+
return {
|
|
995
|
+
...base,
|
|
996
|
+
kind: "mounted",
|
|
997
|
+
open: `m:${u.mount_file_id}`,
|
|
998
|
+
path: file && mount ? `dateien/${mount.slug}/${file.path}` : "",
|
|
999
|
+
title: file?.name ?? "",
|
|
1000
|
+
// Its headings are a field of their own, as a page's are.
|
|
1001
|
+
text: (mountTexts.get(unitKey(u)) ?? "").replace(/^## [^\n]*\n\n/, ""),
|
|
1002
|
+
categories: categoryLines(categories, cats.get(`m:${u.mount_file_id}`)),
|
|
1003
|
+
...(mount ? { mount: { id: mount.id, name: mount.name } } : {}),
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
693
1006
|
if (u.page_id) {
|
|
694
1007
|
const node = tree.get(u.page_id);
|
|
695
1008
|
return {
|
|
@@ -727,6 +1040,20 @@ async function describe(spaceId, units) {
|
|
|
727
1040
|
categories: [],
|
|
728
1041
|
};
|
|
729
1042
|
}
|
|
1043
|
+
const shownOn = u.file_id ? showing.get(u.file_id) : undefined;
|
|
1044
|
+
if (u.file_id && shownOn) {
|
|
1045
|
+
// A page's picture opens its page; it is a picture however it was found.
|
|
1046
|
+
const file = files.find((f) => f.id === u.file_id);
|
|
1047
|
+
return {
|
|
1048
|
+
...base,
|
|
1049
|
+
kind: "file",
|
|
1050
|
+
open: `p:${shownOn.id}`,
|
|
1051
|
+
path: tree.get(shownOn.id)?.path ?? "",
|
|
1052
|
+
title: file?.description.split("\n")[0] || shownOn.title,
|
|
1053
|
+
categories: categoryLines(categories, cats.get(`f:${u.file_id}`)),
|
|
1054
|
+
picture: "image",
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
730
1057
|
if (u.file_id) {
|
|
731
1058
|
return {
|
|
732
1059
|
...base,
|
|
@@ -752,7 +1079,7 @@ export async function reindexSpace(spaceId) {
|
|
|
752
1079
|
columns: { id: true },
|
|
753
1080
|
}),
|
|
754
1081
|
db.query.spaceFile.findMany({
|
|
755
|
-
where: and(eq(schema.spaceFile.spaceId, spaceId), inArray(schema.spaceFile.kind, ["document", "asset"])),
|
|
1082
|
+
where: and(eq(schema.spaceFile.spaceId, spaceId), inArray(schema.spaceFile.kind, ["document", "asset", "picture"])),
|
|
756
1083
|
columns: { id: true, kind: true, mime: true },
|
|
757
1084
|
}),
|
|
758
1085
|
db
|
|
@@ -781,13 +1108,29 @@ export async function reindexAll() {
|
|
|
781
1108
|
await reindexSpace(p.id);
|
|
782
1109
|
}
|
|
783
1110
|
}
|
|
784
|
-
/**
|
|
1111
|
+
/**
|
|
1112
|
+
* 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.
|
|
1115
|
+
*/
|
|
785
1116
|
export async function indexMissingAssets() {
|
|
786
1117
|
const rows = await db.all(sql `
|
|
787
1118
|
SELECT f.id, f.kind, f.mime FROM space_file f
|
|
788
|
-
WHERE f.kind
|
|
1119
|
+
WHERE f.kind IN ('asset', 'picture') AND f.status = 'ready'
|
|
789
1120
|
AND NOT EXISTS (SELECT 1 FROM space_chunk c WHERE c.file_id = f.id)`);
|
|
790
1121
|
for (const row of rows.filter(indexedFile)) {
|
|
791
1122
|
queueIndex(`f:${row.id}`);
|
|
792
1123
|
}
|
|
1124
|
+
if (!(await embeddingModel().catch(() => null))?.embedImage) {
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
const unseen = await db.all(sql `
|
|
1128
|
+
SELECT f.id, f.kind, f.mime FROM space_file f
|
|
1129
|
+
WHERE f.kind IN ('asset', 'document', 'picture') AND f.status = 'ready' AND f.hash IS NOT NULL
|
|
1130
|
+
AND (f.mime IN ('image/png', 'image/jpeg', 'image/webp', 'image/gif', 'application/pdf'))
|
|
1131
|
+
AND NOT EXISTS (SELECT 1 FROM space_chunk c WHERE c.file_id = f.id AND c.kind IS NOT NULL)`);
|
|
1132
|
+
for (const row of unseen.filter(indexedFile)) {
|
|
1133
|
+
queueIndex(`f:${row.id}`);
|
|
1134
|
+
}
|
|
1135
|
+
queuePictures();
|
|
793
1136
|
}
|