@imliulian/dsh-zeromem 0.0.0-stage → 0.2.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/CHANGELOG.md +23 -0
- package/LICENSE +661 -0
- package/NOTICE +34 -0
- package/README.md +137 -2
- package/README.zh.md +139 -0
- package/assets/panel.js +2986 -0
- package/bin/dsh-zeromem.mjs +187 -0
- package/cordis.patch.yml +13 -0
- package/lib/config.mjs +469 -0
- package/lib/contracts.mjs +483 -0
- package/lib/expiry.mjs +359 -0
- package/lib/hooks.mjs +284 -0
- package/lib/index.mjs +120 -0
- package/lib/llm.mjs +827 -0
- package/lib/memory.mjs +824 -0
- package/lib/portability.mjs +819 -0
- package/lib/store.mjs +1248 -0
- package/lib/tools.mjs +527 -0
- package/lib/web.mjs +629 -0
- package/package.json +60 -4
package/lib/web.mjs
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH Web / Desktop HTTP backend and dual-channel UI script injection for ZeroMem.
|
|
3
|
+
*
|
|
4
|
+
* Dual-channel injection (works on both `dsh web` and official Electron DSH Desktop):
|
|
5
|
+
* 1. `registerDesktopIndexInject(root)` — registered synchronously at top of `apply(root)` via
|
|
6
|
+
* `webserver/index-inject` using an inline script that appends `<script src="/dsh-zeromem/panel.js">`
|
|
7
|
+
* with silent `onerror` so hot-disabling NEVER rejects Desktop boot.
|
|
8
|
+
* 2. `ctx.webServer.tapIndex(...)` — injects `<script defer src="/dsh-zeromem/panel.js">` in `dsh web`.
|
|
9
|
+
*
|
|
10
|
+
* Security fence (2-layer fail-closed):
|
|
11
|
+
* 1. Local loopback/trusted-host check + `Sec-Fetch-Site: cross-site` block + same-origin POST check.
|
|
12
|
+
* 2. Delegates to host `connection.requestRejection(req)` when available (fail-closed on throw).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
|
|
19
|
+
const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
20
|
+
const PANEL_JS_PATH = path.join(PACKAGE_ROOT, "assets", "panel.js");
|
|
21
|
+
const PKG_JSON_PATH = path.join(PACKAGE_ROOT, "package.json");
|
|
22
|
+
|
|
23
|
+
const JSON_HEADERS = Object.freeze({
|
|
24
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
25
|
+
"Cache-Control": "no-store",
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const DESKTOP_LOADER_INLINE =
|
|
29
|
+
'(function(){try{if(window.__DSH_ZEROMEM_LOADED__)return;' +
|
|
30
|
+
'var d=document.body||document.head||document.documentElement;if(!d)return;' +
|
|
31
|
+
'var s=document.createElement("script");s.src="/dsh-zeromem/panel.js";' +
|
|
32
|
+
's.onerror=function(){};d.appendChild(s);}catch(e){}})()';
|
|
33
|
+
|
|
34
|
+
let cachedPkgVersion = "0.1.0";
|
|
35
|
+
try {
|
|
36
|
+
const pkg = JSON.parse(fs.readFileSync(PKG_JSON_PATH, "utf8"));
|
|
37
|
+
if (pkg?.version) cachedPkgVersion = String(pkg.version);
|
|
38
|
+
} catch {
|
|
39
|
+
// ignore
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isLoopbackHostname(rawHost) {
|
|
43
|
+
const host = String(rawHost || "").trim().toLowerCase();
|
|
44
|
+
if (!host) return false;
|
|
45
|
+
let hn = host;
|
|
46
|
+
if (hn.startsWith("[")) {
|
|
47
|
+
const end = hn.indexOf("]");
|
|
48
|
+
hn = end !== -1 ? hn.slice(1, end) : hn;
|
|
49
|
+
} else {
|
|
50
|
+
const colon = hn.lastIndexOf(":");
|
|
51
|
+
if (colon !== -1 && hn.indexOf(":") === colon) {
|
|
52
|
+
hn = hn.slice(0, colon);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (hn === "localhost" || hn.endsWith(".localhost") || hn === "::1") return true;
|
|
56
|
+
const parts = hn.split(".");
|
|
57
|
+
if (parts.length === 4 && parts[0] === "127") {
|
|
58
|
+
return parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) >= 0 && Number(p) <= 255);
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function extractAuthority(headerVal) {
|
|
64
|
+
const raw = String(headerVal || "").trim();
|
|
65
|
+
if (!raw) return "";
|
|
66
|
+
try {
|
|
67
|
+
return new URL(raw).host.toLowerCase();
|
|
68
|
+
} catch {
|
|
69
|
+
return raw.toLowerCase();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function createRequestGuard(ctx) {
|
|
74
|
+
const envTrusted = String(process.env.DSH_ZEROMEM_TRUSTED_HOSTS || "")
|
|
75
|
+
.split(",")
|
|
76
|
+
.map((s) => s.trim().toLowerCase())
|
|
77
|
+
.filter(Boolean);
|
|
78
|
+
|
|
79
|
+
function trustedAuthorities() {
|
|
80
|
+
const set = new Set(envTrusted);
|
|
81
|
+
try {
|
|
82
|
+
const conn = typeof ctx?.get === "function" ? ctx.get("connection") : ctx?.connection;
|
|
83
|
+
if (Array.isArray(conn?.trustedHosts)) {
|
|
84
|
+
for (const h of conn.trustedHosts) {
|
|
85
|
+
if (typeof h === "string" && h.trim()) set.add(h.trim().toLowerCase());
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
} catch {
|
|
89
|
+
// ignore
|
|
90
|
+
}
|
|
91
|
+
return set;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return function rejectIfUnauthorized(req, res) {
|
|
95
|
+
const deny = (status, msg) => {
|
|
96
|
+
res.writeHead(status, JSON_HEADERS);
|
|
97
|
+
res.end(JSON.stringify({ ok: false, error: msg }));
|
|
98
|
+
return true;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const headers = req?.headers || {};
|
|
102
|
+
const hostHeader = String(headers.host || "").trim().toLowerCase();
|
|
103
|
+
const trusted = trustedAuthorities();
|
|
104
|
+
const hostAllowed =
|
|
105
|
+
isLoopbackHostname(hostHeader) ||
|
|
106
|
+
trusted.has(hostHeader) ||
|
|
107
|
+
trusted.has(hostHeader.split(":")[0]);
|
|
108
|
+
|
|
109
|
+
if (!hostAllowed) {
|
|
110
|
+
return deny(403, "Forbidden host authority");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const fetchSite = String(headers["sec-fetch-site"] || "").trim().toLowerCase();
|
|
114
|
+
if (fetchSite === "cross-site") {
|
|
115
|
+
return deny(403, "Cross-site request blocked");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const originHeader = String(headers.origin || "").trim();
|
|
119
|
+
if (originHeader) {
|
|
120
|
+
const originAuth = extractAuthority(originHeader);
|
|
121
|
+
const isAppScheme = originHeader.startsWith("dsh-app://") || originHeader === "null";
|
|
122
|
+
if (!isAppScheme && originAuth && hostHeader && originAuth !== hostHeader) {
|
|
123
|
+
return deny(403, "Origin mismatch");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Layer 2: delegate to host connection.requestRejection if present (fail-closed)
|
|
128
|
+
try {
|
|
129
|
+
const conn = typeof ctx?.get === "function" ? ctx.get("connection") : ctx?.connection;
|
|
130
|
+
if (conn && typeof conn.requestRejection === "function") {
|
|
131
|
+
const rejection = conn.requestRejection(req);
|
|
132
|
+
if (rejection !== undefined && rejection !== null && rejection !== false) {
|
|
133
|
+
if (typeof rejection === "number") return deny(rejection, "Rejected by host gate");
|
|
134
|
+
if (typeof rejection === "object" && typeof rejection.status === "number") {
|
|
135
|
+
return deny(rejection.status, String(rejection.message || "Rejected by host gate"));
|
|
136
|
+
}
|
|
137
|
+
return deny(403, "Rejected by host gate");
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
} catch {
|
|
141
|
+
return deny(403, "Host request gate error");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return false;
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function readJsonBody(req, maxBytes = 2 * 1024 * 1024) {
|
|
149
|
+
return new Promise((resolve, reject) => {
|
|
150
|
+
const chunks = [];
|
|
151
|
+
let total = 0;
|
|
152
|
+
req.on("data", (chunk) => {
|
|
153
|
+
total += chunk.length;
|
|
154
|
+
if (total > maxBytes) {
|
|
155
|
+
reject(new Error("Request body too large"));
|
|
156
|
+
req.destroy();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
chunks.push(chunk);
|
|
160
|
+
});
|
|
161
|
+
req.on("end", () => {
|
|
162
|
+
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
163
|
+
if (!raw) {
|
|
164
|
+
resolve({});
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
resolve(JSON.parse(raw));
|
|
169
|
+
} catch {
|
|
170
|
+
reject(new Error("Invalid JSON body"));
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
req.on("error", (err) => reject(err));
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function sendJson(res, status, payload) {
|
|
178
|
+
res.writeHead(status, JSON_HEADERS);
|
|
179
|
+
res.end(JSON.stringify(payload));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function parseQuery(reqUrl) {
|
|
183
|
+
try {
|
|
184
|
+
return new URL(String(reqUrl || "/"), "http://127.0.0.1").searchParams;
|
|
185
|
+
} catch {
|
|
186
|
+
return new URLSearchParams();
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function loadPanelJs() {
|
|
191
|
+
try {
|
|
192
|
+
return fs.readFileSync(PANEL_JS_PATH, "utf8");
|
|
193
|
+
} catch {
|
|
194
|
+
return "/* ZeroMem panel asset missing */";
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Must be called synchronously inside `apply(root)` before any `root.inject(...)`
|
|
200
|
+
* so official DSH Desktop collects the inline loader during initial boot.
|
|
201
|
+
*/
|
|
202
|
+
export function registerDesktopIndexInject(root) {
|
|
203
|
+
if (!root || typeof root.on !== "function") return () => {};
|
|
204
|
+
return root.on("webserver/index-inject", (table) => {
|
|
205
|
+
try {
|
|
206
|
+
if (!Array.isArray(table)) return;
|
|
207
|
+
for (const row of table) {
|
|
208
|
+
if (!row) continue;
|
|
209
|
+
if (row.kind === "script-src" && row.src === "/dsh-zeromem/panel.js") return;
|
|
210
|
+
if (row.kind === "script" && typeof row.text === "string" && row.text.includes("/dsh-zeromem/panel.js")) {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
table.push({ kind: "script", placement: "body", text: DESKTOP_LOADER_INLINE });
|
|
215
|
+
} catch {
|
|
216
|
+
// fail-open
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function mountWebServer(ctx, engine) {
|
|
222
|
+
const disposers = [];
|
|
223
|
+
if (!ctx?.webServer || typeof ctx.webServer.register !== "function") return () => {};
|
|
224
|
+
|
|
225
|
+
const reject = createRequestGuard(ctx);
|
|
226
|
+
const addRoute = (routePath, handler) => {
|
|
227
|
+
const dispose = ctx.webServer.register({
|
|
228
|
+
kind: "exact",
|
|
229
|
+
path: routePath,
|
|
230
|
+
handler: async (req, res) => {
|
|
231
|
+
if (reject(req, res)) return;
|
|
232
|
+
try {
|
|
233
|
+
await handler(req, res);
|
|
234
|
+
} catch (err) {
|
|
235
|
+
sendJson(res, 500, { ok: false, error: String(err?.message || err).slice(0, 300) });
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
if (typeof dispose === "function") disposers.push(dispose);
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const PANEL_ETAG = '"zm-c9f48efabf95bb82"';
|
|
243
|
+
|
|
244
|
+
addRoute("/dsh-zeromem/panel.js", async (_req, res) => {
|
|
245
|
+
const js = loadPanelJs();
|
|
246
|
+
res.writeHead(200, {
|
|
247
|
+
"Content-Type": "application/javascript; charset=utf-8",
|
|
248
|
+
"Cache-Control": "no-store",
|
|
249
|
+
ETag: PANEL_ETAG,
|
|
250
|
+
});
|
|
251
|
+
res.end(js);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
addRoute("/dsh-zeromem/api/status", async (req, res) => {
|
|
255
|
+
const qs = parseQuery(req.url);
|
|
256
|
+
const skipProbe = qs.get("quick") === "1";
|
|
257
|
+
const stats = engine.stats();
|
|
258
|
+
const config = engine.getPublicConfig();
|
|
259
|
+
const providerStatus = skipProbe
|
|
260
|
+
? { ok: true, provider: config.provider, state: "unchecked", model: config.provider === "ollama" ? config.ollamaModel : config.apiModel, message: "" }
|
|
261
|
+
: await engine.probeProvider();
|
|
262
|
+
sendJson(res, 200, {
|
|
263
|
+
ok: true,
|
|
264
|
+
version: cachedPkgVersion,
|
|
265
|
+
stats,
|
|
266
|
+
config,
|
|
267
|
+
provider_status: providerStatus,
|
|
268
|
+
activity: typeof engine.getActivitySnapshot === "function" ? engine.getActivitySnapshot() : { busy: false, count: 0, phase: "idle", label: "", since: 0 },
|
|
269
|
+
setup: typeof engine.getLocalSetupState === "function" ? engine.getLocalSetupState() : { active: false, status: "idle" },
|
|
270
|
+
runtime: engine.runtimeMetrics,
|
|
271
|
+
});
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
addRoute("/dsh-zeromem/api/local-setup", async (req, res) => {
|
|
275
|
+
const method = String(req.method || "GET").toUpperCase();
|
|
276
|
+
if (method === "GET") {
|
|
277
|
+
const probe = await engine.probeProvider({ provider: "ollama" });
|
|
278
|
+
sendJson(res, 200, {
|
|
279
|
+
ok: true,
|
|
280
|
+
probe,
|
|
281
|
+
setup: engine.getLocalSetupState(),
|
|
282
|
+
recommended_models: engine.getRecommendedLocalModels(),
|
|
283
|
+
install_guide: engine.getOllamaInstallGuide(),
|
|
284
|
+
});
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (method === "POST") {
|
|
288
|
+
const body = await readJsonBody(req);
|
|
289
|
+
const action = String(body?.action || "").trim();
|
|
290
|
+
if (action === "start-ollama") {
|
|
291
|
+
const result = await engine.startLocalOllama();
|
|
292
|
+
const probe = result.ok ? await engine.probeProvider({ provider: "ollama" }) : null;
|
|
293
|
+
sendJson(res, result.ok ? 200 : 400, { ok: Boolean(result.ok), result, probe, setup: engine.getLocalSetupState() });
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (action === "pull-model") {
|
|
297
|
+
const model = String(body?.model || "").trim();
|
|
298
|
+
const result = engine.startLocalModelPull(model);
|
|
299
|
+
sendJson(res, 200, { ok: true, ...result });
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (action === "cancel") {
|
|
303
|
+
const result = engine.cancelLocalModelPull();
|
|
304
|
+
sendJson(res, 200, { ok: true, ...result, setup: engine.getLocalSetupState() });
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
sendJson(res, 400, { ok: false, error: "Unsupported setup action" });
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
sendJson(res, 405, { ok: false, error: "GET or POST required" });
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
const sseClients = new Set();
|
|
314
|
+
addRoute("/dsh-zeromem/api/events", async (req, res) => {
|
|
315
|
+
res.writeHead(200, {
|
|
316
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
317
|
+
"Cache-Control": "no-store, no-transform",
|
|
318
|
+
Connection: "keep-alive",
|
|
319
|
+
"X-Accel-Buffering": "no",
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
const writeEvent = (eventName, payload) => {
|
|
323
|
+
try {
|
|
324
|
+
res.write(`event: ${eventName}\ndata: ${JSON.stringify(payload)}\n\n`);
|
|
325
|
+
} catch {
|
|
326
|
+
cleanup();
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
const unsub =
|
|
331
|
+
typeof engine.onActivity === "function"
|
|
332
|
+
? engine.onActivity((payload) => writeEvent("activity", payload))
|
|
333
|
+
: () => {};
|
|
334
|
+
|
|
335
|
+
const hb = setInterval(() => {
|
|
336
|
+
try {
|
|
337
|
+
res.write(": keepalive\n\n");
|
|
338
|
+
} catch {
|
|
339
|
+
cleanup();
|
|
340
|
+
}
|
|
341
|
+
}, 25_000);
|
|
342
|
+
if (typeof hb.unref === "function") hb.unref();
|
|
343
|
+
|
|
344
|
+
let closed = false;
|
|
345
|
+
const cleanup = () => {
|
|
346
|
+
if (closed) return;
|
|
347
|
+
closed = true;
|
|
348
|
+
clearInterval(hb);
|
|
349
|
+
unsub();
|
|
350
|
+
sseClients.delete(cleanup);
|
|
351
|
+
try {
|
|
352
|
+
res.end();
|
|
353
|
+
} catch {
|
|
354
|
+
// ignore
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
sseClients.add(cleanup);
|
|
358
|
+
if (typeof req.on === "function") {
|
|
359
|
+
req.on("close", cleanup);
|
|
360
|
+
req.on("aborted", cleanup);
|
|
361
|
+
}
|
|
362
|
+
if (typeof res.on === "function") {
|
|
363
|
+
res.on("close", cleanup);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
writeEvent("activity", {
|
|
367
|
+
activity: typeof engine.getActivitySnapshot === "function" ? engine.getActivitySnapshot() : { busy: false, count: 0, phase: "idle", label: "", since: 0 },
|
|
368
|
+
setup: typeof engine.getLocalSetupState === "function" ? engine.getLocalSetupState() : { active: false, status: "idle" },
|
|
369
|
+
stats_dirty: false,
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
disposers.push(() => {
|
|
373
|
+
for (const c of [...sseClients]) c();
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
addRoute("/dsh-zeromem/api/background", async (req, res) => {
|
|
377
|
+
const method = String(req.method || "GET").toUpperCase();
|
|
378
|
+
if (method === "GET") {
|
|
379
|
+
const bg = engine.readBackground();
|
|
380
|
+
if (!bg) {
|
|
381
|
+
res.writeHead(204, { "Cache-Control": "no-store" });
|
|
382
|
+
res.end();
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
res.writeHead(200, {
|
|
386
|
+
"Content-Type": bg.contentType,
|
|
387
|
+
"Content-Length": String(bg.buffer.length),
|
|
388
|
+
"Cache-Control": "private, max-age=86400",
|
|
389
|
+
"X-Content-Type-Options": "nosniff",
|
|
390
|
+
});
|
|
391
|
+
res.end(bg.buffer);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
if (method === "POST") {
|
|
395
|
+
const body = await readJsonBody(req, 8.5 * 1024 * 1024);
|
|
396
|
+
const dataUrl = String(body?.dataUrl || "").trim();
|
|
397
|
+
const m = /^data:image\/[a-z0-9.+-]+;base64,([A-Za-z0-9+/=\s]+)$/i.exec(dataUrl);
|
|
398
|
+
if (!m) {
|
|
399
|
+
sendJson(res, 400, { ok: false, error: "无效的图片数据格式" });
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
const buf = Buffer.from(m[1].replace(/\s+/g, ""), "base64");
|
|
403
|
+
try {
|
|
404
|
+
const updated = engine.saveBackground(buf);
|
|
405
|
+
sendJson(res, 200, { ok: true, config: updated });
|
|
406
|
+
} catch (err) {
|
|
407
|
+
sendJson(res, 400, { ok: false, error: String(err?.message || err) });
|
|
408
|
+
}
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (method === "DELETE") {
|
|
412
|
+
const updated = engine.clearBackground();
|
|
413
|
+
sendJson(res, 200, { ok: true, config: updated });
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
sendJson(res, 405, { ok: false, error: "GET, POST or DELETE required" });
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
addRoute("/dsh-zeromem/api/memories", async (req, res) => {
|
|
420
|
+
const qs = parseQuery(req.url);
|
|
421
|
+
const q = qs.get("q") || "";
|
|
422
|
+
const ns = qs.get("ns") || null;
|
|
423
|
+
const limit = Math.max(1, Math.min(Number(qs.get("limit") || 50) || 50, 100));
|
|
424
|
+
const occurredFrom = qs.get("occurred_from") || null;
|
|
425
|
+
const occurredTo = qs.get("occurred_to") || null;
|
|
426
|
+
const rawIncSup = qs.get("include_superseded");
|
|
427
|
+
const includeSuperseded =
|
|
428
|
+
rawIncSup === null ? true : !["0", "false", "no", "off"].includes(rawIncSup.trim().toLowerCase());
|
|
429
|
+
const t0 = Date.now();
|
|
430
|
+
try {
|
|
431
|
+
// Always disable adaptive pruning in the human workbench browse view so users see complete matches
|
|
432
|
+
const items = engine.recall(q, {
|
|
433
|
+
ns,
|
|
434
|
+
limit,
|
|
435
|
+
adaptive: false,
|
|
436
|
+
occurredFrom,
|
|
437
|
+
occurredTo,
|
|
438
|
+
includeSuperseded,
|
|
439
|
+
});
|
|
440
|
+
sendJson(res, 200, {
|
|
441
|
+
ok: true,
|
|
442
|
+
count: items.length,
|
|
443
|
+
elapsed_ms: Date.now() - t0,
|
|
444
|
+
items,
|
|
445
|
+
});
|
|
446
|
+
} catch (err) {
|
|
447
|
+
const msg = String(err?.message || err);
|
|
448
|
+
const status = msg.startsWith("invalid-occurred-") ? 400 : 500;
|
|
449
|
+
sendJson(res, status, { ok: false, error: msg.slice(0, 240) });
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
addRoute("/dsh-zeromem/api/export.md", async (req, res) => {
|
|
454
|
+
const method = String(req.method || "GET").toUpperCase();
|
|
455
|
+
if (method !== "GET") {
|
|
456
|
+
sendJson(res, 405, { ok: false, error: "GET required" });
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
const qs = parseQuery(req.url);
|
|
460
|
+
const ns = qs.get("ns") || null;
|
|
461
|
+
const occurredFrom = qs.get("occurred_from") || null;
|
|
462
|
+
const occurredTo = qs.get("occurred_to") || null;
|
|
463
|
+
const rawIncSup = qs.get("include_superseded");
|
|
464
|
+
const includeSuperseded =
|
|
465
|
+
rawIncSup === null ? true : !["0", "false", "no", "off"].includes(rawIncSup.trim().toLowerCase());
|
|
466
|
+
const includeEvicted = ["1", "true", "yes"].includes(String(qs.get("include_evicted") || "").toLowerCase());
|
|
467
|
+
const frontmatter = !["0", "false", "no"].includes(String(qs.get("frontmatter") || "1").toLowerCase());
|
|
468
|
+
const asDownload = ["1", "true"].includes(String(qs.get("download") || "").toLowerCase());
|
|
469
|
+
|
|
470
|
+
try {
|
|
471
|
+
const exp = engine.exportMarkdown({
|
|
472
|
+
ns,
|
|
473
|
+
occurredFrom,
|
|
474
|
+
occurredTo,
|
|
475
|
+
includeSuperseded,
|
|
476
|
+
includeEvicted,
|
|
477
|
+
frontmatter,
|
|
478
|
+
});
|
|
479
|
+
const stamp = new Date().toISOString().slice(0, 10);
|
|
480
|
+
const safeNs = ns ? `-${String(ns).replace(/[^A-Za-z0-9._-]+/g, "_").slice(0, 32)}` : "";
|
|
481
|
+
const filename = `zeromem-export${safeNs}-${stamp}.md`;
|
|
482
|
+
const headers = {
|
|
483
|
+
"Content-Type": "text/markdown; charset=utf-8",
|
|
484
|
+
"Cache-Control": "no-store",
|
|
485
|
+
"X-Content-Type-Options": "nosniff",
|
|
486
|
+
};
|
|
487
|
+
if (asDownload) {
|
|
488
|
+
headers["Content-Disposition"] = `attachment; filename="${filename}"`;
|
|
489
|
+
}
|
|
490
|
+
res.writeHead(200, headers);
|
|
491
|
+
res.end(exp.markdown || "");
|
|
492
|
+
} catch (err) {
|
|
493
|
+
const msg = String(err?.message || err);
|
|
494
|
+
const status = msg.startsWith("invalid-occurred-") ? 400 : 500;
|
|
495
|
+
sendJson(res, status, { ok: false, error: msg.slice(0, 240) });
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
addRoute("/dsh-zeromem/api/backup", async (req, res) => {
|
|
500
|
+
const method = String(req.method || "POST").toUpperCase();
|
|
501
|
+
if (method !== "POST") {
|
|
502
|
+
sendJson(res, 405, { ok: false, error: "POST required" });
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
const body = await readJsonBody(req);
|
|
506
|
+
const writeSha256 = body?.sha256 !== undefined ? Boolean(body.sha256) : true;
|
|
507
|
+
const verify = body?.verify !== undefined ? Boolean(body.verify) : true;
|
|
508
|
+
// Always write into the fixed local <db_dir>/backups/ folder (never accept arbitrary client paths)
|
|
509
|
+
const receipt = await engine.backup(null, { writeSha256, verify });
|
|
510
|
+
sendJson(res, 200, { ok: true, receipt });
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
addRoute("/dsh-zeromem/api/document", async (req, res) => {
|
|
514
|
+
const qs = parseQuery(req.url);
|
|
515
|
+
const docId = String(qs.get("doc_id") || "").trim();
|
|
516
|
+
if (!docId) {
|
|
517
|
+
sendJson(res, 400, { ok: false, error: "doc_id is required" });
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
const doc = engine.getDocument(docId);
|
|
521
|
+
if (!doc) {
|
|
522
|
+
sendJson(res, 404, { ok: false, error: "document not found" });
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
sendJson(res, 200, { ok: true, document: doc });
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
addRoute("/dsh-zeromem/api/remember", async (req, res) => {
|
|
529
|
+
if (String(req.method || "").toUpperCase() !== "POST") {
|
|
530
|
+
sendJson(res, 405, { ok: false, error: "POST required" });
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
const body = await readJsonBody(req);
|
|
534
|
+
const content = String(body?.content || "").trim();
|
|
535
|
+
if (!content) {
|
|
536
|
+
sendJson(res, 400, { ok: false, error: "请输入要记录的内容" });
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
const result = await engine.remember(content, {
|
|
540
|
+
ns: body?.namespace ? String(body.namespace).trim() : null,
|
|
541
|
+
sourceId: body?.source_id ? String(body.source_id).trim() : "dsh-web-workbench",
|
|
542
|
+
verify: body?.verify !== undefined ? Boolean(body.verify) : null,
|
|
543
|
+
});
|
|
544
|
+
sendJson(res, 200, { ok: true, result });
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
addRoute("/dsh-zeromem/api/evict", async (req, res) => {
|
|
548
|
+
if (String(req.method || "").toUpperCase() !== "POST") {
|
|
549
|
+
sendJson(res, 405, { ok: false, error: "POST required" });
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const body = await readJsonBody(req);
|
|
553
|
+
const result = engine.softEvict({
|
|
554
|
+
factIds: body?.fact_id !== undefined && body?.fact_id !== null ? [Number(body.fact_id)] : Array.isArray(body?.fact_ids) ? body.fact_ids : [],
|
|
555
|
+
docIds: body?.doc_id ? [String(body.doc_id)] : Array.isArray(body?.doc_ids) ? body.doc_ids : [],
|
|
556
|
+
expired: Boolean(body?.expired),
|
|
557
|
+
namespace: body?.namespace ? String(body.namespace).trim() : null,
|
|
558
|
+
reason: body?.reason ? String(body.reason) : "web-workbench",
|
|
559
|
+
force: Boolean(body?.force),
|
|
560
|
+
});
|
|
561
|
+
sendJson(res, 200, { ok: true, result });
|
|
562
|
+
});
|
|
563
|
+
|
|
564
|
+
addRoute("/dsh-zeromem/api/evicted", async (req, res) => {
|
|
565
|
+
const qs = parseQuery(req.url);
|
|
566
|
+
const limit = Math.max(1, Math.min(Number(qs.get("limit") || 50) || 50, 200));
|
|
567
|
+
const batches = engine.listEvictedBatches(limit);
|
|
568
|
+
sendJson(res, 200, { ok: true, batches });
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
addRoute("/dsh-zeromem/api/restore", async (req, res) => {
|
|
572
|
+
if (String(req.method || "").toUpperCase() !== "POST") {
|
|
573
|
+
sendJson(res, 405, { ok: false, error: "POST required" });
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
const body = await readJsonBody(req);
|
|
577
|
+
const batchId = String(body?.batch_id || "").trim();
|
|
578
|
+
if (!batchId) {
|
|
579
|
+
sendJson(res, 400, { ok: false, error: "batch_id is required" });
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
const result = engine.restoreEvicted(batchId);
|
|
583
|
+
sendJson(res, 200, { ok: true, result });
|
|
584
|
+
});
|
|
585
|
+
|
|
586
|
+
addRoute("/dsh-zeromem/api/config", async (req, res) => {
|
|
587
|
+
const method = String(req.method || "GET").toUpperCase();
|
|
588
|
+
if (method === "GET") {
|
|
589
|
+
sendJson(res, 200, { ok: true, config: engine.getPublicConfig() });
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
if (method === "POST") {
|
|
593
|
+
const body = await readJsonBody(req);
|
|
594
|
+
const updated = engine.updateConfig(body || {});
|
|
595
|
+
sendJson(res, 200, { ok: true, config: updated });
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
sendJson(res, 405, { ok: false, error: "GET or POST required" });
|
|
599
|
+
});
|
|
600
|
+
|
|
601
|
+
addRoute("/dsh-zeromem/api/test-provider", async (req, res) => {
|
|
602
|
+
if (String(req.method || "").toUpperCase() !== "POST") {
|
|
603
|
+
sendJson(res, 405, { ok: false, error: "POST required" });
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
const body = await readJsonBody(req);
|
|
607
|
+
const probe = await engine.probeProvider(body || {}, { liveChat: Boolean(body?.liveChat) });
|
|
608
|
+
sendJson(res, 200, { ok: true, probe });
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
if (typeof ctx.webServer.tapIndex === "function") {
|
|
612
|
+
const disposeTap = ctx.webServer.tapIndex((html) => {
|
|
613
|
+
if (typeof html !== "string" || html.includes("/dsh-zeromem/panel.js")) return html;
|
|
614
|
+
const tag = '<script defer src="/dsh-zeromem/panel.js"></script>';
|
|
615
|
+
return html.includes("</body>") ? html.replace("</body>", `${tag}</body>`) : `${html}${tag}`;
|
|
616
|
+
});
|
|
617
|
+
if (typeof disposeTap === "function") disposers.push(disposeTap);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
return () => {
|
|
621
|
+
for (const d of disposers) {
|
|
622
|
+
try {
|
|
623
|
+
d();
|
|
624
|
+
} catch {
|
|
625
|
+
// ignore
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imliulian/dsh-zeromem",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "ZeroMem (零忆) local evidence-grounded memory system for DeepSeek Harness — single-file node:sqlite + CJK/EN FTS5 (<1ms recall), timeline supersession & date-range filtering, read-only Markdown export, SQLite Online Backup, pre-write admission verification, credential redaction, until: expiry, SHA-256 lossless restore, local Ollama & OpenAI-compatible API support.",
|
|
5
|
+
"license": "AGPL-3.0-only",
|
|
6
|
+
"author": "IMLIULIAN (ZeroZoneX)",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./lib/index.mjs",
|
|
9
|
+
"bin": {
|
|
10
|
+
"dsh-zeromem": "bin/dsh-zeromem.mjs"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./lib/index.mjs",
|
|
14
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"bin",
|
|
19
|
+
"lib",
|
|
20
|
+
"assets",
|
|
21
|
+
"cordis.patch.yml",
|
|
22
|
+
"README.md",
|
|
23
|
+
"README.zh.md",
|
|
24
|
+
"CHANGELOG.md",
|
|
25
|
+
"LICENSE",
|
|
26
|
+
"NOTICE"
|
|
27
|
+
],
|
|
28
|
+
"keywords": [
|
|
29
|
+
"dsh",
|
|
30
|
+
"dsh-plugin",
|
|
31
|
+
"deepseek-harness",
|
|
32
|
+
"memory",
|
|
33
|
+
"zeromem",
|
|
34
|
+
"sqlite",
|
|
35
|
+
"fts5",
|
|
36
|
+
"ollama",
|
|
37
|
+
"local-ai"
|
|
38
|
+
],
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": "^22.19.0 || >=24.0.0"
|
|
41
|
+
},
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "git+https://github.com/IMLIULIAN/dsh-zeromem.git"
|
|
45
|
+
},
|
|
46
|
+
"homepage": "https://github.com/IMLIULIAN/dsh-zeromem#readme",
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/IMLIULIAN/dsh-zeromem/issues"
|
|
49
|
+
},
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
},
|
|
53
|
+
"dsh": {
|
|
54
|
+
"bundle": {
|
|
55
|
+
"patch": "./cordis.patch.yml"
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"check": "node --check assets/panel.js && node --check bin/dsh-zeromem.mjs",
|
|
60
|
+
"test": "node --test tests/contracts_and_llm.test.mjs tests/dsh_plugin.test.mjs tests/store_and_expiry.test.mjs tests/timeline_and_portability.test.mjs"
|
|
61
|
+
}
|
|
62
|
+
}
|