@modusensus/dsh-mneme 0.7.23 → 0.7.25

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.en.md CHANGED
@@ -7,7 +7,7 @@ English | [简体中文](README.md)
7
7
  [![npm version](https://img.shields.io/npm/v/@modusensus/dsh-mneme?color=blue&label=npm)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
8
8
  [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
9
9
  [![Awesome](https://awesome-dsh-plugin.com/badge.svg)](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin)
10
- [![tests](https://img.shields.io/badge/tests-712%20passed-success)](https://github.com/modusensus/dsh-mneme)
10
+ [![tests](https://img.shields.io/badge/tests-714%20passed-success)](https://github.com/modusensus/dsh-mneme)
11
11
 
12
12
  > A cross-session memory plugin for DeepSeek Harness: it lets the Agent remember you, remember your projects, and organize memories automatically. **Mneme** (Μνήμη) — named after Mnemosyne, the Greek goddess of memory who presides over memory and dreams, just as autoDream consolidates memories in the background.
13
13
 
@@ -66,7 +66,14 @@ The default `32768` reserves headroom for reasoning models, where reasoning alon
66
66
  | Medium (10k–50k chars) | `65536` |
67
67
  | Large (>50k chars) | `131072` (cap) |
68
68
 
69
- > With **reasoning models** (e.g. DeepSeek-R1-like), the model may spend the entire budget on reasoning and return an empty body (the log shows `no json array in llm output`). Resolution order: ① set `dreamReasoningEffort` to `low` to suppress reasoning overhead (when the provider rejects the parameter it is stripped automatically and retried once — the rejection reason lands in `llm_audit`; some models, e.g. v4-flash-ga, reject every effort tier); ② if the retry still returns an empty body under the model's default reasoning behavior, raise `dreamMaxTokens` (reasoning and body share this budget) or route `dreamProvider`/`dreamModel` to a non-reasoning model. The sleep side has the corresponding `sleepReasoningEffort`.
69
+ > With **reasoning models** (e.g. DeepSeek-R1-like), the model may spend the entire budget on reasoning and return an empty body (the log shows `no json array in llm output`). Resolution order: ① set `dreamReasoningEffort` to `low` to suppress reasoning overhead (when the provider rejects the parameter it is stripped automatically and retried once — the rejection reason lands in `llm_audit`); ② if the retry still returns an empty body under the model's default reasoning behavior, raise `dreamMaxTokens` (reasoning and body share this budget) or route `dreamProvider`/`dreamModel` to a non-reasoning model. The sleep side has the corresponding `sleepReasoningEffort`.
70
+
71
+ **Consolidation model classification** (settings panel "consolidation model" = `dreamProvider`/`dreamModel`; sleep side: `sleepProvider`/`sleepModel`):
72
+
73
+ | Model kind | Examples | Notes |
74
+ |-----------|----------|-------|
75
+ | **Non-reasoning (recommended)** | glm-5-2-class | No reasoning declaration; even if an effort is configured and the harness rejects it, the fallback strips the field and the retry succeeds. Lowest risk of empty-body runs |
76
+ | **Reasoning (test first)** | deepseek-v4-flash-ga and other v4-flash-ga family | Reasons by default and may burn the whole token budget on an empty body; some SKUs (e.g. v4-flash-ga) are additionally declared by the harness as accepting **no reasoning effort at all** — the no-effort retry still gets rejected through the harness `defaultEffort` (`UNSUPPORTED_REASONING_EFFORT`), which the plugin fallback cannot bypass. If you use one, set `dreamReasoningEffort` and test; switch to a non-reasoning model otherwise |
70
77
 
71
78
  ### Sleep Mode: System-Level Sleep 💤 (v0.4.0, opt-in)
72
79
 
@@ -166,6 +173,7 @@ Every **background LLM call** (autoDream consolidation + summary, autoSummarize
166
173
 
167
174
  | Version | Highlights |
168
175
  |------|------|
176
+ | **v0.7.24** | Fixed DSH Desktop plugin-tree load crash (v0.7.23 regression): cordis 4's ctx is a Proxy — accessing a property not declared in `inject` throws `cannot get property "webServer" without inject` (not `undefined`), and removing webServer from inject meant cordis no longer waited for the host service, so Desktop crashed on restart; fix: restored webServer to inject (cordis applies the plugin only after the host service is ready) + apply/register guard switched to `ctx.reflect.get` (inject-free read, returns `undefined` when absent, never throws); verified with a real cordis + dsh-host-webserver plugin (API routes 200, unknown path 404, headless silently inactive); 714 tests green |
169
177
  | **v0.7.23** | Root-caused "memory consolidation keeps failing": a legal empty decision array `[]` from consolidation is no longer treated as a failure (CONSOLIDATION_PROMPT explicitly allows "no output when nothing needs changing", so a model with a healthy, non-redundant memory legitimately returns `[]` — yet `validateDecisions` hard-rejected it as `decision list must be a non-empty array`, failing the whole run and flooding the audit with failures; **model-agnostic** — ChatGPT/Claude hit the same trap; fix: empty array short-circuits to `ok:true` no-op instead of tripping the implicit-keep coverage check). Plus: empty-body fix part 2 (`dreamMaxTokens` default 8192→32768 so thinking models don't burn the whole budget on reasoning) + skipInvalid splice residue bug (length equality ≠ content equality, skipped decisions leaked into apply/audit); 712 tests green |
170
178
  | **v0.7.22** | Restored the v0.6.9 skipInvalid tolerant-validation path (issue #89 regression, lost in the v0.7.11 rewrite): `dreamSkipInvalid` (default true) skips individual invalid decisions, applies the valid subset, and marks the run degraded; `allowCrossTypeMerge` (default false) explicitly relaxes cross-type merging — weak models (e.g. qwen3.8-flash) with jittery schema compliance no longer fail the whole batch and burn LLM calls. Strict mode and the sleep path behave unchanged; global caps/coverage floors still reject the whole run (running over cap = broken model, not minor schema drift). New `dreamMinIntervalMinutes` (0–10080, default 0 = unlimited) minimum autoDream trigger interval — failed/degraded runs also consume the interval (throttling exists to stop back-to-back failing calls); feature_flags whitelist now 34 keys; 696 tests green |
171
179
  | **v0.7.21** | Fixed autoDream/sleep effort fallback being dead code on the stream path (the catch-based retry from v0.7.16 never fired): dsh-llm rc.1 turns adapter-stage failures (incl. `UNSUPPORTED_REASONING_EFFORT`) into a terminal error finish chunk instead of a throw; `streamText` now captures the finish-chunk failure cause (`describeStreamFailure` normalizes `{code,message}`) + `withEffortFallback` gains a `getStreamError` accessor (retries without effort when rejected) + `runAuditedLlm` supports `spec.streamError` (audit `error_message` carries the real cause; `run.error` stays a stable `"llm failed"`); 688 tests green |
@@ -441,7 +449,7 @@ src/
441
449
  lib/
442
450
  ├── client.js # Web 面板(手写 ModuleLoader bundle)
443
451
  └── *.js # src 的同步分发产物
444
- test/ # 712 node:test tests (audit + three-axis stress invariants)
452
+ test/ # 714 node:test tests (audit + three-axis stress invariants)
445
453
  scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压测 · sync-lib.js 同步
446
454
  ```
447
455
 
@@ -450,7 +458,7 @@ scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压
450
458
  ```bash
451
459
  cd dsh-mneme
452
460
  npm install # 安装 peer 依赖(以 devDependencies 形式,用于本地测试)
453
- npm test # 运行 712 个测试
461
+ npm test # 运行 714 个测试
454
462
  npm run stress # 三轴线压测:长会话检索 / 冲突仲裁 / 多 Agent 并发(离线 mock LLM)
455
463
  npm run sync # 把 src/ 同步到 lib/(发布时由 prepack 钩子自动执行)
456
464
  ```
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![npm version](https://img.shields.io/npm/v/@modusensus/dsh-mneme?color=blue&label=npm)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
6
6
  [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
7
7
  [![Awesome](https://awesome-dsh-plugin.com/badge.svg)](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin)
8
- [![tests](https://img.shields.io/badge/tests-712%20passed-success)](https://github.com/modusensus/dsh-mneme)
8
+ [![tests](https://img.shields.io/badge/tests-714%20passed-success)](https://github.com/modusensus/dsh-mneme)
9
9
  [![CI](https://img.shields.io/github/actions/workflow/status/modusensus/dsh-mneme/ci.yml)](https://github.com/modusensus/dsh-mneme/actions)
10
10
  [![node](https://img.shields.io/badge/node-24%2B-blue)](https://nodejs.org)
11
11
  [![npm downloads](https://img.shields.io/npm/dm/@modusensus/dsh-mneme?color=blue&label=downloads)](https://www.npmjs.com/package/@modusensus/dsh-mneme)
@@ -89,7 +89,14 @@ dsh web
89
89
  | 中等(1 万-5 万字) | `65536` |
90
90
  | 大型(5 万字以上) | `131072`(上限) |
91
91
 
92
- > 若使用**思考型模型**(如 deepseek-v4-flash / DeepSeek-R1 类),模型可能把全部预算花在 reasoning 上导致正文为空(日志出现 `no json array in llm output`)。处理顺序:① 把 `dreamReasoningEffort` 设为 `low` 显式压低思考(被方舟拒绝该参数时自动去掉重试一次,拒绝原因会记入 llm_audit——部分模型如 v4-flash-ga 不支持任何 effort 档位);② 重试走模型默认思考行为后正文仍为空的,调大 `dreamMaxTokens`(reasoning 与正文共享该预算)或配置 `dreamProvider`/`dreamModel` 指向非思考模型。sleep 侧对应 `sleepReasoningEffort`。
92
+ > 若使用**思考型模型**(如 deepseek-v4-flash / DeepSeek-R1 类),模型可能把全部预算花在 reasoning 上导致正文为空(日志出现 `no json array in llm output`)。处理顺序:① 把 `dreamReasoningEffort` 设为 `low` 显式压低思考(被方舟拒绝该参数时自动去掉重试一次,拒绝原因会记入 llm_audit);② 重试走模型默认思考行为后正文仍为空的,调大 `dreamMaxTokens`(reasoning 与正文共享该预算)或配置 `dreamProvider`/`dreamModel` 指向非思考模型。sleep 侧对应 `sleepReasoningEffort`。
93
+
94
+ **巩固模型分类声明**(settings panel「巩固模型」= `dreamProvider`/`dreamModel`,睡眠侧对应 `sleepProvider`/`sleepModel`):
95
+
96
+ | 模型类别 | 例子 | 说明 |
97
+ |---------|------|------|
98
+ | **非思考模型(推荐)** | glm-5-2 类等 | 无 reasoning 声明;即使配了 effort 被 harness 拒绝,fallback 去掉字段重试即成功。空体风险最低 |
99
+ | **思考模型(需实测)** | deepseek-v4-flash-ga 等 v4-flash-ga 系 | 默认开推理,可能烧光 token 预算返回空体;且部分型号(如 v4-flash-ga)在 harness 侧被声明为**不接受任何 reasoning effort** —— 去掉 effort 重试时 harness 的 `defaultEffort` 仍会顶上来再次拒绝(`UNSUPPORTED_REASONING_EFFORT`),插件侧 fallback 无法绕开。选用时建议配 `dreamReasoningEffort` 实测,不行就换非思考模型 |
93
100
 
94
101
  ### Sleep Mode 系统级睡眠 💤(v0.4.0,opt-in)
95
102
 
@@ -207,6 +214,7 @@ v0.3.0 起新增**记忆基因**层:从记忆里抽取**命名实体**、**带
207
214
 
208
215
  | 版本 | 亮点 |
209
216
  |------|------|
217
+ | **v0.7.24** | 修复 DSH Desktop 插件树加载崩溃(v0.7.23 回归):cordis 4 的 ctx 是 Proxy,访问未在 inject 声明的 `webServer` 会抛 `cannot get property without inject`(而非返回 undefined),且去掉 inject 后 cordis 不再等待宿主服务 → 桌面端重启即崩;修复:恢复 webServer 到 inject(cordis 等宿主就绪再 apply)+ apply/register 守卫改 `ctx.reflect.get`(免 inject 读取、未提供返回 undefined 不抛错);真实 cordis + dsh-host-webserver 插件实测;714 测试全绿 |
210
218
  | **v0.7.23** | 记忆沉淀「反复失败」根治:consolidation 合法空数组 `[]` 不再误判 failed(CONSOLIDATION_PROMPT 允许「无问题无需输出」,模型无冗余时合法返回 `[]`——此前 `validateDecisions` 硬判 non-empty → 整单 failed、审计反复失败,且与模型无关,ChatGPT/Claude 同样踩中;修复:空数组显式短路 `ok:true` no-op)+ 空体修复第二段(`dreamMaxTokens` 默认 8192→32768,思考模型推理烧光预算的根治余量,设置面板可调)+ skipInvalid splice 残留 bug(长度相等≠内容一致,被跳决策残留);712 测试全绿 |
211
219
  | **v0.7.22** | 恢复 v0.6.9 的 skipInvalid 宽容校验路径(issue #89 回归,v0.7.11 重写丢失):`dreamSkipInvalid`(默认 true)单条非法决策跳过 + 合法子集应用 + run 记 degraded,`allowCrossTypeMerge`(默认 false)显式放宽跨类型合并——弱模型(如 qwen3.8-flash)决策合规抖动不再整单拒绝白烧 LLM 调用;严格模式/sleep 路径行为不变,全局上限/覆盖率下限仍整单拒绝(刷爆上限=模型坏了,非轻微 schema 漂移);新增 `dreamMinIntervalMinutes`(0-10080,默认 0=不限)autoDream 最小触发间隔,失败/degraded run 也占用间隔(节流防失败调用连发);feature_flags 白名单 34 键;696 测试全绿 |
212
220
  | **v0.7.21** | 修复 autoDream/sleep 的 effort 回退在流式路径失效(v0.7.16 的 catch 式回退是死代码):dsh-llm rc.1 把 adapter 阶段异常(含 `UNSUPPORTED_REASONING_EFFORT`)转成终态 error finish chunk 不再抛出;`streamText` 现捕获 finish-chunk 失败原因(新增 `describeStreamFailure` 归一化 `{code,message}`)+ `withEffortFallback` 增加 `getStreamError` 访问器(effort 被拒时去掉重试一次)+ `runAuditedLlm` 支持 `spec.streamError`(audit 行 `error_message` 携带真实原因,`run.error` 稳定 `"llm failed"` 不变);688 测试全绿 |
@@ -293,6 +301,7 @@ v0.3.0 起新增**记忆基因**层:从记忆里抽取**命名实体**、**带
293
301
  | **v0.7.18** | ✅ 完成 | 生态第一步 + 查询收敛 | better-sidebar 软集成(inject 声明 + optional peer `dsh-better-sidebar` + registerTab 复用四视图,未装安全跳过;窄容器 `@container` 适配)+ `/list?deposited=only` 沉淀视图(receipt_chain ∪ source=dream)+ 记忆库沉淀/已归档筛选 chip + 状态页仪表盘化(统计 + 查看全部跳转预置筛选)+ 抽屉归档记忆「恢复」;667 测试全绿 |
294
302
  | **v0.7.20** | ✅ 完成 | heat 回归 + 阶段二前端 + better-sidebar 修复 | heat 热度模型完整找回(issue #87,v0.7.10 移植:幂律衰减 + TYPE_DECAY + sleep 热联合双保护 + 实体热投影)+ 验收清单落地(heatEnabled 默认关 / feature_flags 31 键 / lightMode 联动 / sleep 降级审计暴露 / updated_at⊥last_accessed_at 契约)+ 阶段二前端(/list heat 投影、HeatBadge 三档、order=heat 页内排序)+ better-sidebar 修复(issue #88:内层动态子插件);685 测试全绿 |
295
303
  | **v0.7.21** | ✅ 完成 | effort 回退流式修复 | autoDream/sleep 的 catch 式 effort 回退在流式路径是死代码(dsh-llm rc.1 把 adapter 异常转成终态 error finish chunk 不再抛出)→ `streamText` 捕获 finish-chunk 失败原因(`describeStreamFailure` 归一化)+ `withEffortFallback` 增加 `getStreamError` 访问器(effort 被拒去重试)+ `runAuditedLlm` 支持 `spec.streamError`(audit 记真实原因);688 测试全绿 |
304
+ | **v0.7.24** | ✅ 完成 | 桌面端崩溃紧急修复 | v0.7.23 把 webServer 移出 inject 致 cordis Proxy 抛 `cannot get property "webServer" without inject`(未注入属性直接访问抛错而非 undefined),桌面端重启插件树加载失败;修复:恢复 webServer 到 inject(cordis 等宿主就绪再 apply)+ apply/register 守卫改 `ctx.reflect.get`(免 inject 读取、未提供返回 undefined 不抛错,未来 headless 移出 inject 也安全);真实 cordis + dsh-host-webserver 实测 API 路由 200 / 未知路径 404 / headless 静默不激活;714 测试全绿 |
296
305
  | **v0.7.23** | ✅ 完成 | 记忆沉淀「反复失败」根治 + 空体第二段 + skipInvalid splice 修复 | consolidation 合法空数组 `[]` no-op(CONSOLIDATION_PROMPT 允许无问题无需输出;此前 validateDecisions 硬判 non-empty → 整单 failed,模型无关、ChatGPT/Claude 同样踩中;修复:空数组显式短路 ok,不再触发隐式 keep 覆盖率误判);`dreamMaxTokens` 默认 8192→32768(思考模型推理烧光预算根治余量);skipInvalid splice 残留 bug(长度相等≠内容一致,被跳决策残留进 apply);712 测试全绿 |
297
306
  | **v0.7.22** | ✅ 完成 | skipInvalid 宽容校验回归(issue #89)+ autoDream 节流 | 恢复 v0.6.9 的 skipInvalid 双轨结构(v0.7.11 重写丢失):`dreamSkipInvalid` 单条非法决策跳过 + 合法子集应用 + run 记 degraded,`allowCrossTypeMerge` 显式放宽跨类型合并;弱模型(qwen3.8-flash)决策合规抖动不再整单拒绝;新增 `dreamMinIntervalMinutes`(0-10080,默认 0=不限)最小触发间隔,失败/degraded run 也占用间隔;严格模式/sleep 路径行为不变;feature_flags 白名单 34 键;696 测试全绿 |
298
307
  | **v0.8.0** | 🚧 计划中(9 月末) | 图谱增强 | 兴趣漂移可视化 + scope 隔离(issue #17)+ 跨 workspace 记忆共享 |
@@ -529,7 +538,7 @@ src/
529
538
  ├── api.js # HTTP 路由(Web 面板数据通道)
530
539
  └── index.js # 插件接线
531
540
  lib/ # src 的同步分发产物(npm run sync;发布前由 root prepack 的 check-sync.js 校验一致性;唯一手写例外 lib/client.js——Web 面板 bundle,sync 不覆盖)
532
- test/ # 712 个 node:test 测试(审计与三轴线压测不变量;src↔lib 一致性由 scripts/check-sync.js 发布闸门校验)
541
+ test/ # 714 个 node:test 测试(审计与三轴线压测不变量;src↔lib 一致性由 scripts/check-sync.js 发布闸门校验)
533
542
  scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压测 · sync-lib.js 同步 · check-sync.js 发布闸门 · benchmark-recall.js 召回基准
534
543
  ```
535
544
 
@@ -538,7 +547,7 @@ scripts/ # e2e-dsh.js 端到端演示 · stress-dsh.js 三轴线压
538
547
  ```bash
539
548
  cd dsh-mneme
540
549
  npm install # 安装 peer 依赖(以 devDependencies 形式,用于本地测试)
541
- npm test # 运行 712 个测试
550
+ npm test # 运行 714 个测试
542
551
  npm run stress # 三轴线压测:长会话检索 / 冲突仲裁 / 多 Agent 并发(离线 mock LLM)
543
552
  npm run sync # 把 src/ 同步到 lib/(发布时由 prepack 钩子自动执行)
544
553
  ```
@@ -16,6 +16,46 @@ const DEFAULT_HOST = "127.0.0.1";
16
16
  // Hardcoded release version (package.json is bumped at publish time and may
17
17
  // lag the code that ships in between).
18
18
  const VERSION = "0.7.12";
19
+ const MAX_PORT_ATTEMPTS = 20;
20
+
21
+ /**
22
+ * Listen with automatic EADDRINUSE recovery. Tries the configured port, then
23
+ * the next MAX_PORT_ATTEMPTS-1 ports, and finally falls back to port 0 so the
24
+ * OS assigns a free port. Multiple DSH profiles/instances sharing the default
25
+ * port no longer leave the standalone API permanently unavailable.
26
+ */
27
+ function listenWithRetry(server, startPort, host, logger) {
28
+ return new Promise((resolve, reject) => {
29
+ let attempt = 0;
30
+ const tryListen = (port) => {
31
+ const onListening = () => {
32
+ server.off("error", onError);
33
+ const address = server.address();
34
+ resolve(address && typeof address === "object" ? address.port : port);
35
+ };
36
+ const onError = (error) => {
37
+ server.off("listening", onListening);
38
+ if (error?.code === "EADDRINUSE" && attempt < MAX_PORT_ATTEMPTS - 1) {
39
+ attempt++;
40
+ const next = startPort + attempt;
41
+ logger?.warn?.(`[dsh-mneme] standalone API port ${port} in use, retrying ${next}`);
42
+ tryListen(next);
43
+ return;
44
+ }
45
+ if (error?.code === "EADDRINUSE") {
46
+ logger?.warn?.(`[dsh-mneme] standalone API port ${port} still in use, falling back to OS-assigned port`);
47
+ tryListen(0);
48
+ return;
49
+ }
50
+ reject(error);
51
+ };
52
+ server.once("listening", onListening);
53
+ server.once("error", onError);
54
+ server.listen(port, host);
55
+ };
56
+ tryListen(startPort);
57
+ });
58
+ }
19
59
 
20
60
  function sendJson(res, status, payload) {
21
61
  res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
@@ -243,10 +283,10 @@ export function createStandaloneApi({ service, store, config = {}, logger, setti
243
283
  logger?.warn?.(`[dsh-mneme] standalone API error: ${String(error)}`);
244
284
  });
245
285
  const ready = new Promise((resolve, reject) => {
246
- server.once("listening", resolve);
247
- server.once("error", reject);
286
+ // listening handled by listenWithRetry
287
+ listenWithRetry(server, boundPort, boundHost, logger).then(resolve, reject);
248
288
  });
249
- server.listen(boundPort, boundHost);
289
+ // server.listen is called inside listenWithRetry
250
290
  ready.then(() => {
251
291
  const address = server.address();
252
292
  if (address && typeof address === "object") {
package/lib/api.js CHANGED
@@ -98,6 +98,14 @@ function parseBody(text) {
98
98
  export function createApi(ctx, service, settings, commands, embedder, semantic = null, apiToken = "", config = null) {
99
99
  const disposers = [];
100
100
 
101
+ // webServer 在 index.js 的 inject 声明中(cordis 等宿主服务就绪后 apply),
102
+ // 这里做防御性读取:cordis ctx 的 Proxy 不允许直接访问未 inject 的属性
103
+ // (会抛 "cannot get property without inject"),用 ctx.reflect.get 免
104
+ // inject 读取(未提供返回 undefined);对象字面量 mock ctx(测试)没有
105
+ // reflect,退回直接属性访问。createApi 只在有 webServer 时被调用(index.js
106
+ // 守卫 + 测试 mock),故下方 register 用之非空。
107
+ const webServer = typeof ctx.reflect?.get === "function" ? ctx.reflect.get("webServer") : ctx.webServer;
108
+
101
109
  // feature flags 快照(GET/PUT 共用):overrides 是持久化的用户显式覆盖;
102
110
  // effective 是启动配置在白名单键上被 overrides 覆盖后的最终值。config 缺席
103
111
  // (旧调用方直连、未传 cfg)时只报被覆盖的键,不把不存在的默认值编造给前端。
@@ -140,7 +148,7 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
140
148
  }
141
149
 
142
150
  const register = (route) => {
143
- disposers.push(ctx.webServer.register(route));
151
+ disposers.push(webServer.register(route));
144
152
  };
145
153
 
146
154
  // /api/dsh-mneme prefix fallback → 404 JSON for unknown sub-paths
package/lib/client.js CHANGED
@@ -3610,9 +3610,14 @@ window.__ModuleLoader__.load({
3610
3610
  if (dead) return;
3611
3611
  const reg = bsCtx.betterSidebar;
3612
3612
  if (!reg || typeof reg.registerTab !== "function") return;
3613
+ const TAB_ID = "dsh-mneme:memory";
3614
+ if (typeof reg.getTab === "function" && reg.getTab(TAB_ID)) {
3615
+ console.warn(`[dsh-mneme] better-sidebar tab "${TAB_ID}" already registered, skipping duplicate`);
3616
+ return;
3617
+ }
3613
3618
  try {
3614
3619
  reg.registerTab({
3615
- id: "dsh-mneme:memory",
3620
+ id: TAB_ID,
3616
3621
  title: () => t("memory.view.label"),
3617
3622
  icon: (size) => h(IconArchiveOutline20, { size }),
3618
3623
  order: 60,
@@ -3620,7 +3625,7 @@ window.__ModuleLoader__.load({
3620
3625
  });
3621
3626
  } catch (err) {
3622
3627
  // id 重复等注册失败不应拖垮其余功能,留一条线索即可
3623
- console.error("[dsh-mneme] better-sidebar registerTab failed:", err);
3628
+ console.warn("[dsh-mneme] better-sidebar registerTab failed, falling back to native sidebar entry:", err);
3624
3629
  }
3625
3630
  }, "dsh-mneme: better-sidebar tab");
3626
3631
  }
package/lib/config.js CHANGED
@@ -52,6 +52,16 @@ export const Config = z.object({
52
52
  // 起算,失败/degraded 的 run 也占用间隔;间隔内的触发请求静默跳过,下一次
53
53
  // 写入事件会重新评估。
54
54
  dreamMinIntervalMinutes: z.natural().min(0).max(10080).default(0),
55
+ // 巩固模型路由(settings panel「巩固模型」/ dreamProvider+dreamModel):
56
+ // dream 的记忆沉淀专用 LLM 路由,显式配置优先于 agent 默认模型(config-first,
57
+ // Issue #25)。模型分类声明:
58
+ // - 非思考模型(推荐,如 glm-5-2 类):无 reasoning 声明,effort 请求被 harness
59
+ // 拒绝后 withEffortFallback 去掉字段重试即成功;空体/no json array 风险最低。
60
+ // - 思考模型(如 deepseek-v4-flash-ga 等 v4-flash-ga 系):默认开推理,可能烧光
61
+ // token 预算返回空体;且部分(如 v4-flash-ga)在 harness 侧被声明为不接受任何
62
+ // reasoning effort —— 即使去掉 effort 重试,harness 的 defaultEffort 也会顶上来
63
+ // 再次拒绝(UNSUPPORTED_REASONING_EFFORT),插件 fallback 无法绕开。
64
+ // 选用时建议配 dreamReasoningEffort 并实测;不行就换非思考模型。
55
65
  dreamProvider: z.string(),
56
66
  dreamModel: z.string(),
57
67
  dreamMaxTokens: z.natural().min(256).max(131072).default(32768),
@@ -60,6 +70,9 @@ export const Config = z.object({
60
70
  // are forwarded verbatim. Useful to cap reasoning spend on thinking-type
61
71
  // models that would otherwise drain the whole token budget and return an
62
72
  // empty body ("no json array in llm output").
73
+ // Caveat: on some thinking models (e.g. v4-flash-ga) the harness declares NO
74
+ // supported effort, so even the fallback retry (field stripped) is rejected
75
+ // again via its defaultEffort — prefer a non-reasoning dreamProvider/dreamModel.
63
76
  dreamReasoningEffort: z.union([
64
77
  z.const("low"),
65
78
  z.const("medium"),
package/lib/index.js CHANGED
@@ -21,10 +21,13 @@ import { join } from "node:path";
21
21
  import { homedir } from "node:os";
22
22
 
23
23
  export const name = "dsh-mneme";
24
- // webServer 为可选依赖(headless/无 UI 宿主兼容):从 inject 声明中去掉,cordis
25
- // 不再等待它激活;运行时 ctx.webServer 为空则跳过 API 注册(下方 if 守卫),
26
- // 记忆工具/注入/dream 全部照常工作。
27
- export const inject = ["tools", "systemPrompt", "llm", "agentDefaultModel", "commands"];
24
+ // webServer inject 声明中:cordis 会等宿主 webServer 服务激活后才 apply 本
25
+ // 插件,保证 apply 时路由注册不落时序(v0.7.23 曾移出 inject 想支持 headless,
26
+ // 结果 cordis 不再等待,apply 时宿主 webServer 未就绪 → 桌面端 "cannot get
27
+ // property without inject" 崩溃)。守卫用 ctx.reflect.get(免 inject 读取,
28
+ // 未提供返回 undefined)而非 if (ctx.webServer):直接访问未注入属性在 cordis
29
+ // Proxy 下会抛错而非返回 undefined。
30
+ export const inject = ["tools", "systemPrompt", "llm", "agentDefaultModel", "commands", "webServer"];
28
31
  export { Config };
29
32
 
30
33
  // Arrow (not function declaration): cordis 4 treats any apply with a
@@ -362,7 +365,14 @@ export const apply = (ctx, config) => {
362
365
  const summarizer = createSummarizer(ctx, service, cfg);
363
366
  disposers.push(summarizer.dispose);
364
367
 
365
- if (ctx.webServer) {
368
+ // webServer 可选依赖:cordis 4 的 ctx 是 Proxy,直接访问未在 inject 声明的
369
+ // 属性会抛 "cannot get property without inject"(不会返回 undefined),所以
370
+ // 不能用 if (ctx.webServer) 守卫。ctx.reflect.get 是 cordis 提供的免 inject
371
+ // 读取(未提供时返回 undefined);对象字面量 mock ctx(测试)没有 reflect,
372
+ // 退回直接属性访问。headless/无 UI 宿主无 webServer 时跳过 API 注册,其余
373
+ // 功能(工具/注入/dream)照常。
374
+ const webServer = typeof ctx.reflect?.get === "function" ? ctx.reflect.get("webServer") : ctx.webServer;
375
+ if (webServer) {
366
376
  const api = createApi(ctx, service, settings, commands ?? {
367
377
  add: () => { throw new Error("commands unavailable"); },
368
378
  remove: () => false,
package/lib/tools.js CHANGED
@@ -1,6 +1,10 @@
1
1
  import { defineTool } from "@deepseek-ai/dsh-tools";
2
2
 
3
3
  const TEXT_OUTPUT = (text) => [{ type: "text", text }];
4
+ // Per-registry tool-name registry: guards against duplicate registration on
5
+ // live patch reload (DSH Desktop `patchReload: "live"`) where a plugin may be
6
+ // re-applied on the same tools registry without an intervening unregister.
7
+ const REGISTERED_TOOLS = new WeakMap();
4
8
 
5
9
  // Wire shape emitted by service.toApiList: shared by memory_search and
6
10
  // memory_list so their output schemas always declare every key the runtime
@@ -22,6 +26,12 @@ const MEMORY_ITEM_SCHEMA = {
22
26
  };
23
27
 
24
28
  export function createTools(ctx, service, config, embedder) {
29
+ const toolsRegistry = ctx.tools;
30
+ let registeredTools = REGISTERED_TOOLS.get(toolsRegistry);
31
+ if (!registeredTools) {
32
+ registeredTools = new Set();
33
+ REGISTERED_TOOLS.set(toolsRegistry, registeredTools);
34
+ }
25
35
  const tools = [
26
36
  defineTool({
27
37
  name: "memory_save",
@@ -82,7 +92,18 @@ export function createTools(ctx, service, config, embedder) {
82
92
  }
83
93
  }
84
94
  },
85
- render: (_args, value) => TEXT_OUTPUT(`Found ${value.items.length} memory entr${value.items.length === 1 ? "y" : "ies"}.`)
95
+ render: (_args, value) => {
96
+ const items = value.items ?? [];
97
+ if (items.length === 0) return TEXT_OUTPUT("No memory entries found.");
98
+ const body = items
99
+ .map((m, i) => {
100
+ const preview = (m.content ?? "").replace(/\s+/g, " ").trim();
101
+ const cut = preview.length > 200 ? `${preview.slice(0, 200)}…` : preview;
102
+ return `[${i + 1}] ${m.title}\n ID: ${m.id} | type: ${m.type} | importance: ${m.importance} | updated: ${m.updated_at}\n ${cut}`;
103
+ })
104
+ .join("\n\n");
105
+ return TEXT_OUTPUT(`Found ${items.length} memory entr${items.length === 1 ? "y" : "ies"}:\n\n${body}`);
106
+ }
86
107
  },
87
108
  async execute(args) {
88
109
  const limit = args.limit ?? 20;
@@ -117,7 +138,14 @@ export function createTools(ctx, service, config, embedder) {
117
138
  total: { type: "integer", required: true }
118
139
  }
119
140
  },
120
- render: (_args, value) => TEXT_OUTPUT(`${value.items.length} memory entries (of ${value.total}).`)
141
+ render: (_args, value) => {
142
+ const items = value.items ?? [];
143
+ if (items.length === 0) return TEXT_OUTPUT(`0 memory entries (of ${value.total}).`);
144
+ const body = items
145
+ .map((m, i) => `[${i + 1}] ${m.title} (type=${m.type}, importance=${m.importance})\n ID: ${m.id} | updated: ${m.updated_at}`)
146
+ .join("\n\n");
147
+ return TEXT_OUTPUT(`${items.length} memory entries (of ${value.total}):\n\n${body}`);
148
+ }
121
149
  },
122
150
  async execute(args) {
123
151
  const includeArchived = args.include_archived === true;
@@ -131,6 +159,46 @@ export function createTools(ctx, service, config, embedder) {
131
159
  }
132
160
  }),
133
161
 
162
+ defineTool({
163
+ name: "memory_get",
164
+ description: "Fetch one memory entry by ID and return its full content as text. Use after memory_list to read a specific entry.",
165
+ parameters: {
166
+ id: { type: "string", required: true, description: "Memory id" }
167
+ },
168
+ output: {
169
+ schema: {
170
+ type: "object",
171
+ additionalProperties: false,
172
+ properties: {
173
+ memory: {
174
+ type: "object",
175
+ additionalProperties: false,
176
+ properties: {
177
+ id: { type: "string", required: true },
178
+ title: { type: "string", required: true },
179
+ type: { type: "string", required: true },
180
+ importance: { type: "integer", required: true },
181
+ tags: { type: "array", items: { type: "string" } },
182
+ content: { type: "string", required: true },
183
+ source: { type: "string" },
184
+ created_at: { type: "string" },
185
+ updated_at: { type: "string" }
186
+ }
187
+ }
188
+ }
189
+ },
190
+ render: (_args, value) => {
191
+ const m = value.memory;
192
+ return TEXT_OUTPUT(`${m.title}\nID: ${m.id} | type: ${m.type} | importance: ${m.importance}\n\n${m.content}`);
193
+ }
194
+ },
195
+ async execute(args) {
196
+ const memory = service.getById(args.id);
197
+ if (memory === undefined) throw new Error("memory not found");
198
+ return { memory: service.toApiList([memory])[0] };
199
+ }
200
+ }),
201
+
134
202
  defineTool({
135
203
  name: "memory_update",
136
204
  description: "Modify an existing memory entry (title, content, type, tags, importance).",
@@ -267,7 +335,12 @@ export function createTools(ctx, service, config, embedder) {
267
335
  ];
268
336
 
269
337
  for (const tool of tools) {
270
- ctx.tools.register(tool);
338
+ if (registeredTools.has(tool.name)) {
339
+ ctx.logger?.warn?.(`[dsh-mneme] tool "${tool.name}" already registered, skipping duplicate`);
340
+ continue;
341
+ }
342
+ registeredTools.add(tool.name);
343
+ ctx.tools.register(tool);
271
344
  }
272
345
 
273
346
  return tools;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@modusensus/dsh-mneme",
3
3
  "description": "Cross-session memory plugin for DeepSeek Harness with autoDream consolidation: SQLite store, Markdown mirrors, 7 model tools, automatic injection, session summarization, user profile/rules, custom slash commands, vector (semantic) search, and a Web GUI panel",
4
- "version": "0.7.23",
4
+ "version": "0.7.25",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -37,9 +37,7 @@
37
37
  "client": {
38
38
  "inject": [
39
39
  "slots",
40
- "locale",
41
- "layout",
42
- "connection"
40
+ "locale"
43
41
  ],
44
42
  "platform": "web"
45
43
  },
@@ -54,7 +52,7 @@
54
52
  "@deepseek-ai/dsh-system-prompt": "^0.1.0-rc.6",
55
53
  "@deepseek-ai/dsh-tools": "^0.1.0-rc.6",
56
54
  "@deepseek-ai/schemastery": "^3.18.1",
57
- "dsh-better-sidebar": "*"
55
+ "dsh-better-sidebar": "^0.18.0"
58
56
  },
59
57
  "peerDependenciesMeta": {
60
58
  "dsh-better-sidebar": {
@@ -16,6 +16,46 @@ const DEFAULT_HOST = "127.0.0.1";
16
16
  // Hardcoded release version (package.json is bumped at publish time and may
17
17
  // lag the code that ships in between).
18
18
  const VERSION = "0.7.12";
19
+ const MAX_PORT_ATTEMPTS = 20;
20
+
21
+ /**
22
+ * Listen with automatic EADDRINUSE recovery. Tries the configured port, then
23
+ * the next MAX_PORT_ATTEMPTS-1 ports, and finally falls back to port 0 so the
24
+ * OS assigns a free port. Multiple DSH profiles/instances sharing the default
25
+ * port no longer leave the standalone API permanently unavailable.
26
+ */
27
+ function listenWithRetry(server, startPort, host, logger) {
28
+ return new Promise((resolve, reject) => {
29
+ let attempt = 0;
30
+ const tryListen = (port) => {
31
+ const onListening = () => {
32
+ server.off("error", onError);
33
+ const address = server.address();
34
+ resolve(address && typeof address === "object" ? address.port : port);
35
+ };
36
+ const onError = (error) => {
37
+ server.off("listening", onListening);
38
+ if (error?.code === "EADDRINUSE" && attempt < MAX_PORT_ATTEMPTS - 1) {
39
+ attempt++;
40
+ const next = startPort + attempt;
41
+ logger?.warn?.(`[dsh-mneme] standalone API port ${port} in use, retrying ${next}`);
42
+ tryListen(next);
43
+ return;
44
+ }
45
+ if (error?.code === "EADDRINUSE") {
46
+ logger?.warn?.(`[dsh-mneme] standalone API port ${port} still in use, falling back to OS-assigned port`);
47
+ tryListen(0);
48
+ return;
49
+ }
50
+ reject(error);
51
+ };
52
+ server.once("listening", onListening);
53
+ server.once("error", onError);
54
+ server.listen(port, host);
55
+ };
56
+ tryListen(startPort);
57
+ });
58
+ }
19
59
 
20
60
  function sendJson(res, status, payload) {
21
61
  res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
@@ -243,10 +283,10 @@ export function createStandaloneApi({ service, store, config = {}, logger, setti
243
283
  logger?.warn?.(`[dsh-mneme] standalone API error: ${String(error)}`);
244
284
  });
245
285
  const ready = new Promise((resolve, reject) => {
246
- server.once("listening", resolve);
247
- server.once("error", reject);
286
+ // listening handled by listenWithRetry
287
+ listenWithRetry(server, boundPort, boundHost, logger).then(resolve, reject);
248
288
  });
249
- server.listen(boundPort, boundHost);
289
+ // server.listen is called inside listenWithRetry
250
290
  ready.then(() => {
251
291
  const address = server.address();
252
292
  if (address && typeof address === "object") {
package/src/api.js CHANGED
@@ -98,6 +98,14 @@ function parseBody(text) {
98
98
  export function createApi(ctx, service, settings, commands, embedder, semantic = null, apiToken = "", config = null) {
99
99
  const disposers = [];
100
100
 
101
+ // webServer 在 index.js 的 inject 声明中(cordis 等宿主服务就绪后 apply),
102
+ // 这里做防御性读取:cordis ctx 的 Proxy 不允许直接访问未 inject 的属性
103
+ // (会抛 "cannot get property without inject"),用 ctx.reflect.get 免
104
+ // inject 读取(未提供返回 undefined);对象字面量 mock ctx(测试)没有
105
+ // reflect,退回直接属性访问。createApi 只在有 webServer 时被调用(index.js
106
+ // 守卫 + 测试 mock),故下方 register 用之非空。
107
+ const webServer = typeof ctx.reflect?.get === "function" ? ctx.reflect.get("webServer") : ctx.webServer;
108
+
101
109
  // feature flags 快照(GET/PUT 共用):overrides 是持久化的用户显式覆盖;
102
110
  // effective 是启动配置在白名单键上被 overrides 覆盖后的最终值。config 缺席
103
111
  // (旧调用方直连、未传 cfg)时只报被覆盖的键,不把不存在的默认值编造给前端。
@@ -140,7 +148,7 @@ export function createApi(ctx, service, settings, commands, embedder, semantic =
140
148
  }
141
149
 
142
150
  const register = (route) => {
143
- disposers.push(ctx.webServer.register(route));
151
+ disposers.push(webServer.register(route));
144
152
  };
145
153
 
146
154
  // /api/dsh-mneme prefix fallback → 404 JSON for unknown sub-paths
package/src/config.js CHANGED
@@ -52,6 +52,16 @@ export const Config = z.object({
52
52
  // 起算,失败/degraded 的 run 也占用间隔;间隔内的触发请求静默跳过,下一次
53
53
  // 写入事件会重新评估。
54
54
  dreamMinIntervalMinutes: z.natural().min(0).max(10080).default(0),
55
+ // 巩固模型路由(settings panel「巩固模型」/ dreamProvider+dreamModel):
56
+ // dream 的记忆沉淀专用 LLM 路由,显式配置优先于 agent 默认模型(config-first,
57
+ // Issue #25)。模型分类声明:
58
+ // - 非思考模型(推荐,如 glm-5-2 类):无 reasoning 声明,effort 请求被 harness
59
+ // 拒绝后 withEffortFallback 去掉字段重试即成功;空体/no json array 风险最低。
60
+ // - 思考模型(如 deepseek-v4-flash-ga 等 v4-flash-ga 系):默认开推理,可能烧光
61
+ // token 预算返回空体;且部分(如 v4-flash-ga)在 harness 侧被声明为不接受任何
62
+ // reasoning effort —— 即使去掉 effort 重试,harness 的 defaultEffort 也会顶上来
63
+ // 再次拒绝(UNSUPPORTED_REASONING_EFFORT),插件 fallback 无法绕开。
64
+ // 选用时建议配 dreamReasoningEffort 并实测;不行就换非思考模型。
55
65
  dreamProvider: z.string(),
56
66
  dreamModel: z.string(),
57
67
  dreamMaxTokens: z.natural().min(256).max(131072).default(32768),
@@ -60,6 +70,9 @@ export const Config = z.object({
60
70
  // are forwarded verbatim. Useful to cap reasoning spend on thinking-type
61
71
  // models that would otherwise drain the whole token budget and return an
62
72
  // empty body ("no json array in llm output").
73
+ // Caveat: on some thinking models (e.g. v4-flash-ga) the harness declares NO
74
+ // supported effort, so even the fallback retry (field stripped) is rejected
75
+ // again via its defaultEffort — prefer a non-reasoning dreamProvider/dreamModel.
63
76
  dreamReasoningEffort: z.union([
64
77
  z.const("low"),
65
78
  z.const("medium"),
package/src/index.js CHANGED
@@ -21,10 +21,13 @@ import { join } from "node:path";
21
21
  import { homedir } from "node:os";
22
22
 
23
23
  export const name = "dsh-mneme";
24
- // webServer 为可选依赖(headless/无 UI 宿主兼容):从 inject 声明中去掉,cordis
25
- // 不再等待它激活;运行时 ctx.webServer 为空则跳过 API 注册(下方 if 守卫),
26
- // 记忆工具/注入/dream 全部照常工作。
27
- export const inject = ["tools", "systemPrompt", "llm", "agentDefaultModel", "commands"];
24
+ // webServer inject 声明中:cordis 会等宿主 webServer 服务激活后才 apply 本
25
+ // 插件,保证 apply 时路由注册不落时序(v0.7.23 曾移出 inject 想支持 headless,
26
+ // 结果 cordis 不再等待,apply 时宿主 webServer 未就绪 → 桌面端 "cannot get
27
+ // property without inject" 崩溃)。守卫用 ctx.reflect.get(免 inject 读取,
28
+ // 未提供返回 undefined)而非 if (ctx.webServer):直接访问未注入属性在 cordis
29
+ // Proxy 下会抛错而非返回 undefined。
30
+ export const inject = ["tools", "systemPrompt", "llm", "agentDefaultModel", "commands", "webServer"];
28
31
  export { Config };
29
32
 
30
33
  // Arrow (not function declaration): cordis 4 treats any apply with a
@@ -362,7 +365,14 @@ export const apply = (ctx, config) => {
362
365
  const summarizer = createSummarizer(ctx, service, cfg);
363
366
  disposers.push(summarizer.dispose);
364
367
 
365
- if (ctx.webServer) {
368
+ // webServer 可选依赖:cordis 4 的 ctx 是 Proxy,直接访问未在 inject 声明的
369
+ // 属性会抛 "cannot get property without inject"(不会返回 undefined),所以
370
+ // 不能用 if (ctx.webServer) 守卫。ctx.reflect.get 是 cordis 提供的免 inject
371
+ // 读取(未提供时返回 undefined);对象字面量 mock ctx(测试)没有 reflect,
372
+ // 退回直接属性访问。headless/无 UI 宿主无 webServer 时跳过 API 注册,其余
373
+ // 功能(工具/注入/dream)照常。
374
+ const webServer = typeof ctx.reflect?.get === "function" ? ctx.reflect.get("webServer") : ctx.webServer;
375
+ if (webServer) {
366
376
  const api = createApi(ctx, service, settings, commands ?? {
367
377
  add: () => { throw new Error("commands unavailable"); },
368
378
  remove: () => false,
package/src/tools.js CHANGED
@@ -1,6 +1,10 @@
1
1
  import { defineTool } from "@deepseek-ai/dsh-tools";
2
2
 
3
3
  const TEXT_OUTPUT = (text) => [{ type: "text", text }];
4
+ // Per-registry tool-name registry: guards against duplicate registration on
5
+ // live patch reload (DSH Desktop `patchReload: "live"`) where a plugin may be
6
+ // re-applied on the same tools registry without an intervening unregister.
7
+ const REGISTERED_TOOLS = new WeakMap();
4
8
 
5
9
  // Wire shape emitted by service.toApiList: shared by memory_search and
6
10
  // memory_list so their output schemas always declare every key the runtime
@@ -22,6 +26,12 @@ const MEMORY_ITEM_SCHEMA = {
22
26
  };
23
27
 
24
28
  export function createTools(ctx, service, config, embedder) {
29
+ const toolsRegistry = ctx.tools;
30
+ let registeredTools = REGISTERED_TOOLS.get(toolsRegistry);
31
+ if (!registeredTools) {
32
+ registeredTools = new Set();
33
+ REGISTERED_TOOLS.set(toolsRegistry, registeredTools);
34
+ }
25
35
  const tools = [
26
36
  defineTool({
27
37
  name: "memory_save",
@@ -82,7 +92,18 @@ export function createTools(ctx, service, config, embedder) {
82
92
  }
83
93
  }
84
94
  },
85
- render: (_args, value) => TEXT_OUTPUT(`Found ${value.items.length} memory entr${value.items.length === 1 ? "y" : "ies"}.`)
95
+ render: (_args, value) => {
96
+ const items = value.items ?? [];
97
+ if (items.length === 0) return TEXT_OUTPUT("No memory entries found.");
98
+ const body = items
99
+ .map((m, i) => {
100
+ const preview = (m.content ?? "").replace(/\s+/g, " ").trim();
101
+ const cut = preview.length > 200 ? `${preview.slice(0, 200)}…` : preview;
102
+ return `[${i + 1}] ${m.title}\n ID: ${m.id} | type: ${m.type} | importance: ${m.importance} | updated: ${m.updated_at}\n ${cut}`;
103
+ })
104
+ .join("\n\n");
105
+ return TEXT_OUTPUT(`Found ${items.length} memory entr${items.length === 1 ? "y" : "ies"}:\n\n${body}`);
106
+ }
86
107
  },
87
108
  async execute(args) {
88
109
  const limit = args.limit ?? 20;
@@ -117,7 +138,14 @@ export function createTools(ctx, service, config, embedder) {
117
138
  total: { type: "integer", required: true }
118
139
  }
119
140
  },
120
- render: (_args, value) => TEXT_OUTPUT(`${value.items.length} memory entries (of ${value.total}).`)
141
+ render: (_args, value) => {
142
+ const items = value.items ?? [];
143
+ if (items.length === 0) return TEXT_OUTPUT(`0 memory entries (of ${value.total}).`);
144
+ const body = items
145
+ .map((m, i) => `[${i + 1}] ${m.title} (type=${m.type}, importance=${m.importance})\n ID: ${m.id} | updated: ${m.updated_at}`)
146
+ .join("\n\n");
147
+ return TEXT_OUTPUT(`${items.length} memory entries (of ${value.total}):\n\n${body}`);
148
+ }
121
149
  },
122
150
  async execute(args) {
123
151
  const includeArchived = args.include_archived === true;
@@ -131,6 +159,46 @@ export function createTools(ctx, service, config, embedder) {
131
159
  }
132
160
  }),
133
161
 
162
+ defineTool({
163
+ name: "memory_get",
164
+ description: "Fetch one memory entry by ID and return its full content as text. Use after memory_list to read a specific entry.",
165
+ parameters: {
166
+ id: { type: "string", required: true, description: "Memory id" }
167
+ },
168
+ output: {
169
+ schema: {
170
+ type: "object",
171
+ additionalProperties: false,
172
+ properties: {
173
+ memory: {
174
+ type: "object",
175
+ additionalProperties: false,
176
+ properties: {
177
+ id: { type: "string", required: true },
178
+ title: { type: "string", required: true },
179
+ type: { type: "string", required: true },
180
+ importance: { type: "integer", required: true },
181
+ tags: { type: "array", items: { type: "string" } },
182
+ content: { type: "string", required: true },
183
+ source: { type: "string" },
184
+ created_at: { type: "string" },
185
+ updated_at: { type: "string" }
186
+ }
187
+ }
188
+ }
189
+ },
190
+ render: (_args, value) => {
191
+ const m = value.memory;
192
+ return TEXT_OUTPUT(`${m.title}\nID: ${m.id} | type: ${m.type} | importance: ${m.importance}\n\n${m.content}`);
193
+ }
194
+ },
195
+ async execute(args) {
196
+ const memory = service.getById(args.id);
197
+ if (memory === undefined) throw new Error("memory not found");
198
+ return { memory: service.toApiList([memory])[0] };
199
+ }
200
+ }),
201
+
134
202
  defineTool({
135
203
  name: "memory_update",
136
204
  description: "Modify an existing memory entry (title, content, type, tags, importance).",
@@ -267,7 +335,12 @@ export function createTools(ctx, service, config, embedder) {
267
335
  ];
268
336
 
269
337
  for (const tool of tools) {
270
- ctx.tools.register(tool);
338
+ if (registeredTools.has(tool.name)) {
339
+ ctx.logger?.warn?.(`[dsh-mneme] tool "${tool.name}" already registered, skipping duplicate`);
340
+ continue;
341
+ }
342
+ registeredTools.add(tool.name);
343
+ ctx.tools.register(tool);
271
344
  }
272
345
 
273
346
  return tools;
@@ -235,7 +235,7 @@ test("better-sidebar tab mounts via an inner sub-plugin, standalone mode intact"
235
235
  "the inner apply must still guard the service shape before registering"
236
236
  );
237
237
  assert.ok(
238
- /id: "dsh-mneme:memory"/.test(clientSource),
238
+ /(?:const TAB_ID = |id: )"dsh-mneme:memory"/.test(clientSource),
239
239
  "the registered tab id must be package-prefixed"
240
240
  );
241
241
  assert.ok(
@@ -44,15 +44,15 @@ function walkSchema(node, path, problems) {
44
44
  }
45
45
  }
46
46
 
47
- test("registers seven tools with correct names", () => {
47
+ test("registers eight tools with correct names", () => {
48
48
  const { registered } = setup();
49
49
  const names = registered.map((t) => t.name).sort();
50
- assert.deepEqual(names, ["memory_archive", "memory_delete", "memory_forget", "memory_list", "memory_save", "memory_search", "memory_update"]);
50
+ assert.deepEqual(names, ["memory_archive", "memory_delete", "memory_forget", "memory_get", "memory_list", "memory_save", "memory_search", "memory_update"]);
51
51
  });
52
52
 
53
53
  test("compiled schemas pass the enforced DSH subset (defineTool projection)", () => {
54
54
  const { registered } = setup();
55
- assert.equal(registered.length, 7);
55
+ assert.equal(registered.length, 8);
56
56
  for (const tool of registered) {
57
57
  assertSupportedJsonSchema(tool.parameters);
58
58
  assertSupportedJsonSchema(tool.output.schema);
@@ -91,6 +91,57 @@ test("memory_search finds by CJK substring", async () => {
91
91
  assert.equal(result.items[0].title, "记忆插件");
92
92
  });
93
93
 
94
+ // Regression: memory_get.execute must live on the defineTool options (top
95
+ // level), NOT nested inside output — a misplaced execute silently becomes
96
+ // options.execute === undefined and every call throws "userExecute is not a
97
+ // function" while tests that only count tool names still pass.
98
+ test("memory_get returns the full body via execute and render", async () => {
99
+ const { registered, service } = setup();
100
+ const { memory } = service.saveWithDedupe({ type: "decision", title: "t", content: "完整正文内容" });
101
+ const get = registered.find((t) => t.name === "memory_get");
102
+ const res = await get.execute({ id: memory.id });
103
+ assert.equal(res.memory.id, memory.id);
104
+ assert.equal(res.memory.content, "完整正文内容");
105
+ assert.deepEqual(validateJsonSchemaValue(get.output.schema, res), []);
106
+ const text = get.output.render({}, res)[0].text;
107
+ assert.ok(text.includes("完整正文内容"), "full body in render");
108
+ assert.ok(text.includes(memory.id) && text.includes("t"), "id + title in render");
109
+ });
110
+
111
+ test("memory_get on missing id rejects", async () => {
112
+ const { registered } = setup();
113
+ const get = registered.find((t) => t.name === "memory_get");
114
+ await assert.rejects(() => get.execute({ id: "missing" }), /memory not found/);
115
+ });
116
+
117
+ // Render output is what hosts surface to the model (not the structured JSON),
118
+ // so it must embed titles + body previews, not just a hit count.
119
+ test("memory_search render embeds titles and body previews, not just a count", async () => {
120
+ const { registered, service } = setup();
121
+ service.saveWithDedupe({ type: "history", title: "旅行计划", content: "用户当前最苦恼时间安排与伦敦行程" });
122
+ service.saveWithDedupe({ type: "project", title: "插件定位", content: "dsh-mneme 插件做记忆沉淀" });
123
+ const search = registered.find((t) => t.name === "memory_search");
124
+ const res = await search.execute({ query: "时间" });
125
+ assert.ok(res.items.length >= 1, "search hit exists");
126
+ const text = search.output.render({}, res)[0].text;
127
+ assert.match(text, /Found \d+ memory entr/);
128
+ assert.ok(text.includes("旅行计划"), "title embedded in render");
129
+ assert.ok(text.includes("伦敦行程"), "body preview embedded in render");
130
+ assert.ok(text.includes("ID: "), "id embedded");
131
+ });
132
+
133
+ test("memory_list render embeds titles and ids, not just counts", async () => {
134
+ const { registered, service } = setup();
135
+ service.saveWithDedupe({ type: "preference", title: "昵称", content: "桉桉" });
136
+ service.saveWithDedupe({ type: "project", title: "博客", content: "modusensus" });
137
+ const list = registered.find((t) => t.name === "memory_list");
138
+ const res = await list.execute({});
139
+ const text = list.output.render({}, res)[0].text;
140
+ assert.match(text, /\d+ memory entries \(of \d+\):/);
141
+ assert.ok(text.includes("昵称") && text.includes("博客"), "titles embedded");
142
+ assert.ok(text.includes("ID: "), "ids embedded");
143
+ });
144
+
94
145
  test("memory_list filters by type", async () => {
95
146
  const { registered, service } = setup();
96
147
  service.saveWithDedupe({ type: "preference", title: "a", content: "x" });
@@ -0,0 +1,49 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { Context } from "@deepseek-ai/cordis";
4
+ import { mkdtempSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import * as mneme from "../lib/index.js";
8
+
9
+ // webServer 可选依赖回归(v0.7.24 修复):v0.7.23 曾把 webServer 从 inject 声明
10
+ // 中去掉想支持 headless,但 apply 里 `if (ctx.webServer)` 在 cordis 4 的 Proxy
11
+ // 下访问未注入属性会抛 "cannot get property without inject"(不会返回
12
+ // undefined),桌面端插件树直接加载失败。本测试用真实 cordis Context 复现两种
13
+ // 宿主形态,守住「有 webServer 时注册 API 路由 / 无 webServer 时不崩」两条底线。
14
+ //
15
+ // 修复后 webServer 保留在 inject(cordis 等待宿主服务就绪后再 apply,路由注册
16
+ // 不落时序),apply 守卫用 ctx.reflect.get 而非直接属性访问。headless 宿主
17
+ // 缺 webServer 时 fiber 静默不激活(与 v0.7.22 一致),不抛错。
18
+
19
+ function buildHost(withWebServer) {
20
+ const ctx = new Context();
21
+ const apiRoutes = [];
22
+ ctx.provide("tools", { register() { return () => {}; } });
23
+ ctx.provide("commands", { register() { return () => {}; } });
24
+ ctx.provide("systemPrompt", { context() { return () => {}; } });
25
+ ctx.provide("agentDefaultModel", { currentSelection() { return { provider: "mock", model: "mock" }; } });
26
+ ctx.provide("llm", {
27
+ async *stream() { yield { type: "finish", reason: { kind: "stop" } }; }
28
+ });
29
+ if (withWebServer) {
30
+ ctx.provide("webServer", { register(route) { apiRoutes.push(route); return () => {}; } });
31
+ }
32
+ return { ctx, apiRoutes };
33
+ }
34
+
35
+ test("desktop host (webServer present): plugin boots and registers API routes", async () => {
36
+ const { ctx, apiRoutes } = buildHost(true);
37
+ const fiber = ctx.plugin(mneme, { memoryDir: mkdtempSync(join(tmpdir(), "mneme-desk-")) });
38
+ await fiber;
39
+ assert.ok(apiRoutes.length > 0, "webServer routes must be registered on desktop");
40
+ assert.ok(apiRoutes.some((r) => r.kind === "exact"), "expect exact routes, got: " + apiRoutes.map((r) => r.kind).join(","));
41
+ });
42
+
43
+ test("headless host (no webServer): plugin must not throw", async () => {
44
+ const { ctx } = buildHost(false);
45
+ const fiber = ctx.plugin(mneme, { memoryDir: mkdtempSync(join(tmpdir(), "mneme-head-")) });
46
+ // INACTIVE fiber 静默等待依赖,fiber promise 不会 reject;只要不抛错即为通过。
47
+ await fiber;
48
+ assert.ok(true, "headless load must not throw");
49
+ });