limixbot 0.3.145 → 0.3.146
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/dist/assets/{ActivityPanel-CqObZQbN.js → ActivityPanel-DTqdgF9v.js} +1 -1
- package/dist/assets/{App-DcG1JmK6.js → App-FkCoivKo.js} +102 -102
- package/dist/assets/{AppEventEditor-DR01sHAK.js → AppEventEditor-hBLRTJCh.js} +1 -1
- package/dist/assets/{BotSettingsDialog-BHgSIU9E.js → BotSettingsDialog-0CLALU4h.js} +1 -1
- package/dist/assets/{BrowserPanel-g96rlnqQ.js → BrowserPanel-BjqIxdsD.js} +1 -1
- package/dist/assets/{BrowserProfilesManager-UJJC6OPf.js → BrowserProfilesManager-C2DEX5Dz.js} +1 -1
- package/dist/assets/{CloudAddDialog-BjPYPhnk.js → CloudAddDialog-Ce6eiErj.js} +1 -1
- package/dist/assets/{ComputerFilesPane-DA7MBSD0.js → ComputerFilesPane-CUls-HDE.js} +1 -1
- package/dist/assets/{ComputerPanel--rY7_KCN.js → ComputerPanel-CY6rmF7p.js} +2 -2
- package/dist/assets/{DataPanel-CEhe1WKo.js → DataPanel-BMItjksI.js} +1 -1
- package/dist/assets/{DesktopViewer-RNuariIo.js → DesktopViewer-uyCSG2he.js} +1 -1
- package/dist/assets/{GrokMoveDialog-DoUN6m5b.js → GrokMoveDialog-BjIt7fo_.js} +1 -1
- package/dist/assets/{InspectorPanel-CdCXUouJ.js → InspectorPanel-Be9J8vTL.js} +1 -1
- package/dist/assets/{KeyboardShortcutsModal-CZ-BQqzV.js → KeyboardShortcutsModal-CJhaJp59.js} +1 -1
- package/dist/assets/KnowledgePanel-BsdqL7-z.js +1 -0
- package/dist/assets/{LimixResizeHandles-BUe_6hSJ.js → LimixResizeHandles-DKdU_JFS.js} +1 -1
- package/dist/assets/{LiveDesktop-BnaxuTzU.js → LiveDesktop-QudEVPsj.js} +1 -1
- package/dist/assets/{LocalVmWorkspace-X1ev9Wov.js → LocalVmWorkspace-Cs2BgRNV.js} +1 -1
- package/dist/assets/{MacLocalControl-RXW-1ET9.js → MacLocalControl-Cq3ZxYZY.js} +1 -1
- package/dist/assets/{MarkdownFilePreview-CIYTKbNj.js → MarkdownFilePreview-CVTDyg_G.js} +1 -1
- package/dist/assets/{MenuMotion-C-qcisoG.js → MenuMotion-B0aZnuh_.js} +1 -1
- package/dist/assets/{NewBotDialog-D_22AmDd.js → NewBotDialog-aItvxrvB.js} +1 -1
- package/dist/assets/{PhoneAppDialog-WOhzSF82.js → PhoneAppDialog-8-dgtBhp.js} +1 -1
- package/dist/assets/{PlacesRail-DoUGQSpd.js → PlacesRail-tZyNm-l3.js} +1 -1
- package/dist/assets/{PluginsPanel-DxM_qWtC.js → PluginsPanel-DVS8g955.js} +6 -6
- package/dist/assets/{ProIntroduction-CQFDxYxi.js → ProIntroduction-DV0pDAEU.js} +1 -1
- package/dist/assets/{RemoteAgentSettingsPanel-CdQmz7Qu.js → RemoteAgentSettingsPanel-CNlzF4Cp.js} +1 -1
- package/dist/assets/{RoomPanel-DVsYTCX7.js → RoomPanel-Cc_GKn6x.js} +1 -1
- package/dist/assets/{RoutinesPage-DG30sQw7.js → RoutinesPage-DOBkHlRF.js} +3 -3
- package/dist/assets/{SettingsModal-BFeWJ1OS.js → SettingsModal-B7Qc3XzL.js} +1 -1
- package/dist/assets/{ShareTeamDialog-BLddRjax.js → ShareTeamDialog-CSlDvD9U.js} +1 -1
- package/dist/assets/{SignedInSites-BREmZ6gH.js → SignedInSites-D-0eKIyP.js} +1 -1
- package/dist/assets/{TeamLibraryPanel-Sg1D_gYP.js → TeamLibraryPanel-DM76EFJx.js} +1 -1
- package/dist/assets/{TeamMapPage-CP7ug7dF.js → TeamMapPage-DhrPVbXJ.js} +1 -1
- package/dist/assets/{TriggersPage-DmY-ibGg.js → TriggersPage-DjSUS5gg.js} +1 -1
- package/dist/assets/{VisibilitySection-BqQTMT_O.js → VisibilitySection-DwI5DSDK.js} +5 -5
- package/dist/assets/{WebhookTrigger-Bk2khhKt.js → WebhookTrigger-DZqMzEbP.js} +1 -1
- package/dist/assets/{WorksOnGrid-BhZTjLmG.js → WorksOnGrid-CDTdX4z9.js} +1 -1
- package/dist/assets/{abnfDiagram-YUKMZFIV-4h66COg4.js → abnfDiagram-YUKMZFIV-DDXPrZzl.js} +1 -1
- package/dist/assets/{activity-JVyqvn--.js → activity-BlL5ycb5.js} +1 -1
- package/dist/assets/{architectureDiagram-47P4ROYG-XVFtgz_w.js → architectureDiagram-47P4ROYG-BiqBgMDV.js} +1 -1
- package/dist/assets/{blockDiagram-E7TT5TSB-Bzpnrunu.js → blockDiagram-E7TT5TSB-vc1neoFp.js} +1 -1
- package/dist/assets/{c4Diagram-CRA5TL53-Baf7lWcX.js → c4Diagram-CRA5TL53-CQbtBKOv.js} +1 -1
- package/dist/assets/{calendar-days-DJ8Sk4Wo.js → calendar-days-_dtxyR4U.js} +1 -1
- package/dist/assets/channel-BzyEyDo_.js +1 -0
- package/dist/assets/{chunk-2Q5K7J3B-C01NJDuW.js → chunk-2Q5K7J3B-Dq_aCCIt.js} +1 -1
- package/dist/assets/{chunk-5VM5RSS4-zCxCK82Z.js → chunk-5VM5RSS4-EcX_ZXzF.js} +1 -1
- package/dist/assets/{chunk-7TKQ45FW-Dn3xzwzp.js → chunk-7TKQ45FW-BA7CgKU2.js} +1 -1
- package/dist/assets/{chunk-AW2ZBBNX-D5v1LEvi.js → chunk-AW2ZBBNX-DkvVwaph.js} +1 -1
- package/dist/assets/{chunk-FVRAUYC3-B_j2BQfP.js → chunk-FVRAUYC3-CdyGRg6v.js} +2 -2
- package/dist/assets/{chunk-HTAEGDNF-CYEfb4lj.js → chunk-HTAEGDNF-CS-veEVV.js} +1 -1
- package/dist/assets/{chunk-JWPE2WC7-DYxCqsdI.js → chunk-JWPE2WC7-BiUYpinX.js} +1 -1
- package/dist/assets/{chunk-KQW6MTUR-BVs1owNv.js → chunk-KQW6MTUR-DDPkIuwB.js} +1 -1
- package/dist/assets/{chunk-XXDRQBXY-oNREPc9w.js → chunk-XXDRQBXY-C4YyKEem.js} +1 -1
- package/dist/assets/{classDiagram-v2-K4WV4PDN-B8JOWdQM.js → classDiagram-v2-K4WV4PDN-BjmVbVHi.js} +1 -1
- package/dist/assets/{coins-D-zVxeJ6.js → coins-Cu3qn-3t.js} +1 -1
- package/dist/assets/{core-DGyt94O8.js → core-DBsdXcHm.js} +1 -1
- package/dist/assets/{cose-bilkent-JH36ORCC-Cvvvdg2x.js → cose-bilkent-JH36ORCC-Bra0B-5z.js} +1 -1
- package/dist/assets/{cynefin-EF2NZ3EQ-BlyJPVpP.js → cynefin-EF2NZ3EQ-BRMKNbnx.js} +1 -1
- package/dist/assets/{cynefinDiagram-3GCD6N5R-aXWhkS0N.js → cynefinDiagram-3GCD6N5R-DMhNix9A.js} +1 -1
- package/dist/assets/{dagre-W4DXFKR2-CK9mZlxS.js → dagre-W4DXFKR2-BWwdFKCx.js} +1 -1
- package/dist/assets/{diagram-2UJZ2QOL-ciDDPAUW.js → diagram-2UJZ2QOL-D_4J-D-V.js} +1 -1
- package/dist/assets/{diagram-OVF4WLC6-ZC2XGXAQ.js → diagram-OVF4WLC6-CQ4l30Dm.js} +1 -1
- package/dist/assets/{diagram-PFPMY2P6-B_UNW8Y1.js → diagram-PFPMY2P6-D3W2IEHX.js} +1 -1
- package/dist/assets/{diagram-UMYRVEAY-BzqwG15l.js → diagram-UMYRVEAY-C9cpNhET.js} +1 -1
- package/dist/assets/{diagram-YEKJPTXX-f7zBrJwE.js → diagram-YEKJPTXX-DIyquCXt.js} +1 -1
- package/dist/assets/{diagram-ZIFT7M5P-QClomp2E.js → diagram-ZIFT7M5P-CO6216kK.js} +1 -1
- package/dist/assets/{ebnfDiagram-VR2GEFS7-BwcmIXBL.js → ebnfDiagram-VR2GEFS7-BeHXJPN4.js} +1 -1
- package/dist/assets/{elk-IJKZMXRS-DPv8qzg-.js → elk-IJKZMXRS-BdT_tK3j.js} +1 -1
- package/dist/assets/{erDiagram-O2IAPWRE-BHknllso.js → erDiagram-O2IAPWRE-Cz_TiHab.js} +1 -1
- package/dist/assets/{file-up-B5lQ3tIu.js → file-up-flw1aUka.js} +1 -1
- package/dist/assets/{flowDiagram-OXPTDLAJ-LwDo9oFR.js → flowDiagram-OXPTDLAJ-BXLr0anm.js} +1 -1
- package/dist/assets/{ganttDiagram-R7TSEDQI-DDXQuF2p.js → ganttDiagram-R7TSEDQI-C37QIpaR.js} +1 -1
- package/dist/assets/{gitGraphDiagram-XJZIOB7I-DxAL8MxK.js → gitGraphDiagram-XJZIOB7I-Cs8fTfJZ.js} +1 -1
- package/dist/assets/{import-name-fUZKEQiu.js → import-name-DRn9LvPS.js} +1 -1
- package/dist/assets/{index-C_1rKgRm.js → index-CaQlk_HV.js} +3 -3
- package/dist/assets/{index-Bb6OwohQ.js → index-Cnv_eiqT.js} +2 -2
- package/dist/assets/{infoDiagram-5W2HQ5XZ-BxZNIlp6.js → infoDiagram-5W2HQ5XZ-BpliNVPR.js} +1 -1
- package/dist/assets/{ishikawaDiagram-K3B6WC7H-C6c1u1w2.js → ishikawaDiagram-K3B6WC7H-Dov7w4qz.js} +1 -1
- package/dist/assets/{journeyDiagram-COXZFDF6-BrngL-3X.js → journeyDiagram-COXZFDF6-DoihiGaK.js} +1 -1
- package/dist/assets/{kanban-definition-P3RFRI5V-BhTOtF-B.js → kanban-definition-P3RFRI5V-D_gNx8dG.js} +1 -1
- package/dist/assets/{mermaid.core-Cy9_uq1T.js → mermaid.core-BYPxVPn-.js} +4 -4
- package/dist/assets/{mindmap-definition-LZFPQGKD-Dr3QB9wA.js → mindmap-definition-LZFPQGKD-wH2aKxFy.js} +1 -1
- package/dist/assets/{minimize-Ct6C2khA.js → minimize-sGQL0Xsy.js} +1 -1
- package/dist/assets/{monitor-BZrhga_j.js → monitor-zecPzfR5.js} +1 -1
- package/dist/assets/{new-bot-DCA0S24E.js → new-bot-LJs5i8O5.js} +1 -1
- package/dist/assets/{org-library-DgVAGwBY.js → org-library-B4fn4bHb.js} +1 -1
- package/dist/assets/{package-format-BvWgfqGs.js → package-format-CbAOdMeR.js} +1 -1
- package/dist/assets/{pegDiagram-BGZESJAR-D0bSaHqd.js → pegDiagram-BGZESJAR-B7RTZksQ.js} +1 -1
- package/dist/assets/{pieDiagram-CAPJLFHJ-B8i7ox8l.js → pieDiagram-CAPJLFHJ-B5mPB7O-.js} +1 -1
- package/dist/assets/{quadrantDiagram-GDMTTRAM-BcJTpsdR.js → quadrantDiagram-GDMTTRAM-CZqo7j7U.js} +1 -1
- package/dist/assets/{rail-Bzq4BbCt.js → rail-Ok0cs7cA.js} +1 -1
- package/dist/assets/{railroadDiagram-SM67HX2B-DSO-XOKW.js → railroadDiagram-SM67HX2B-MFpfIts_.js} +1 -1
- package/dist/assets/{remote-desktop-panel-BVRS7AXc.js → remote-desktop-panel-0Aj0_kDX.js} +1 -1
- package/dist/assets/{requirementDiagram-X7JNWC4A-B5gEynme.js → requirementDiagram-X7JNWC4A-CJ49gC_q.js} +1 -1
- package/dist/assets/{sankeyDiagram-UM26HJRW-CK2T6Pgm.js → sankeyDiagram-UM26HJRW-DxpTSw3D.js} +1 -1
- package/dist/assets/{sequenceDiagram-ZO4K6R2Y-Dx9DVGEG.js → sequenceDiagram-ZO4K6R2Y-XEyCx2Ue.js} +1 -1
- package/dist/assets/{sizeCapture-INFHLROL-BbirmlCW.js → sizeCapture-INFHLROL-1Fx1tcNn.js} +1 -1
- package/dist/assets/{stateDiagram-v2-TBUQTH76-CuJOlmiS.js → stateDiagram-v2-TBUQTH76-CwxyNDK4.js} +1 -1
- package/dist/assets/styles-CMOouTIW.css +1 -0
- package/dist/assets/{styles-CLQR3ehf.js → styles-DO3EUxm2.js} +1 -1
- package/dist/assets/{swimlanes-N4OXWK64-BWFqBYF_.js → swimlanes-N4OXWK64-BuwwuENy.js} +1 -1
- package/dist/assets/swimlanesDiagram-K3J5GTZL-CcmXEgRh.js +8 -0
- package/dist/assets/{team-share-1e1FK9fo.js → team-share-CL18_anr.js} +1 -1
- package/dist/assets/{timeline-definition-YOQAKGHF-CzxPBKDi.js → timeline-definition-YOQAKGHF-CauwqKMA.js} +1 -1
- package/dist/assets/{usecaseDiagram-VIAY4XPW-B5-pXbU3.js → usecaseDiagram-VIAY4XPW-YZ3Cf2do.js} +1 -1
- package/dist/assets/{vennDiagram-BLWOH2XV-BccL1p-U.js → vennDiagram-BLWOH2XV-CDX8i7ID.js} +1 -1
- package/dist/assets/{vi-DyvsTHbT.js → vi-CiY3ddy3.js} +1 -1
- package/dist/assets/{wardleyDiagram-YMQ3BMBF-DdJ9Pves.js → wardleyDiagram-YMQ3BMBF-CCdRrEMh.js} +1 -1
- package/dist/assets/{xychartDiagram-TAQBALBS-BAg7I3YQ.js → xychartDiagram-TAQBALBS-Vz4NaN0U.js} +1 -1
- package/dist/index.html +3 -3
- package/dist/rail.html +5 -5
- package/dist-server/drivers/agents-proxy.js +412 -400
- package/dist-server/index.js +6844 -6649
- package/dist-server/knowledge-collection.worker.js +4737 -0
- package/dist-server/licenses/knowledge.txt +688 -0
- package/dist-server/limixbot.js +1560 -1542
- package/dist-server/package.json +1 -1
- package/dist-server/pair-cli.js +1560 -1542
- package/dist-server/server/agents-turn.js +1 -0
- package/dist-server/server/bot-moves.js +16 -13
- package/dist-server/server/drivers/agents-call.js +8 -0
- package/dist-server/server/drivers/agents-catalog-profile.js +1 -0
- package/dist-server/server/drivers/agents-catalog.js +4 -1
- package/dist-server/server/host/bot-access-gate.js +3 -0
- package/dist-server/server/index.js +52 -3
- package/dist-server/server/knowledge/core.bench.js +35 -0
- package/dist-server/server/knowledge/core.js +338 -0
- package/dist-server/server/knowledge/database.js +153 -0
- package/dist-server/server/knowledge/documents.js +169 -0
- package/dist-server/server/knowledge/files.js +64 -0
- package/dist-server/server/knowledge/host.js +158 -0
- package/dist-server/server/knowledge/memory.js +51 -0
- package/dist-server/server/knowledge/plugin.js +17 -0
- package/dist-server/server/knowledge/retrieval.js +90 -0
- package/dist-server/server/knowledge/schema.js +39 -0
- package/dist-server/server/knowledge/semantic.js +135 -0
- package/dist-server/server/knowledge/tools.js +58 -0
- package/dist-server/server/knowledge-collection-fetch.js +101 -0
- package/dist-server/server/knowledge-collection.js +300 -0
- package/dist-server/server/knowledge-collection.worker.js +142 -0
- package/dist-server/server/move-freeze.js +1 -16
- package/dist-server/server/plugin-hub.js +17 -0
- package/dist-server/server/routes/knowledge.js +48 -0
- package/dist-server/server/routes/move-freeze.js +2 -6
- package/package.json +1 -1
- package/dist/assets/channel-DJthUr0W.js +0 -1
- package/dist/assets/styles-CE5PtWhb.css +0 -1
- package/dist/assets/swimlanesDiagram-K3J5GTZL-BjpCZGc-.js +0 -8
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { addAbortListener } from "node:events";
|
|
4
|
+
import { closeSync, existsSync, lstatSync, mkdirSync, openSync } from "node:fs";
|
|
5
|
+
import { isAbsolute, join } from "node:path";
|
|
6
|
+
import { DatabaseSync } from "node:sqlite";
|
|
7
|
+
import { Worker } from "node:worker_threads";
|
|
8
|
+
import { redactSecretsInText } from "../shared/redact.js";
|
|
9
|
+
import { fetchKnowledgePage, publicSourceUrl, MAX_PAGE_BYTES } from "./knowledge-collection-fetch.js";
|
|
10
|
+
const stages = ["DISCOVER", "FETCH", "ARCHIVE", "EXTRACT", "NORMALIZE", "DEDUPLICATE", "ANALYZE", "VALIDATE", "CLASSIFY", "LINK", "INDEX", "PUBLISH"];
|
|
11
|
+
const hash = (text) => createHash("sha256").update(text).digest("hex");
|
|
12
|
+
const activeJobs = new Map();
|
|
13
|
+
let activeWorkers = 0;
|
|
14
|
+
const now = () => new Date().toISOString();
|
|
15
|
+
async function worker(data, signal) {
|
|
16
|
+
signal.throwIfAborted();
|
|
17
|
+
if (activeWorkers >= 4)
|
|
18
|
+
throw new Error("Collection workers are busy");
|
|
19
|
+
const source = new URL("./knowledge-collection.worker.ts", import.meta.url);
|
|
20
|
+
const worker = new Worker(existsSync(source) ? source : new URL("./knowledge-collection.worker.js", import.meta.url), {
|
|
21
|
+
workerData: data, execArgv: [], env: {}, stdout: true, stderr: true, resourceLimits: { maxOldGenerationSizeMb: 96, maxYoungGenerationSizeMb: 16, stackSizeMb: 4 },
|
|
22
|
+
});
|
|
23
|
+
worker.stdout.resume();
|
|
24
|
+
worker.stderr.resume();
|
|
25
|
+
activeWorkers++;
|
|
26
|
+
let onAbort;
|
|
27
|
+
try {
|
|
28
|
+
return await new Promise((resolve, reject) => {
|
|
29
|
+
const fail = () => reject(new Error("Collection adapter failed or exceeded its limits"));
|
|
30
|
+
onAbort = addAbortListener(signal, fail);
|
|
31
|
+
worker.once("error", fail);
|
|
32
|
+
worker.once("exit", fail);
|
|
33
|
+
worker.once("message", reply => { if (reply?.ok)
|
|
34
|
+
resolve(reply.result);
|
|
35
|
+
else
|
|
36
|
+
fail(); });
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
onAbort?.[Symbol.dispose]();
|
|
41
|
+
await worker.terminate();
|
|
42
|
+
activeWorkers--;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export async function renderKnowledgeBatch(batch, signal = new AbortController().signal) {
|
|
46
|
+
if (Buffer.byteLength(JSON.stringify(batch)) > 256_000)
|
|
47
|
+
throw new Error("Template batch exceeds limit");
|
|
48
|
+
const rows = await worker({ action: "template", batch }, AbortSignal.any([signal, AbortSignal.timeout(6000)]));
|
|
49
|
+
return rows.map(row => ({ filename: redactSecretsInText(row.filename), markdown: redactSecretsInText(row.markdown) }));
|
|
50
|
+
}
|
|
51
|
+
function runMonolith(file, args, input, signal) {
|
|
52
|
+
if (!isAbsolute(file))
|
|
53
|
+
throw new Error("Monolith path must be absolute");
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
const proc = execFile(file, args, {
|
|
56
|
+
signal, timeout: 5000, maxBuffer: 2 * MAX_PAGE_BYTES, windowsHide: true,
|
|
57
|
+
env: { ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}), LANG: "C" },
|
|
58
|
+
}, (error, stdout) => error ? reject(new Error("Monolith adapter failed")) : resolve(stdout));
|
|
59
|
+
proc.stdin?.on("error", () => { });
|
|
60
|
+
proc.stdin?.end(input);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
export class KnowledgeCollection {
|
|
64
|
+
#db;
|
|
65
|
+
#fetch;
|
|
66
|
+
#monolith;
|
|
67
|
+
constructor(dataDir, options = {}) {
|
|
68
|
+
this.#fetch = options.fetchPage ?? fetchKnowledgePage;
|
|
69
|
+
this.#monolith = options.monolith ?? process.env.LIMIX_KNOWLEDGE_MONOLITH;
|
|
70
|
+
mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
|
71
|
+
const file = join(dataDir, "knowledge-collection.sqlite");
|
|
72
|
+
for (const name of [file, file + "-wal", file + "-shm", file + "-journal"]) {
|
|
73
|
+
if (existsSync(name) && !lstatSync(name).isFile())
|
|
74
|
+
throw new Error("Invalid collection storage");
|
|
75
|
+
}
|
|
76
|
+
closeSync(openSync(file, "a", 0o600));
|
|
77
|
+
this.#db = new DatabaseSync(file);
|
|
78
|
+
this.#db.exec("PRAGMA busy_timeout=3000; PRAGMA max_page_count=32768; PRAGMA secure_delete=ON;");
|
|
79
|
+
this.#db.exec([
|
|
80
|
+
"CREATE TABLE IF NOT EXISTS snapshots(scope TEXT NOT NULL,digest TEXT NOT NULL,html TEXT NOT NULL,PRIMARY KEY(scope,digest))",
|
|
81
|
+
"CREATE TABLE IF NOT EXISTS jobs(id TEXT PRIMARY KEY,scope TEXT NOT NULL,url TEXT NOT NULL,archive INTEGER NOT NULL,state TEXT NOT NULL,checkpoint TEXT NOT NULL,snapshot TEXT,lease TEXT NOT NULL DEFAULT '',leased_until INTEGER NOT NULL DEFAULT 0,document TEXT NOT NULL DEFAULT '',touched INTEGER NOT NULL DEFAULT 0)",
|
|
82
|
+
"CREATE INDEX IF NOT EXISTS collection_document ON jobs(scope,document)",
|
|
83
|
+
"CREATE INDEX IF NOT EXISTS collection_snapshot ON jobs(scope,snapshot)",
|
|
84
|
+
"CREATE TABLE IF NOT EXISTS budgets(scope TEXT PRIMARY KEY,start INTEGER NOT NULL,used INTEGER NOT NULL)",
|
|
85
|
+
].join(";"));
|
|
86
|
+
}
|
|
87
|
+
#prune(scope) {
|
|
88
|
+
this.#db.prepare("DELETE FROM snapshots WHERE scope=? AND NOT EXISTS (SELECT 1 FROM jobs WHERE jobs.scope=snapshots.scope AND jobs.snapshot=snapshots.digest)").run(scope);
|
|
89
|
+
}
|
|
90
|
+
jobs(scope) {
|
|
91
|
+
const rows = this.#db.prepare("SELECT id,url,archive,state,json_extract(checkpoint,'$.steps') AS steps,touched FROM jobs WHERE scope=? ORDER BY touched DESC LIMIT 100").all(scope);
|
|
92
|
+
return rows.map(row => ({ job_id: row.id, source_url: row.url, archive: !!row.archive, status: row.state, steps: JSON.parse(String(row.steps)), updated_at: new Date(Number(row.touched)).toISOString() }));
|
|
93
|
+
}
|
|
94
|
+
cancel(scope, jobId) {
|
|
95
|
+
const changed = this.#db.prepare("UPDATE jobs SET state='cancelled',lease='',leased_until=0,checkpoint=json_object('steps',json_extract(checkpoint,'$.steps'),'previous',json_extract(checkpoint,'$.previous')) WHERE scope=? AND id=? AND state IN ('running','failed')").run(scope, jobId).changes;
|
|
96
|
+
if (changed)
|
|
97
|
+
activeJobs.get(jobId)?.abort();
|
|
98
|
+
return !!changed;
|
|
99
|
+
}
|
|
100
|
+
archive(scope, documentId) {
|
|
101
|
+
if (!documentId)
|
|
102
|
+
return null;
|
|
103
|
+
const row = this.#db.prepare("SELECT snapshots.html AS html FROM jobs JOIN snapshots ON jobs.scope=snapshots.scope AND jobs.snapshot=snapshots.digest WHERE jobs.scope=? AND document=? ORDER BY touched DESC LIMIT 1").get(scope, documentId);
|
|
104
|
+
return row?.html ? String(row.html) : null;
|
|
105
|
+
}
|
|
106
|
+
forget(scope, documentId) {
|
|
107
|
+
if (!documentId)
|
|
108
|
+
return;
|
|
109
|
+
const ids = this.#db.prepare("SELECT id FROM jobs WHERE scope=? AND document=?").all(scope, documentId);
|
|
110
|
+
this.#db.exec("BEGIN IMMEDIATE");
|
|
111
|
+
try {
|
|
112
|
+
this.#db.prepare("DELETE FROM jobs WHERE scope=? AND document=?").run(scope, documentId);
|
|
113
|
+
this.#prune(scope);
|
|
114
|
+
this.#db.exec("COMMIT");
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
this.#db.exec("ROLLBACK");
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
for (const { id } of ids)
|
|
121
|
+
activeJobs.get(String(id))?.abort();
|
|
122
|
+
}
|
|
123
|
+
close() { this.#db.close(); }
|
|
124
|
+
async collect(input, hooks) {
|
|
125
|
+
await hooks.authorize();
|
|
126
|
+
if (!input.scope || input.scope.length > 512)
|
|
127
|
+
throw new Error("Invalid collection scope");
|
|
128
|
+
const url = publicSourceUrl(input.url).href;
|
|
129
|
+
const id = hash(JSON.stringify([input.scope, url, !!input.archive]));
|
|
130
|
+
const load = () => this.#db.prepare("SELECT * FROM jobs WHERE id=? AND scope=?").get(id, input.scope);
|
|
131
|
+
let row = load();
|
|
132
|
+
if (row?.state === "done" && !input.refresh) {
|
|
133
|
+
const cached = JSON.parse(row.checkpoint);
|
|
134
|
+
await hooks.authorize();
|
|
135
|
+
hooks.signal?.throwIfAborted();
|
|
136
|
+
return { ...cached.previous, steps: cached.steps };
|
|
137
|
+
}
|
|
138
|
+
if (activeJobs.has(id) || activeJobs.size >= 4 || (row?.leased_until ?? 0) > Date.now())
|
|
139
|
+
throw new Error("Collection is busy");
|
|
140
|
+
const minute = Math.floor(Date.now() / 60_000);
|
|
141
|
+
const rate = this.#db.prepare("INSERT INTO budgets(scope,start,used) VALUES(?,?,1) ON CONFLICT(scope) DO UPDATE SET start=excluded.start,used=CASE WHEN start=excluded.start THEN used+1 ELSE 1 END WHERE start<>excluded.start OR used<12").run(input.scope, minute);
|
|
142
|
+
if (!rate.changes)
|
|
143
|
+
throw new Error("Collection rate limit reached");
|
|
144
|
+
if (!row) {
|
|
145
|
+
const { count } = this.#db.prepare("SELECT count(*) AS count FROM jobs WHERE scope=?").get(input.scope);
|
|
146
|
+
if (Number(count) >= 250)
|
|
147
|
+
throw new Error("Collection quota reached");
|
|
148
|
+
this.#db.prepare("INSERT INTO jobs (id,scope,url,archive,state,checkpoint,touched) VALUES(?,?,?,?,'new',?,?) ON CONFLICT DO NOTHING").run(id, input.scope, url, Number(!!input.archive), '{"steps":[]}', Date.now());
|
|
149
|
+
row = load();
|
|
150
|
+
}
|
|
151
|
+
const freshRun = row.state === "done" || row.state === "cancelled" || (input.refresh && row.state === "failed");
|
|
152
|
+
const saved = JSON.parse(row.checkpoint);
|
|
153
|
+
const cp = freshRun ? { steps: [], previous: saved.previous } : saved;
|
|
154
|
+
const lease = randomUUID();
|
|
155
|
+
const controller = new AbortController();
|
|
156
|
+
const timeout = AbortSignal.timeout(55_000);
|
|
157
|
+
const signal = AbortSignal.any([controller.signal, timeout, ...(hooks.signal ? [hooks.signal] : [])]);
|
|
158
|
+
const claimed = this.#db.prepare("UPDATE jobs SET state='running',lease=?,leased_until=?,touched=? WHERE id=? AND leased_until<=?").run(lease, Date.now() + 65_000, Date.now(), id, Date.now());
|
|
159
|
+
if (!claimed.changes)
|
|
160
|
+
throw new Error("Collection is busy");
|
|
161
|
+
activeJobs.set(id, controller);
|
|
162
|
+
const save = () => {
|
|
163
|
+
signal.throwIfAborted();
|
|
164
|
+
const changed = this.#db.prepare("UPDATE jobs SET checkpoint=?,touched=? WHERE id=? AND lease=?").run(JSON.stringify(cp), Date.now(), id, lease);
|
|
165
|
+
if (!changed.changes)
|
|
166
|
+
throw new Error("Collection was cancelled");
|
|
167
|
+
};
|
|
168
|
+
try {
|
|
169
|
+
for (const stage of stages) {
|
|
170
|
+
await hooks.authorize();
|
|
171
|
+
signal.throwIfAborted();
|
|
172
|
+
let step = cp.steps.find(s => s.stage === stage);
|
|
173
|
+
if (step?.status === "done" || step?.status === "skipped")
|
|
174
|
+
continue;
|
|
175
|
+
if (!step) {
|
|
176
|
+
step = { stage, attempts: 0, status: "running", at: now() };
|
|
177
|
+
cp.steps.push(step);
|
|
178
|
+
}
|
|
179
|
+
if (step.attempts >= 3)
|
|
180
|
+
throw new Error("Collection retry budget exhausted");
|
|
181
|
+
step.attempts++;
|
|
182
|
+
step.status = "running";
|
|
183
|
+
step.at = now();
|
|
184
|
+
save();
|
|
185
|
+
const bounded = AbortSignal.any([signal, AbortSignal.timeout(12_000)]);
|
|
186
|
+
if (stage === "DISCOVER") {
|
|
187
|
+
cp.source_url = url;
|
|
188
|
+
}
|
|
189
|
+
else if (stage === "FETCH") {
|
|
190
|
+
const page = await this.#fetch(url, bounded);
|
|
191
|
+
bounded.throwIfAborted();
|
|
192
|
+
cp.source_url = publicSourceUrl(page.source_url).href;
|
|
193
|
+
cp.content_hash = page.content_hash;
|
|
194
|
+
cp.fetched_at = page.fetched_at;
|
|
195
|
+
cp.page = await worker({ action: "prepare", html: redactSecretsInText(page.html), source: cp.source_url }, bounded);
|
|
196
|
+
cp.page.html = redactSecretsInText(cp.page.html);
|
|
197
|
+
cp.links = cp.page.links.map(link => redactSecretsInText(link)).filter(link => !link.includes("«") && !link.includes("••"));
|
|
198
|
+
}
|
|
199
|
+
else if (stage === "ARCHIVE" && input.archive) {
|
|
200
|
+
cp.html = cp.page.html;
|
|
201
|
+
cp.archiveTool = "inert-html";
|
|
202
|
+
if (this.#monolith) {
|
|
203
|
+
const version = await runMonolith(this.#monolith, ["--version"], "", bounded);
|
|
204
|
+
if (version.trim() !== "monolith 2.9.0")
|
|
205
|
+
throw new Error("Expected Monolith 2.9.0");
|
|
206
|
+
const output = await runMonolith(this.#monolith, ["-I", "-j", "-c", "-F", "-f", "-i", "-a", "-v", "-M", "-q", "-t", "2", "-o", "-", "-"], cp.html, bounded);
|
|
207
|
+
cp.html = (await worker({ action: "prepare", html: output }, bounded)).html;
|
|
208
|
+
cp.archiveTool = "monolith 2.9.0";
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
else if (stage === "ARCHIVE") {
|
|
212
|
+
step.status = "skipped";
|
|
213
|
+
}
|
|
214
|
+
else if (stage === "EXTRACT") {
|
|
215
|
+
if (cp.previous?.content_hash !== cp.content_hash) {
|
|
216
|
+
cp.extracted = await worker({ action: "extract", page: cp.page, source: cp.source_url }, bounded);
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
step.status = "skipped";
|
|
220
|
+
}
|
|
221
|
+
delete cp.page;
|
|
222
|
+
}
|
|
223
|
+
else if (stage === "NORMALIZE" && cp.extracted) {
|
|
224
|
+
const ex = cp.extracted;
|
|
225
|
+
cp.record = { title: redactSecretsInText((ex.title.trim() || new URL(cp.source_url).hostname).slice(0, 160)), markdown: redactSecretsInText(ex.markdown.normalize("NFC").replace(/\r\n?/g, "\n").trim()),
|
|
226
|
+
author: redactSecretsInText(ex.author).slice(0, 200), description: redactSecretsInText(ex.description).slice(0, 512), source_url: cp.source_url, content_hash: cp.content_hash, fetched_at: cp.fetched_at,
|
|
227
|
+
tags: [], warnings: [], related_sources: [], verification_status: "unverified", extractor: ex.extractor, idempotency_key: hash(id + cp.content_hash), previous_document_id: cp.previous?.document_id };
|
|
228
|
+
delete cp.extracted;
|
|
229
|
+
}
|
|
230
|
+
else if (stage === "DEDUPLICATE") {
|
|
231
|
+
if (cp.previous?.content_hash === cp.content_hash)
|
|
232
|
+
delete cp.record;
|
|
233
|
+
}
|
|
234
|
+
else if (stage === "ANALYZE" && cp.record) {
|
|
235
|
+
if (/\b(?:ignore|override|forget)\b.{0,40}\b(?:instructions|system prompt|policies)\b|(?:bỏ qua|ghi đè).{0,40}(?:chỉ dẫn|hướng dẫn|lệnh hệ thống)/iu.test(cp.record.markdown))
|
|
236
|
+
cp.record.warnings.push("instruction-like-text");
|
|
237
|
+
}
|
|
238
|
+
else if (stage === "VALIDATE" && cp.record) {
|
|
239
|
+
if (!cp.record.markdown || cp.record.markdown.length > 128_000 || !/^[0-9a-f]{64}$/.test(cp.record.content_hash))
|
|
240
|
+
throw new Error("Source record failed validation");
|
|
241
|
+
}
|
|
242
|
+
else if (stage === "CLASSIFY" && cp.record) {
|
|
243
|
+
const domain = new URL(cp.record.source_url).hostname;
|
|
244
|
+
cp.record.tags = domain.length <= 64 ? ["web-source", domain] : ["web-source"];
|
|
245
|
+
}
|
|
246
|
+
else if (stage === "LINK" && cp.record) {
|
|
247
|
+
cp.record.related_sources = (cp.links ?? []).filter(link => link !== cp.record.source_url);
|
|
248
|
+
}
|
|
249
|
+
else if (stage === "INDEX" && cp.record) {
|
|
250
|
+
// Vault indexing and publication commit together. The callback uses this key to replay a crash after commit.
|
|
251
|
+
cp.record.idempotency_key = hash(JSON.stringify([input.scope, url, cp.content_hash]));
|
|
252
|
+
}
|
|
253
|
+
else if (stage === "PUBLISH") {
|
|
254
|
+
const document = cp.record ? await hooks.publish(cp.record) : cp.previous;
|
|
255
|
+
if (!document?.document_id)
|
|
256
|
+
throw new Error("Vault did not identify a document");
|
|
257
|
+
cp.previous = { document_id: document.document_id, source_url: cp.source_url, content_hash: cp.content_hash, fetched_at: cp.fetched_at, archived: !!cp.html };
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
step.status = "skipped";
|
|
261
|
+
}
|
|
262
|
+
await hooks.authorize();
|
|
263
|
+
bounded.throwIfAborted();
|
|
264
|
+
if (step.status === "running")
|
|
265
|
+
step.status = "done";
|
|
266
|
+
save();
|
|
267
|
+
}
|
|
268
|
+
await hooks.authorize();
|
|
269
|
+
signal.throwIfAborted();
|
|
270
|
+
const done = cp.previous;
|
|
271
|
+
this.#db.exec("BEGIN IMMEDIATE");
|
|
272
|
+
try {
|
|
273
|
+
const snapshot = cp.html ? hash(cp.html) : null;
|
|
274
|
+
if (cp.html && snapshot)
|
|
275
|
+
this.#db.prepare("INSERT INTO snapshots(scope,digest,html) VALUES(?,?,?) ON CONFLICT DO NOTHING").run(input.scope, snapshot, cp.html);
|
|
276
|
+
const changed = this.#db.prepare("UPDATE jobs SET state='done',checkpoint=?,snapshot=?,document=?,lease='',leased_until=0,touched=? WHERE id=? AND lease=?").run(JSON.stringify({ steps: cp.steps, previous: done }), snapshot, done.document_id, Date.now(), id, lease);
|
|
277
|
+
if (!changed.changes)
|
|
278
|
+
throw new Error("Collection was cancelled");
|
|
279
|
+
this.#prune(input.scope);
|
|
280
|
+
this.#db.exec("COMMIT");
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
this.#db.exec("ROLLBACK");
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
return { ...done, steps: cp.steps };
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
const durable = JSON.parse(load()?.checkpoint ?? '{"steps":[]}');
|
|
290
|
+
const step = durable.steps.find(s => s.status === "running");
|
|
291
|
+
if (step)
|
|
292
|
+
step.status = "failed";
|
|
293
|
+
this.#db.prepare("UPDATE jobs SET state=?,checkpoint=?,lease='',leased_until=0 WHERE id=? AND lease=?").run(signal.aborted ? "cancelled" : "failed", JSON.stringify(durable), id, lease);
|
|
294
|
+
throw new Error("Collection interrupted at " + (step?.stage ?? "authorization") + ". See collection history to resume.");
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
activeJobs.delete(id);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
import { parse } from "parse5";
|
|
3
|
+
import { Defuddle } from "defuddle/node";
|
|
4
|
+
import { createEngine, standardFilters } from "knap";
|
|
5
|
+
import { redactSecretsInText } from "../shared/redact.js";
|
|
6
|
+
const blocks = new Set("article main section header h1 h2 h3 h4 h5 h6 p ul ol li dl dt dd blockquote pre code em strong b i s sup sub br hr figure figcaption table thead tbody tr td th caption".split(" "));
|
|
7
|
+
const omitted = new Set("script style template svg math iframe frame object embed form input textarea button select nav aside footer noscript meta link base title head canvas video audio source picture img".split(" "));
|
|
8
|
+
const policy = "default-src 'none'; base-uri 'none'; form-action 'none'";
|
|
9
|
+
const escapeHtml = (s) => s.replace(/[&<>"]/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
10
|
+
const cleanText = (s) => redactSecretsInText(s)
|
|
11
|
+
.replace(/\b(?:set-cookie|cookie|authorization)\s*:[^\n\r]+/gi, "[redacted header]")
|
|
12
|
+
.replace(/\b(api[_-]?key|password|passwd|access[_-]?token|refresh[_-]?token|session[_-]?id|cookie)["']?\s*[:=]\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;<>"']+)/gi, "$1=[redacted]");
|
|
13
|
+
function prepare(html, source) {
|
|
14
|
+
const doc = parse(html);
|
|
15
|
+
let count = 0;
|
|
16
|
+
const links = new Set();
|
|
17
|
+
let title = "", author = "", description = "";
|
|
18
|
+
function walk(node, depth) {
|
|
19
|
+
if (++count > 40_000 || depth > 120)
|
|
20
|
+
throw new Error("Page structure exceeds limit");
|
|
21
|
+
if ("value" in node)
|
|
22
|
+
return escapeHtml(cleanText(node.value));
|
|
23
|
+
if (!("childNodes" in node))
|
|
24
|
+
return "";
|
|
25
|
+
if (!("tagName" in node))
|
|
26
|
+
return node.childNodes.map(n => walk(n, depth + 1)).join("");
|
|
27
|
+
const tag = node.tagName;
|
|
28
|
+
const attr = (name) => node.attrs.find(a => a.name === name)?.value ?? "";
|
|
29
|
+
if (tag === "head") {
|
|
30
|
+
for (const item of node.childNodes) {
|
|
31
|
+
if (!("tagName" in item))
|
|
32
|
+
continue;
|
|
33
|
+
if (item.tagName === "title")
|
|
34
|
+
title = cleanText(item.childNodes.map(n => "value" in n ? n.value : "").join("")).trim().slice(0, 200);
|
|
35
|
+
if (item.tagName === "meta") {
|
|
36
|
+
const name = item.attrs.find(a => a.name === "name")?.value.toLowerCase();
|
|
37
|
+
const value = cleanText(item.attrs.find(a => a.name === "content")?.value ?? "").trim().slice(0, 512);
|
|
38
|
+
if (name === "author")
|
|
39
|
+
author = value;
|
|
40
|
+
if (name === "description")
|
|
41
|
+
description = value;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return "";
|
|
45
|
+
}
|
|
46
|
+
if (omitted.has(tag) || node.namespaceURI !== "http://www.w3.org/1999/xhtml" || node.attrs.some(a => a.name === "hidden")
|
|
47
|
+
|| attr("aria-hidden") === "true" || /(?:^|[\s_-])(?:ads?|advertisement|cookie-banner|sponsored)(?:$|[\s_-])/i.test(attr("class") + " " + attr("id")))
|
|
48
|
+
return "";
|
|
49
|
+
if (tag === "a" && source && attr("href") && links.size < 24) {
|
|
50
|
+
let target;
|
|
51
|
+
try {
|
|
52
|
+
target = new URL(attr("href"), source);
|
|
53
|
+
}
|
|
54
|
+
catch { }
|
|
55
|
+
if (target && target.protocol === "https:" && !target.username && !target.password && !target.search && !target.port
|
|
56
|
+
&& target.hostname.includes(".") && target.href.length <= 500 && cleanText(target.href) === target.href) {
|
|
57
|
+
target.hash = "";
|
|
58
|
+
links.add(target.href);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const inner = node.childNodes.map(n => walk(n, depth + 1)).join("");
|
|
62
|
+
if (!blocks.has(tag))
|
|
63
|
+
return inner;
|
|
64
|
+
return "<" + tag + ">" + inner + (tag === "br" || tag === "hr" ? "" : "</" + tag + ">");
|
|
65
|
+
}
|
|
66
|
+
const body = walk(doc, 0);
|
|
67
|
+
return { title, author, description, links: [...links], html: '<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="' + policy + '"><title>' + escapeHtml(title) + "</title></head><body>" + body + "</body></html>" };
|
|
68
|
+
}
|
|
69
|
+
async function extract(page, source) {
|
|
70
|
+
try {
|
|
71
|
+
const extracted = await Defuddle(page.html, source, { markdown: true, useAsync: false, removeImages: true,
|
|
72
|
+
fetch: async () => { throw new Error("Network disabled in extraction"); } });
|
|
73
|
+
if (extracted.content?.trim())
|
|
74
|
+
return { title: page.title || cleanText(extracted.title ?? ""), author: page.author || cleanText(extracted.author ?? ""),
|
|
75
|
+
description: page.description || cleanText(extracted.description ?? ""), markdown: cleanText(extracted.content).slice(0, 128_000), extractor: "defuddle" };
|
|
76
|
+
}
|
|
77
|
+
catch { /* A local DOM extraction failure falls back to visible text. */ }
|
|
78
|
+
const tree = parse(page.html);
|
|
79
|
+
const lines = [];
|
|
80
|
+
function visit(node) {
|
|
81
|
+
if ("value" in node) {
|
|
82
|
+
lines.push(node.value);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (!("childNodes" in node) || "tagName" in node && node.tagName === "head")
|
|
86
|
+
return;
|
|
87
|
+
node.childNodes.forEach(visit);
|
|
88
|
+
if ("tagName" in node && ["p", "li", "br", "article", "h1", "h2", "h3"].includes(node.tagName))
|
|
89
|
+
lines.push("\n");
|
|
90
|
+
}
|
|
91
|
+
visit(tree);
|
|
92
|
+
const markdown = cleanText(lines.join("")).trim().slice(0, 128_000);
|
|
93
|
+
if (!markdown)
|
|
94
|
+
throw new Error("No readable content");
|
|
95
|
+
return { title: page.title, author: page.author, description: page.description, markdown, extractor: "text" };
|
|
96
|
+
}
|
|
97
|
+
async function render({ template, rows }) {
|
|
98
|
+
if (!template || template.length > 8192 || !Array.isArray(rows) || !rows.length || rows.length > 32)
|
|
99
|
+
throw new Error("Invalid template batch");
|
|
100
|
+
const filters = Object.fromEntries(["trim", "upper", "lower", "capitalize", "list", "yaml_property", "safe_name"].filter(k => Object.hasOwn(standardFilters, k)).map(k => [k, standardFilters[k]]));
|
|
101
|
+
const engine = createEngine({ filters, allowRegex: false, limits: { maxTemplateLength: 8192, maxValueLength: 8192, maxOutputLength: 32_000, maxOperations: 3000, maxDepth: 12 } });
|
|
102
|
+
if (engine.validate(template).length)
|
|
103
|
+
throw new Error("Invalid template or unsupported filter");
|
|
104
|
+
const files = new Set();
|
|
105
|
+
const outputs = [];
|
|
106
|
+
for (const { filename, variables } of rows) {
|
|
107
|
+
if (!/^[\p{L}\p{N}][\p{L}\p{N} _.-]{0,88}\.md$/iu.test(filename) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(filename)
|
|
108
|
+
|| filename.includes("..") || files.has(filename.normalize("NFC").toLowerCase()))
|
|
109
|
+
throw new Error("Invalid or duplicate Markdown filename");
|
|
110
|
+
files.add(filename.normalize("NFC").toLowerCase());
|
|
111
|
+
if (!variables || Array.isArray(variables) || Object.keys(variables).length > 64)
|
|
112
|
+
throw new Error("Invalid template data");
|
|
113
|
+
const data = Object.create(null);
|
|
114
|
+
for (const [key, value] of Object.entries(variables)) {
|
|
115
|
+
if (!/^[a-zA-Z][a-zA-Z0-9_]{0,63}$/.test(key) || key in Object.prototype || key === "prototype"
|
|
116
|
+
|| !["string", "number", "boolean"].includes(typeof value) || String(value).length > 8192)
|
|
117
|
+
throw new Error("Invalid template variable");
|
|
118
|
+
data[key] = value;
|
|
119
|
+
}
|
|
120
|
+
outputs.push({ filename, markdown: cleanText(await engine.renderOrThrow(template, { variables: data })) });
|
|
121
|
+
}
|
|
122
|
+
return outputs;
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
let result;
|
|
126
|
+
switch (workerData.action) {
|
|
127
|
+
case "prepare":
|
|
128
|
+
result = prepare(workerData.html, workerData.source);
|
|
129
|
+
break;
|
|
130
|
+
case "extract":
|
|
131
|
+
result = await extract(workerData.page, workerData.source);
|
|
132
|
+
break;
|
|
133
|
+
case "template":
|
|
134
|
+
result = await render(workerData.batch);
|
|
135
|
+
break;
|
|
136
|
+
default: throw new Error("Unknown collection operation");
|
|
137
|
+
}
|
|
138
|
+
parentPort.postMessage({ ok: true, result });
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
parentPort.postMessage({ ok: false });
|
|
142
|
+
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// move's own with one sentence. Nothing in the workspace is edited, so lifting the marker leaves this computer exactly
|
|
4
4
|
// as it was. A Cloud that ended, started only so its owner can take their things home (OMB_CLOUD_EXPORT_ONLY=1), runs
|
|
5
5
|
// frozen the same way and is never lifted.
|
|
6
|
-
import { existsSync,
|
|
6
|
+
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { writeFileAtomic } from "./atomic.js";
|
|
9
9
|
export const MOVED_REFUSAL = "This bot lives on My Cloud now.";
|
|
@@ -26,11 +26,6 @@ export const ENDED_REFUSAL = "My Cloud has ended. It is open only so you can tak
|
|
|
26
26
|
* own exact exemption in refuses().) */
|
|
27
27
|
const STILL_CHANGES = /^\/api\/(?:move\/|cloud-send\/|auth\/|workspace-backup\/|cloud\/|sync\/|shared-computers\/)/u;
|
|
28
28
|
const READS = new Set(["GET", "HEAD", "OPTIONS"]);
|
|
29
|
-
/** What a frozen copy keeps once its workspace is deleted: the marker, this server's identity, Files, downloaded tools
|
|
30
|
-
* and caches, and its own runtime files. Everything else, credentials included, is the person's workspace. */
|
|
31
|
-
const DEVICE_STATE = new Set(["moved.json", "environment-id", "sync", "tools", "cache", ".cache", "tmp", ".tmp", "dist-native", "tunnel-runtime",
|
|
32
|
-
".limixbot-server-child", ".openmausbot-server-child", "openmausbot-server.lease", "limixbot-server.lease"]);
|
|
33
|
-
const kept = (name) => DEVICE_STATE.has(name) || /^(?:limixbot|openmausbot)-server\.lease\./.test(name);
|
|
34
29
|
/** Switches off every automation that is on, or only those named by key ("routine:<id>", "call:<id>", "webhook:<id>",
|
|
35
30
|
* "app-event:<id>", "wait:<id>"); the person can switch each on again by hand, and a wait is cancelled. Done while frozen,
|
|
36
31
|
* so none of them runs once the freeze lifts. One that can't be switched off is logged, never a reason to stay frozen.
|
|
@@ -137,16 +132,6 @@ export function createMoveFreeze({ dataDir, exportOnly = false }) {
|
|
|
137
132
|
place = named;
|
|
138
133
|
each("stop");
|
|
139
134
|
},
|
|
140
|
-
/** Deletes this computer's copy of the workspace, credentials included, once the move is long done; only a computer
|
|
141
|
-
* frozen by a move ever does. The server starts again after, frozen and empty. */
|
|
142
|
-
forget() {
|
|
143
|
-
if (exportOnly || !existsSync(file))
|
|
144
|
-
return false;
|
|
145
|
-
for (const name of readdirSync(dataDir))
|
|
146
|
-
if (!kept(name))
|
|
147
|
-
rmSync(join(dataDir, name), { recursive: true, force: true });
|
|
148
|
-
return true;
|
|
149
|
-
},
|
|
150
135
|
/** False for a server that may never be lifted: a Cloud that ended. */
|
|
151
136
|
lifts: () => !exportOnly,
|
|
152
137
|
/** False when this server may never be lifted: a Cloud that ended. */
|
|
@@ -313,6 +313,23 @@ export function createPluginHub(dir, targets, load = download) {
|
|
|
313
313
|
};
|
|
314
314
|
const approved = (id, sha256) => state.installed.find(p => p.id === id && p.sha256 === sha256)?.manifest;
|
|
315
315
|
return { route,
|
|
316
|
+
builtinActive(bot, pin) {
|
|
317
|
+
return active(bot, []).some(row => row.id === pin.id && row.sha256 === pin.sha256);
|
|
318
|
+
},
|
|
319
|
+
configureBuiltin(bot, revision, enabled, actor) {
|
|
320
|
+
const current = state.installed.find(row => row.id === revision.id && row.sha256 === revision.sha256);
|
|
321
|
+
if (!current && !enabled)
|
|
322
|
+
return;
|
|
323
|
+
if (current?.bots[bot.id] === enabled)
|
|
324
|
+
return;
|
|
325
|
+
const { warnings: _warnings, ...pack } = revision;
|
|
326
|
+
const row = current ?? { ...pack, instructions: "", teams: [], bots: {} };
|
|
327
|
+
const selected = { ...row, bots: { ...row.bots, [bot.id]: enabled } };
|
|
328
|
+
const installed = state.installed.filter(p => p !== current).map(p => enabled && p.id === row.id
|
|
329
|
+
? { ...p, bots: { ...p.bots, [bot.id]: false } } : p);
|
|
330
|
+
const events = current ? [] : [audit("install", row, actor)];
|
|
331
|
+
save({ ...state, installed: [...installed, selected], pending: state.pending.filter(p => p.sha256 !== row.sha256) }, [...events, audit("assign", row, actor, "bot:" + bot.id, enabled)]);
|
|
332
|
+
},
|
|
316
333
|
getApproved(id, sha256) {
|
|
317
334
|
const m = approved(id, sha256);
|
|
318
335
|
return m && !m.source ? m : null;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { ZodError } from "zod";
|
|
2
|
+
import { KnowledgeError } from "../knowledge/schema.js";
|
|
3
|
+
import { PASS } from "./table.js";
|
|
4
|
+
export function knowledgeFailure(error) {
|
|
5
|
+
if (error instanceof ZodError)
|
|
6
|
+
return { status: 400, body: { error: "Invalid knowledge input.", fields: error.issues.slice(0, 6).map(issue => issue.path.join(".")) } };
|
|
7
|
+
if (error instanceof KnowledgeError)
|
|
8
|
+
return { status: error.status, body: { error: error.message } };
|
|
9
|
+
if (error instanceof Error && error.name === "AbortError")
|
|
10
|
+
return { status: 409, body: { error: "Knowledge operation cancelled." } };
|
|
11
|
+
return { status: 500, body: { error: "The knowledge operation could not finish." } };
|
|
12
|
+
}
|
|
13
|
+
export function knowledgeRoutes(host, actor) {
|
|
14
|
+
return async ({ req, res, auth, path, method, readBody, json }) => {
|
|
15
|
+
const found = /^\/api\/bots\/([\w-]+)\/knowledge\/([a-z_]+)$/.exec(path);
|
|
16
|
+
if (!found)
|
|
17
|
+
return PASS;
|
|
18
|
+
const id = found[1], action = found[2];
|
|
19
|
+
const identify = () => actor(auth, id);
|
|
20
|
+
const controller = new AbortController();
|
|
21
|
+
const cancel = () => controller.abort();
|
|
22
|
+
res.once("close", cancel);
|
|
23
|
+
try {
|
|
24
|
+
identify();
|
|
25
|
+
if (action === "settings") {
|
|
26
|
+
if (method === "GET")
|
|
27
|
+
return json(res, 200, host.settings(id, identify()));
|
|
28
|
+
if (method === "PUT") {
|
|
29
|
+
const input = await readBody(req, 1024);
|
|
30
|
+
return json(res, 200, host.configure(id, identify(), input));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
else if (method === "POST") {
|
|
34
|
+
const input = await readBody(req, action === "import" ? 2_000_000 : 256_000);
|
|
35
|
+
return json(res, 200, await host.run(id, action, input, identify, controller.signal));
|
|
36
|
+
}
|
|
37
|
+
return json(res, 405, { error: "Method not allowed." });
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
const { status, body } = knowledgeFailure(error);
|
|
41
|
+
if (!res.destroyed)
|
|
42
|
+
return json(res, status, body);
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
res.off("close", cancel);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -7,7 +7,7 @@ import { phoneMovedRefusal } from "../move-freeze.js";
|
|
|
7
7
|
import { PASS } from "./table.js";
|
|
8
8
|
const freezeBody = z.object({ cloud: z.string().url().max(300).optional(), place: z.string().trim().min(1).max(120).optional() });
|
|
9
9
|
const thawBody = z.object({ automations: z.literal("off").optional() });
|
|
10
|
-
export function createMoveFreezeRoutes({ freeze, busy,
|
|
10
|
+
export function createMoveFreezeRoutes({ freeze, busy, automationsOff, platform = process.platform }) {
|
|
11
11
|
return async ({ req, res, path, method, auth, json, readBody }) => {
|
|
12
12
|
// Health still answers: without it the companion tells the phone OpenMausBot isn't ready here, and the phone keeps
|
|
13
13
|
// trying instead of reading the reason.
|
|
@@ -20,11 +20,7 @@ export function createMoveFreezeRoutes({ freeze, busy, restart, automationsOff,
|
|
|
20
20
|
return json(res, 403, { error: "Only Limix Bot on this computer can do this." });
|
|
21
21
|
if (method !== "POST")
|
|
22
22
|
return json(res, 405, { error: "method not allowed" });
|
|
23
|
-
|
|
24
|
-
return json(res, 409, { error: "Only a computer whose bots moved to My Cloud deletes its copy." });
|
|
25
|
-
json(res, 200, { forgot: true });
|
|
26
|
-
restart();
|
|
27
|
-
return;
|
|
23
|
+
return json(res, 409, { error: "This computer keeps its workspace after a transfer." });
|
|
28
24
|
}
|
|
29
25
|
if (path === "/api/move/freeze") {
|
|
30
26
|
if (auth.kind !== "loopback")
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{U as a,C as n}from"./mermaid.core-Cy9_uq1T.js";const t=(r,o)=>a.lang.round(n.parse(r)[o]);export{t as c};
|