@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/lib/tools.mjs ADDED
@@ -0,0 +1,527 @@
1
+ /**
2
+ * Native DSH Cordis tool registrations (`ctx.tools.register`).
3
+ *
4
+ * Invariants:
5
+ * - Strictly lossless JSON outputs (no `undefined`, no `NaN`, no `Infinity` — DSH host rejects non-lossless values).
6
+ * - 100% Fail-Open: catches SQLite/Ollama/API errors and returns clear structured `{ ok: false, error }` responses.
7
+ * - Workspace-aware default namespace resolution via `exec?.agent?.session?.header?.cwd`.
8
+ */
9
+
10
+ import path from "node:path";
11
+
12
+ export function deriveWorkspaceNamespace(cwd, cfg) {
13
+ if (cfg?.namespaceMode === "fixed") {
14
+ return String(cfg.defaultNamespace || "default").trim() || "default";
15
+ }
16
+ const raw = String(cwd || "").trim();
17
+ if (!raw) return String(cfg?.defaultNamespace || "default").trim() || "default";
18
+ const base = path.basename(raw).replace(/[^A-Za-z0-9\u4e00-\u9fff._-]+/g, "-").replace(/^-+|-+$/g, "");
19
+ return base ? `project:${base.slice(0, 64)}` : String(cfg?.defaultNamespace || "default").trim() || "default";
20
+ }
21
+
22
+ function cleanLosslessHit(h) {
23
+ const item = {
24
+ fact_id: Number(h.fact_id),
25
+ doc_id: String(h.doc_id || ""),
26
+ namespace: String(h.namespace || "default"),
27
+ text: String(h.text || ""),
28
+ type: String(h.type || "world"),
29
+ action: String(h.action || "pass"),
30
+ mentioned_at: String(h.mentioned_at || ""),
31
+ score: Number.isFinite(Number(h.score)) ? Number(h.score) : 0,
32
+ entities: Array.isArray(h.entities) ? h.entities.map(String) : [],
33
+ evidence: Array.isArray(h.evidence)
34
+ ? h.evidence.map((e) => ({
35
+ id: String(e.id || ""),
36
+ text: String(e.text || ""),
37
+ }))
38
+ : [],
39
+ };
40
+ if (h.occurred_start) item.occurred_start = String(h.occurred_start);
41
+ if (h.occurred_end) item.occurred_end = String(h.occurred_end);
42
+ if (h.where) item.where = String(h.where);
43
+ if (typeof h.supersedes_fact_id === "number" && Number.isInteger(h.supersedes_fact_id)) {
44
+ item.supersedes_fact_id = h.supersedes_fact_id;
45
+ }
46
+ if (Array.isArray(h.superseded_by) && h.superseded_by.length) {
47
+ item.superseded_by = h.superseded_by.map((x) => Number(x)).filter(Number.isInteger);
48
+ }
49
+ if (h.until_expiry) {
50
+ item.until_expiry = {
51
+ until: String(h.until_expiry.until),
52
+ expired: true,
53
+ expired_days: Number(h.until_expiry.expired_days || 0),
54
+ label: String(h.until_expiry.label || ""),
55
+ };
56
+ }
57
+ return item;
58
+ }
59
+
60
+ function renderRecall(value) {
61
+ if (!value?.ok) return [{ type: "text", text: value?.error || "ZeroMem 检索失败。" }];
62
+ if (!value.count) {
63
+ return [{ type: "text", text: "ZeroMem 本地记忆库中未找到匹配记录。" }];
64
+ }
65
+ const lines = value.items.map((item, idx) => {
66
+ const badges = [];
67
+ if (item.occurred_start) {
68
+ const occ = item.occurred_end && item.occurred_end !== item.occurred_start
69
+ ? `${item.occurred_start}~${item.occurred_end}`
70
+ : item.occurred_start;
71
+ badges.push(occ);
72
+ }
73
+ if (item.action === "revise") badges.push("已纠错");
74
+ if (item.supersedes_fact_id) badges.push(`替代 #${item.supersedes_fact_id}`);
75
+ if (Array.isArray(item.superseded_by) && item.superseded_by.length) {
76
+ badges.push(`已被 ${item.superseded_by.map((x) => `#${x}`).join(",")} 替代`);
77
+ }
78
+ if (item.until_expiry?.label) badges.push(item.until_expiry.label);
79
+ const badgeStr = badges.length ? ` [${badges.join(" | ")}]` : "";
80
+ const evText = item.evidence?.length
81
+ ? `\n 原文(${item.evidence.map((e) => e.id).join(",")}): ${item.evidence.map((e) => e.text).join(" / ").slice(0, 220)}`
82
+ : "";
83
+ return `${idx + 1}. (#${item.fact_id} · ${item.namespace}${badgeStr}) ${item.text}${evText}`;
84
+ });
85
+ return [{ type: "text", text: lines.join("\n") }];
86
+ }
87
+
88
+ export function registerZeroMemTools(toolCtx, engine) {
89
+ const disposers = [];
90
+ if (!toolCtx?.tools || typeof toolCtx.tools.register !== "function") return () => {};
91
+
92
+ const reg = (spec) => {
93
+ const d = toolCtx.tools.register(spec);
94
+ if (typeof d === "function") disposers.push(d);
95
+ };
96
+
97
+ reg({
98
+ name: "zeromem_recall",
99
+ description:
100
+ "Search ZeroMem local SQLite memory by concise keywords across both verified facts and bound original evidence (Chinese/English FTS5, <1ms, zero LLM cost). " +
101
+ "For multi-topic questions, issue 2 short keyword calls in parallel instead of one long sentence.",
102
+ parameters: {
103
+ type: "object",
104
+ additionalProperties: false,
105
+ required: ["query"],
106
+ properties: {
107
+ query: {
108
+ type: "string",
109
+ description: "Concise keywords for one topic (empty string returns most recent facts).",
110
+ },
111
+ namespace: {
112
+ type: "string",
113
+ description: "Optional namespace filter; omit to search across all namespaces.",
114
+ },
115
+ limit: {
116
+ type: "integer",
117
+ description: "Optional max results (1-20; omit for adaptive 2-8 score gating).",
118
+ },
119
+ adaptive: {
120
+ type: "boolean",
121
+ description: "Enable adaptive relative-score tail pruning (default from config).",
122
+ },
123
+ as_of: {
124
+ type: "string",
125
+ description: "Optional YYYY-MM-DD date for evaluating until: expiry demotion.",
126
+ },
127
+ occurred_from: {
128
+ type: "string",
129
+ description: "Optional event time lower bound (YYYY, YYYY-MM, or YYYY-MM-DD).",
130
+ },
131
+ occurred_to: {
132
+ type: "string",
133
+ description: "Optional event time upper bound (YYYY, YYYY-MM, or YYYY-MM-DD).",
134
+ },
135
+ include_superseded: {
136
+ type: "boolean",
137
+ description: "Include historical facts superseded by newer facts (default true; active facts rank first).",
138
+ },
139
+ },
140
+ },
141
+ timeoutMs: 15_000,
142
+ isConcurrencySafe: true,
143
+ output: {
144
+ schema: {
145
+ type: "object",
146
+ additionalProperties: false,
147
+ required: ["ok", "count", "items"],
148
+ properties: {
149
+ ok: { type: "boolean" },
150
+ count: { type: "integer" },
151
+ expired_count: { type: "integer" },
152
+ superseded_count: { type: "integer" },
153
+ items: { type: "array", items: { type: "object" } },
154
+ error: { type: "string" },
155
+ },
156
+ },
157
+ render(_args, value) {
158
+ return renderRecall(value);
159
+ },
160
+ },
161
+ async execute(args) {
162
+ try {
163
+ const query = String(args?.query ?? "");
164
+ const ns = args?.namespace ? String(args.namespace).trim() : null;
165
+ const limit = args?.limit !== undefined && args?.limit !== null ? Number(args.limit) : null;
166
+ const adaptive = args?.adaptive !== undefined ? Boolean(args.adaptive) : null;
167
+ const asOf = args?.as_of ? String(args.as_of).trim() : null;
168
+ const occurredFrom = args?.occurred_from ? String(args.occurred_from).trim() : null;
169
+ const occurredTo = args?.occurred_to ? String(args.occurred_to).trim() : null;
170
+ const includeSuperseded =
171
+ args?.include_superseded !== undefined ? Boolean(args.include_superseded) : true;
172
+ const hits = engine.recall(query, {
173
+ ns,
174
+ limit,
175
+ adaptive,
176
+ asOf,
177
+ occurredFrom,
178
+ occurredTo,
179
+ includeSuperseded,
180
+ });
181
+ const items = hits.map(cleanLosslessHit);
182
+ const expiredCount = items.filter((i) => Boolean(i.until_expiry)).length;
183
+ const supersededCount = items.filter((i) => Array.isArray(i.superseded_by) && i.superseded_by.length > 0).length;
184
+ return {
185
+ ok: true,
186
+ count: items.length,
187
+ expired_count: expiredCount,
188
+ superseded_count: supersededCount,
189
+ items,
190
+ };
191
+ } catch (err) {
192
+ return {
193
+ ok: false,
194
+ count: 0,
195
+ expired_count: 0,
196
+ superseded_count: 0,
197
+ items: [],
198
+ error: `ZeroMem 检索失败:${String(err?.message || err).slice(0, 240)}`,
199
+ };
200
+ }
201
+ },
202
+ });
203
+
204
+ reg({
205
+ name: "zeromem_remember",
206
+ description:
207
+ "Store important decisions, configurations, facts, or notes into local ZeroMem SQLite. " +
208
+ "Redacts credentials before extraction, runs structured fact extraction + 1-round pre-write verification via the configured local Ollama model or OpenAI-compatible API, and binds original evidence segments.",
209
+ parameters: {
210
+ type: "object",
211
+ additionalProperties: false,
212
+ required: ["content"],
213
+ properties: {
214
+ content: {
215
+ type: "string",
216
+ description: "Text or note to remember. Long content is auto-chunked into <1400-char windows.",
217
+ },
218
+ namespace: {
219
+ type: "string",
220
+ description: "Optional namespace (defaults to current workspace namespace).",
221
+ },
222
+ source_id: {
223
+ type: "string",
224
+ description: "Optional source label or file path.",
225
+ },
226
+ mentioned_at: {
227
+ type: "string",
228
+ description: "Optional ISO-8601 record timestamp.",
229
+ },
230
+ verify: {
231
+ type: "boolean",
232
+ description: "Run 1-round pre-write admission/revision check (default from config).",
233
+ },
234
+ link_supersessions: {
235
+ type: "boolean",
236
+ description: "Detect and link superseded historical facts in the same namespace during admission (default true).",
237
+ },
238
+ },
239
+ },
240
+ timeoutMs: 120_000,
241
+ isConcurrencySafe: false,
242
+ output: {
243
+ schema: {
244
+ type: "object",
245
+ additionalProperties: false,
246
+ required: ["ok"],
247
+ properties: {
248
+ ok: { type: "boolean" },
249
+ doc_id: { type: "string" },
250
+ namespace: { type: "string" },
251
+ deduplicated: { type: "boolean" },
252
+ extracted: { type: "integer" },
253
+ saved: { type: "integer" },
254
+ revised: { type: "integer" },
255
+ superseded: { type: "integer" },
256
+ dropped: { type: "integer" },
257
+ held: { type: "integer" },
258
+ provider: { type: "string" },
259
+ model: { type: "string" },
260
+ error: { type: "string" },
261
+ },
262
+ },
263
+ render(_args, value) {
264
+ if (!value?.ok) return [{ type: "text", text: value?.error || "ZeroMem 写入失败。" }];
265
+ if (value.deduplicated) {
266
+ return [{ type: "text", text: `内容已存在于 ZeroMem(${value.namespace} · ${value.doc_id}),跳过重复写入。` }];
267
+ }
268
+ const supPart = value.superseded ? `,替代旧事实 ${value.superseded}` : "";
269
+ return [
270
+ {
271
+ type: "text",
272
+ text: `已写入 ZeroMem(${value.namespace} · ${value.doc_id}):抽取 ${value.extracted} 条,入库 ${value.saved} 条(纠错 ${value.revised}${supPart},拦截 ${value.dropped},挂起 ${value.held}),后端 ${value.provider}/${value.model || "auto"}。`,
273
+ },
274
+ ];
275
+ },
276
+ },
277
+ async execute(args, exec) {
278
+ try {
279
+ const content = String(args?.content ?? "").trim();
280
+ if (!content) return { ok: false, error: "content 不能为空。" };
281
+ const cfg = engine.getConfig();
282
+ const cwd = exec?.agent?.session?.header?.cwd || process.cwd();
283
+ const ns = args?.namespace
284
+ ? String(args.namespace).trim()
285
+ : deriveWorkspaceNamespace(cwd, cfg);
286
+ const res = await engine.remember(content, {
287
+ ns,
288
+ sourceId: args?.source_id ? String(args.source_id) : null,
289
+ mentionedAt: args?.mentioned_at ? String(args.mentioned_at) : null,
290
+ verify: args?.verify !== undefined ? Boolean(args.verify) : null,
291
+ linkSupersessions:
292
+ args?.link_supersessions !== undefined ? Boolean(args.link_supersessions) : true,
293
+ });
294
+ return {
295
+ ok: true,
296
+ doc_id: String(res.doc_id || ""),
297
+ namespace: String(res.namespace || ns),
298
+ deduplicated: Boolean(res.deduplicated),
299
+ extracted: Number(res.extracted || 0),
300
+ saved: Number(res.saved || 0),
301
+ revised: Number(res.revised || 0),
302
+ superseded: Number(res.superseded || 0),
303
+ dropped: Number(res.dropped || 0),
304
+ held: Number(res.held || 0),
305
+ provider: String(res.provider || cfg.provider),
306
+ model: String(res.model || ""),
307
+ };
308
+ } catch (err) {
309
+ return {
310
+ ok: false,
311
+ error: `ZeroMem 写入失败:${String(err?.message || err).slice(0, 300)}`,
312
+ };
313
+ }
314
+ },
315
+ });
316
+
317
+ reg({
318
+ name: "zeromem_stats",
319
+ description:
320
+ "Inspect local ZeroMem database statistics (documents, facts, revised facts, soft-evicted records, namespaces) and current backend mode (Ollama or API) without invoking an LLM.",
321
+ parameters: {
322
+ type: "object",
323
+ additionalProperties: false,
324
+ properties: {
325
+ namespace: {
326
+ type: "string",
327
+ description: "Optional namespace filter.",
328
+ },
329
+ },
330
+ },
331
+ timeoutMs: 15_000,
332
+ isConcurrencySafe: true,
333
+ output: {
334
+ schema: {
335
+ type: "object",
336
+ additionalProperties: false,
337
+ required: ["ok"],
338
+ properties: {
339
+ ok: { type: "boolean" },
340
+ provider: { type: "string" },
341
+ db_path: { type: "string" },
342
+ documents: { type: "integer" },
343
+ segments: { type: "integer" },
344
+ facts: { type: "integer" },
345
+ revised_facts: { type: "integer" },
346
+ supersessions: { type: "integer" },
347
+ evicted_records: { type: "integer" },
348
+ namespaces: { type: "array", items: { type: "string" } },
349
+ error: { type: "string" },
350
+ },
351
+ },
352
+ render(_args, value) {
353
+ if (!value?.ok) return [{ type: "text", text: value?.error || "读取统计失败。" }];
354
+ const supText = value.supersessions ? ` · 演化链 ${value.supersessions}` : "";
355
+ return [
356
+ {
357
+ type: "text",
358
+ text:
359
+ `ZeroMem (${value.provider}) · ${value.db_path}\n` +
360
+ `文档 ${value.documents} · 原文段 ${value.segments} · 事实 ${value.facts}(已纠错 ${value.revised_facts})${supText} · 回收站 ${value.evicted_records}\n` +
361
+ `空间:${value.namespaces.length ? value.namespaces.join(", ") : "(空)"}`,
362
+ },
363
+ ];
364
+ },
365
+ },
366
+ async execute(args) {
367
+ try {
368
+ const ns = args?.namespace ? String(args.namespace).trim() : null;
369
+ const st = engine.stats(ns);
370
+ const cfg = engine.getConfig();
371
+ return {
372
+ ok: true,
373
+ provider: String(cfg.provider),
374
+ db_path: String(st.db_path),
375
+ documents: Number(st.documents),
376
+ segments: Number(st.segments),
377
+ facts: Number(st.facts),
378
+ revised_facts: Number(st.revised_facts),
379
+ supersessions: Number(st.supersessions || 0),
380
+ evicted_records: Number(st.evicted_records),
381
+ namespaces: st.namespaces.map(String),
382
+ };
383
+ } catch (err) {
384
+ return {
385
+ ok: false,
386
+ error: `读取 ZeroMem 统计失败:${String(err?.message || err).slice(0, 240)}`,
387
+ };
388
+ }
389
+ },
390
+ });
391
+
392
+ reg({
393
+ name: "zeromem_evict",
394
+ description:
395
+ "Losslessly soft-evict outdated or incorrect facts/documents into ZeroMem's same-DB recycle table (evicted_records) with SHA-256 fingerprints so they can be restored anytime via zeromem_restore.",
396
+ parameters: {
397
+ type: "object",
398
+ additionalProperties: false,
399
+ properties: {
400
+ fact_id: { type: "integer", description: "Numeric fact_id to soft-evict." },
401
+ doc_id: { type: "string", description: "Document ID (doc-...) to soft-evict." },
402
+ expired: { type: "boolean", description: "Soft-evict all facts with expired until: tags." },
403
+ namespace: { type: "string", description: "Optional namespace scope." },
404
+ reason: { type: "string", description: "Short reason recorded in the eviction batch." },
405
+ force: { type: "boolean", description: "Allow emptying all active facts in scope." },
406
+ },
407
+ },
408
+ timeoutMs: 15_000,
409
+ isConcurrencySafe: false,
410
+ output: {
411
+ schema: {
412
+ type: "object",
413
+ additionalProperties: false,
414
+ required: ["ok"],
415
+ properties: {
416
+ ok: { type: "boolean" },
417
+ batch_id: { type: "string" },
418
+ moved_facts: { type: "integer" },
419
+ moved_documents: { type: "integer" },
420
+ total_records: { type: "integer" },
421
+ error: { type: "string" },
422
+ },
423
+ },
424
+ render(_args, value) {
425
+ if (!value?.ok) return [{ type: "text", text: value?.error || "软淘汰失败。" }];
426
+ if (!value.total_records) return [{ type: "text", text: "没有符合条件的活跃记忆需要软淘汰。" }];
427
+ return [
428
+ {
429
+ type: "text",
430
+ text: `已无损软淘汰 ${value.total_records} 项(事实 ${value.moved_facts}、文档 ${value.moved_documents}),批次号 ${value.batch_id}(可随时用 zeromem_restore 或 Web 回收站恢复)。`,
431
+ },
432
+ ];
433
+ },
434
+ },
435
+ async execute(args) {
436
+ try {
437
+ const res = engine.softEvict({
438
+ factIds: args?.fact_id !== undefined && args?.fact_id !== null ? [Number(args.fact_id)] : [],
439
+ docIds: args?.doc_id ? [String(args.doc_id)] : [],
440
+ expired: Boolean(args?.expired),
441
+ namespace: args?.namespace ? String(args.namespace).trim() : null,
442
+ reason: args?.reason ? String(args.reason) : "tool-evict",
443
+ force: Boolean(args?.force),
444
+ });
445
+ return {
446
+ ok: true,
447
+ batch_id: String(res.batch_id),
448
+ moved_facts: Number(res.moved_facts || 0),
449
+ moved_documents: Number(res.moved_documents || 0),
450
+ total_records: Number(res.total_records || 0),
451
+ };
452
+ } catch (err) {
453
+ return {
454
+ ok: false,
455
+ error: `软淘汰失败:${String(err?.message || err).slice(0, 240)}`,
456
+ };
457
+ }
458
+ },
459
+ });
460
+
461
+ reg({
462
+ name: "zeromem_restore",
463
+ description:
464
+ "Verify SHA-256 fingerprints and atomically restore a soft-evicted batch back into active ZeroMem tables and FTS5 index.",
465
+ parameters: {
466
+ type: "object",
467
+ additionalProperties: false,
468
+ required: ["batch_id"],
469
+ properties: {
470
+ batch_id: { type: "string", description: "Batch ID returned by zeromem_evict or listed in the Web recycle bin." },
471
+ },
472
+ },
473
+ timeoutMs: 15_000,
474
+ isConcurrencySafe: false,
475
+ output: {
476
+ schema: {
477
+ type: "object",
478
+ additionalProperties: false,
479
+ required: ["ok"],
480
+ properties: {
481
+ ok: { type: "boolean" },
482
+ batch_id: { type: "string" },
483
+ restored_facts: { type: "integer" },
484
+ restored_documents: { type: "integer" },
485
+ verified_rows: { type: "integer" },
486
+ error: { type: "string" },
487
+ },
488
+ },
489
+ render(_args, value) {
490
+ if (!value?.ok) return [{ type: "text", text: value?.error || "恢复失败。" }];
491
+ return [
492
+ {
493
+ type: "text",
494
+ text: `已通过 ${value.verified_rows} 项 SHA-256 校验并恢复批次 ${value.batch_id}(事实 ${value.restored_facts},文档 ${value.restored_documents})。`,
495
+ },
496
+ ];
497
+ },
498
+ },
499
+ async execute(args) {
500
+ try {
501
+ const res = engine.restoreEvicted(String(args?.batch_id || ""));
502
+ return {
503
+ ok: true,
504
+ batch_id: String(res.batch_id),
505
+ restored_facts: Number(res.restored_facts || 0),
506
+ restored_documents: Number(res.restored_documents || 0),
507
+ verified_rows: Number(res.verified_rows || 0),
508
+ };
509
+ } catch (err) {
510
+ return {
511
+ ok: false,
512
+ error: `恢复失败:${String(err?.message || err).slice(0, 240)}`,
513
+ };
514
+ }
515
+ },
516
+ });
517
+
518
+ return () => {
519
+ for (const d of disposers) {
520
+ try {
521
+ d();
522
+ } catch {
523
+ // ignore dispose errors
524
+ }
525
+ }
526
+ };
527
+ }