@imliulian/dsh-zeromem 0.0.0-stage → 0.1.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 +13 -0
- package/LICENSE +661 -0
- package/NOTICE +17 -0
- package/README.md +112 -2
- package/README.zh.md +114 -0
- package/assets/panel.js +2880 -0
- package/cordis.patch.yml +13 -0
- package/lib/config.mjs +469 -0
- package/lib/contracts.mjs +391 -0
- package/lib/expiry.mjs +255 -0
- package/lib/hooks.mjs +278 -0
- package/lib/index.mjs +118 -0
- package/lib/llm.mjs +823 -0
- package/lib/memory.mjs +654 -0
- package/lib/store.mjs +1008 -0
- package/lib/tools.mjs +470 -0
- package/lib/web.mjs +551 -0
- package/package.json +56 -4
package/lib/memory.mjs
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* High-level ZeroMem engine for DeepSeek Harness.
|
|
3
|
+
*
|
|
4
|
+
* Bridges:
|
|
5
|
+
* - ConfigManager (live-reloadable Local Ollama <-> OpenAI-compatible API switch)
|
|
6
|
+
* - SQLiteMemoryStore (node:sqlite single-file DB, 100% compatible with Python ZeroMem)
|
|
7
|
+
* - V2 dual-contract extraction + 1-round admission + deterministic guard + pre-API redaction
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import {
|
|
12
|
+
FACT_ADMISSION_SYSTEM,
|
|
13
|
+
FACT_EXTRACTION_SYSTEM,
|
|
14
|
+
VALID_DECISIONS,
|
|
15
|
+
buildSegments,
|
|
16
|
+
guardFact,
|
|
17
|
+
parseJsonObject,
|
|
18
|
+
segmentToPayload,
|
|
19
|
+
windowSegments,
|
|
20
|
+
} from "./contracts.mjs";
|
|
21
|
+
import { ConfigManager } from "./config.mjs";
|
|
22
|
+
import { ADAPTIVE_MIN_LIMIT, ADAPTIVE_SCORE_RATIO } from "./expiry.mjs";
|
|
23
|
+
import {
|
|
24
|
+
RECOMMENDED_LOCAL_PULL_MODELS,
|
|
25
|
+
createLlmAdapter,
|
|
26
|
+
getOllamaInstallGuide,
|
|
27
|
+
pullOllamaModel,
|
|
28
|
+
startLocalOllamaService,
|
|
29
|
+
} from "./llm.mjs";
|
|
30
|
+
import { SQLiteMemoryStore } from "./store.mjs";
|
|
31
|
+
|
|
32
|
+
function utcNowIso() {
|
|
33
|
+
return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class ZeroMemEngine {
|
|
37
|
+
constructor({ configManager = null, configOptions = {}, llmFactory = createLlmAdapter } = {}) {
|
|
38
|
+
this.configManager = configManager || new ConfigManager(configOptions);
|
|
39
|
+
this.llmFactory = llmFactory;
|
|
40
|
+
this._store = null;
|
|
41
|
+
this._storePath = "";
|
|
42
|
+
this._taskSeq = 0;
|
|
43
|
+
this._activeTasks = new Map();
|
|
44
|
+
this._activityListeners = new Set();
|
|
45
|
+
this._pulse = null;
|
|
46
|
+
this._pulseTimer = null;
|
|
47
|
+
this._setupState = {
|
|
48
|
+
active: false,
|
|
49
|
+
action: "",
|
|
50
|
+
model: "",
|
|
51
|
+
status: "idle",
|
|
52
|
+
completed: 0,
|
|
53
|
+
total: 0,
|
|
54
|
+
percent: null,
|
|
55
|
+
error: "",
|
|
56
|
+
startedAt: 0,
|
|
57
|
+
};
|
|
58
|
+
this._pullAbort = null;
|
|
59
|
+
this.runtimeMetrics = {
|
|
60
|
+
startedAt: utcNowIso(),
|
|
61
|
+
autoRecalls: 0,
|
|
62
|
+
autoRemembers: 0,
|
|
63
|
+
autoRememberErrors: 0,
|
|
64
|
+
lastError: "",
|
|
65
|
+
lastRememberAt: "",
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
_emitActivity(extra = {}) {
|
|
70
|
+
if (!this._activityListeners.size) return;
|
|
71
|
+
const payload = {
|
|
72
|
+
activity: this.getActivitySnapshot(),
|
|
73
|
+
setup: this.getLocalSetupState(),
|
|
74
|
+
stats_dirty: Boolean(extra.statsDirty),
|
|
75
|
+
};
|
|
76
|
+
for (const fn of [...this._activityListeners]) {
|
|
77
|
+
try {
|
|
78
|
+
fn(payload);
|
|
79
|
+
} catch {
|
|
80
|
+
// fail-open
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
getLocalSetupState() {
|
|
86
|
+
return { ...this._setupState };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async startLocalOllama() {
|
|
90
|
+
if (this._setupState.active) {
|
|
91
|
+
return { ok: false, error: "当前已有安装或启动任务进行中" };
|
|
92
|
+
}
|
|
93
|
+
const cfg = this.getConfig();
|
|
94
|
+
const task = this.beginActivity("setup", "启动 Ollama");
|
|
95
|
+
this._setupState = {
|
|
96
|
+
active: true,
|
|
97
|
+
action: "start-ollama",
|
|
98
|
+
model: "",
|
|
99
|
+
status: "starting",
|
|
100
|
+
completed: 0,
|
|
101
|
+
total: 0,
|
|
102
|
+
percent: null,
|
|
103
|
+
error: "",
|
|
104
|
+
startedAt: Date.now(),
|
|
105
|
+
};
|
|
106
|
+
this._emitActivity();
|
|
107
|
+
try {
|
|
108
|
+
const res = await startLocalOllamaService({ baseUrl: cfg.ollamaUrl });
|
|
109
|
+
this._setupState = {
|
|
110
|
+
...this._setupState,
|
|
111
|
+
active: false,
|
|
112
|
+
status: res.ok ? "done" : "error",
|
|
113
|
+
error: res.ok ? "" : String(res.message || "启动失败"),
|
|
114
|
+
};
|
|
115
|
+
return res;
|
|
116
|
+
} catch (err) {
|
|
117
|
+
const msg = String(err?.message || err);
|
|
118
|
+
this._setupState = { ...this._setupState, active: false, status: "error", error: msg };
|
|
119
|
+
return { ok: false, message: msg };
|
|
120
|
+
} finally {
|
|
121
|
+
task.end({ statsDirty: true });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
startLocalModelPull(requestedModel = "") {
|
|
126
|
+
if (this._setupState.active) {
|
|
127
|
+
return { ok: true, alreadyActive: true, setup: this.getLocalSetupState() };
|
|
128
|
+
}
|
|
129
|
+
const cfg = this.getConfig();
|
|
130
|
+
const model = String(requestedModel || RECOMMENDED_LOCAL_PULL_MODELS[0].id).trim();
|
|
131
|
+
const abortCtrl = new AbortController();
|
|
132
|
+
this._pullAbort = abortCtrl;
|
|
133
|
+
const task = this.beginActivity("pull", "下载模型");
|
|
134
|
+
this._setupState = {
|
|
135
|
+
active: true,
|
|
136
|
+
action: "pull-model",
|
|
137
|
+
model,
|
|
138
|
+
status: "connecting",
|
|
139
|
+
completed: 0,
|
|
140
|
+
total: 0,
|
|
141
|
+
percent: 0,
|
|
142
|
+
error: "",
|
|
143
|
+
startedAt: Date.now(),
|
|
144
|
+
};
|
|
145
|
+
this._emitActivity();
|
|
146
|
+
|
|
147
|
+
let lastBroadcastAt = 0;
|
|
148
|
+
void pullOllamaModel({
|
|
149
|
+
baseUrl: cfg.ollamaUrl,
|
|
150
|
+
model,
|
|
151
|
+
signal: abortCtrl.signal,
|
|
152
|
+
onProgress: (p) => {
|
|
153
|
+
this._setupState = {
|
|
154
|
+
...this._setupState,
|
|
155
|
+
status: p.status || "pulling",
|
|
156
|
+
completed: p.completed || 0,
|
|
157
|
+
total: p.total || 0,
|
|
158
|
+
percent: p.percent,
|
|
159
|
+
};
|
|
160
|
+
const now = Date.now();
|
|
161
|
+
if (now - lastBroadcastAt >= 250 || p.percent === 100) {
|
|
162
|
+
lastBroadcastAt = now;
|
|
163
|
+
const label = Number.isFinite(p.percent) && p.percent > 0 ? `下载 ${p.percent}%` : "下载模型";
|
|
164
|
+
task.update("pull", label);
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
})
|
|
168
|
+
.then(() => {
|
|
169
|
+
this._setupState = {
|
|
170
|
+
...this._setupState,
|
|
171
|
+
active: false,
|
|
172
|
+
status: "success",
|
|
173
|
+
percent: 100,
|
|
174
|
+
error: "",
|
|
175
|
+
};
|
|
176
|
+
if (this.getConfig().provider !== "ollama") {
|
|
177
|
+
this.updateConfig({ provider: "ollama" });
|
|
178
|
+
}
|
|
179
|
+
})
|
|
180
|
+
.catch((err) => {
|
|
181
|
+
const cancelled = abortCtrl.signal.aborted;
|
|
182
|
+
this._setupState = {
|
|
183
|
+
...this._setupState,
|
|
184
|
+
active: false,
|
|
185
|
+
status: cancelled ? "cancelled" : "error",
|
|
186
|
+
error: cancelled ? "已取消下载" : String(err?.message || err),
|
|
187
|
+
};
|
|
188
|
+
})
|
|
189
|
+
.finally(() => {
|
|
190
|
+
if (this._pullAbort === abortCtrl) this._pullAbort = null;
|
|
191
|
+
task.end({ statsDirty: true });
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
return { ok: true, started: true, setup: this.getLocalSetupState() };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
cancelLocalModelPull() {
|
|
198
|
+
if (this._pullAbort) {
|
|
199
|
+
this._pullAbort.abort();
|
|
200
|
+
return { ok: true, cancelled: true };
|
|
201
|
+
}
|
|
202
|
+
return { ok: true, cancelled: false };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
getRecommendedLocalModels() {
|
|
206
|
+
return RECOMMENDED_LOCAL_PULL_MODELS;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
getOllamaInstallGuide() {
|
|
210
|
+
return getOllamaInstallGuide();
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
onActivity(fn) {
|
|
214
|
+
if (typeof fn !== "function") return () => {};
|
|
215
|
+
this._activityListeners.add(fn);
|
|
216
|
+
return () => {
|
|
217
|
+
this._activityListeners.delete(fn);
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
getActivitySnapshot() {
|
|
222
|
+
const now = Date.now();
|
|
223
|
+
if (this._activeTasks.size > 0) {
|
|
224
|
+
let oldest = Infinity;
|
|
225
|
+
let latest = null;
|
|
226
|
+
for (const t of this._activeTasks.values()) {
|
|
227
|
+
if (t.startedAt < oldest) oldest = t.startedAt;
|
|
228
|
+
latest = t;
|
|
229
|
+
}
|
|
230
|
+
return {
|
|
231
|
+
busy: true,
|
|
232
|
+
count: this._activeTasks.size,
|
|
233
|
+
phase: latest?.phase || "working",
|
|
234
|
+
label: latest?.label || "处理中",
|
|
235
|
+
since: Number.isFinite(oldest) ? oldest : now,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
if (this._pulse && this._pulse.until > now) {
|
|
239
|
+
return {
|
|
240
|
+
busy: true,
|
|
241
|
+
count: 1,
|
|
242
|
+
phase: this._pulse.phase,
|
|
243
|
+
label: this._pulse.label,
|
|
244
|
+
since: this._pulse.since,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
busy: false,
|
|
249
|
+
count: 0,
|
|
250
|
+
phase: "idle",
|
|
251
|
+
label: "",
|
|
252
|
+
since: 0,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
beginActivity(phase = "working", label = "处理中") {
|
|
257
|
+
const id = ++this._taskSeq;
|
|
258
|
+
const entry = { phase: String(phase || "working"), label: String(label || "处理中"), startedAt: Date.now() };
|
|
259
|
+
this._activeTasks.set(id, entry);
|
|
260
|
+
this._emitActivity();
|
|
261
|
+
let ended = false;
|
|
262
|
+
return {
|
|
263
|
+
update: (nextPhase, nextLabel) => {
|
|
264
|
+
if (ended) return;
|
|
265
|
+
const cur = this._activeTasks.get(id);
|
|
266
|
+
if (!cur) return;
|
|
267
|
+
cur.phase = String(nextPhase || cur.phase);
|
|
268
|
+
cur.label = String(nextLabel || cur.label);
|
|
269
|
+
this._emitActivity();
|
|
270
|
+
},
|
|
271
|
+
end: ({ statsDirty = false } = {}) => {
|
|
272
|
+
if (ended) return;
|
|
273
|
+
ended = true;
|
|
274
|
+
this._activeTasks.delete(id);
|
|
275
|
+
this._emitActivity({ statsDirty });
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
pulseActivity(phase = "recall", label = "召回", durationMs = 1800) {
|
|
281
|
+
const now = Date.now();
|
|
282
|
+
const dur = Math.max(300, Math.min(8000, Number(durationMs) || 1800));
|
|
283
|
+
this._pulse = { phase: String(phase || "recall"), label: String(label || "处理中"), since: now, until: now + dur };
|
|
284
|
+
this._emitActivity();
|
|
285
|
+
if (this._pulseTimer) clearTimeout(this._pulseTimer);
|
|
286
|
+
this._pulseTimer = setTimeout(() => {
|
|
287
|
+
this._pulse = null;
|
|
288
|
+
this._pulseTimer = null;
|
|
289
|
+
this._emitActivity();
|
|
290
|
+
}, dur + 30);
|
|
291
|
+
if (typeof this._pulseTimer.unref === "function") this._pulseTimer.unref();
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
readBackground() {
|
|
295
|
+
return this.configManager.readBackground();
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
saveBackground(buffer) {
|
|
299
|
+
return this.configManager.saveBackground(buffer);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
clearBackground() {
|
|
303
|
+
return this.configManager.clearBackground();
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
getConfig() {
|
|
307
|
+
return this.configManager.get();
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
getPublicConfig() {
|
|
311
|
+
return this.configManager.publicConfig();
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
updateConfig(patch) {
|
|
315
|
+
const pub = this.configManager.update(patch);
|
|
316
|
+
// Reset cached store pointer if DB path changed
|
|
317
|
+
if (this._storePath && this._storePath !== pub.dbPath) {
|
|
318
|
+
this._store = null;
|
|
319
|
+
this._storePath = "";
|
|
320
|
+
}
|
|
321
|
+
return pub;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
getStore() {
|
|
325
|
+
const cfg = this.getConfig();
|
|
326
|
+
if (!this._store || this._storePath !== cfg.dbPath) {
|
|
327
|
+
this._store = new SQLiteMemoryStore(cfg.dbPath);
|
|
328
|
+
this._storePath = cfg.dbPath;
|
|
329
|
+
}
|
|
330
|
+
return this._store;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
getLlm(overrideCfg = null) {
|
|
334
|
+
const cfg = overrideCfg || this.getConfig();
|
|
335
|
+
const apiKey =
|
|
336
|
+
overrideCfg && typeof overrideCfg.apiKey === "string" && overrideCfg.apiKey.trim()
|
|
337
|
+
? overrideCfg.apiKey.trim()
|
|
338
|
+
: this.configManager.effectiveApiKey(cfg);
|
|
339
|
+
return this.llmFactory(cfg, { apiKey });
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async probeProvider(overridePatch = null, { liveChat = false } = {}) {
|
|
343
|
+
const task = this.beginActivity("probe", "检测中");
|
|
344
|
+
try {
|
|
345
|
+
const base = this.getConfig();
|
|
346
|
+
const merged = overridePatch
|
|
347
|
+
? {
|
|
348
|
+
...base,
|
|
349
|
+
...overridePatch,
|
|
350
|
+
provider: overridePatch.provider || base.provider,
|
|
351
|
+
apiKey:
|
|
352
|
+
overridePatch.clearApiKey === true
|
|
353
|
+
? ""
|
|
354
|
+
: typeof overridePatch.apiKey === "string" && overridePatch.apiKey.trim()
|
|
355
|
+
? overridePatch.apiKey.trim()
|
|
356
|
+
: this.configManager.effectiveApiKey(base),
|
|
357
|
+
}
|
|
358
|
+
: base;
|
|
359
|
+
const adapter = this.getLlm(merged);
|
|
360
|
+
return await adapter.probe({ liveChat });
|
|
361
|
+
} finally {
|
|
362
|
+
task.end();
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Ingest text or chat turns: redact -> short-window chunk -> extract -> 1-round admit -> guard -> SQLite.
|
|
368
|
+
*/
|
|
369
|
+
async remember(
|
|
370
|
+
content,
|
|
371
|
+
{
|
|
372
|
+
ns = null,
|
|
373
|
+
sourceId = null,
|
|
374
|
+
mentionedAt = null,
|
|
375
|
+
verify = null,
|
|
376
|
+
maxWindowChars = 1400,
|
|
377
|
+
} = {}
|
|
378
|
+
) {
|
|
379
|
+
const cfg = this.getConfig();
|
|
380
|
+
const namespace = String(ns || cfg.defaultNamespace || "default").trim() || "default";
|
|
381
|
+
const ts = String(mentionedAt || utcNowIso()).trim();
|
|
382
|
+
const createdAt = utcNowIso();
|
|
383
|
+
const shouldVerify = verify === null || verify === undefined ? Boolean(cfg.verify) : Boolean(verify);
|
|
384
|
+
|
|
385
|
+
const segments = buildSegments(content);
|
|
386
|
+
if (!segments.length) {
|
|
387
|
+
return {
|
|
388
|
+
doc_id: "",
|
|
389
|
+
namespace,
|
|
390
|
+
deduplicated: false,
|
|
391
|
+
windows: 0,
|
|
392
|
+
extracted: 0,
|
|
393
|
+
saved: 0,
|
|
394
|
+
revised: 0,
|
|
395
|
+
dropped: 0,
|
|
396
|
+
held: 0,
|
|
397
|
+
guard_rejected: 0,
|
|
398
|
+
provider: cfg.provider,
|
|
399
|
+
model: "",
|
|
400
|
+
fact_ids: [],
|
|
401
|
+
facts: [],
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const canonicalBody = segments.map((s) => `${s.role || ""}:${s.text}`).join("\n");
|
|
406
|
+
const contentSha = createHash("sha256").update(canonicalBody, "utf8").digest("hex");
|
|
407
|
+
const store = this.getStore();
|
|
408
|
+
const existingDoc = store.hasDocument(namespace, contentSha);
|
|
409
|
+
if (existingDoc) {
|
|
410
|
+
return {
|
|
411
|
+
doc_id: existingDoc,
|
|
412
|
+
namespace,
|
|
413
|
+
deduplicated: true,
|
|
414
|
+
windows: 0,
|
|
415
|
+
extracted: 0,
|
|
416
|
+
saved: 0,
|
|
417
|
+
revised: 0,
|
|
418
|
+
dropped: 0,
|
|
419
|
+
held: 0,
|
|
420
|
+
guard_rejected: 0,
|
|
421
|
+
provider: cfg.provider,
|
|
422
|
+
model: "",
|
|
423
|
+
fact_ids: [],
|
|
424
|
+
facts: [],
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const docId = `doc-${contentSha.slice(0, 12)}`;
|
|
429
|
+
const windows = windowSegments(segments, { maxWindowChars, overlap: 1 });
|
|
430
|
+
const segMap = new Map(segments.map((s) => [s.id, s]));
|
|
431
|
+
const llm = this.getLlm(cfg);
|
|
432
|
+
|
|
433
|
+
const result = {
|
|
434
|
+
doc_id: docId,
|
|
435
|
+
namespace,
|
|
436
|
+
deduplicated: false,
|
|
437
|
+
windows: windows.length,
|
|
438
|
+
extracted: 0,
|
|
439
|
+
saved: 0,
|
|
440
|
+
revised: 0,
|
|
441
|
+
dropped: 0,
|
|
442
|
+
held: 0,
|
|
443
|
+
guard_rejected: 0,
|
|
444
|
+
provider: cfg.provider,
|
|
445
|
+
model: "",
|
|
446
|
+
fact_ids: [],
|
|
447
|
+
facts: [],
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
const acceptedFacts = [];
|
|
451
|
+
const seenFactKeys = new Set();
|
|
452
|
+
const task = this.beginActivity("remember", "沉淀中");
|
|
453
|
+
let statsDirty = false;
|
|
454
|
+
|
|
455
|
+
try {
|
|
456
|
+
for (let winIdx = 0; winIdx < windows.length; winIdx++) {
|
|
457
|
+
const win = windows[winIdx];
|
|
458
|
+
const winDocId = windows.length === 1 ? docId : `${docId}-w${winIdx}`;
|
|
459
|
+
task.update("extract", windows.length > 1 ? `抽取 ${winIdx + 1}/${windows.length}` : "抽取中");
|
|
460
|
+
const { candidates, model } = await this._extractWindow(llm, {
|
|
461
|
+
namespace,
|
|
462
|
+
docId: winDocId,
|
|
463
|
+
window: win,
|
|
464
|
+
});
|
|
465
|
+
if (model) result.model = model;
|
|
466
|
+
result.extracted += candidates.length;
|
|
467
|
+
if (!candidates.length) continue;
|
|
468
|
+
|
|
469
|
+
let reviewed;
|
|
470
|
+
if (shouldVerify) {
|
|
471
|
+
task.update("verify", "审校中");
|
|
472
|
+
reviewed = await this._admitWindow(llm, {
|
|
473
|
+
window: win,
|
|
474
|
+
candidates,
|
|
475
|
+
mentionedAt: ts,
|
|
476
|
+
namespace,
|
|
477
|
+
result,
|
|
478
|
+
});
|
|
479
|
+
} else {
|
|
480
|
+
reviewed = candidates.map((c) => ({ ...c, action: "bypass" }));
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
for (const cand of reviewed) {
|
|
484
|
+
const action = String(cand.action || "pass");
|
|
485
|
+
const { guarded } = guardFact(cand, segMap, { mentionedAt: ts });
|
|
486
|
+
if (!guarded) {
|
|
487
|
+
result.guard_rejected += 1;
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
const dedupKey = guarded.text.toLowerCase();
|
|
491
|
+
if (seenFactKeys.has(dedupKey)) continue;
|
|
492
|
+
seenFactKeys.add(dedupKey);
|
|
493
|
+
acceptedFacts.push({ ...guarded, action });
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
task.update("saving", "入库中");
|
|
498
|
+
const savedIds = store.saveDocumentAndFacts({
|
|
499
|
+
docId,
|
|
500
|
+
namespace,
|
|
501
|
+
contentSha256: contentSha,
|
|
502
|
+
sourceId: sourceId ?? null,
|
|
503
|
+
mentionedAt: ts,
|
|
504
|
+
createdAt,
|
|
505
|
+
segments,
|
|
506
|
+
facts: acceptedFacts,
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
result.saved = savedIds.length;
|
|
510
|
+
result.fact_ids = savedIds;
|
|
511
|
+
result.facts = acceptedFacts;
|
|
512
|
+
this.runtimeMetrics.lastRememberAt = createdAt;
|
|
513
|
+
statsDirty = true;
|
|
514
|
+
return result;
|
|
515
|
+
} finally {
|
|
516
|
+
task.end({ statsDirty });
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
async _extractWindow(llm, { namespace, docId, window }) {
|
|
521
|
+
const payload = {
|
|
522
|
+
bank: namespace,
|
|
523
|
+
document_id: docId,
|
|
524
|
+
evidence: window.map(segmentToPayload),
|
|
525
|
+
};
|
|
526
|
+
const { content, meta } = await llm.chatJson(FACT_EXTRACTION_SYSTEM, payload, { numPredict: 1024 });
|
|
527
|
+
const parsed = parseJsonObject(content);
|
|
528
|
+
if (!parsed || !Array.isArray(parsed.facts)) {
|
|
529
|
+
return { candidates: [], model: String(meta?.model || "") };
|
|
530
|
+
}
|
|
531
|
+
const candidates = parsed.facts.filter((f) => f && typeof f === "object" && !Array.isArray(f));
|
|
532
|
+
return { candidates, model: String(meta?.model || "") };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
async _admitWindow(llm, { window, candidates, mentionedAt, namespace, result }) {
|
|
536
|
+
const factsMap = {};
|
|
537
|
+
for (let idx = 0; idx < candidates.length; idx++) {
|
|
538
|
+
const cand = candidates[idx];
|
|
539
|
+
factsMap[String(idx)] = {
|
|
540
|
+
text: String(cand.text || ""),
|
|
541
|
+
type: String(cand.type || "world"),
|
|
542
|
+
occurred_start: cand.occurred_start ?? null,
|
|
543
|
+
occurred_end: cand.occurred_end ?? null,
|
|
544
|
+
where: cand.where ?? null,
|
|
545
|
+
entities: Array.isArray(cand.entities) ? cand.entities : [],
|
|
546
|
+
mentioned_at: mentionedAt,
|
|
547
|
+
context: namespace,
|
|
548
|
+
tags: [],
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
const payload = {
|
|
553
|
+
evidence: window.map(segmentToPayload),
|
|
554
|
+
facts: factsMap,
|
|
555
|
+
};
|
|
556
|
+
const { content } = await llm.chatJson(FACT_ADMISSION_SYSTEM, payload, { numPredict: 768 });
|
|
557
|
+
const verdicts = parseJsonObject(content);
|
|
558
|
+
if (!verdicts) {
|
|
559
|
+
return candidates.map((c) => ({ ...c, action: "pass_fallback" }));
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const approved = [];
|
|
563
|
+
for (let idx = 0; idx < candidates.length; idx++) {
|
|
564
|
+
const cand = candidates[idx];
|
|
565
|
+
const verdict = verdicts[String(idx)];
|
|
566
|
+
if (!verdict || typeof verdict !== "object") {
|
|
567
|
+
result.held += 1;
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
const decision = String(verdict.decision || "").trim().toLowerCase();
|
|
571
|
+
if (!VALID_DECISIONS.has(decision)) {
|
|
572
|
+
result.held += 1;
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
const ev =
|
|
576
|
+
Array.isArray(verdict.evidence) && verdict.evidence.length ? verdict.evidence : cand.evidence;
|
|
577
|
+
|
|
578
|
+
if (decision === "pass") {
|
|
579
|
+
approved.push({ ...cand, evidence: ev, action: "pass" });
|
|
580
|
+
} else if (decision === "revise") {
|
|
581
|
+
const replacement = String(verdict.replacement || "").trim();
|
|
582
|
+
if (replacement) {
|
|
583
|
+
result.revised += 1;
|
|
584
|
+
approved.push({ ...cand, text: replacement, evidence: ev, action: "revise" });
|
|
585
|
+
} else {
|
|
586
|
+
result.held += 1;
|
|
587
|
+
}
|
|
588
|
+
} else if (decision === "drop") {
|
|
589
|
+
result.dropped += 1;
|
|
590
|
+
} else {
|
|
591
|
+
result.held += 1;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return approved;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
recall(
|
|
598
|
+
query,
|
|
599
|
+
{
|
|
600
|
+
ns = null,
|
|
601
|
+
limit = null,
|
|
602
|
+
adaptive = null,
|
|
603
|
+
minLimit = ADAPTIVE_MIN_LIMIT,
|
|
604
|
+
scoreRatio = ADAPTIVE_SCORE_RATIO,
|
|
605
|
+
asOf = null,
|
|
606
|
+
untilEnabled = null,
|
|
607
|
+
} = {}
|
|
608
|
+
) {
|
|
609
|
+
const cfg = this.getConfig();
|
|
610
|
+
const useAdaptive = adaptive === null || adaptive === undefined ? Boolean(cfg.adaptive) : Boolean(adaptive);
|
|
611
|
+
const useUntil = untilEnabled === null || untilEnabled === undefined ? Boolean(cfg.untilExpiry) : Boolean(untilEnabled);
|
|
612
|
+
return this.getStore().search(query, {
|
|
613
|
+
namespace: ns || null,
|
|
614
|
+
limit,
|
|
615
|
+
adaptive: useAdaptive,
|
|
616
|
+
minLimit,
|
|
617
|
+
scoreRatio,
|
|
618
|
+
asOf,
|
|
619
|
+
untilEnabled: useUntil,
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
stats(ns = null) {
|
|
624
|
+
return this.getStore().stats(ns || null);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
getDocument(docId) {
|
|
628
|
+
return this.getStore().getDocument(docId);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
softEvict(opts) {
|
|
632
|
+
const res = this.getStore().softEvict(opts);
|
|
633
|
+
if (res?.moved_facts || res?.total_records) this._emitActivity({ statsDirty: true });
|
|
634
|
+
return res;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
listEvictedBatches(limit = 50) {
|
|
638
|
+
return this.getStore().listEvictedBatches(limit);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
restoreEvicted(batchId) {
|
|
642
|
+
const res = this.getStore().restoreEvicted(batchId);
|
|
643
|
+
if (res?.restored_facts || res?.restored_documents) this._emitActivity({ statsDirty: true });
|
|
644
|
+
return res;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
deleteFact(factId) {
|
|
648
|
+
return this.getStore().deleteFact(factId);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
deleteDocument(docId) {
|
|
652
|
+
return this.getStore().deleteDocument(docId);
|
|
653
|
+
}
|
|
654
|
+
}
|