@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/expiry.mjs
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Time-expiry tags (`until:YYYY-MM-DD` / `until:YYYYMMDD`) and adaptive dual-lane gating.
|
|
3
|
+
*
|
|
4
|
+
* Parity with Python ZeroMem (`v2mem/expiry.py`):
|
|
5
|
+
* - Zero schema changes: inspects explicit `until:` markers in tags, entities, text, or bound evidence.
|
|
6
|
+
* - Strict calendar validation (fail-open: invalid dates such as 2026-02-30 are ignored).
|
|
7
|
+
* - Non-destructive annotation: never rewrites `text` or evidence quotes; expired records are
|
|
8
|
+
* stable-partitioned to the tail with structured `until_expiry` metadata.
|
|
9
|
+
* - Adaptive relative-score gating: keeps hits within `[minLimit, cap]` above
|
|
10
|
+
* `score >= scoreRatio * leadingActiveScore`, with rollback via env `ZEROMEM_ADAPTIVE_LIMIT_DISABLED=1`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const ADAPTIVE_MIN_LIMIT = 2;
|
|
14
|
+
export const ADAPTIVE_MAX_LIMIT = 8;
|
|
15
|
+
export const LEGACY_FIXED_LIMIT = 6;
|
|
16
|
+
export const ADAPTIVE_SCORE_RATIO = 0.35;
|
|
17
|
+
|
|
18
|
+
const UNTIL_TOKEN_RE = /^until:(\d{4})-?(\d{2})-?(\d{2})$/i;
|
|
19
|
+
const UNTIL_INLINE_RE = /(?<![A-Za-z0-9_])until:(\d{4})-?(\d{2})-?(\d{2})(?![0-9])/gi;
|
|
20
|
+
const OCCURRED_FULL_RE = /^(\d{4})-?(\d{2})-?(\d{2})(?:$|T|\s)/;
|
|
21
|
+
const OCCURRED_YM_RE = /^(\d{4})-(\d{2})$/;
|
|
22
|
+
const OCCURRED_Y_RE = /^(\d{4})$/;
|
|
23
|
+
const DISABLED_VALUES = new Set(["0", "off", "false", "no"]);
|
|
24
|
+
const ENABLED_VALUES = new Set(["1", "true", "yes", "on"]);
|
|
25
|
+
|
|
26
|
+
export function isUntilDisabled(env = process.env) {
|
|
27
|
+
for (const key of ["ZEROMEM_UNTIL", "MEMORY_UNTIL"]) {
|
|
28
|
+
const raw = env?.[key];
|
|
29
|
+
if (typeof raw === "string" && DISABLED_VALUES.has(raw.trim().toLowerCase())) {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function isAdaptiveLimitDisabled(env = process.env) {
|
|
37
|
+
for (const key of ["ZEROMEM_ADAPTIVE_LIMIT_DISABLED", "EVENT_MEMORY_ADAPTIVE_LIMIT_DISABLED"]) {
|
|
38
|
+
const raw = env?.[key];
|
|
39
|
+
if (typeof raw === "string" && ENABLED_VALUES.has(raw.trim().toLowerCase())) {
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function resolveDefaultLimit(limit = null, { adaptive = true, env = process.env } = {}) {
|
|
47
|
+
if (limit !== null && limit !== undefined) {
|
|
48
|
+
const n = Number(limit);
|
|
49
|
+
if (Number.isFinite(n)) return Math.max(1, Math.min(Math.trunc(n), 50));
|
|
50
|
+
}
|
|
51
|
+
if (!adaptive || isAdaptiveLimitDisabled(env)) {
|
|
52
|
+
return LEGACY_FIXED_LIMIT;
|
|
53
|
+
}
|
|
54
|
+
return ADAPTIVE_MAX_LIMIT;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Validate calendar date strictly and return canonical YYYY-MM-DD or null.
|
|
59
|
+
*/
|
|
60
|
+
export function parseCalendarDate(year, month, day) {
|
|
61
|
+
const y = Number(year);
|
|
62
|
+
const m = Number(month);
|
|
63
|
+
const d = Number(day);
|
|
64
|
+
if (!Number.isInteger(y) || !Number.isInteger(m) || !Number.isInteger(d)) return null;
|
|
65
|
+
if (y < 1970 || y > 9999 || m < 1 || m > 12 || d < 1 || d > 31) return null;
|
|
66
|
+
const dt = new Date(Date.UTC(y, m - 1, d));
|
|
67
|
+
if (
|
|
68
|
+
dt.getUTCFullYear() !== y ||
|
|
69
|
+
dt.getUTCMonth() !== m - 1 ||
|
|
70
|
+
dt.getUTCDate() !== d
|
|
71
|
+
) {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
return `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function daysInMonth(year, month) {
|
|
78
|
+
return new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Parse YYYY, YYYY-MM, YYYY-MM-DD, YYYYMMDD, or ISO-8601 prefix into a canonical YYYY-MM-DD bound.
|
|
83
|
+
*/
|
|
84
|
+
export function parseOccurredBound(value, { isEnd = false } = {}) {
|
|
85
|
+
if (value === null || value === undefined) return null;
|
|
86
|
+
if (value instanceof Date && Number.isFinite(value.getTime())) {
|
|
87
|
+
return parseCalendarDate(value.getUTCFullYear(), value.getUTCMonth() + 1, value.getUTCDate());
|
|
88
|
+
}
|
|
89
|
+
if (typeof value !== "string") return null;
|
|
90
|
+
const s = value.trim();
|
|
91
|
+
if (!s) return null;
|
|
92
|
+
|
|
93
|
+
let m = OCCURRED_FULL_RE.exec(s);
|
|
94
|
+
if (m) {
|
|
95
|
+
return parseCalendarDate(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
96
|
+
}
|
|
97
|
+
m = OCCURRED_YM_RE.exec(s);
|
|
98
|
+
if (m) {
|
|
99
|
+
const year = Number(m[1]);
|
|
100
|
+
const month = Number(m[2]);
|
|
101
|
+
if (year < 1970 || year > 9999 || month < 1 || month > 12) return null;
|
|
102
|
+
const day = isEnd ? daysInMonth(year, month) : 1;
|
|
103
|
+
return parseCalendarDate(year, month, day);
|
|
104
|
+
}
|
|
105
|
+
m = OCCURRED_Y_RE.exec(s);
|
|
106
|
+
if (m) {
|
|
107
|
+
const year = Number(m[1]);
|
|
108
|
+
if (year < 1970 || year > 9999) return null;
|
|
109
|
+
return isEnd ? parseCalendarDate(year, 12, 31) : parseCalendarDate(year, 1, 1);
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Validate optional occurred_from / occurred_to filter bounds (fail-closed on bad dates or inverted range).
|
|
116
|
+
*/
|
|
117
|
+
export function normalizeOccurredRange(occurredFrom = null, occurredTo = null) {
|
|
118
|
+
let fromDate = null;
|
|
119
|
+
let toDate = null;
|
|
120
|
+
|
|
121
|
+
if (occurredFrom !== null && occurredFrom !== undefined && (typeof occurredFrom !== "string" || occurredFrom.trim())) {
|
|
122
|
+
fromDate = parseOccurredBound(occurredFrom, { isEnd: false });
|
|
123
|
+
if (!fromDate) {
|
|
124
|
+
throw new Error(`invalid-occurred-from: ${JSON.stringify(occurredFrom)} (expected YYYY, YYYY-MM, or YYYY-MM-DD)`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (occurredTo !== null && occurredTo !== undefined && (typeof occurredTo !== "string" || occurredTo.trim())) {
|
|
128
|
+
toDate = parseOccurredBound(occurredTo, { isEnd: true });
|
|
129
|
+
if (!toDate) {
|
|
130
|
+
throw new Error(`invalid-occurred-to: ${JSON.stringify(occurredTo)} (expected YYYY, YYYY-MM, or YYYY-MM-DD)`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (fromDate && toDate && fromDate > toDate) {
|
|
134
|
+
throw new Error(`invalid-occurred-range: occurred_from (${fromDate}) > occurred_to (${toDate})`);
|
|
135
|
+
}
|
|
136
|
+
return { fromDate, toDate };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Return true iff a fact's occurred interval overlaps [fromDate, toDate].
|
|
141
|
+
*/
|
|
142
|
+
export function factMatchesOccurredRange(occurredStart, occurredEnd = null, { fromDate = null, toDate = null } = {}) {
|
|
143
|
+
if (!fromDate && !toDate) return true;
|
|
144
|
+
const fStart = parseOccurredBound(occurredStart, { isEnd: false });
|
|
145
|
+
if (!fStart) return false;
|
|
146
|
+
let fEnd = occurredEnd ? parseOccurredBound(occurredEnd, { isEnd: true }) : null;
|
|
147
|
+
if (!fEnd) {
|
|
148
|
+
fEnd = parseOccurredBound(occurredStart, { isEnd: true }) || fStart;
|
|
149
|
+
}
|
|
150
|
+
if (fEnd < fStart) fEnd = fStart;
|
|
151
|
+
if (fromDate && fEnd < fromDate) return false;
|
|
152
|
+
if (toDate && fStart > toDate) return false;
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Stable-partition non-superseded records ahead of superseded historical facts without dropping any item.
|
|
158
|
+
*/
|
|
159
|
+
export function partitionSuperseded(records) {
|
|
160
|
+
if (!Array.isArray(records) || !records.length) {
|
|
161
|
+
return { items: [], supersededCount: 0 };
|
|
162
|
+
}
|
|
163
|
+
const current = [];
|
|
164
|
+
const superseded = [];
|
|
165
|
+
for (const row of records) {
|
|
166
|
+
if (Array.isArray(row?.superseded_by) && row.superseded_by.length > 0) {
|
|
167
|
+
superseded.push({ ...row });
|
|
168
|
+
} else {
|
|
169
|
+
current.push({ ...row });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (!superseded.length) {
|
|
173
|
+
return { items: current, supersededCount: 0 };
|
|
174
|
+
}
|
|
175
|
+
return { items: [...current, ...superseded], supersededCount: superseded.length };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function resolveAsOfDate(today = null) {
|
|
179
|
+
if (today instanceof Date && Number.isFinite(today.getTime())) {
|
|
180
|
+
return parseCalendarDate(today.getUTCFullYear(), today.getUTCMonth() + 1, today.getUTCDate());
|
|
181
|
+
}
|
|
182
|
+
if (typeof today === "string") {
|
|
183
|
+
const m = /^\s*(\d{4})-?(\d{2})-?(\d{2})(?:$|T)/.exec(today);
|
|
184
|
+
if (m) {
|
|
185
|
+
const parsed = parseCalendarDate(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
186
|
+
if (parsed) return parsed;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const now = new Date();
|
|
190
|
+
return parseCalendarDate(now.getFullYear(), now.getMonth() + 1, now.getDate());
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function daysBetween(isoA, isoB) {
|
|
194
|
+
const msA = Date.parse(`${isoA}T00:00:00Z`);
|
|
195
|
+
const msB = Date.parse(`${isoB}T00:00:00Z`);
|
|
196
|
+
return Math.round((msA - msB) / 86_400_000);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function extractDatesFromText(text) {
|
|
200
|
+
const found = [];
|
|
201
|
+
if (typeof text !== "string" || !text.toLowerCase().includes("until:")) return found;
|
|
202
|
+
UNTIL_INLINE_RE.lastIndex = 0;
|
|
203
|
+
let m;
|
|
204
|
+
while ((m = UNTIL_INLINE_RE.exec(text)) !== null) {
|
|
205
|
+
const parsed = parseCalendarDate(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
206
|
+
if (parsed) found.push(parsed);
|
|
207
|
+
}
|
|
208
|
+
return found;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Return the latest valid `until:` YYYY-MM-DD date from tags, metadata, text, or bound evidence.
|
|
213
|
+
*/
|
|
214
|
+
export function parseUntilDate({ tags = null, metadata = null, text = null, evidence = null } = {}) {
|
|
215
|
+
const candidates = [];
|
|
216
|
+
|
|
217
|
+
let tokens = [];
|
|
218
|
+
if (typeof tags === "string") {
|
|
219
|
+
tokens = tags.trim().split(/[\s,]+/).filter(Boolean);
|
|
220
|
+
} else if (Array.isArray(tags)) {
|
|
221
|
+
tokens = tags.filter((t) => typeof t === "string");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
for (const token of tokens) {
|
|
225
|
+
const trimmed = token.trim().replace(/^[\[\]()]+|[\[\]()]+$/g, "");
|
|
226
|
+
const m = UNTIL_TOKEN_RE.exec(trimmed);
|
|
227
|
+
if (m) {
|
|
228
|
+
const parsed = parseCalendarDate(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
229
|
+
if (parsed) candidates.push(parsed);
|
|
230
|
+
} else {
|
|
231
|
+
candidates.push(...extractDatesFromText(trimmed));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (metadata && typeof metadata === "object" && typeof metadata.until === "string" && metadata.until.trim()) {
|
|
236
|
+
const trimmed = metadata.until.trim();
|
|
237
|
+
const prefixed = trimmed.toLowerCase().startsWith("until:") ? trimmed : `until:${trimmed}`;
|
|
238
|
+
const m = UNTIL_TOKEN_RE.exec(prefixed);
|
|
239
|
+
if (m) {
|
|
240
|
+
const parsed = parseCalendarDate(Number(m[1]), Number(m[2]), Number(m[3]));
|
|
241
|
+
if (parsed) candidates.push(parsed);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (typeof text === "string") {
|
|
246
|
+
candidates.push(...extractDatesFromText(text));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (Array.isArray(evidence)) {
|
|
250
|
+
for (const seg of evidence) {
|
|
251
|
+
if (seg && typeof seg === "object" && typeof seg.text === "string") {
|
|
252
|
+
candidates.push(...extractDatesFromText(seg.text));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (!candidates.length) return null;
|
|
258
|
+
candidates.sort();
|
|
259
|
+
return candidates[candidates.length - 1];
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export function evaluateExpiry(untilIso, asOfIso) {
|
|
263
|
+
if (!untilIso || !asOfIso) return null;
|
|
264
|
+
const expiredDays = daysBetween(asOfIso, untilIso);
|
|
265
|
+
if (expiredDays <= 0) return null;
|
|
266
|
+
return {
|
|
267
|
+
until: untilIso,
|
|
268
|
+
expired: true,
|
|
269
|
+
expired_days: expiredDays,
|
|
270
|
+
label: `已过期(until ${untilIso})`,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Non-destructively stable-partition expired records to the tail.
|
|
276
|
+
*/
|
|
277
|
+
export function partitionExpired(records, { today = null, enabled = true, env = process.env } = {}) {
|
|
278
|
+
if (!enabled || isUntilDisabled(env)) {
|
|
279
|
+
return {
|
|
280
|
+
items: records.map((r) => ({ ...r })),
|
|
281
|
+
expiredCount: 0,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
const asOf = resolveAsOfDate(today);
|
|
285
|
+
const active = [];
|
|
286
|
+
const expired = [];
|
|
287
|
+
for (const row of records) {
|
|
288
|
+
const untilDate = parseUntilDate({
|
|
289
|
+
tags: row.entities,
|
|
290
|
+
text: row.text,
|
|
291
|
+
evidence: row.evidence,
|
|
292
|
+
});
|
|
293
|
+
const info = evaluateExpiry(untilDate, asOf);
|
|
294
|
+
if (info) {
|
|
295
|
+
expired.push({ ...row, until_expiry: info });
|
|
296
|
+
} else {
|
|
297
|
+
const copy = { ...row };
|
|
298
|
+
delete copy.until_expiry;
|
|
299
|
+
active.push(copy);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
items: [...active, ...expired],
|
|
304
|
+
expiredCount: expired.length,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Adaptive relative-score gating anchored on leading active hit.
|
|
310
|
+
*/
|
|
311
|
+
export function selectAdaptiveHits(
|
|
312
|
+
records,
|
|
313
|
+
{
|
|
314
|
+
limit = ADAPTIVE_MAX_LIMIT,
|
|
315
|
+
minLimit = ADAPTIVE_MIN_LIMIT,
|
|
316
|
+
scoreRatio = ADAPTIVE_SCORE_RATIO,
|
|
317
|
+
adaptive = true,
|
|
318
|
+
env = process.env,
|
|
319
|
+
} = {}
|
|
320
|
+
) {
|
|
321
|
+
const cap = Math.max(1, Number(limit) || ADAPTIVE_MAX_LIMIT);
|
|
322
|
+
if (!records.length) return [];
|
|
323
|
+
if (!adaptive || isAdaptiveLimitDisabled(env)) {
|
|
324
|
+
return records.slice(0, cap);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const floor = Math.max(1, Math.min(Number(minLimit) || ADAPTIVE_MIN_LIMIT, cap));
|
|
328
|
+
const ratio = Math.max(0, Math.min(Number(scoreRatio) || ADAPTIVE_SCORE_RATIO, 1));
|
|
329
|
+
|
|
330
|
+
let leading = 0;
|
|
331
|
+
for (const row of records) {
|
|
332
|
+
if (!row.until_expiry && !(Array.isArray(row.superseded_by) && row.superseded_by.length > 0)) {
|
|
333
|
+
const sc = Number(row.score || 0);
|
|
334
|
+
if (sc > leading) leading = sc;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (leading <= 0) {
|
|
338
|
+
for (const row of records) {
|
|
339
|
+
const sc = Number(row.score || 0);
|
|
340
|
+
if (sc > leading) leading = sc;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (leading <= 0) {
|
|
344
|
+
return records.slice(0, cap);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const cutoff = leading * ratio;
|
|
348
|
+
const selected = [];
|
|
349
|
+
for (const row of records) {
|
|
350
|
+
if (selected.length >= cap) break;
|
|
351
|
+
const sc = Number(row.score || 0);
|
|
352
|
+
if (selected.length < floor || sc >= cutoff) {
|
|
353
|
+
selected.push(row);
|
|
354
|
+
} else {
|
|
355
|
+
break;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return selected;
|
|
359
|
+
}
|
package/lib/hooks.mjs
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native DSH Cordis agent lifecycle hooks (`agent/session-start`, `agent/pre-step`,
|
|
3
|
+
* `agent/turn-stopping`, `agent/disposed`).
|
|
4
|
+
*
|
|
5
|
+
* Design invariants:
|
|
6
|
+
* - 100% Fail-Open: never throws into the DSH host loop; Ollama/API offline degrades silently.
|
|
7
|
+
* - Anti-loop protection: injected memory blocks carry explicit markers and `source.kind = "plugin:zeromem"`,
|
|
8
|
+
* and are stripped before background extraction so recalled memories are never re-ingested.
|
|
9
|
+
* - Subagents (`origin === "subagent"`) are skipped to avoid duplicate recall/extraction noise.
|
|
10
|
+
* - Live config toggles (`autoRecall`, `autoRemember`) take effect immediately without restart.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { deriveWorkspaceNamespace } from "./tools.mjs";
|
|
15
|
+
|
|
16
|
+
export const PLUGIN_ID = "zeromem";
|
|
17
|
+
export const TRIVIAL_ACK_WORDS = Object.freeze([
|
|
18
|
+
"indeed",
|
|
19
|
+
"mhm",
|
|
20
|
+
"lol",
|
|
21
|
+
"i see",
|
|
22
|
+
"uh-huh",
|
|
23
|
+
"lmao",
|
|
24
|
+
"ic",
|
|
25
|
+
"alright",
|
|
26
|
+
"nice",
|
|
27
|
+
"hi",
|
|
28
|
+
"hello",
|
|
29
|
+
"hey",
|
|
30
|
+
"ok",
|
|
31
|
+
"okay",
|
|
32
|
+
"thanks",
|
|
33
|
+
"thank you",
|
|
34
|
+
"sure",
|
|
35
|
+
"got it",
|
|
36
|
+
"好的",
|
|
37
|
+
"嗯",
|
|
38
|
+
"谢谢",
|
|
39
|
+
"收到",
|
|
40
|
+
"继续",
|
|
41
|
+
"行",
|
|
42
|
+
"好",
|
|
43
|
+
]);
|
|
44
|
+
const INJECT_START = "<!-- zeromem-recall:begin -->";
|
|
45
|
+
const INJECT_END = "<!-- zeromem-recall:end -->";
|
|
46
|
+
const INJECT_BLOCK_RE = /<!--\s*zeromem-recall:begin\s*-->[\s\S]*?<!--\s*zeromem-recall:end\s*-->/g;
|
|
47
|
+
const TRIVIAL_PROMPT_RE = new RegExp(
|
|
48
|
+
`^(?:${TRIVIAL_ACK_WORDS.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})[!!。.\\s]*$`,
|
|
49
|
+
"i"
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
export function stripInjectedMemory(text) {
|
|
53
|
+
return String(text || "").replace(INJECT_BLOCK_RE, "").trim();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function textOfMessage(message) {
|
|
57
|
+
const blocks = Array.isArray(message?.content) ? message.content : [];
|
|
58
|
+
return blocks
|
|
59
|
+
.filter((b) => b?.type === "text" && typeof b.text === "string")
|
|
60
|
+
.map((b) => b.text)
|
|
61
|
+
.join("\n")
|
|
62
|
+
.trim();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function extractPromptText(messages) {
|
|
66
|
+
return (Array.isArray(messages) ? messages : [])
|
|
67
|
+
.filter((m) => m?.source?.kind === "user")
|
|
68
|
+
.map((m) => stripInjectedMemory(textOfMessage(m)))
|
|
69
|
+
.filter(Boolean)
|
|
70
|
+
.join("\n")
|
|
71
|
+
.trim();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function readDshTranscriptTurns(events) {
|
|
75
|
+
const turns = [];
|
|
76
|
+
for (const ev of Array.isArray(events) ? events : []) {
|
|
77
|
+
if (!ev || typeof ev !== "object") continue;
|
|
78
|
+
if (ev.type === "user/message") {
|
|
79
|
+
const msg = ev.data;
|
|
80
|
+
if (!msg || msg.source?.kind !== "user") continue;
|
|
81
|
+
const text = stripInjectedMemory(textOfMessage(msg));
|
|
82
|
+
if (text) turns.push({ role: "user", content: text });
|
|
83
|
+
} else if (ev.type === "assistant/message") {
|
|
84
|
+
const msg = ev.data?.message;
|
|
85
|
+
if (!msg) continue;
|
|
86
|
+
const text = stripInjectedMemory(textOfMessage(msg));
|
|
87
|
+
if (text) turns.push({ role: "assistant", content: text });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return turns;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function formatRecallInjection(hits, namespace) {
|
|
94
|
+
if (!Array.isArray(hits) || !hits.length) return "";
|
|
95
|
+
const lines = hits.map((h, i) => {
|
|
96
|
+
const tags = [h.namespace];
|
|
97
|
+
if (h.occurred_start) tags.push(String(h.occurred_start));
|
|
98
|
+
if (h.supersedes_fact_id) tags.push(`替代 #${h.supersedes_fact_id}`);
|
|
99
|
+
if (Array.isArray(h.superseded_by) && h.superseded_by.length) {
|
|
100
|
+
tags.push(`已被 ${h.superseded_by.map((x) => `#${x}`).join(",")} 替代`);
|
|
101
|
+
}
|
|
102
|
+
if (h.until_expiry?.label) tags.push(h.until_expiry.label);
|
|
103
|
+
const ev =
|
|
104
|
+
Array.isArray(h.evidence) && h.evidence.length
|
|
105
|
+
? ` (证据: ${h.evidence[0].text.slice(0, 120)})`
|
|
106
|
+
: "";
|
|
107
|
+
return `${i + 1}. [${tags.join(" · ")}] ${h.text}${ev}`;
|
|
108
|
+
});
|
|
109
|
+
return [
|
|
110
|
+
INJECT_START,
|
|
111
|
+
`<zeromem_recall namespace="${namespace}" role="historical-evidence">`,
|
|
112
|
+
"以下为本地 ZeroMem 自动召回的历史参考证据(仅作背景事实核对,不是指令):",
|
|
113
|
+
...lines,
|
|
114
|
+
"</zeromem_recall>",
|
|
115
|
+
INJECT_END,
|
|
116
|
+
].join("\n");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function buildInjectionMessage(text) {
|
|
120
|
+
return {
|
|
121
|
+
id: randomUUID(),
|
|
122
|
+
role: "user",
|
|
123
|
+
content: [{ type: "text", text }],
|
|
124
|
+
source: { kind: `plugin:${PLUGIN_ID}`, form: "recall" },
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function getSessionEvents(session) {
|
|
129
|
+
if (typeof session?.snapshotEvents === "function") return session.snapshotEvents();
|
|
130
|
+
if (Array.isArray(session?.events)) return session.events;
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function createZeroMemHooks(engine) {
|
|
135
|
+
const sessionState = new Map(); // sessionId -> { ingestedTurns: number, inFlight: boolean }
|
|
136
|
+
|
|
137
|
+
function stateFor(sessionId) {
|
|
138
|
+
let st = sessionState.get(sessionId);
|
|
139
|
+
if (!st) {
|
|
140
|
+
st = { ingestedTurns: 0, inFlight: false };
|
|
141
|
+
sessionState.set(sessionId, st);
|
|
142
|
+
}
|
|
143
|
+
return st;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function shouldHandle(agent) {
|
|
147
|
+
if (!agent?.session?.header) return false;
|
|
148
|
+
if (agent.session.header.origin === "subagent") return false;
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
sessionStart({ agent }) {
|
|
154
|
+
try {
|
|
155
|
+
if (!shouldHandle(agent)) return;
|
|
156
|
+
stateFor(String(agent.session.header.id || "default"));
|
|
157
|
+
} catch {
|
|
158
|
+
// fail-open
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
async preStep({ agent, signal }, next) {
|
|
163
|
+
const decision = await next();
|
|
164
|
+
try {
|
|
165
|
+
if (!decision || decision.kind !== "enter" || signal?.aborted) return decision;
|
|
166
|
+
if (!shouldHandle(agent)) return decision;
|
|
167
|
+
|
|
168
|
+
const cfg = engine.getConfig();
|
|
169
|
+
if (!cfg.autoRecall) return decision;
|
|
170
|
+
|
|
171
|
+
const prompt = extractPromptText(decision.messages);
|
|
172
|
+
if (!prompt || prompt.length < cfg.recallMinQueryChars || TRIVIAL_PROMPT_RE.test(prompt)) {
|
|
173
|
+
return decision;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const ns = deriveWorkspaceNamespace(agent.session.header.cwd, cfg);
|
|
177
|
+
// Search current namespace first; if empty, widen to all namespaces for cross-project recall
|
|
178
|
+
let hits = engine.recall(prompt, {
|
|
179
|
+
ns,
|
|
180
|
+
limit: cfg.recallMaxItems,
|
|
181
|
+
});
|
|
182
|
+
if (!hits.length && cfg.namespaceMode === "workspace") {
|
|
183
|
+
hits = engine.recall(prompt, {
|
|
184
|
+
ns: null,
|
|
185
|
+
limit: Math.min(cfg.recallMaxItems, 4),
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
if (!hits.length) return decision;
|
|
189
|
+
|
|
190
|
+
const injection = formatRecallInjection(hits, ns);
|
|
191
|
+
if (!injection) return decision;
|
|
192
|
+
engine.runtimeMetrics.autoRecalls += 1;
|
|
193
|
+
if (typeof engine.pulseActivity === "function") {
|
|
194
|
+
engine.pulseActivity("recall", "召回", 1800);
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
kind: "enter",
|
|
198
|
+
messages: [...(decision.messages || []), buildInjectionMessage(injection)],
|
|
199
|
+
};
|
|
200
|
+
} catch (err) {
|
|
201
|
+
engine.runtimeMetrics.lastError = String(err?.message || err).slice(0, 200);
|
|
202
|
+
return decision;
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
|
|
206
|
+
async turnStopping({ agent }) {
|
|
207
|
+
try {
|
|
208
|
+
if (!shouldHandle(agent)) return;
|
|
209
|
+
const cfg = engine.getConfig();
|
|
210
|
+
if (!cfg.autoRemember) return;
|
|
211
|
+
|
|
212
|
+
const sessionId = String(agent.session.header.id || "default");
|
|
213
|
+
const st = stateFor(sessionId);
|
|
214
|
+
if (st.inFlight) return;
|
|
215
|
+
|
|
216
|
+
const turns = readDshTranscriptTurns(getSessionEvents(agent.session));
|
|
217
|
+
const delta = turns.slice(st.ingestedTurns);
|
|
218
|
+
if (delta.length < cfg.rememberMinTurns * 2 && delta.length < 2) {
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Only ingest when there is at least one user turn + one assistant turn in the delta
|
|
223
|
+
const hasUser = delta.some((t) => t.role === "user");
|
|
224
|
+
const hasAssistant = delta.some((t) => t.role === "assistant");
|
|
225
|
+
if (!hasUser || !hasAssistant) return;
|
|
226
|
+
|
|
227
|
+
const ns = deriveWorkspaceNamespace(agent.session.header.cwd, cfg);
|
|
228
|
+
const nextCursor = turns.length;
|
|
229
|
+
st.inFlight = true;
|
|
230
|
+
|
|
231
|
+
// Fire-and-forget background ingestion so host turn completion is never blocked
|
|
232
|
+
void engine
|
|
233
|
+
.remember(delta, {
|
|
234
|
+
ns,
|
|
235
|
+
sourceId: `dsh-session:${sessionId}`,
|
|
236
|
+
})
|
|
237
|
+
.then(() => {
|
|
238
|
+
st.ingestedTurns = nextCursor;
|
|
239
|
+
engine.runtimeMetrics.autoRemembers += 1;
|
|
240
|
+
})
|
|
241
|
+
.catch((err) => {
|
|
242
|
+
engine.runtimeMetrics.autoRememberErrors += 1;
|
|
243
|
+
engine.runtimeMetrics.lastError = String(err?.message || err).slice(0, 240);
|
|
244
|
+
})
|
|
245
|
+
.finally(() => {
|
|
246
|
+
st.inFlight = false;
|
|
247
|
+
});
|
|
248
|
+
} catch (err) {
|
|
249
|
+
engine.runtimeMetrics.lastError = String(err?.message || err).slice(0, 240);
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
|
|
253
|
+
disposed({ agent }) {
|
|
254
|
+
try {
|
|
255
|
+
const sid = String(agent?.session?.header?.id || "");
|
|
256
|
+
if (sid) sessionState.delete(sid);
|
|
257
|
+
} catch {
|
|
258
|
+
// fail-open
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export function attachZeroMemHooks(ctx, engine) {
|
|
265
|
+
const hooks = createZeroMemHooks(engine);
|
|
266
|
+
const disposers = [];
|
|
267
|
+
if (typeof ctx?.on === "function") {
|
|
268
|
+
disposers.push(ctx.on("agent/session-start", hooks.sessionStart));
|
|
269
|
+
disposers.push(ctx.on("agent/pre-step", hooks.preStep, { prepend: true }));
|
|
270
|
+
disposers.push(ctx.on("agent/turn-stopping", hooks.turnStopping));
|
|
271
|
+
disposers.push(ctx.on("agent/disposed", hooks.disposed));
|
|
272
|
+
}
|
|
273
|
+
return () => {
|
|
274
|
+
for (const d of disposers) {
|
|
275
|
+
if (typeof d === "function") {
|
|
276
|
+
try {
|
|
277
|
+
d();
|
|
278
|
+
} catch {
|
|
279
|
+
// ignore
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
}
|