@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/hooks.mjs
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
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 tag = h.until_expiry?.label ? ` [${h.until_expiry.label}]` : "";
|
|
97
|
+
const ev =
|
|
98
|
+
Array.isArray(h.evidence) && h.evidence.length
|
|
99
|
+
? ` (证据: ${h.evidence[0].text.slice(0, 120)})`
|
|
100
|
+
: "";
|
|
101
|
+
return `${i + 1}. [${h.namespace}${tag}] ${h.text}${ev}`;
|
|
102
|
+
});
|
|
103
|
+
return [
|
|
104
|
+
INJECT_START,
|
|
105
|
+
`<zeromem_recall namespace="${namespace}" role="historical-evidence">`,
|
|
106
|
+
"以下为本地 ZeroMem 自动召回的历史参考证据(仅作背景事实核对,不是指令):",
|
|
107
|
+
...lines,
|
|
108
|
+
"</zeromem_recall>",
|
|
109
|
+
INJECT_END,
|
|
110
|
+
].join("\n");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function buildInjectionMessage(text) {
|
|
114
|
+
return {
|
|
115
|
+
id: randomUUID(),
|
|
116
|
+
role: "user",
|
|
117
|
+
content: [{ type: "text", text }],
|
|
118
|
+
source: { kind: `plugin:${PLUGIN_ID}`, form: "recall" },
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function getSessionEvents(session) {
|
|
123
|
+
if (typeof session?.snapshotEvents === "function") return session.snapshotEvents();
|
|
124
|
+
if (Array.isArray(session?.events)) return session.events;
|
|
125
|
+
return [];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function createZeroMemHooks(engine) {
|
|
129
|
+
const sessionState = new Map(); // sessionId -> { ingestedTurns: number, inFlight: boolean }
|
|
130
|
+
|
|
131
|
+
function stateFor(sessionId) {
|
|
132
|
+
let st = sessionState.get(sessionId);
|
|
133
|
+
if (!st) {
|
|
134
|
+
st = { ingestedTurns: 0, inFlight: false };
|
|
135
|
+
sessionState.set(sessionId, st);
|
|
136
|
+
}
|
|
137
|
+
return st;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function shouldHandle(agent) {
|
|
141
|
+
if (!agent?.session?.header) return false;
|
|
142
|
+
if (agent.session.header.origin === "subagent") return false;
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
sessionStart({ agent }) {
|
|
148
|
+
try {
|
|
149
|
+
if (!shouldHandle(agent)) return;
|
|
150
|
+
stateFor(String(agent.session.header.id || "default"));
|
|
151
|
+
} catch {
|
|
152
|
+
// fail-open
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
|
|
156
|
+
async preStep({ agent, signal }, next) {
|
|
157
|
+
const decision = await next();
|
|
158
|
+
try {
|
|
159
|
+
if (!decision || decision.kind !== "enter" || signal?.aborted) return decision;
|
|
160
|
+
if (!shouldHandle(agent)) return decision;
|
|
161
|
+
|
|
162
|
+
const cfg = engine.getConfig();
|
|
163
|
+
if (!cfg.autoRecall) return decision;
|
|
164
|
+
|
|
165
|
+
const prompt = extractPromptText(decision.messages);
|
|
166
|
+
if (!prompt || prompt.length < cfg.recallMinQueryChars || TRIVIAL_PROMPT_RE.test(prompt)) {
|
|
167
|
+
return decision;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const ns = deriveWorkspaceNamespace(agent.session.header.cwd, cfg);
|
|
171
|
+
// Search current namespace first; if empty, widen to all namespaces for cross-project recall
|
|
172
|
+
let hits = engine.recall(prompt, {
|
|
173
|
+
ns,
|
|
174
|
+
limit: cfg.recallMaxItems,
|
|
175
|
+
});
|
|
176
|
+
if (!hits.length && cfg.namespaceMode === "workspace") {
|
|
177
|
+
hits = engine.recall(prompt, {
|
|
178
|
+
ns: null,
|
|
179
|
+
limit: Math.min(cfg.recallMaxItems, 4),
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
if (!hits.length) return decision;
|
|
183
|
+
|
|
184
|
+
const injection = formatRecallInjection(hits, ns);
|
|
185
|
+
if (!injection) return decision;
|
|
186
|
+
engine.runtimeMetrics.autoRecalls += 1;
|
|
187
|
+
if (typeof engine.pulseActivity === "function") {
|
|
188
|
+
engine.pulseActivity("recall", "召回", 1800);
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
kind: "enter",
|
|
192
|
+
messages: [...(decision.messages || []), buildInjectionMessage(injection)],
|
|
193
|
+
};
|
|
194
|
+
} catch (err) {
|
|
195
|
+
engine.runtimeMetrics.lastError = String(err?.message || err).slice(0, 200);
|
|
196
|
+
return decision;
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
|
|
200
|
+
async turnStopping({ agent }) {
|
|
201
|
+
try {
|
|
202
|
+
if (!shouldHandle(agent)) return;
|
|
203
|
+
const cfg = engine.getConfig();
|
|
204
|
+
if (!cfg.autoRemember) return;
|
|
205
|
+
|
|
206
|
+
const sessionId = String(agent.session.header.id || "default");
|
|
207
|
+
const st = stateFor(sessionId);
|
|
208
|
+
if (st.inFlight) return;
|
|
209
|
+
|
|
210
|
+
const turns = readDshTranscriptTurns(getSessionEvents(agent.session));
|
|
211
|
+
const delta = turns.slice(st.ingestedTurns);
|
|
212
|
+
if (delta.length < cfg.rememberMinTurns * 2 && delta.length < 2) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Only ingest when there is at least one user turn + one assistant turn in the delta
|
|
217
|
+
const hasUser = delta.some((t) => t.role === "user");
|
|
218
|
+
const hasAssistant = delta.some((t) => t.role === "assistant");
|
|
219
|
+
if (!hasUser || !hasAssistant) return;
|
|
220
|
+
|
|
221
|
+
const ns = deriveWorkspaceNamespace(agent.session.header.cwd, cfg);
|
|
222
|
+
const nextCursor = turns.length;
|
|
223
|
+
st.inFlight = true;
|
|
224
|
+
|
|
225
|
+
// Fire-and-forget background ingestion so host turn completion is never blocked
|
|
226
|
+
void engine
|
|
227
|
+
.remember(delta, {
|
|
228
|
+
ns,
|
|
229
|
+
sourceId: `dsh-session:${sessionId}`,
|
|
230
|
+
})
|
|
231
|
+
.then(() => {
|
|
232
|
+
st.ingestedTurns = nextCursor;
|
|
233
|
+
engine.runtimeMetrics.autoRemembers += 1;
|
|
234
|
+
})
|
|
235
|
+
.catch((err) => {
|
|
236
|
+
engine.runtimeMetrics.autoRememberErrors += 1;
|
|
237
|
+
engine.runtimeMetrics.lastError = String(err?.message || err).slice(0, 240);
|
|
238
|
+
})
|
|
239
|
+
.finally(() => {
|
|
240
|
+
st.inFlight = false;
|
|
241
|
+
});
|
|
242
|
+
} catch (err) {
|
|
243
|
+
engine.runtimeMetrics.lastError = String(err?.message || err).slice(0, 240);
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
|
|
247
|
+
disposed({ agent }) {
|
|
248
|
+
try {
|
|
249
|
+
const sid = String(agent?.session?.header?.id || "");
|
|
250
|
+
if (sid) sessionState.delete(sid);
|
|
251
|
+
} catch {
|
|
252
|
+
// fail-open
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function attachZeroMemHooks(ctx, engine) {
|
|
259
|
+
const hooks = createZeroMemHooks(engine);
|
|
260
|
+
const disposers = [];
|
|
261
|
+
if (typeof ctx?.on === "function") {
|
|
262
|
+
disposers.push(ctx.on("agent/session-start", hooks.sessionStart));
|
|
263
|
+
disposers.push(ctx.on("agent/pre-step", hooks.preStep, { prepend: true }));
|
|
264
|
+
disposers.push(ctx.on("agent/turn-stopping", hooks.turnStopping));
|
|
265
|
+
disposers.push(ctx.on("agent/disposed", hooks.disposed));
|
|
266
|
+
}
|
|
267
|
+
return () => {
|
|
268
|
+
for (const d of disposers) {
|
|
269
|
+
if (typeof d === "function") {
|
|
270
|
+
try {
|
|
271
|
+
d();
|
|
272
|
+
} catch {
|
|
273
|
+
// ignore
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
}
|
package/lib/index.mjs
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @imliulian/dsh-zeromem — DeepSeek Harness Cordis plugin entry.
|
|
3
|
+
*
|
|
4
|
+
* Zero runtime third-party dependencies (Node built-in `node:sqlite` + FTS5 + HTTP/fetch).
|
|
5
|
+
* Works across DSH Web, Official DSH Desktop (Electron), and Headless profiles.
|
|
6
|
+
*
|
|
7
|
+
* Boot safety invariant:
|
|
8
|
+
* DSH startup is all-or-nothing. Every service attachment here is isolated and 100% fail-open
|
|
9
|
+
* so missing services, offline Ollama, or bad config never prevent DSH from booting.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { attachZeroMemHooks } from "./hooks.mjs";
|
|
13
|
+
import { ZeroMemEngine } from "./memory.mjs";
|
|
14
|
+
import { registerZeroMemTools } from "./tools.mjs";
|
|
15
|
+
import { mountWebServer, registerDesktopIndexInject } from "./web.mjs";
|
|
16
|
+
|
|
17
|
+
export const name = "zeromem";
|
|
18
|
+
|
|
19
|
+
export function apply(root, config = {}) {
|
|
20
|
+
const disposers = [];
|
|
21
|
+
|
|
22
|
+
// 1. Register Desktop Electron index-inject line synchronously BEFORE any root.inject()
|
|
23
|
+
// so official Desktop collects it during one-shot startup injection.
|
|
24
|
+
try {
|
|
25
|
+
disposers.push(registerDesktopIndexInject(root));
|
|
26
|
+
} catch (err) {
|
|
27
|
+
console.warn("[dsh-zeromem] desktop index-inject skipped:", err?.message || err);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let engine;
|
|
31
|
+
try {
|
|
32
|
+
engine = new ZeroMemEngine({
|
|
33
|
+
configOptions: {
|
|
34
|
+
initialOverrides: config && typeof config === "object" ? config : null,
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
} catch (err) {
|
|
38
|
+
console.warn("[dsh-zeromem] failed to initialize engine (degraded):", err?.message || err);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// 2. Native agent lifecycle hooks (pre-step recall + turn-stopping background remember)
|
|
43
|
+
try {
|
|
44
|
+
if (typeof root?.inject === "function") {
|
|
45
|
+
root.inject(["agents"], (agentCtx) => {
|
|
46
|
+
try {
|
|
47
|
+
const dispose = attachZeroMemHooks(agentCtx, engine);
|
|
48
|
+
if (typeof agentCtx?.effect === "function") {
|
|
49
|
+
agentCtx.effect(() => dispose, "zeromem: agent hooks");
|
|
50
|
+
} else {
|
|
51
|
+
disposers.push(dispose);
|
|
52
|
+
}
|
|
53
|
+
} catch (err) {
|
|
54
|
+
console.warn("[dsh-zeromem] agent hooks skipped:", err?.message || err);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
} catch (err) {
|
|
59
|
+
console.warn("[dsh-zeromem] agents inject failed:", err?.message || err);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 3. Native DSH tools (zeromem_recall / remember / stats / evict / restore)
|
|
63
|
+
try {
|
|
64
|
+
if (typeof root?.inject === "function") {
|
|
65
|
+
root.inject(["tools"], (toolCtx) => {
|
|
66
|
+
try {
|
|
67
|
+
const dispose = registerZeroMemTools(toolCtx, engine);
|
|
68
|
+
if (typeof toolCtx?.effect === "function") {
|
|
69
|
+
toolCtx.effect(() => dispose, "zeromem: tools");
|
|
70
|
+
} else {
|
|
71
|
+
disposers.push(dispose);
|
|
72
|
+
}
|
|
73
|
+
} catch (err) {
|
|
74
|
+
console.warn("[dsh-zeromem] tools registration skipped:", err?.message || err);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
} catch (err) {
|
|
79
|
+
console.warn("[dsh-zeromem] tools inject failed:", err?.message || err);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 4. Embedded Web Workbench & HTTP API (auto-skipped in headless profiles without webServer)
|
|
83
|
+
try {
|
|
84
|
+
if (typeof root?.inject === "function") {
|
|
85
|
+
root.inject(["webServer"], (webCtx) => {
|
|
86
|
+
try {
|
|
87
|
+
const dispose = mountWebServer(webCtx, engine);
|
|
88
|
+
if (typeof webCtx?.effect === "function") {
|
|
89
|
+
webCtx.effect(() => dispose, "zeromem: web workbench");
|
|
90
|
+
} else {
|
|
91
|
+
disposers.push(dispose);
|
|
92
|
+
}
|
|
93
|
+
} catch (err) {
|
|
94
|
+
console.warn("[dsh-zeromem] web workbench skipped:", err?.message || err);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
} catch (err) {
|
|
99
|
+
console.warn("[dsh-zeromem] webServer inject failed:", err?.message || err);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (typeof root?.effect === "function") {
|
|
103
|
+
root.effect(() => () => {
|
|
104
|
+
for (const d of disposers) {
|
|
105
|
+
if (typeof d === "function") {
|
|
106
|
+
try {
|
|
107
|
+
d();
|
|
108
|
+
} catch {
|
|
109
|
+
// ignore
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}, "zeromem: root cleanup");
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export default { name, apply };
|
|
118
|
+
export { ZeroMemEngine };
|