@modusensus/dsh-mneme 0.1.2 → 0.1.4

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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![npm version](https://img.shields.io/npm/v/@modusensus/dsh-mneme?color=blue&label=npm)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
4
4
  [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
5
5
  [![dsh-plugin](https://img.shields.io/badge/dsh-plugin-awesome-orange)](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin)
6
- [![tests](https://img.shields.io/badge/tests-106%20passed-success)](https://github.com/modusensus/dsh-mneme)
6
+ [![tests](https://img.shields.io/badge/tests-129%20passed-success)](https://github.com/modusensus/dsh-mneme)
7
7
 
8
8
  > 给 DeepSeek Harness 的跨会话记忆插件:让 Agent 记住你、记住项目、自动整理记忆。**Mneme**(Μνήμη)——希腊记忆女神 Mnemosyne 之名,掌管记忆与梦境,正如 autoDream 在后台巩固记忆。
9
9
 
@@ -47,6 +47,16 @@
47
47
 
48
48
  侧边栏"记忆"按钮 → 模态面板:按类型浏览、全文搜索、查看详情。
49
49
 
50
+ ### 用户设置(画像 / 规则)与自定义指令 ⚙️
51
+
52
+ 侧边栏"设置"按钮 → 设置面板:
53
+
54
+ - **用户画像**:一段自由文本描述用户自己(角色、背景、偏好),**每轮注入**到系统提示,让 Agent 始终遵循
55
+ - **规则**:Agent 必须遵守的行为规则列表(如"回答先给结论"),同样每轮注入
56
+ - **自定义指令**:注册斜杠命令(`/名称`),触发时把用户定义的指令内容交给 Agent。命令持久化到 SQLite,启动时自动注册到 DSH 命令表,增删实时生效
57
+
58
+ > 画像与规则通过独立的 `[用户设置]` 注入区块(优先级高于记忆库),即使记忆为空也会注入。
59
+
50
60
  ## 📦 安装
51
61
 
52
62
  ### 前置条件
@@ -150,7 +160,7 @@ src/
150
160
  lib/
151
161
  ├── client.js # Web 面板(手写 ModuleLoader bundle)
152
162
  └── *.js # src 的同步分发产物
153
- test/ # 106 个 node:test 测试
163
+ test/ # 129 个 node:test 测试
154
164
  ```
155
165
 
156
166
  ## 🧪 开发
@@ -158,7 +168,7 @@ test/ # 106 个 node:test 测试
158
168
  ```bash
159
169
  cd dsh-mneme
160
170
  npm install # 安装 peer 依赖(以 devDependencies 形式,用于本地测试)
161
- npm test # 运行 106 个测试(--test-isolation=none 用于受限沙箱,禁止子进程 spawn)
171
+ npm test # 运行 129 个测试(--test-isolation=none 用于受限沙箱,禁止子进程 spawn)
162
172
  npm run sync # 把 src/ 同步到 lib/(发布时由 prepack 钩子自动执行)
163
173
  ```
164
174
 
package/lib/api.js CHANGED
@@ -5,19 +5,41 @@ function sendJson(res, status, payload) {
5
5
  res.end(JSON.stringify(payload));
6
6
  }
7
7
 
8
- export function createApi(ctx, service) {
8
+ /** Collect the request body as text (tolerant of empty/invalid bodies). */
9
+ function readBody(req) {
10
+ return new Promise((resolve) => {
11
+ let body = "";
12
+ req.on("data", (chunk) => { body += chunk; });
13
+ req.on("end", () => resolve(body));
14
+ req.on("error", () => resolve(""));
15
+ });
16
+ }
17
+
18
+ function parseBody(text) {
19
+ try {
20
+ return JSON.parse(text || "{}");
21
+ } catch {
22
+ return {};
23
+ }
24
+ }
25
+
26
+ export function createApi(ctx, service, settings, commands) {
9
27
  const disposers = [];
10
28
 
29
+ const register = (route) => {
30
+ disposers.push(ctx.webServer.register(route));
31
+ };
32
+
11
33
  // /api/dsh-mneme prefix fallback → 404 JSON for unknown sub-paths
12
- disposers.push(ctx.webServer.register({
34
+ register({
13
35
  kind: "prefix",
14
36
  path: "/api/dsh-mneme",
15
37
  handler(req, res) {
16
38
  sendJson(res, 404, { error: "not-found" });
17
39
  }
18
- }));
40
+ });
19
41
 
20
- disposers.push(ctx.webServer.register({
42
+ register({
21
43
  kind: "exact",
22
44
  path: "/api/dsh-mneme/list",
23
45
  handler(req, res) {
@@ -32,9 +54,9 @@ export function createApi(ctx, service) {
32
54
  sendJson(res, 500, { error: "internal" });
33
55
  }
34
56
  }
35
- }));
57
+ });
36
58
 
37
- disposers.push(ctx.webServer.register({
59
+ register({
38
60
  kind: "exact",
39
61
  path: "/api/dsh-mneme/search",
40
62
  handler(req, res) {
@@ -48,10 +70,85 @@ export function createApi(ctx, service) {
48
70
  sendJson(res, 500, { error: "internal" });
49
71
  }
50
72
  }
51
- }));
73
+ });
74
+
75
+ // --- user profile ---
76
+ register({
77
+ kind: "exact",
78
+ path: "/api/dsh-mneme/profile",
79
+ handler(req, res) {
80
+ try {
81
+ if (req.method === "PUT" || req.method === "POST") {
82
+ return readBody(req).then((text) => {
83
+ const body = parseBody(text);
84
+ settings.setProfile(typeof body.profile === "string" ? body.profile : "");
85
+ sendJson(res, 200, { profile: settings.getProfile() });
86
+ });
87
+ }
88
+ sendJson(res, 200, { profile: settings.getProfile() });
89
+ } catch {
90
+ sendJson(res, 500, { error: "internal" });
91
+ }
92
+ }
93
+ });
94
+
95
+ // --- rules ---
96
+ register({
97
+ kind: "exact",
98
+ path: "/api/dsh-mneme/rules",
99
+ handler(req, res) {
100
+ try {
101
+ if (req.method === "PUT" || req.method === "POST") {
102
+ return readBody(req).then((text) => {
103
+ const body = parseBody(text);
104
+ settings.setRules(Array.isArray(body.rules) ? body.rules : []);
105
+ sendJson(res, 200, { rules: settings.getRules() });
106
+ });
107
+ }
108
+ sendJson(res, 200, { rules: settings.getRules() });
109
+ } catch {
110
+ sendJson(res, 500, { error: "internal" });
111
+ }
112
+ }
113
+ });
114
+
115
+ // --- custom commands ---
116
+ register({
117
+ kind: "exact",
118
+ path: "/api/dsh-mneme/commands",
119
+ handler(req, res) {
120
+ try {
121
+ if (req.method === "POST") {
122
+ return readBody(req).then((text) => {
123
+ const body = parseBody(text);
124
+ try {
125
+ const command = commands.add({
126
+ name: body.name,
127
+ description: body.description,
128
+ instruction: body.instruction
129
+ });
130
+ sendJson(res, 200, { command });
131
+ } catch (error) {
132
+ sendJson(res, 400, { error: error.message });
133
+ }
134
+ });
135
+ }
136
+ if (req.method === "DELETE") {
137
+ const url = new URL(req.url, "http://localhost");
138
+ const id = url.searchParams.get("id");
139
+ const removed = id ? commands.remove(id) : false;
140
+ sendJson(res, 200, { removed });
141
+ return;
142
+ }
143
+ sendJson(res, 200, { commands: commands.list() });
144
+ } catch {
145
+ sendJson(res, 500, { error: "internal" });
146
+ }
147
+ }
148
+ });
52
149
 
53
150
  return {
54
- routes: 3,
151
+ routes: 6,
55
152
  dispose: () => {
56
153
  for (const dispose of disposers) dispose();
57
154
  }
package/lib/client.js CHANGED
@@ -23,7 +23,25 @@ window.__ModuleLoader__.load({
23
23
  "memory.tab.preference": "偏好",
24
24
  "memory.tab.project": "项目",
25
25
  "memory.tab.decision": "决策",
26
- "memory.tab.history": "历史"
26
+ "memory.tab.history": "历史",
27
+ "memory.settings.open": "设置",
28
+ "memory.settings.title": "记忆库设置",
29
+ "memory.settings.profile": "用户画像",
30
+ "memory.settings.profileHint": "描述你自己(角色、背景、偏好),Agent 会在每轮遵循",
31
+ "memory.settings.profileSave": "保存画像",
32
+ "memory.settings.profileSaved": "画像已保存",
33
+ "memory.settings.rules": "规则",
34
+ "memory.settings.rulesHint": "Agent 必须遵守的行为规则,每轮注入",
35
+ "memory.settings.ruleAdd": "添加规则",
36
+ "memory.settings.rulePlaceholder": "例如:回答时总是先给结论",
37
+ "memory.settings.commands": "自定义指令",
38
+ "memory.settings.commandsHint": "注册斜杠命令(/名称),触发时把指令内容交给 Agent",
39
+ "memory.settings.cmdName": "命令名",
40
+ "memory.settings.cmdDesc": "描述",
41
+ "memory.settings.cmdInstruction": "指令内容",
42
+ "memory.settings.cmdAdd": "添加命令",
43
+ "memory.settings.cmdDelete": "删除",
44
+ "memory.settings.empty": "暂无内容"
27
45
  },
28
46
  en: {
29
47
  "memory.panel.title": "Memory",
@@ -34,7 +52,25 @@ window.__ModuleLoader__.load({
34
52
  "memory.tab.preference": "Preferences",
35
53
  "memory.tab.project": "Projects",
36
54
  "memory.tab.decision": "Decisions",
37
- "memory.tab.history": "History"
55
+ "memory.tab.history": "History",
56
+ "memory.settings.open": "Settings",
57
+ "memory.settings.title": "Memory Settings",
58
+ "memory.settings.profile": "User Profile",
59
+ "memory.settings.profileHint": "Describe yourself — the agent follows this every turn",
60
+ "memory.settings.profileSave": "Save Profile",
61
+ "memory.settings.profileSaved": "Profile saved",
62
+ "memory.settings.rules": "Rules",
63
+ "memory.settings.rulesHint": "Behavior rules the agent must follow every turn",
64
+ "memory.settings.ruleAdd": "Add Rule",
65
+ "memory.settings.rulePlaceholder": "e.g. Always lead with a conclusion",
66
+ "memory.settings.commands": "Custom Commands",
67
+ "memory.settings.commandsHint": "Register slash commands (/name) whose instruction is handed to the agent",
68
+ "memory.settings.cmdName": "Name",
69
+ "memory.settings.cmdDesc": "Description",
70
+ "memory.settings.cmdInstruction": "Instruction",
71
+ "memory.settings.cmdAdd": "Add Command",
72
+ "memory.settings.cmdDelete": "Delete",
73
+ "memory.settings.empty": "Nothing yet"
38
74
  }
39
75
  };
40
76
 
@@ -134,6 +170,163 @@ window.__ModuleLoader__.load({
134
170
  );
135
171
  }
136
172
 
173
+ const h = react.createElement;
174
+
175
+ // --- Settings panel: user profile, rules, custom commands ---
176
+ function SettingsPanel({ t, onClose }) {
177
+ const [profile, setProfile] = react.useState("");
178
+ const [rules, setRules] = react.useState([]);
179
+ const [commands, setCommands] = react.useState([]);
180
+ const [newRule, setNewRule] = react.useState("");
181
+ const [newCmd, setNewCmd] = react.useState({ name: "", description: "", instruction: "" });
182
+ const [saved, setSaved] = react.useState(false);
183
+ const [cmdError, setCmdError] = react.useState("");
184
+
185
+ const load = react.useCallback(async () => {
186
+ try {
187
+ const [p, r, c] = await Promise.all([
188
+ fetch("/api/dsh-mneme/profile").then((res) => res.json()),
189
+ fetch("/api/dsh-mneme/rules").then((res) => res.json()),
190
+ fetch("/api/dsh-mneme/commands").then((res) => res.json())
191
+ ]);
192
+ setProfile(p.profile || "");
193
+ setRules(Array.isArray(r.rules) ? r.rules : []);
194
+ setCommands(Array.isArray(c.commands) ? c.commands : []);
195
+ } catch { /* ignore */ }
196
+ }, []);
197
+
198
+ react.useEffect(() => { load(); }, [load]);
199
+
200
+ async function saveProfile() {
201
+ try {
202
+ await fetch("/api/dsh-mneme/profile", {
203
+ method: "PUT",
204
+ headers: { "Content-Type": "application/json" },
205
+ body: JSON.stringify({ profile })
206
+ });
207
+ setSaved(true);
208
+ setTimeout(() => setSaved(false), 1500);
209
+ } catch { /* ignore */ }
210
+ }
211
+
212
+ async function putRules(next) {
213
+ await fetch("/api/dsh-mneme/rules", {
214
+ method: "PUT",
215
+ headers: { "Content-Type": "application/json" },
216
+ body: JSON.stringify({ rules: next })
217
+ });
218
+ }
219
+
220
+ async function addRule() {
221
+ const text = newRule.trim();
222
+ if (!text) return;
223
+ const next = [...rules, text];
224
+ await putRules(next);
225
+ setRules(next);
226
+ setNewRule("");
227
+ }
228
+
229
+ async function removeRule(index) {
230
+ const next = rules.filter((_, i) => i !== index);
231
+ await putRules(next);
232
+ setRules(next);
233
+ }
234
+
235
+ async function addCommand() {
236
+ const name = newCmd.name.trim();
237
+ const instruction = newCmd.instruction.trim();
238
+ if (!name || !instruction) return;
239
+ try {
240
+ const res = await fetch("/api/dsh-mneme/commands", {
241
+ method: "POST",
242
+ headers: { "Content-Type": "application/json" },
243
+ body: JSON.stringify({ name, description: newCmd.description, instruction })
244
+ });
245
+ const data = await res.json();
246
+ if (!res.ok) { setCmdError(data.error || "failed"); return; }
247
+ setCmdError("");
248
+ setCommands([...commands, data.command]);
249
+ setNewCmd({ name: "", description: "", instruction: "" });
250
+ } catch { setCmdError("failed"); }
251
+ }
252
+
253
+ async function removeCommand(id) {
254
+ await fetch(`/api/dsh-mneme/commands?id=${encodeURIComponent(id)}`, { method: "DELETE" });
255
+ setCommands(commands.filter((c) => c.id !== id));
256
+ }
257
+
258
+ const inputStyle = { ...styles.search, marginBottom: 8 };
259
+ const labelStyle = { fontSize: 12, fontWeight: 600, margin: "12px 0 4px" };
260
+ const hintStyle = { fontSize: 11, color: "var(--dsw-alias-label-tertiary, #999)", marginBottom: 8 };
261
+ const rowStyle = { display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, padding: "6px 0", borderBottom: "1px solid var(--dsw-alias-border-l1, #eee)" };
262
+
263
+ return createPortal(
264
+ h("div", { style: styles.overlay },
265
+ h("div", { style: styles.panel },
266
+ h("div", { style: styles.header },
267
+ h("span", { style: styles.title }, t("memory.settings.title")),
268
+ h("button", { style: styles.close, onClick: onClose }, "×")
269
+ ),
270
+ h("div", { style: { overflowY: "auto" } },
271
+ // profile
272
+ h("div", { style: labelStyle }, t("memory.settings.profile")),
273
+ h("div", { style: hintStyle }, t("memory.settings.profileHint")),
274
+ h("textarea", {
275
+ style: { ...inputStyle, minHeight: 72, resize: "vertical", fontFamily: "inherit" },
276
+ value: profile,
277
+ placeholder: t("memory.settings.profile"),
278
+ onChange: (e) => setProfile(e.target.value)
279
+ }),
280
+ h("div", null,
281
+ h("button", { style: styles.footerButton, onClick: saveProfile }, t("memory.settings.profileSave")),
282
+ saved && h("span", { style: { fontSize: 12, color: "var(--dsw-alias-state-success, #2a7)" } }, t("memory.settings.profileSaved"))
283
+ ),
284
+ // rules
285
+ h("div", { style: labelStyle }, t("memory.settings.rules")),
286
+ h("div", { style: hintStyle }, t("memory.settings.rulesHint")),
287
+ rules.length === 0 && h("div", { style: styles.hint }, t("memory.settings.empty")),
288
+ rules.map((rule, i) =>
289
+ h("div", { key: i, style: rowStyle },
290
+ h("span", { style: { fontSize: 13, flex: 1 } }, rule),
291
+ h("button", { style: { ...styles.footerButton, color: "var(--dsw-alias-state-error, #c33)" }, onClick: () => removeRule(i) }, "×")
292
+ )
293
+ ),
294
+ h("div", { style: { display: "flex", gap: 6 } },
295
+ h("input", {
296
+ style: { ...inputStyle, flex: 1, marginBottom: 0 },
297
+ value: newRule,
298
+ placeholder: t("memory.settings.rulePlaceholder"),
299
+ onChange: (e) => setNewRule(e.target.value)
300
+ }),
301
+ h("button", { style: styles.footerButton, onClick: addRule }, t("memory.settings.ruleAdd"))
302
+ ),
303
+ // custom commands
304
+ h("div", { style: labelStyle }, t("memory.settings.commands")),
305
+ h("div", { style: hintStyle }, t("memory.settings.commandsHint")),
306
+ commands.length === 0 && h("div", { style: styles.hint }, t("memory.settings.empty")),
307
+ commands.map((cmd) =>
308
+ h("div", { key: cmd.id, style: rowStyle },
309
+ h("div", { style: { flex: 1 } },
310
+ h("div", { style: { fontSize: 13, fontWeight: 600 } }, `/${cmd.name}`),
311
+ h("div", { style: { fontSize: 11, color: "var(--dsw-alias-label-tertiary, #999)" } }, cmd.description || cmd.instruction)
312
+ ),
313
+ h("button", { style: { ...styles.footerButton, color: "var(--dsw-alias-state-error, #c33)" }, onClick: () => removeCommand(cmd.id) }, t("memory.settings.cmdDelete"))
314
+ )
315
+ ),
316
+ h("div", { style: { display: "grid", gap: 6, marginTop: 6 } },
317
+ h("input", { style: { ...inputStyle, marginBottom: 0 }, value: newCmd.name, placeholder: t("memory.settings.cmdName"), onChange: (e) => setNewCmd({ ...newCmd, name: e.target.value }) }),
318
+ h("input", { style: { ...inputStyle, marginBottom: 0 }, value: newCmd.description, placeholder: t("memory.settings.cmdDesc"), onChange: (e) => setNewCmd({ ...newCmd, description: e.target.value }) }),
319
+ h("textarea", { style: { ...inputStyle, marginBottom: 0, minHeight: 48, resize: "vertical", fontFamily: "inherit" }, value: newCmd.instruction, placeholder: t("memory.settings.cmdInstruction"), onChange: (e) => setNewCmd({ ...newCmd, instruction: e.target.value }) }),
320
+ h("button", { style: styles.footerButton, onClick: addCommand }, t("memory.settings.cmdAdd")),
321
+ cmdError && h("div", { style: { fontSize: 12, color: "var(--dsw-alias-state-error, #c33)" } }, cmdError)
322
+ )
323
+ )
324
+ )
325
+ ),
326
+ document.body
327
+ );
328
+ }
329
+
137
330
  const styles = {
138
331
  overlay: { position: "fixed", inset: 0, background: "rgba(0,0,0,0.4)", zIndex: 1000, display: "flex", alignItems: "center", justifyContent: "center" },
139
332
  panel: { background: "var(--dsw-alias-bg-base, #fff)", borderRadius: 12, width: 640, maxWidth: "90vw", maxHeight: "80vh", display: "flex", flexDirection: "column", padding: 16, boxShadow: "0 8px 40px rgba(0,0,0,0.2)" },
@@ -168,12 +361,18 @@ window.__ModuleLoader__.load({
168
361
  inject: () => ({})
169
362
  }, () => {
170
363
  const [open, setOpen] = react.useState(false);
364
+ const [openSettings, setOpenSettings] = react.useState(false);
171
365
  return react.createElement(react.Fragment, null,
172
366
  react.createElement("button", {
173
367
  onClick: () => setOpen(true),
174
368
  style: { ...styles.footerButton, ...(open ? styles.footerButtonActive : {}) }
175
369
  }, t("memory.panel.open")),
176
- open && react.createElement(MemoryPanel, { t, onClose: () => setOpen(false) })
370
+ react.createElement("button", {
371
+ onClick: () => setOpenSettings(true),
372
+ style: { ...styles.footerButton, ...(openSettings ? styles.footerButtonActive : {}) }
373
+ }, t("memory.settings.open")),
374
+ open && react.createElement(MemoryPanel, { t, onClose: () => setOpen(false) }),
375
+ openSettings && react.createElement(SettingsPanel, { t, onClose: () => setOpenSettings(false) })
177
376
  );
178
377
  })
179
378
  );
@@ -0,0 +1,64 @@
1
+ // Custom slash-command manager: keeps the DSH command registry in sync with
2
+ // user-defined commands persisted in SQLite. Commands are registered on boot
3
+ // and (re)registered on add/remove through the API.
4
+ //
5
+ // Each custom command's handler returns the user-authored instruction as a
6
+ // success result; the DSH UI surfaces it as a model-directed instruction.
7
+ export function createCommandManager({ ctx, settings, logger }) {
8
+ const registered = new Map(); // name -> disposer
9
+
10
+ function registerOne(command) {
11
+ if (registered.has(command.name)) return;
12
+ let dispose;
13
+ try {
14
+ dispose = ctx.commands.register({
15
+ name: command.name,
16
+ description: command.description || `自定义指令 ${command.name}`,
17
+ handler: () => ({ kind: "success", text: command.instruction })
18
+ });
19
+ } catch (error) {
20
+ logger?.warn?.(`dsh-mneme: failed to register command /${command.name}: ${String(error)}`);
21
+ return;
22
+ }
23
+ registered.set(command.name, dispose);
24
+ }
25
+
26
+ function unregisterOne(name) {
27
+ const dispose = registered.get(name);
28
+ if (dispose) {
29
+ try {
30
+ dispose();
31
+ } catch {
32
+ /* ignore double-dispose */
33
+ }
34
+ registered.delete(name);
35
+ }
36
+ }
37
+
38
+ /** Register every stored command (boot-time sync). */
39
+ function sync() {
40
+ for (const command of settings.listCommands()) registerOne(command);
41
+ }
42
+
43
+ /** Add (or replace) a command and register it live. */
44
+ function add({ name, description, instruction }) {
45
+ const command = settings.addCommand({ name, description, instruction });
46
+ registerOne(command);
47
+ return command;
48
+ }
49
+
50
+ /** Remove a command by id and unregister it live. */
51
+ function remove(id) {
52
+ const existing = settings.listCommands().find((c) => c.id === id);
53
+ if (!existing) return false;
54
+ if (!settings.removeCommand(id)) return false;
55
+ unregisterOne(existing.name);
56
+ return true;
57
+ }
58
+
59
+ function dispose() {
60
+ for (const name of [...registered.keys()]) unregisterOne(name);
61
+ }
62
+
63
+ return { sync, add, remove, list: () => settings.listCommands(), dispose };
64
+ }
package/lib/dream.js CHANGED
@@ -62,6 +62,7 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
62
62
  let running = false;
63
63
  let disposed = false;
64
64
  let baseline = { count: 0, chars: 0 };
65
+ let inFlight = null;
65
66
 
66
67
  function shouldTrigger(service) {
67
68
  const memories = service.all().filter((m) => !m.archived && m.type !== "summary");
@@ -81,8 +82,9 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
81
82
  running = true;
82
83
  // Defer the onRun invocation so a synchronous throw cannot escape the
83
84
  // timer callback (which would crash the process) and skip the teardown.
84
- // Errors are logged, never swallowed silently.
85
- Promise.resolve()
85
+ // Errors are logged, never swallowed silently. inFlight lets dispose()
86
+ // await the running consolidation before the caller closes the store.
87
+ inFlight = Promise.resolve()
86
88
  .then(() => (onRun ? onRun() : Promise.resolve({ ok: true, skipped: true })))
87
89
  .then((result) => {
88
90
  // Refresh the baseline only for a successful run (design §5.3: an
@@ -105,17 +107,19 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
105
107
  })
106
108
  .finally(() => {
107
109
  running = false;
110
+ inFlight = null;
108
111
  });
109
112
  }, delayMs);
110
113
  return true;
111
114
  }
112
115
 
113
- function dispose() {
116
+ async function dispose() {
114
117
  disposed = true;
115
118
  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
+ // An in-flight run is left to complete naturally (its LLM calls are
120
+ // already paid for and aborting would discard the work). Await it so the
121
+ // caller can close the store only after every write has landed.
122
+ if (inFlight) await inFlight.catch(() => {});
119
123
  }
120
124
 
121
125
  async function runDream(ctx, service, config) {
package/lib/index.js CHANGED
@@ -6,13 +6,15 @@ import { createInjector } from "./inject.js";
6
6
  import { createSummarizer } from "./summarize.js";
7
7
  import { createDreamScheduler } from "./dream.js";
8
8
  import { createApi } from "./api.js";
9
+ import { createSettings } from "./settings.js";
10
+ import { createCommandManager } from "./commands.js";
9
11
  import { Config } from "./config.js";
10
12
  import { mkdirSync } from "node:fs";
11
13
  import { join } from "node:path";
12
14
  import { homedir } from "node:os";
13
15
 
14
16
  export const name = "dsh-mneme";
15
- export const inject = ["tools", "systemPrompt", "webServer", "llm", "agentDefaultModel"];
17
+ export const inject = ["tools", "systemPrompt", "webServer", "llm", "agentDefaultModel", "commands"];
16
18
  export { Config };
17
19
 
18
20
  // Arrow (not function declaration): cordis 4 treats any apply with a
@@ -33,10 +35,28 @@ export const apply = (ctx, config) => {
33
35
  const mirror = createMirror(memoryDir);
34
36
  const service = createService({ store, mirror, config: cfg });
35
37
 
38
+ // User-configurable settings (profile, rules) and custom commands share the
39
+ // same SQLite file but live in dedicated tables, isolated from memories.
40
+ const settings = createSettings(store.db);
41
+
42
+ // Custom commands: register persisted commands into the DSH command registry
43
+ // on boot; add/remove re-register live through the API.
44
+ let commands = null;
45
+ if (ctx.commands) {
46
+ commands = createCommandManager({ ctx, settings, logger: ctx.logger });
47
+ commands.sync();
48
+ }
49
+
36
50
  // Human edits in mirror files win on every sync; merge them back first.
37
- // TYPE_FILE maps each memory type to its mirror filename.
51
+ // TYPE_FILE maps each memory type to its mirror filename. Read every type's
52
+ // edits up front: mergeHumanEdits re-renders ALL mirror files on success, so
53
+ // a per-type read-then-merge loop would overwrite edits in files not yet read
54
+ // (e.g. preferences.md merging would clobber unsynced projects.md edits).
55
+ const humanEdits = new Map();
38
56
  for (const type of Object.keys(TYPE_FILE)) {
39
- const edits = mirror.readHumanEdits(type);
57
+ humanEdits.set(type, mirror.readHumanEdits(type));
58
+ }
59
+ for (const [type, edits] of humanEdits) {
40
60
  if (edits.length) service.mergeHumanEdits(type, edits);
41
61
  }
42
62
 
@@ -61,7 +81,7 @@ export const apply = (ctx, config) => {
61
81
  const disposers = [];
62
82
 
63
83
  ctx.inject(["systemPrompt"], (promptCtx) => {
64
- if (cfg.autoInject) disposers.push(createInjector(promptCtx, service, cfg));
84
+ if (cfg.autoInject) disposers.push(createInjector(promptCtx, service, settings, cfg));
65
85
  });
66
86
 
67
87
  ctx.inject(["tools"], (toolsCtx) => {
@@ -72,15 +92,23 @@ export const apply = (ctx, config) => {
72
92
  disposers.push(summarizer.dispose);
73
93
 
74
94
  if (ctx.webServer) {
75
- const api = createApi(ctx, service);
95
+ const api = createApi(ctx, service, settings, commands ?? {
96
+ add: () => { throw new Error("commands unavailable"); },
97
+ remove: () => false,
98
+ list: () => []
99
+ });
76
100
  disposers.push(api.dispose);
77
101
  }
78
102
 
79
- return () => {
103
+ // Async disposer: cordis awaits the returned promise on unload (runDisposable),
104
+ // so an in-flight dream run is allowed to finish before the SQLite store is
105
+ // closed — dream.dispose() resolves only after its current run settles.
106
+ return async () => {
80
107
  for (const dispose of disposers) {
81
108
  if (typeof dispose === "function") dispose();
82
109
  }
83
- if (dream) dream.dispose();
110
+ commands?.dispose();
111
+ if (dream) await dream.dispose();
84
112
  store.close();
85
113
  };
86
114
  };
package/lib/inject.js CHANGED
@@ -1,4 +1,4 @@
1
- export function createInjector(ctx, service, config) {
1
+ export function createInjector(ctx, service, settings, config) {
2
2
  const maxItems = config.maxInjectedItems ?? 5;
3
3
  const threshold = config.importanceThreshold ?? 3;
4
4
 
@@ -11,12 +11,37 @@ export function createInjector(ctx, service, config) {
11
11
  return lines.join("\n");
12
12
  }
13
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);
14
+ // User profile + rules: injected ahead of the memory block because they are
15
+ // always-relevant instructions the agent should follow every turn.
16
+ function renderUserSettings() {
17
+ const profile = settings.getProfile().trim();
18
+ const rules = settings.getRules();
19
+ if (!profile && !rules.length) return "";
20
+ const lines = ["[用户设置] 来自 dsh-mneme 的用户画像与规则:"];
21
+ if (profile) lines.push(`- 用户画像:${profile}`);
22
+ for (const rule of rules) lines.push(`- 规则:${rule}`);
23
+ return lines.join("\n");
24
+ }
25
+
26
+ const disposers = [
27
+ ctx.systemPrompt.context({
28
+ name: "memory",
29
+ order: 90,
30
+ text: () => {
31
+ const candidates = service.injectCandidates({ maxItems, threshold });
32
+ return render(candidates);
33
+ }
34
+ }),
35
+ ctx.systemPrompt.context({
36
+ name: "user-settings",
37
+ order: 85,
38
+ text: renderUserSettings
39
+ })
40
+ ];
41
+
42
+ return () => {
43
+ for (const dispose of disposers) {
44
+ if (typeof dispose === "function") dispose();
20
45
  }
21
- });
46
+ };
22
47
  }