@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
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Zero-dependency CLI for @imliulian/dsh-zeromem:
|
|
4
|
+
* dsh-zeromem search <query> [--db PATH] [--ns NS] [--occurred-from DATE] [--occurred-to DATE] [--hide-superseded] [--limit N] [--json]
|
|
5
|
+
* dsh-zeromem export --md [--db PATH] [-o FILE | --dir DIR] [--ns NS] [--occurred-from DATE] [--occurred-to DATE] [--as-of DATE] [--hide-superseded] [--include-evicted] [--no-frontmatter] [--json]
|
|
6
|
+
* dsh-zeromem backup [OUT] [--db PATH] [-o OUT] [--overwrite] [--no-verify] [--sha256] [--json]
|
|
7
|
+
* dsh-zeromem stats [--db PATH] [--ns NS] [--json]
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { defaultDbPath, expandHome } from "../lib/config.mjs";
|
|
11
|
+
import { backupDatabase, exportMarkdown } from "../lib/portability.mjs";
|
|
12
|
+
import { SQLiteMemoryStore } from "../lib/store.mjs";
|
|
13
|
+
|
|
14
|
+
function printHelp() {
|
|
15
|
+
console.log(`dsh-zeromem — ZeroMem (零忆) local SQLite memory CLI
|
|
16
|
+
|
|
17
|
+
Usage:
|
|
18
|
+
dsh-zeromem search [query] [--db PATH] [--ns NS] [--occurred-from DATE] [--occurred-to DATE] [--hide-superseded] [--limit N] [--json]
|
|
19
|
+
dsh-zeromem export --md [--db PATH] [-o FILE | --dir DIR] [--ns NS] [--occurred-from DATE] [--occurred-to DATE] [--as-of DATE] [--hide-superseded] [--include-evicted] [--no-frontmatter] [--json]
|
|
20
|
+
dsh-zeromem backup [OUT] [--db PATH] [-o OUT] [--overwrite] [--no-verify] [--sha256] [--json]
|
|
21
|
+
dsh-zeromem stats [--db PATH] [--ns NS] [--json]
|
|
22
|
+
`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function parseArgs(argv) {
|
|
26
|
+
const flags = {};
|
|
27
|
+
const positionals = [];
|
|
28
|
+
const valueFlags = new Set([
|
|
29
|
+
"--db",
|
|
30
|
+
"--ns",
|
|
31
|
+
"--namespace",
|
|
32
|
+
"--limit",
|
|
33
|
+
"--as-of",
|
|
34
|
+
"--occurred-from",
|
|
35
|
+
"--occurred-to",
|
|
36
|
+
"-o",
|
|
37
|
+
"--output",
|
|
38
|
+
"--dir",
|
|
39
|
+
]);
|
|
40
|
+
for (let i = 0; i < argv.length; i++) {
|
|
41
|
+
const arg = argv[i];
|
|
42
|
+
if (arg === "-h" || arg === "--help") {
|
|
43
|
+
flags.help = true;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (valueFlags.has(arg)) {
|
|
47
|
+
const next = argv[i + 1];
|
|
48
|
+
if (next === undefined) throw new Error(`Missing value for ${arg}`);
|
|
49
|
+
flags[arg] = next;
|
|
50
|
+
i += 1;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (arg.startsWith("--") && arg.includes("=")) {
|
|
54
|
+
const idx = arg.indexOf("=");
|
|
55
|
+
flags[arg.slice(0, idx)] = arg.slice(idx + 1);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (arg.startsWith("-")) {
|
|
59
|
+
flags[arg] = true;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
positionals.push(arg);
|
|
63
|
+
}
|
|
64
|
+
return { flags, positionals };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function runCli(argv = process.argv.slice(2)) {
|
|
68
|
+
const { flags, positionals } = parseArgs(argv);
|
|
69
|
+
const cmd = positionals[0];
|
|
70
|
+
if (!cmd || flags.help) {
|
|
71
|
+
printHelp();
|
|
72
|
+
return 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const dbPath = flags["--db"] ? expandHome(flags["--db"]) : defaultDbPath();
|
|
76
|
+
const ns = flags["--ns"] || flags["--namespace"] || null;
|
|
77
|
+
const asJson = Boolean(flags["--json"]);
|
|
78
|
+
|
|
79
|
+
if (cmd === "stats") {
|
|
80
|
+
const store = new SQLiteMemoryStore(dbPath);
|
|
81
|
+
const st = store.stats(ns);
|
|
82
|
+
if (asJson) {
|
|
83
|
+
console.log(JSON.stringify(st, null, 2));
|
|
84
|
+
} else {
|
|
85
|
+
console.log(`DB: ${st.db_path}`);
|
|
86
|
+
console.log(
|
|
87
|
+
`Documents: ${st.documents} | Segments: ${st.segments} | Facts: ${st.facts} (revised ${st.revised_facts}) | Supersessions: ${st.supersessions} | Evicted: ${st.evicted_records}`
|
|
88
|
+
);
|
|
89
|
+
console.log(`Namespaces: ${st.namespaces.length ? st.namespaces.join(", ") : "(none)"}`);
|
|
90
|
+
}
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (cmd === "search") {
|
|
95
|
+
const query = positionals.slice(1).join(" ");
|
|
96
|
+
const store = new SQLiteMemoryStore(dbPath);
|
|
97
|
+
const hits = store.search(query, {
|
|
98
|
+
namespace: ns,
|
|
99
|
+
limit: flags["--limit"] ? Number(flags["--limit"]) : null,
|
|
100
|
+
asOf: flags["--as-of"] || null,
|
|
101
|
+
occurredFrom: flags["--occurred-from"] || null,
|
|
102
|
+
occurredTo: flags["--occurred-to"] || null,
|
|
103
|
+
includeSuperseded: !flags["--hide-superseded"],
|
|
104
|
+
});
|
|
105
|
+
if (asJson) {
|
|
106
|
+
console.log(JSON.stringify(hits, null, 2));
|
|
107
|
+
} else if (!hits.length) {
|
|
108
|
+
console.log("(no matching memories)");
|
|
109
|
+
} else {
|
|
110
|
+
for (let i = 0; i < hits.length; i++) {
|
|
111
|
+
const h = hits[i];
|
|
112
|
+
const badges = [];
|
|
113
|
+
if (h.occurred_start) badges.push(h.occurred_start);
|
|
114
|
+
if (h.supersedes_fact_id) badges.push(`替代 #${h.supersedes_fact_id}`);
|
|
115
|
+
if (h.superseded_by?.length) badges.push(`已被 ${h.superseded_by.map((x) => `#${x}`).join(",")} 替代`);
|
|
116
|
+
if (h.until_expiry?.label) badges.push(h.until_expiry.label);
|
|
117
|
+
const badgeStr = badges.length ? ` [${badges.join(" | ")}]` : "";
|
|
118
|
+
console.log(`${i + 1}. (#${h.fact_id} · ${h.namespace}${badgeStr}) ${h.text}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return 0;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (cmd === "export") {
|
|
125
|
+
const outputPath = flags["-o"] || flags["--output"] || null;
|
|
126
|
+
const outputDir = flags["--dir"] || null;
|
|
127
|
+
const res = exportMarkdown({
|
|
128
|
+
dbPath,
|
|
129
|
+
outputPath,
|
|
130
|
+
outputDir,
|
|
131
|
+
namespace: ns,
|
|
132
|
+
occurredFrom: flags["--occurred-from"] || null,
|
|
133
|
+
occurredTo: flags["--occurred-to"] || null,
|
|
134
|
+
asOf: flags["--as-of"] || null,
|
|
135
|
+
includeSuperseded: !flags["--hide-superseded"],
|
|
136
|
+
includeEvicted: Boolean(flags["--include-evicted"]),
|
|
137
|
+
frontmatter: !flags["--no-frontmatter"],
|
|
138
|
+
});
|
|
139
|
+
if (res.mode === "stdout" && !asJson) {
|
|
140
|
+
process.stdout.write(res.markdown || "");
|
|
141
|
+
} else if (asJson) {
|
|
142
|
+
const out = { ...res };
|
|
143
|
+
if (out.mode !== "stdout") delete out.markdown;
|
|
144
|
+
console.log(JSON.stringify(out, null, 2));
|
|
145
|
+
} else {
|
|
146
|
+
console.log(
|
|
147
|
+
`Exported ${res.facts_exported} facts (${res.documents_referenced} docs) -> ${res.output_dir || res.output_path}`
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
return 0;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (cmd === "backup") {
|
|
154
|
+
const outTarget = flags["-o"] || flags["--output"] || positionals[1] || null;
|
|
155
|
+
const receipt = await backupDatabase({
|
|
156
|
+
dbPath,
|
|
157
|
+
outputPath: outTarget,
|
|
158
|
+
overwrite: Boolean(flags["--overwrite"]),
|
|
159
|
+
verify: !flags["--no-verify"],
|
|
160
|
+
writeSha256: Boolean(flags["--sha256"]),
|
|
161
|
+
});
|
|
162
|
+
if (asJson) {
|
|
163
|
+
console.log(JSON.stringify(receipt, null, 2));
|
|
164
|
+
} else {
|
|
165
|
+
console.log(
|
|
166
|
+
`Backup OK (${receipt.journal_mode}, integrity=${receipt.integrity_check}, ${receipt.size_bytes} B): ${receipt.backup_path}`
|
|
167
|
+
);
|
|
168
|
+
console.log(`SHA-256: ${receipt.sha256}`);
|
|
169
|
+
}
|
|
170
|
+
return 0;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
throw new Error(`Unknown command: ${cmd}`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const isMain = process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop());
|
|
177
|
+
if (isMain) {
|
|
178
|
+
runCli().then(
|
|
179
|
+
(code) => {
|
|
180
|
+
process.exitCode = code;
|
|
181
|
+
},
|
|
182
|
+
(err) => {
|
|
183
|
+
console.error(`dsh-zeromem error: ${err?.message || err}`);
|
|
184
|
+
process.exitCode = 1;
|
|
185
|
+
}
|
|
186
|
+
);
|
|
187
|
+
}
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# DeepSeek Harness profile bundle patch for ZeroMem (零忆).
|
|
2
|
+
#
|
|
3
|
+
# Install via DSH CLI or DSH Plugin Market:
|
|
4
|
+
# dsh plugin --profile web add @imliulian/dsh-zeromem
|
|
5
|
+
# Or local link during development:
|
|
6
|
+
# dsh plugin --profile <test-profile> add link:<absolute-path>
|
|
7
|
+
#
|
|
8
|
+
# To disable without uninstalling, add `disabled: true` under `id: zeromem` in
|
|
9
|
+
# your profile's cordis.patch.yml.
|
|
10
|
+
- insert:
|
|
11
|
+
- id: zeromem
|
|
12
|
+
name: "@imliulian/dsh-zeromem"
|
|
13
|
+
config: {}
|
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration management for @imliulian/dsh-zeromem.
|
|
3
|
+
*
|
|
4
|
+
* Supports dual LLM extraction/admission backends:
|
|
5
|
+
* 1. Local Ollama (`provider: "ollama"`, default — Qwen3.5-4B-Memory-V2, zero cloud cost)
|
|
6
|
+
* 2. OpenAI-compatible API (`provider: "openai-compatible"` — DeepSeek, OpenAI, SiliconFlow,
|
|
7
|
+
* OpenRouter, LM Studio, vLLM, or any `/v1/chat/completions` endpoint)
|
|
8
|
+
*
|
|
9
|
+
* Security invariants:
|
|
10
|
+
* - Config persisted locally at `~/.zeromem/dsh-zeromem.json` (0600 on POSIX).
|
|
11
|
+
* - `publicConfig()` NEVER returns plaintext `apiKey` (only `apiKeySet` + masked hint).
|
|
12
|
+
* - Database path defaults to `~/.zeromem/memory.db` (compatible with Python ZeroMem & legacy `~/.v2-memory/memory.db`).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import os from "node:os";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434";
|
|
20
|
+
export const DEFAULT_API_BASE_URL = "https://api.deepseek.com/v1";
|
|
21
|
+
export const DEFAULT_API_MODEL = "deepseek-chat";
|
|
22
|
+
export const DEFAULT_NUM_CTX = 8192;
|
|
23
|
+
export const MAX_BACKGROUND_BYTES = 6 * 1024 * 1024;
|
|
24
|
+
export const CONFIG_SCHEMA_REV = "c9f48efa";
|
|
25
|
+
|
|
26
|
+
const SAFE_BG_FILE_RE = /^panel-bg\.(png|jpg|webp|gif|avif)$/;
|
|
27
|
+
const EXT_TO_MIME = Object.freeze({
|
|
28
|
+
png: "image/png",
|
|
29
|
+
jpg: "image/jpeg",
|
|
30
|
+
webp: "image/webp",
|
|
31
|
+
gif: "image/gif",
|
|
32
|
+
avif: "image/avif",
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
export function detectSafeImageType(buf) {
|
|
36
|
+
if (!Buffer.isBuffer(buf) || buf.length < 12) return null;
|
|
37
|
+
// PNG: 89 50 4E 47 0D 0A 1A 0A
|
|
38
|
+
if (
|
|
39
|
+
buf[0] === 0x89 &&
|
|
40
|
+
buf[1] === 0x50 &&
|
|
41
|
+
buf[2] === 0x4e &&
|
|
42
|
+
buf[3] === 0x47 &&
|
|
43
|
+
buf[4] === 0x0d &&
|
|
44
|
+
buf[5] === 0x0a &&
|
|
45
|
+
buf[6] === 0x1a &&
|
|
46
|
+
buf[7] === 0x0a
|
|
47
|
+
) {
|
|
48
|
+
return { ext: "png", mime: "image/png" };
|
|
49
|
+
}
|
|
50
|
+
// JPEG: FF D8 FF
|
|
51
|
+
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
|
|
52
|
+
return { ext: "jpg", mime: "image/jpeg" };
|
|
53
|
+
}
|
|
54
|
+
// WebP: RIFF....WEBP
|
|
55
|
+
if (
|
|
56
|
+
buf.toString("ascii", 0, 4) === "RIFF" &&
|
|
57
|
+
buf.toString("ascii", 8, 12) === "WEBP"
|
|
58
|
+
) {
|
|
59
|
+
return { ext: "webp", mime: "image/webp" };
|
|
60
|
+
}
|
|
61
|
+
// GIF: GIF87a / GIF89a
|
|
62
|
+
const gifSig = buf.toString("ascii", 0, 6);
|
|
63
|
+
if (gifSig === "GIF87a" || gifSig === "GIF89a") {
|
|
64
|
+
return { ext: "gif", mime: "image/gif" };
|
|
65
|
+
}
|
|
66
|
+
// AVIF: ....ftypavif / ....ftypavis
|
|
67
|
+
if (buf.toString("ascii", 4, 8) === "ftyp") {
|
|
68
|
+
const brand = buf.toString("ascii", 8, 12);
|
|
69
|
+
if (brand === "avif" || brand === "avis") {
|
|
70
|
+
return { ext: "avif", mime: "image/avif" };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function normalizeUiTheme(raw) {
|
|
77
|
+
const low = String(raw || "").trim().toLowerCase();
|
|
78
|
+
if (low === "dark") return "dark";
|
|
79
|
+
return "light";
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function sanitizeBgFileName(raw) {
|
|
83
|
+
const s = String(raw || "").trim();
|
|
84
|
+
return SAFE_BG_FILE_RE.test(s) ? s : "";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const API_PRESETS = Object.freeze([
|
|
88
|
+
{
|
|
89
|
+
id: "deepseek",
|
|
90
|
+
label: "DeepSeek",
|
|
91
|
+
baseUrl: "https://api.deepseek.com/v1",
|
|
92
|
+
model: "deepseek-chat",
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
id: "openai",
|
|
96
|
+
label: "OpenAI",
|
|
97
|
+
baseUrl: "https://api.openai.com/v1",
|
|
98
|
+
model: "gpt-4o-mini",
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: "siliconflow",
|
|
102
|
+
label: "SiliconFlow",
|
|
103
|
+
baseUrl: "https://api.siliconflow.cn/v1",
|
|
104
|
+
model: "Qwen/Qwen2.5-7B-Instruct",
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
id: "openrouter",
|
|
108
|
+
label: "OpenRouter",
|
|
109
|
+
baseUrl: "https://openrouter.ai/api/v1",
|
|
110
|
+
model: "deepseek/deepseek-chat",
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
id: "custom",
|
|
114
|
+
label: "自定义 API",
|
|
115
|
+
baseUrl: "",
|
|
116
|
+
model: "",
|
|
117
|
+
isCustom: true,
|
|
118
|
+
},
|
|
119
|
+
]);
|
|
120
|
+
|
|
121
|
+
export function defaultHomeDir(homeDir = os.homedir()) {
|
|
122
|
+
const newDir = path.join(homeDir, ".zeromem");
|
|
123
|
+
const legacyDir = path.join(homeDir, ".v2-memory");
|
|
124
|
+
if (
|
|
125
|
+
fs.existsSync(path.join(legacyDir, "memory.db")) &&
|
|
126
|
+
!fs.existsSync(path.join(newDir, "memory.db"))
|
|
127
|
+
) {
|
|
128
|
+
return legacyDir;
|
|
129
|
+
}
|
|
130
|
+
return newDir;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function defaultDbPath(env = process.env, homeDir = os.homedir()) {
|
|
134
|
+
const envPath = String(env.ZEROMEM_DB || env.V2MEM_DB || "").trim();
|
|
135
|
+
if (envPath) return expandHome(envPath, homeDir);
|
|
136
|
+
return path.join(defaultHomeDir(homeDir), "memory.db");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function defaultConfigPath(env = process.env, homeDir = os.homedir()) {
|
|
140
|
+
const explicit = String(env.ZEROMEM_DSH_CONFIG || "").trim();
|
|
141
|
+
if (explicit) return expandHome(explicit, homeDir);
|
|
142
|
+
return path.join(defaultHomeDir(homeDir), "dsh-zeromem.json");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function expandHome(inputPath, homeDir = os.homedir()) {
|
|
146
|
+
const raw = String(inputPath || "").trim();
|
|
147
|
+
if (!raw) return "";
|
|
148
|
+
if (raw === "~") return homeDir;
|
|
149
|
+
if (raw.startsWith("~/") || raw.startsWith("~\\")) {
|
|
150
|
+
return path.join(homeDir, raw.slice(2));
|
|
151
|
+
}
|
|
152
|
+
return path.resolve(raw);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function maskSecret(secret) {
|
|
156
|
+
const s = String(secret || "").trim();
|
|
157
|
+
if (!s) return "";
|
|
158
|
+
if (s.length <= 8) return "*".repeat(Math.max(4, s.length));
|
|
159
|
+
return `${s.slice(0, 4)}***${s.slice(-4)}`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function asBool(value, fallback) {
|
|
163
|
+
if (typeof value === "boolean") return value;
|
|
164
|
+
if (typeof value === "string") {
|
|
165
|
+
const low = value.trim().toLowerCase();
|
|
166
|
+
if (["1", "true", "yes", "on"].includes(low)) return true;
|
|
167
|
+
if (["0", "false", "no", "off"].includes(low)) return false;
|
|
168
|
+
}
|
|
169
|
+
return fallback;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function asPositiveInt(value, fallback, minVal, maxVal) {
|
|
173
|
+
const n = Number(value);
|
|
174
|
+
if (!Number.isFinite(n)) return fallback;
|
|
175
|
+
return Math.max(minVal, Math.min(maxVal, Math.round(n)));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function normalizeProvider(raw) {
|
|
179
|
+
const low = String(raw || "").trim().toLowerCase();
|
|
180
|
+
if (["api", "openai", "openai-compatible", "remote", "cloud"].includes(low)) {
|
|
181
|
+
return "openai-compatible";
|
|
182
|
+
}
|
|
183
|
+
return "ollama";
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function normalizeNamespaceMode(raw) {
|
|
187
|
+
const low = String(raw || "").trim().toLowerCase();
|
|
188
|
+
if (low === "fixed" || low === "single") return "fixed";
|
|
189
|
+
return "workspace";
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function buildDefaultConfig({ env = process.env, homeDir = os.homedir() } = {}) {
|
|
193
|
+
return {
|
|
194
|
+
provider: normalizeProvider(env.ZEROMEM_PROVIDER || "ollama"),
|
|
195
|
+
dbPath: defaultDbPath(env, homeDir),
|
|
196
|
+
ollamaUrl: String(env.ZEROMEM_OLLAMA_URL || env.V2MEM_OLLAMA_URL || DEFAULT_OLLAMA_URL).trim(),
|
|
197
|
+
ollamaModel: String(env.ZEROMEM_MODEL || env.V2MEM_MODEL || "").trim(),
|
|
198
|
+
numCtx: asPositiveInt(env.ZEROMEM_NUM_CTX || env.V2MEM_NUM_CTX, DEFAULT_NUM_CTX, 2048, 32768),
|
|
199
|
+
apiBaseUrl: String(env.ZEROMEM_API_BASE_URL || DEFAULT_API_BASE_URL).trim(),
|
|
200
|
+
apiKey: String(env.ZEROMEM_API_KEY || "").trim(),
|
|
201
|
+
apiModel: String(env.ZEROMEM_API_MODEL || DEFAULT_API_MODEL).trim(),
|
|
202
|
+
customApiBaseUrl: "",
|
|
203
|
+
customApiModel: "",
|
|
204
|
+
timeoutMs: asPositiveInt(Number(env.ZEROMEM_TIMEOUT || 90) * 1000, 90_000, 5_000, 300_000),
|
|
205
|
+
verify: true,
|
|
206
|
+
autoRecall: true,
|
|
207
|
+
autoRemember: true,
|
|
208
|
+
adaptive: true,
|
|
209
|
+
untilExpiry: true,
|
|
210
|
+
namespaceMode: "workspace",
|
|
211
|
+
defaultNamespace: "default",
|
|
212
|
+
recallMaxItems: 6,
|
|
213
|
+
recallMinQueryChars: 4,
|
|
214
|
+
rememberMinTurns: 1,
|
|
215
|
+
uiTheme: normalizeUiTheme(env.ZEROMEM_UI_THEME || "light"),
|
|
216
|
+
uiGlassBlur: 30,
|
|
217
|
+
uiGlassTint: 60,
|
|
218
|
+
uiBgFile: "",
|
|
219
|
+
uiBgUpdatedAt: "",
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export function sanitizeConfigPatch(patch, base, { homeDir = os.homedir() } = {}) {
|
|
224
|
+
const next = { ...base };
|
|
225
|
+
if (!patch || typeof patch !== "object") return next;
|
|
226
|
+
|
|
227
|
+
if (patch.provider !== undefined) next.provider = normalizeProvider(patch.provider);
|
|
228
|
+
if (patch.dbPath !== undefined && String(patch.dbPath).trim()) {
|
|
229
|
+
next.dbPath = expandHome(patch.dbPath, homeDir);
|
|
230
|
+
}
|
|
231
|
+
if (patch.ollamaUrl !== undefined) {
|
|
232
|
+
const u = String(patch.ollamaUrl || "").trim().replace(/\/+$/, "");
|
|
233
|
+
if (u) next.ollamaUrl = u;
|
|
234
|
+
}
|
|
235
|
+
if (patch.ollamaModel !== undefined) {
|
|
236
|
+
next.ollamaModel = String(patch.ollamaModel || "").trim();
|
|
237
|
+
}
|
|
238
|
+
if (patch.numCtx !== undefined) {
|
|
239
|
+
next.numCtx = asPositiveInt(patch.numCtx, next.numCtx, 2048, 32768);
|
|
240
|
+
}
|
|
241
|
+
if (patch.apiBaseUrl !== undefined) {
|
|
242
|
+
const u = String(patch.apiBaseUrl || "").trim().replace(/\/+$/, "");
|
|
243
|
+
if (u) next.apiBaseUrl = u;
|
|
244
|
+
}
|
|
245
|
+
if (patch.clearApiKey === true) {
|
|
246
|
+
next.apiKey = "";
|
|
247
|
+
} else if (typeof patch.apiKey === "string") {
|
|
248
|
+
const trimmed = patch.apiKey.trim();
|
|
249
|
+
// Ignore empty string so UI updates without retyping key keep existing key
|
|
250
|
+
if (trimmed) next.apiKey = trimmed;
|
|
251
|
+
}
|
|
252
|
+
if (patch.apiModel !== undefined) {
|
|
253
|
+
const m = String(patch.apiModel || "").trim();
|
|
254
|
+
if (m) next.apiModel = m;
|
|
255
|
+
}
|
|
256
|
+
if (patch.customApiBaseUrl !== undefined) {
|
|
257
|
+
next.customApiBaseUrl = String(patch.customApiBaseUrl || "").trim().replace(/\/+$/, "").slice(0, 300);
|
|
258
|
+
}
|
|
259
|
+
if (patch.customApiModel !== undefined) {
|
|
260
|
+
next.customApiModel = String(patch.customApiModel || "").trim().slice(0, 160);
|
|
261
|
+
}
|
|
262
|
+
if (patch.timeoutMs !== undefined) {
|
|
263
|
+
next.timeoutMs = asPositiveInt(patch.timeoutMs, next.timeoutMs, 5_000, 300_000);
|
|
264
|
+
}
|
|
265
|
+
if (patch.verify !== undefined) next.verify = asBool(patch.verify, next.verify);
|
|
266
|
+
if (patch.autoRecall !== undefined) next.autoRecall = asBool(patch.autoRecall, next.autoRecall);
|
|
267
|
+
if (patch.autoRemember !== undefined) next.autoRemember = asBool(patch.autoRemember, next.autoRemember);
|
|
268
|
+
if (patch.adaptive !== undefined) next.adaptive = asBool(patch.adaptive, next.adaptive);
|
|
269
|
+
if (patch.untilExpiry !== undefined) next.untilExpiry = asBool(patch.untilExpiry, next.untilExpiry);
|
|
270
|
+
if (patch.namespaceMode !== undefined) next.namespaceMode = normalizeNamespaceMode(patch.namespaceMode);
|
|
271
|
+
if (patch.defaultNamespace !== undefined) {
|
|
272
|
+
const ns = String(patch.defaultNamespace || "").trim();
|
|
273
|
+
if (ns) next.defaultNamespace = ns.slice(0, 80);
|
|
274
|
+
}
|
|
275
|
+
if (patch.recallMaxItems !== undefined) {
|
|
276
|
+
next.recallMaxItems = asPositiveInt(patch.recallMaxItems, next.recallMaxItems, 1, 16);
|
|
277
|
+
}
|
|
278
|
+
if (patch.recallMinQueryChars !== undefined) {
|
|
279
|
+
next.recallMinQueryChars = asPositiveInt(patch.recallMinQueryChars, next.recallMinQueryChars, 1, 64);
|
|
280
|
+
}
|
|
281
|
+
if (patch.rememberMinTurns !== undefined) {
|
|
282
|
+
next.rememberMinTurns = asPositiveInt(patch.rememberMinTurns, next.rememberMinTurns, 1, 20);
|
|
283
|
+
}
|
|
284
|
+
if (patch.uiTheme !== undefined) {
|
|
285
|
+
next.uiTheme = normalizeUiTheme(patch.uiTheme);
|
|
286
|
+
}
|
|
287
|
+
if (patch.uiGlassBlur !== undefined) {
|
|
288
|
+
next.uiGlassBlur = asPositiveInt(patch.uiGlassBlur, next.uiGlassBlur, 0, 48);
|
|
289
|
+
}
|
|
290
|
+
if (patch.uiGlassTint !== undefined) {
|
|
291
|
+
next.uiGlassTint = asPositiveInt(patch.uiGlassTint, next.uiGlassTint, 25, 95);
|
|
292
|
+
}
|
|
293
|
+
if (patch.uiBgFile !== undefined) {
|
|
294
|
+
next.uiBgFile = sanitizeBgFileName(patch.uiBgFile);
|
|
295
|
+
}
|
|
296
|
+
if (patch.uiBgUpdatedAt !== undefined) {
|
|
297
|
+
next.uiBgUpdatedAt = String(patch.uiBgUpdatedAt || "").trim().slice(0, 40);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return next;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export class ConfigManager {
|
|
304
|
+
constructor({ configPath, initialOverrides = null, env = process.env, homeDir = os.homedir() } = {}) {
|
|
305
|
+
this.env = env;
|
|
306
|
+
this.homeDir = homeDir;
|
|
307
|
+
this.configPath = configPath ? expandHome(configPath, homeDir) : defaultConfigPath(env, homeDir);
|
|
308
|
+
this.initialOverrides = initialOverrides && typeof initialOverrides === "object" ? initialOverrides : null;
|
|
309
|
+
this._config = this.reload();
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
reload() {
|
|
313
|
+
let cfg = buildDefaultConfig({ env: this.env, homeDir: this.homeDir });
|
|
314
|
+
if (this.initialOverrides) {
|
|
315
|
+
cfg = sanitizeConfigPatch(this.initialOverrides, cfg, { homeDir: this.homeDir });
|
|
316
|
+
}
|
|
317
|
+
try {
|
|
318
|
+
if (fs.existsSync(this.configPath)) {
|
|
319
|
+
const raw = fs.readFileSync(this.configPath, "utf8");
|
|
320
|
+
const parsed = JSON.parse(raw);
|
|
321
|
+
cfg = sanitizeConfigPatch(parsed, cfg, { homeDir: this.homeDir });
|
|
322
|
+
}
|
|
323
|
+
} catch {
|
|
324
|
+
// Fail-open: corrupted user JSON falls back cleanly to defaults
|
|
325
|
+
}
|
|
326
|
+
this._config = cfg;
|
|
327
|
+
return cfg;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
get() {
|
|
331
|
+
return { ...this._config };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
effectiveApiKey(cfg = this._config) {
|
|
335
|
+
return (
|
|
336
|
+
String(cfg.apiKey || "").trim() ||
|
|
337
|
+
String(this.env.ZEROMEM_API_KEY || "").trim()
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
backgroundPathFor(fileName = this._config?.uiBgFile) {
|
|
342
|
+
const safe = sanitizeBgFileName(fileName);
|
|
343
|
+
if (!safe) return "";
|
|
344
|
+
return path.join(path.dirname(this.configPath), safe);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
hasBackgroundFile() {
|
|
348
|
+
const fp = this.backgroundPathFor();
|
|
349
|
+
return Boolean(fp && fs.existsSync(fp));
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
readBackground() {
|
|
353
|
+
const safe = sanitizeBgFileName(this._config?.uiBgFile);
|
|
354
|
+
if (!safe) return null;
|
|
355
|
+
const fp = path.join(path.dirname(this.configPath), safe);
|
|
356
|
+
if (!fs.existsSync(fp)) return null;
|
|
357
|
+
const ext = safe.split(".").pop();
|
|
358
|
+
const contentType = EXT_TO_MIME[ext] || "application/octet-stream";
|
|
359
|
+
return {
|
|
360
|
+
buffer: fs.readFileSync(fp),
|
|
361
|
+
contentType,
|
|
362
|
+
updatedAt: this._config.uiBgUpdatedAt || "",
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
saveBackground(buffer) {
|
|
367
|
+
if (!Buffer.isBuffer(buffer) || !buffer.length) {
|
|
368
|
+
throw new Error("背景图片为空");
|
|
369
|
+
}
|
|
370
|
+
if (buffer.length > MAX_BACKGROUND_BYTES) {
|
|
371
|
+
throw new Error("图片超过 6 MB 限制,请压缩后重试");
|
|
372
|
+
}
|
|
373
|
+
const detected = detectSafeImageType(buffer);
|
|
374
|
+
if (!detected) {
|
|
375
|
+
throw new Error("仅支持 PNG / JPG / WebP / GIF / AVIF 图片");
|
|
376
|
+
}
|
|
377
|
+
const dir = path.dirname(this.configPath);
|
|
378
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
379
|
+
const fileName = `panel-bg.${detected.ext}`;
|
|
380
|
+
const targetPath = path.join(dir, fileName);
|
|
381
|
+
const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
|
|
382
|
+
fs.writeFileSync(tmpPath, buffer, { mode: 0o600 });
|
|
383
|
+
fs.renameSync(tmpPath, targetPath);
|
|
384
|
+
|
|
385
|
+
// Clean up any previous background file with another extension
|
|
386
|
+
for (const ext of Object.keys(EXT_TO_MIME)) {
|
|
387
|
+
if (ext === detected.ext) continue;
|
|
388
|
+
const oldPath = path.join(dir, `panel-bg.${ext}`);
|
|
389
|
+
try {
|
|
390
|
+
if (fs.existsSync(oldPath)) fs.unlinkSync(oldPath);
|
|
391
|
+
} catch {
|
|
392
|
+
// ignore
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const updatedAt = String(Date.now());
|
|
397
|
+
return this.update({ uiBgFile: fileName, uiBgUpdatedAt: updatedAt });
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
clearBackground() {
|
|
401
|
+
const dir = path.dirname(this.configPath);
|
|
402
|
+
for (const ext of Object.keys(EXT_TO_MIME)) {
|
|
403
|
+
const oldPath = path.join(dir, `panel-bg.${ext}`);
|
|
404
|
+
try {
|
|
405
|
+
if (fs.existsSync(oldPath)) fs.unlinkSync(oldPath);
|
|
406
|
+
} catch {
|
|
407
|
+
// ignore
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return this.update({ uiBgFile: "", uiBgUpdatedAt: "" });
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
publicConfig() {
|
|
414
|
+
const cfg = this._config;
|
|
415
|
+
const key = this.effectiveApiKey(cfg);
|
|
416
|
+
const keyFromEnv = !cfg.apiKey && Boolean(String(this.env.ZEROMEM_API_KEY || "").trim());
|
|
417
|
+
const hasBg = this.hasBackgroundFile();
|
|
418
|
+
const bgVer = cfg.uiBgUpdatedAt || "1";
|
|
419
|
+
return {
|
|
420
|
+
provider: cfg.provider,
|
|
421
|
+
dbPath: cfg.dbPath,
|
|
422
|
+
configPath: this.configPath,
|
|
423
|
+
ollamaUrl: cfg.ollamaUrl,
|
|
424
|
+
ollamaModel: cfg.ollamaModel,
|
|
425
|
+
numCtx: cfg.numCtx,
|
|
426
|
+
apiBaseUrl: cfg.apiBaseUrl,
|
|
427
|
+
apiModel: cfg.apiModel,
|
|
428
|
+
customApiBaseUrl: cfg.customApiBaseUrl || "",
|
|
429
|
+
customApiModel: cfg.customApiModel || "",
|
|
430
|
+
apiKeySet: Boolean(key),
|
|
431
|
+
apiKeyMasked: key ? maskSecret(key) : "",
|
|
432
|
+
apiKeySource: cfg.apiKey ? "config" : keyFromEnv ? "env" : "none",
|
|
433
|
+
timeoutMs: cfg.timeoutMs,
|
|
434
|
+
verify: cfg.verify,
|
|
435
|
+
autoRecall: cfg.autoRecall,
|
|
436
|
+
autoRemember: cfg.autoRemember,
|
|
437
|
+
adaptive: cfg.adaptive,
|
|
438
|
+
untilExpiry: cfg.untilExpiry,
|
|
439
|
+
namespaceMode: cfg.namespaceMode,
|
|
440
|
+
defaultNamespace: cfg.defaultNamespace,
|
|
441
|
+
recallMaxItems: cfg.recallMaxItems,
|
|
442
|
+
recallMinQueryChars: cfg.recallMinQueryChars,
|
|
443
|
+
rememberMinTurns: cfg.rememberMinTurns,
|
|
444
|
+
uiTheme: cfg.uiTheme || "light",
|
|
445
|
+
uiGlassBlur: cfg.uiGlassBlur ?? 30,
|
|
446
|
+
uiGlassTint: cfg.uiGlassTint ?? 60,
|
|
447
|
+
uiHasBackground: hasBg,
|
|
448
|
+
uiBackgroundUrl: hasBg ? `/dsh-zeromem/api/background?v=${encodeURIComponent(bgVer)}` : "",
|
|
449
|
+
presets: API_PRESETS,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
update(patch) {
|
|
454
|
+
const next = sanitizeConfigPatch(patch, this._config, { homeDir: this.homeDir });
|
|
455
|
+
const dir = path.dirname(this.configPath);
|
|
456
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
457
|
+
const tmp = `${this.configPath}.tmp.${process.pid}.${Date.now()}`;
|
|
458
|
+
const serialized = `${JSON.stringify({ configRev: CONFIG_SCHEMA_REV, ...next }, null, 2)}\n`;
|
|
459
|
+
fs.writeFileSync(tmp, serialized, { encoding: "utf8", mode: 0o600 });
|
|
460
|
+
fs.renameSync(tmp, this.configPath);
|
|
461
|
+
try {
|
|
462
|
+
fs.chmodSync(this.configPath, 0o600);
|
|
463
|
+
} catch {
|
|
464
|
+
// Windows does not enforce POSIX chmod bits
|
|
465
|
+
}
|
|
466
|
+
this._config = next;
|
|
467
|
+
return this.publicConfig();
|
|
468
|
+
}
|
|
469
|
+
}
|