@modusensus/dsh-mneme 0.1.0 → 0.1.2

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/src/dream.js CHANGED
@@ -1,205 +1,205 @@
1
- import { validateDecisions, applyDecisions } from "./dream/decisions.js";
2
- export { validateDecisions, applyDecisions };
3
-
4
- const SUMMARY_PROMPT = `你是记忆库摘要助手。根据整理后的记忆,生成一段 150-200 字的记忆库总览,覆盖:用户偏好、活跃项目、关键决策。之后作为会话上下文注入。只输出摘要文本,不要其他内容。`;
5
-
6
- const CONSOLIDATION_PROMPT = `你是记忆库整理助手。下面是全部记忆条目(id、类型、标题、内容、重要性、更新时间)。
7
- 请执行记忆巩固(consolidation):
8
- 1. 识别主题相近的条目 → 输出 merge(合并为更精炼的摘要,保留信息最完整的 id 作为 keepSource)
9
- 2. 识别重复/过时信息 → 输出 archive
10
- 3. 识别内容矛盾的条目 → 输出 conflict(根据时间新旧、来源完整性、信息具体程度判断 winner/loser)
11
- 4. 无问题的条目 → 输出 keep
12
-
13
- 规则:
14
- - 每条记忆至少出现在一个决策中
15
- - merge 的 keepSource 必须是 ids 之一
16
- - 仅合并同类型条目(type 相同)
17
- - 不要编造 ids;只使用提供的 id
18
- - 重要性 1-5,合并后取最高
19
- - 只输出 JSON 数组,不要其他文字`;
20
-
21
- function totalChars(memories) {
22
- return memories.reduce((sum, m) => sum + (m.title?.length ?? 0) + (m.content?.length ?? 0), 0);
23
- }
24
-
25
- /**
26
- * Consume an LLM stream and return the accumulated text. Direct text-delta
27
- * accumulation covers both the real protocol ({type:"text-delta", index, text})
28
- * and looser test doubles ({type:"text-delta", text}); a terminal error/abort
29
- * surfaces as undefined. The caller decides how to treat an empty result.
30
- */
31
- async function streamText(ctx, options) {
32
- let text = "";
33
- for await (const chunk of ctx.llm.stream(options)) {
34
- if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
35
- if (chunk.type === "finish" && (chunk.reason?.kind === "error" || chunk.reason?.kind === "aborted")) {
36
- return undefined;
37
- }
38
- }
39
- return text;
40
- }
41
-
42
- /**
43
- * Resolve the LLM route: agent default model (deployment) first, plugin config
44
- * (dreamProvider/dreamModel) as fallback. Falls through to undefined when no
45
- * route exists — runDream then fails safe. Fallback is logged so a silent
46
- * route switch is observable.
47
- */
48
- function resolveRoute(ctx, config, logger) {
49
- try {
50
- const sel = ctx.agentDefaultModel?.currentSelection?.();
51
- if (sel?.provider && sel?.model) return { provider: sel.provider, model: sel.model };
52
- logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, falling back to config route");
53
- } catch (error) {
54
- logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed, falling back to config route: ${String(error)}`);
55
- }
56
- if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
57
- return undefined;
58
- }
59
-
60
- export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChars = 5000, delayMs = 2000, logger }) {
61
- let pendingTimer = null;
62
- let running = false;
63
- let disposed = false;
64
- let baseline = { count: 0, chars: 0 };
65
-
66
- function shouldTrigger(service) {
67
- const memories = service.all().filter((m) => !m.archived && m.type !== "summary");
68
- const count = memories.length;
69
- const chars = totalChars(memories);
70
- const overBase = count >= baseline.count + thresholdCount || chars >= baseline.chars + thresholdChars;
71
- const overAbs = count >= thresholdCount || chars >= thresholdChars;
72
- return { trigger: overAbs && overBase, count, chars };
73
- }
74
-
75
- function maybeSchedule(service) {
76
- if (disposed || running || pendingTimer) return false;
77
- const { trigger, count, chars } = shouldTrigger(service);
78
- if (!trigger) return false;
79
- pendingTimer = setTimeout(() => {
80
- pendingTimer = null;
81
- running = true;
82
- // Defer the onRun invocation so a synchronous throw cannot escape the
83
- // timer callback (which would crash the process) and skip the teardown.
84
- // Errors are logged, never swallowed silently.
85
- Promise.resolve()
86
- .then(() => (onRun ? onRun() : Promise.resolve({ ok: true, skipped: true })))
87
- .then((result) => {
88
- // Refresh the baseline only for a successful run (design §5.3: an
89
- // LLM failure must not move the baseline, so the next write can
90
- // immediately re-trigger a retry). A `{ok:false}` result or a throw
91
- // keeps the old baseline. A run that reports nothing is treated as
92
- // completed without failure (no-op hooks / minimal test doubles).
93
- if (result && result.ok) {
94
- try {
95
- baseline = shouldTrigger(service);
96
- } catch (error) {
97
- // Store closed mid-flight: keep the last known baseline.
98
- logger?.warn?.(`dsh-mneme dream: baseline refresh failed: ${String(error)}`);
99
- }
100
- }
101
- })
102
- .catch((error) => {
103
- logger?.warn?.(`dsh-mneme dream: run failed: ${error?.message ?? error}`);
104
- // Failed runs do not refresh the baseline.
105
- })
106
- .finally(() => {
107
- running = false;
108
- });
109
- }, delayMs);
110
- return true;
111
- }
112
-
113
- function dispose() {
114
- disposed = true;
115
- if (pendingTimer) { clearTimeout(pendingTimer); pendingTimer = null; }
116
- // An in-flight run is left to complete naturally: its LLM calls are
117
- // already paid for and aborting would discard the work. The caller is
118
- // responsible for closing the store only after the run has finished.
119
- }
120
-
121
- async function runDream(ctx, service, config) {
122
- const logger = ctx.logger;
123
- const memories = service.all().filter((m) => !m.archived && m.type !== "summary");
124
- if (memories.length === 0) return { ok: true, applied: 0, skipped: true, summary: false };
125
- const snapshot = new Map(memories.map((m) => [m.id, m]));
126
- const route = resolveRoute(ctx, config, logger);
127
- if (!route) {
128
- logger?.warn?.("dsh-mneme dream: no llm route available");
129
- return { ok: false, error: "no llm route", summary: false };
130
- }
131
-
132
- const listText = [...snapshot.values()].map((m) =>
133
- `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`
134
- ).join("\n");
135
-
136
- let decisionText;
137
- try {
138
- decisionText = await streamText(ctx, {
139
- provider: route.provider,
140
- model: route.model,
141
- purpose: "compaction",
142
- maxTokens: config.dreamMaxTokens ?? 4096,
143
- messages: [
144
- { role: "system", content: [{ type: "text", text: CONSOLIDATION_PROMPT }] },
145
- { role: "user", content: [{ type: "text", text: listText }] }
146
- ]
147
- });
148
- } catch (error) {
149
- logger?.warn?.(`dsh-mneme dream: consolidation llm call failed: ${String(error)}`);
150
- return { ok: false, error: "llm failed", summary: false };
151
- }
152
- if (decisionText === undefined) {
153
- logger?.warn?.("dsh-mneme dream: consolidation llm stream aborted or errored");
154
- return { ok: false, error: "llm failed", summary: false };
155
- }
156
-
157
- let decisions;
158
- try {
159
- const start = decisionText.indexOf("[");
160
- const end = decisionText.lastIndexOf("]");
161
- if (start === -1 || end <= start) {
162
- logger?.warn?.("dsh-mneme dream: no json array in llm output");
163
- return { ok: false, error: "no json array in llm output", summary: false };
164
- }
165
- decisions = JSON.parse(decisionText.slice(start, end + 1));
166
- } catch {
167
- logger?.warn?.("dsh-mneme dream: invalid decisions json");
168
- return { ok: false, error: "invalid decisions json", summary: false };
169
- }
170
- const { ok, errors } = validateDecisions(decisions, snapshot);
171
- if (!ok) {
172
- logger?.warn?.(`dsh-mneme dream: invalid decisions: ${errors.join("; ")}`);
173
- return { ok: false, error: `invalid decisions: ${errors.length} errors`, summary: false };
174
- }
175
-
176
- const applied = applyDecisions(decisions, service, logger);
177
-
178
- // Summary generation (second LLM call). A throwing stream is reported as
179
- // a failed run; summary:false marks a run that produced no summary.
180
- let summaryText;
181
- try {
182
- summaryText = await streamText(ctx, {
183
- provider: route.provider,
184
- model: route.model,
185
- purpose: "compaction",
186
- maxTokens: config.dreamMaxTokens ?? 2048,
187
- messages: [
188
- { role: "system", content: [{ type: "text", text: SUMMARY_PROMPT }] },
189
- { role: "user", content: [{ type: "text", text: service.all().filter((m) => !m.archived && m.type !== "summary").map((m) => `- ${m.title}: ${m.content}`).join("\n") }] }
190
- ]
191
- });
192
- } catch (error) {
193
- logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
194
- return { ok: false, error: "llm failed", summary: false };
195
- }
196
- let summaryStored = false;
197
- if (summaryText !== undefined && summaryText.trim()) {
198
- service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: summaryText.trim(), importance: 5, source: "dream" });
199
- summaryStored = true;
200
- }
201
- return { ok: true, applied, summary: summaryStored };
202
- }
203
-
204
- return { maybeSchedule, runDream, dispose };
205
- }
1
+ import { validateDecisions, applyDecisions } from "./dream/decisions.js";
2
+ export { validateDecisions, applyDecisions };
3
+
4
+ const SUMMARY_PROMPT = `你是记忆库摘要助手。根据整理后的记忆,生成一段 150-200 字的记忆库总览,覆盖:用户偏好、活跃项目、关键决策。之后作为会话上下文注入。只输出摘要文本,不要其他内容。`;
5
+
6
+ const CONSOLIDATION_PROMPT = `你是记忆库整理助手。下面是全部记忆条目(id、类型、标题、内容、重要性、更新时间)。
7
+ 请执行记忆巩固(consolidation):
8
+ 1. 识别主题相近的条目 → 输出 merge(合并为更精炼的摘要,保留信息最完整的 id 作为 keepSource)
9
+ 2. 识别重复/过时信息 → 输出 archive
10
+ 3. 识别内容矛盾的条目 → 输出 conflict(根据时间新旧、来源完整性、信息具体程度判断 winner/loser)
11
+ 4. 无问题的条目 → 输出 keep
12
+
13
+ 规则:
14
+ - 每条记忆至少出现在一个决策中
15
+ - merge 的 keepSource 必须是 ids 之一
16
+ - 仅合并同类型条目(type 相同)
17
+ - 不要编造 ids;只使用提供的 id
18
+ - 重要性 1-5,合并后取最高
19
+ - 只输出 JSON 数组,不要其他文字`;
20
+
21
+ function totalChars(memories) {
22
+ return memories.reduce((sum, m) => sum + (m.title?.length ?? 0) + (m.content?.length ?? 0), 0);
23
+ }
24
+
25
+ /**
26
+ * Consume an LLM stream and return the accumulated text. Direct text-delta
27
+ * accumulation covers both the real protocol ({type:"text-delta", index, text})
28
+ * and looser test doubles ({type:"text-delta", text}); a terminal error/abort
29
+ * surfaces as undefined. The caller decides how to treat an empty result.
30
+ */
31
+ async function streamText(ctx, options) {
32
+ let text = "";
33
+ for await (const chunk of ctx.llm.stream(options)) {
34
+ if (chunk.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
35
+ if (chunk.type === "finish" && (chunk.reason?.kind === "error" || chunk.reason?.kind === "aborted")) {
36
+ return undefined;
37
+ }
38
+ }
39
+ return text;
40
+ }
41
+
42
+ /**
43
+ * Resolve the LLM route: agent default model (deployment) first, plugin config
44
+ * (dreamProvider/dreamModel) as fallback. Falls through to undefined when no
45
+ * route exists — runDream then fails safe. Fallback is logged so a silent
46
+ * route switch is observable.
47
+ */
48
+ function resolveRoute(ctx, config, logger) {
49
+ try {
50
+ const sel = ctx.agentDefaultModel?.currentSelection?.();
51
+ if (sel?.provider && sel?.model) return { provider: sel.provider, model: sel.model };
52
+ logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, falling back to config route");
53
+ } catch (error) {
54
+ logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed, falling back to config route: ${String(error)}`);
55
+ }
56
+ if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
57
+ return undefined;
58
+ }
59
+
60
+ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChars = 5000, delayMs = 2000, logger }) {
61
+ let pendingTimer = null;
62
+ let running = false;
63
+ let disposed = false;
64
+ let baseline = { count: 0, chars: 0 };
65
+
66
+ function shouldTrigger(service) {
67
+ const memories = service.all().filter((m) => !m.archived && m.type !== "summary");
68
+ const count = memories.length;
69
+ const chars = totalChars(memories);
70
+ const overBase = count >= baseline.count + thresholdCount || chars >= baseline.chars + thresholdChars;
71
+ const overAbs = count >= thresholdCount || chars >= thresholdChars;
72
+ return { trigger: overAbs && overBase, count, chars };
73
+ }
74
+
75
+ function maybeSchedule(service) {
76
+ if (disposed || running || pendingTimer) return false;
77
+ const { trigger, count, chars } = shouldTrigger(service);
78
+ if (!trigger) return false;
79
+ pendingTimer = setTimeout(() => {
80
+ pendingTimer = null;
81
+ running = true;
82
+ // Defer the onRun invocation so a synchronous throw cannot escape the
83
+ // timer callback (which would crash the process) and skip the teardown.
84
+ // Errors are logged, never swallowed silently.
85
+ Promise.resolve()
86
+ .then(() => (onRun ? onRun() : Promise.resolve({ ok: true, skipped: true })))
87
+ .then((result) => {
88
+ // Refresh the baseline only for a successful run (design §5.3: an
89
+ // LLM failure must not move the baseline, so the next write can
90
+ // immediately re-trigger a retry). A `{ok:false}` result or a throw
91
+ // keeps the old baseline. A run that reports nothing is treated as
92
+ // completed without failure (no-op hooks / minimal test doubles).
93
+ if (result && result.ok) {
94
+ try {
95
+ baseline = shouldTrigger(service);
96
+ } catch (error) {
97
+ // Store closed mid-flight: keep the last known baseline.
98
+ logger?.warn?.(`dsh-mneme dream: baseline refresh failed: ${String(error)}`);
99
+ }
100
+ }
101
+ })
102
+ .catch((error) => {
103
+ logger?.warn?.(`dsh-mneme dream: run failed: ${error?.message ?? error}`);
104
+ // Failed runs do not refresh the baseline.
105
+ })
106
+ .finally(() => {
107
+ running = false;
108
+ });
109
+ }, delayMs);
110
+ return true;
111
+ }
112
+
113
+ function dispose() {
114
+ disposed = true;
115
+ if (pendingTimer) { clearTimeout(pendingTimer); pendingTimer = null; }
116
+ // An in-flight run is left to complete naturally: its LLM calls are
117
+ // already paid for and aborting would discard the work. The caller is
118
+ // responsible for closing the store only after the run has finished.
119
+ }
120
+
121
+ async function runDream(ctx, service, config) {
122
+ const logger = ctx.logger;
123
+ const memories = service.all().filter((m) => !m.archived && m.type !== "summary");
124
+ if (memories.length === 0) return { ok: true, applied: 0, skipped: true, summary: false };
125
+ const snapshot = new Map(memories.map((m) => [m.id, m]));
126
+ const route = resolveRoute(ctx, config, logger);
127
+ if (!route) {
128
+ logger?.warn?.("dsh-mneme dream: no llm route available");
129
+ return { ok: false, error: "no llm route", summary: false };
130
+ }
131
+
132
+ const listText = [...snapshot.values()].map((m) =>
133
+ `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`
134
+ ).join("\n");
135
+
136
+ let decisionText;
137
+ try {
138
+ decisionText = await streamText(ctx, {
139
+ provider: route.provider,
140
+ model: route.model,
141
+ purpose: "compaction",
142
+ maxTokens: config.dreamMaxTokens ?? 4096,
143
+ messages: [
144
+ { role: "system", content: [{ type: "text", text: CONSOLIDATION_PROMPT }] },
145
+ { role: "user", content: [{ type: "text", text: listText }] }
146
+ ]
147
+ });
148
+ } catch (error) {
149
+ logger?.warn?.(`dsh-mneme dream: consolidation llm call failed: ${String(error)}`);
150
+ return { ok: false, error: "llm failed", summary: false };
151
+ }
152
+ if (decisionText === undefined) {
153
+ logger?.warn?.("dsh-mneme dream: consolidation llm stream aborted or errored");
154
+ return { ok: false, error: "llm failed", summary: false };
155
+ }
156
+
157
+ let decisions;
158
+ try {
159
+ const start = decisionText.indexOf("[");
160
+ const end = decisionText.lastIndexOf("]");
161
+ if (start === -1 || end <= start) {
162
+ logger?.warn?.("dsh-mneme dream: no json array in llm output");
163
+ return { ok: false, error: "no json array in llm output", summary: false };
164
+ }
165
+ decisions = JSON.parse(decisionText.slice(start, end + 1));
166
+ } catch {
167
+ logger?.warn?.("dsh-mneme dream: invalid decisions json");
168
+ return { ok: false, error: "invalid decisions json", summary: false };
169
+ }
170
+ const { ok, errors } = validateDecisions(decisions, snapshot);
171
+ if (!ok) {
172
+ logger?.warn?.(`dsh-mneme dream: invalid decisions: ${errors.join("; ")}`);
173
+ return { ok: false, error: `invalid decisions: ${errors.length} errors`, summary: false };
174
+ }
175
+
176
+ const applied = applyDecisions(decisions, service, logger);
177
+
178
+ // Summary generation (second LLM call). A throwing stream is reported as
179
+ // a failed run; summary:false marks a run that produced no summary.
180
+ let summaryText;
181
+ try {
182
+ summaryText = await streamText(ctx, {
183
+ provider: route.provider,
184
+ model: route.model,
185
+ purpose: "compaction",
186
+ maxTokens: config.dreamMaxTokens ?? 2048,
187
+ messages: [
188
+ { role: "system", content: [{ type: "text", text: SUMMARY_PROMPT }] },
189
+ { role: "user", content: [{ type: "text", text: service.all().filter((m) => !m.archived && m.type !== "summary").map((m) => `- ${m.title}: ${m.content}`).join("\n") }] }
190
+ ]
191
+ });
192
+ } catch (error) {
193
+ logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
194
+ return { ok: false, error: "llm failed", summary: false };
195
+ }
196
+ let summaryStored = false;
197
+ if (summaryText !== undefined && summaryText.trim()) {
198
+ service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: summaryText.trim(), importance: 5, source: "dream" });
199
+ summaryStored = true;
200
+ }
201
+ return { ok: true, applied, summary: summaryStored };
202
+ }
203
+
204
+ return { maybeSchedule, runDream, dispose };
205
+ }
package/src/index.js CHANGED
@@ -1,86 +1,86 @@
1
- import { createStore } from "./store.js";
2
- import { createMirror, TYPE_FILE } from "./mirror.js";
3
- import { createService } from "./service.js";
4
- import { createTools } from "./tools.js";
5
- import { createInjector } from "./inject.js";
6
- import { createSummarizer } from "./summarize.js";
7
- import { createDreamScheduler } from "./dream.js";
8
- import { createApi } from "./api.js";
9
- import { Config } from "./config.js";
10
- import { mkdirSync } from "node:fs";
11
- import { join } from "node:path";
12
- import { homedir } from "node:os";
13
-
14
- export const name = "dsh-mneme";
15
- export const inject = ["tools", "systemPrompt", "webServer", "llm", "agentDefaultModel"];
16
- export { Config };
17
-
18
- // Arrow (not function declaration): cordis 4 treats any apply with a
19
- // prototype as a class constructor (`new apply(...)`) and discards its return
20
- // value, so a `function apply` disposer would never run on unload. An arrow
21
- // has no prototype, is called normally, and its returned disposer is collected
22
- // and run by the fiber on unload.
23
- export const apply = (ctx, config) => {
24
- const cfg = Config(config);
25
-
26
- // Resolve memoryDir: expand leading "~"
27
- const memoryDir = cfg.memoryDir.startsWith("~")
28
- ? join(homedir(), cfg.memoryDir.slice(1))
29
- : cfg.memoryDir;
30
- mkdirSync(memoryDir, { recursive: true });
31
-
32
- const store = createStore(join(memoryDir, "memory.db"));
33
- const mirror = createMirror(memoryDir);
34
- const service = createService({ store, mirror, config: cfg });
35
-
36
- // Human edits in mirror files win on every sync; merge them back first.
37
- // TYPE_FILE maps each memory type to its mirror filename.
38
- for (const type of Object.keys(TYPE_FILE)) {
39
- const edits = mirror.readHumanEdits(type);
40
- if (edits.length) service.mergeHumanEdits(type, edits);
41
- }
42
-
43
- // Dream scheduler: automatic consolidation + summary runs, triggered by
44
- // store growth. Writes through the service fire the dream hook, which asks
45
- // the scheduler to (re)schedule a run once absolute and since-last-run
46
- // thresholds are both exceeded. onRun is deferred through `dream` so the
47
- // closure sees the assigned scheduler; the null guard keeps a run safe even
48
- // if the hook fires before assignment or after dispose.
49
- let dream = null;
50
- if (cfg.autoDream) {
51
- dream = createDreamScheduler({
52
- thresholdCount: cfg.dreamThresholdCount,
53
- thresholdChars: cfg.dreamThresholdChars,
54
- delayMs: cfg.dreamDelayMs,
55
- logger: ctx.logger,
56
- onRun: () => (dream ? dream.runDream(ctx, service, cfg) : Promise.resolve({ ok: true, skipped: true }))
57
- });
58
- service.setDreamHook(() => dream.maybeSchedule(service));
59
- }
60
-
61
- const disposers = [];
62
-
63
- ctx.inject(["systemPrompt"], (promptCtx) => {
64
- if (cfg.autoInject) disposers.push(createInjector(promptCtx, service, cfg));
65
- });
66
-
67
- ctx.inject(["tools"], (toolsCtx) => {
68
- disposers.push(createTools(toolsCtx, service, cfg));
69
- });
70
-
71
- const summarizer = createSummarizer(ctx, service, cfg);
72
- disposers.push(summarizer.dispose);
73
-
74
- if (ctx.webServer) {
75
- const api = createApi(ctx, service);
76
- disposers.push(api.dispose);
77
- }
78
-
79
- return () => {
80
- for (const dispose of disposers) {
81
- if (typeof dispose === "function") dispose();
82
- }
83
- if (dream) dream.dispose();
84
- store.close();
85
- };
86
- };
1
+ import { createStore } from "./store.js";
2
+ import { createMirror, TYPE_FILE } from "./mirror.js";
3
+ import { createService } from "./service.js";
4
+ import { createTools } from "./tools.js";
5
+ import { createInjector } from "./inject.js";
6
+ import { createSummarizer } from "./summarize.js";
7
+ import { createDreamScheduler } from "./dream.js";
8
+ import { createApi } from "./api.js";
9
+ import { Config } from "./config.js";
10
+ import { mkdirSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { homedir } from "node:os";
13
+
14
+ export const name = "dsh-mneme";
15
+ export const inject = ["tools", "systemPrompt", "webServer", "llm", "agentDefaultModel"];
16
+ export { Config };
17
+
18
+ // Arrow (not function declaration): cordis 4 treats any apply with a
19
+ // prototype as a class constructor (`new apply(...)`) and discards its return
20
+ // value, so a `function apply` disposer would never run on unload. An arrow
21
+ // has no prototype, is called normally, and its returned disposer is collected
22
+ // and run by the fiber on unload.
23
+ export const apply = (ctx, config) => {
24
+ const cfg = Config(config);
25
+
26
+ // Resolve memoryDir: expand leading "~"
27
+ const memoryDir = cfg.memoryDir.startsWith("~")
28
+ ? join(homedir(), cfg.memoryDir.slice(1))
29
+ : cfg.memoryDir;
30
+ mkdirSync(memoryDir, { recursive: true });
31
+
32
+ const store = createStore(join(memoryDir, "memory.db"));
33
+ const mirror = createMirror(memoryDir);
34
+ const service = createService({ store, mirror, config: cfg });
35
+
36
+ // Human edits in mirror files win on every sync; merge them back first.
37
+ // TYPE_FILE maps each memory type to its mirror filename.
38
+ for (const type of Object.keys(TYPE_FILE)) {
39
+ const edits = mirror.readHumanEdits(type);
40
+ if (edits.length) service.mergeHumanEdits(type, edits);
41
+ }
42
+
43
+ // Dream scheduler: automatic consolidation + summary runs, triggered by
44
+ // store growth. Writes through the service fire the dream hook, which asks
45
+ // the scheduler to (re)schedule a run once absolute and since-last-run
46
+ // thresholds are both exceeded. onRun is deferred through `dream` so the
47
+ // closure sees the assigned scheduler; the null guard keeps a run safe even
48
+ // if the hook fires before assignment or after dispose.
49
+ let dream = null;
50
+ if (cfg.autoDream) {
51
+ dream = createDreamScheduler({
52
+ thresholdCount: cfg.dreamThresholdCount,
53
+ thresholdChars: cfg.dreamThresholdChars,
54
+ delayMs: cfg.dreamDelayMs,
55
+ logger: ctx.logger,
56
+ onRun: () => (dream ? dream.runDream(ctx, service, cfg) : Promise.resolve({ ok: true, skipped: true }))
57
+ });
58
+ service.setDreamHook(() => dream.maybeSchedule(service));
59
+ }
60
+
61
+ const disposers = [];
62
+
63
+ ctx.inject(["systemPrompt"], (promptCtx) => {
64
+ if (cfg.autoInject) disposers.push(createInjector(promptCtx, service, cfg));
65
+ });
66
+
67
+ ctx.inject(["tools"], (toolsCtx) => {
68
+ disposers.push(createTools(toolsCtx, service, cfg));
69
+ });
70
+
71
+ const summarizer = createSummarizer(ctx, service, cfg);
72
+ disposers.push(summarizer.dispose);
73
+
74
+ if (ctx.webServer) {
75
+ const api = createApi(ctx, service);
76
+ disposers.push(api.dispose);
77
+ }
78
+
79
+ return () => {
80
+ for (const dispose of disposers) {
81
+ if (typeof dispose === "function") dispose();
82
+ }
83
+ if (dream) dream.dispose();
84
+ store.close();
85
+ };
86
+ };
package/src/inject.js CHANGED
@@ -1,22 +1,22 @@
1
- export function createInjector(ctx, service, config) {
2
- const maxItems = config.maxInjectedItems ?? 5;
3
- const threshold = config.importanceThreshold ?? 3;
4
-
5
- function render(candidates) {
6
- if (!candidates.length) return "";
7
- const lines = ["[记忆库] 来自 dsh-mneme 的跨会话记忆(用户偏好与高优先级项目/决策):"];
8
- for (const m of candidates) {
9
- lines.push(`- [${m.type}] ${m.title}(重要性 ${m.importance}):${m.content}`);
10
- }
11
- return lines.join("\n");
12
- }
13
-
14
- return ctx.systemPrompt.context({
15
- name: "memory",
16
- order: 90,
17
- text: () => {
18
- const candidates = service.injectCandidates({ maxItems, threshold });
19
- return render(candidates);
20
- }
21
- });
22
- }
1
+ export function createInjector(ctx, service, config) {
2
+ const maxItems = config.maxInjectedItems ?? 5;
3
+ const threshold = config.importanceThreshold ?? 3;
4
+
5
+ function render(candidates) {
6
+ if (!candidates.length) return "";
7
+ const lines = ["[记忆库] 来自 dsh-mneme 的跨会话记忆(用户偏好与高优先级项目/决策):"];
8
+ for (const m of candidates) {
9
+ lines.push(`- [${m.type}] ${m.title}(重要性 ${m.importance}):${m.content}`);
10
+ }
11
+ return lines.join("\n");
12
+ }
13
+
14
+ return ctx.systemPrompt.context({
15
+ name: "memory",
16
+ order: 90,
17
+ text: () => {
18
+ const candidates = service.injectCandidates({ maxItems, threshold });
19
+ return render(candidates);
20
+ }
21
+ });
22
+ }