dsh-memo-sync 2.74.9 → 2.76.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 +44 -7
- package/cordis.patch.yml +8 -1
- package/docs/DETAIL.md +4 -1
- package/index.js +413 -33
- package/index.json +6 -4
- package/package.json +4 -2
- package/scripts/gen-index.mjs +2 -2
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
> **默认不调用任何模型、不联网、无遥测**,也不需要在本机装本地模型或额外 API Key。
|
|
6
6
|
> 唯一的模型调用是「自动归纳成纪要」,**默认关闭**(`autoDigest: false`);要用时默认复用你已有的主模型,也可以单独指定本地小模型(见下文「摘要单独用哪个模型」)。
|
|
7
7
|
>
|
|
8
|
-
> 近版新增:**多会话在场**(v2.69,AGENTS 里一行「谁刚在动」)、**段索引**(v2.70,召回先筛后读,跳过 30~50% 的归档段)、**工具输出守卫**(v2.72,schema 缺字段降级为日志而不是工具坏掉)、**摘要可单独指定模型**(v2.73,支持本地/离线)、**索引状态自检**(v2.73.3,`
|
|
8
|
+
> 近版新增:**多会话在场**(v2.69,AGENTS 里一行「谁刚在动」)、**段索引**(v2.70,召回先筛后读,跳过 30~50% 的归档段)、**工具输出守卫**(v2.72,schema 缺字段降级为日志而不是工具坏掉)、**摘要可单独指定模型**(v2.73,支持本地/离线)、**索引状态自检**(v2.73.3)、**整条覆盖**(v2.75,`memo_supersede`,旧内容只留在备份里)、**摘要模型自动切换**(v2.76,本地可用走本地;本地挂了只有 owner 内容降级在线,群聊内容永不出本机)、**看门狗与熔断**(v2.76.1/2,超时先 abort 请求再冷却本地)、**日志轮转与索引自愈**(v2.76.3/4)。
|
|
9
9
|
|
|
10
10
|
把**目录式记忆**自动变成每次新会话都能读到的全局指令:
|
|
11
11
|
|
|
@@ -22,7 +22,7 @@ dsh plugin --profile web add dsh-memo-sync
|
|
|
22
22
|
也可以用 git 源装(不经过 npm,按 tag 锁版本):
|
|
23
23
|
|
|
24
24
|
```sh
|
|
25
|
-
dsh plugin --profile web add github:10110011-ling/dsh-memo-sync#v2.74.
|
|
25
|
+
dsh plugin --profile web add github:10110011-ling/dsh-memo-sync#v2.74.9
|
|
26
26
|
```
|
|
27
27
|
|
|
28
28
|
> `dsh plugin` 本质是把参数转发给 profile 里的 pnpm,所以 npm 包名、git 地址、本地 tarball 都能装。
|
|
@@ -118,9 +118,12 @@ _更早的变更记录已按月归档:`memo_read changelog-2026-10`_
|
|
|
118
118
|
|
|
119
119
|
依据是那期冷热记忆评测:冷热方案 356/714 输给直接检索 596/714,输在"细节被摘要掉"。所以我们**不做自动注入摘要**,只做「候选 + 出处」,让模型自己决定读哪一段。
|
|
120
120
|
|
|
121
|
-
##
|
|
121
|
+
## 多人场景的边界(v2.10)
|
|
122
122
|
|
|
123
|
-
|
|
123
|
+
> 这节讲的是**机制**:任何把"第二个人说的话"送进来的场景(群聊、协作会话、多用户频道)都能用。
|
|
124
|
+
> 具体怎么把某个平台接进来,属于平台适配工具的事,不在这里。
|
|
125
|
+
|
|
126
|
+
**机制先于承诺**:
|
|
124
127
|
|
|
125
128
|
- 明细 front matter 加 `visibility: private` → 目录页标题前带 🔒;`memo_append(..., visibility: "private")` 新建时生效
|
|
126
129
|
- `memo_recall(cue, audience: "group")`:**跳过 private 条目,且完全不搜 `.memo-archive/` 原话**(群里只给提炼过的共享记忆)
|
|
@@ -142,9 +145,9 @@ defaultAudience: group # 拿不到会话 id 时按这个(CLI 单机可设
|
|
|
142
145
|
|
|
143
146
|
规则一句话:**host 模式下 `audience` 入参被忽略**,命中白名单 → owner,其余 → group(私密条目整条不出现、原文不搜)。生效时日志会记一行 `privacy host-mode owners=…`,配错了能立刻看出来。
|
|
144
147
|
|
|
145
|
-
> 为什么默认还是 `arg`:本机单用户时按参数走更省事;只有"会有第二个人说话"
|
|
148
|
+
> 为什么默认还是 `arg`:本机单用户时按参数走更省事;只有"会有第二个人说话"的场合(群聊/多人频道)才需要真强制。
|
|
146
149
|
|
|
147
|
-
|
|
150
|
+
已知未做(等真接多人频道再补):稳定的 chat key(会话重建后记忆不散)、成员身份映射与 α 门控、外发前的二次确认闸门。
|
|
148
151
|
|
|
149
152
|
## 召回计数与星图(v2.5)
|
|
150
153
|
|
|
@@ -277,7 +280,13 @@ AGENTS.md 每个会话都注入,写坏了代价最高,所以同步不再「
|
|
|
277
280
|
| `autoDigest` | `false` | 自动归纳(唯一会调模型的开关) |
|
|
278
281
|
| `autoDigestMode` | `archive` | `archive`=会话归档时;`idle`=闲置兜底 |
|
|
279
282
|
| `digestProvider` / `digestModel` | 空 | 摘要单独用哪个模型(两个都填才生效,v2.73) |
|
|
280
|
-
| `
|
|
283
|
+
| `modelRoute` | 空 | 本地/在线自动切换:`auto` / `local` / `cloud`;空=旧行为(v2.76) |
|
|
284
|
+
| `localProbeUrl` | `http://127.0.0.1:11434` | 本地模型探活地址(ollama `/api/tags`) |
|
|
285
|
+
| `localProvider` / `localModel` | 空 | 本地模型;默认沿用 `digestProvider` / `digestModel` |
|
|
286
|
+
| `digestTimeoutMs` | `120000` | 单次模型调用的看门狗;超时按失败处理(v2.76.1) |
|
|
287
|
+
| `logMaxBytes` | `2000000` | 运行日志超过上限就轮转到 `memo-sync.log.1`(只留一代,v2.76.3) |
|
|
288
|
+
| `digestCooldownMs` | `300000` | 本地卡死后暂停本地路由的时长(5 分钟) |
|
|
289
|
+
| `privacyMode` | `arg` | `host` 才按会话强制私密(接群聊/多人频道前必看) |
|
|
281
290
|
| `presenceTopics` | `true` | 在场表是否写「在干什么」 |
|
|
282
291
|
| `backup` | `false` | 归档后原样冷备份会话日志 |
|
|
283
292
|
|
|
@@ -393,6 +402,34 @@ digestModel: qwen2.5:14b # 例如本地 14B
|
|
|
393
402
|
|
|
394
403
|
> 判断依据:摘要是后台批处理,天然适合便宜/本地模型;主对话需要质量,维持云端。
|
|
395
404
|
|
|
405
|
+
### 本地 / 在线自动切换(v2.76)
|
|
406
|
+
|
|
407
|
+
摘要模型可以按环境自动切,不必手工改配置:
|
|
408
|
+
|
|
409
|
+
```yaml
|
|
410
|
+
modelRoute: auto # 留空=不启用(旧行为);auto | local | cloud
|
|
411
|
+
localProbeUrl: 'http://127.0.0.1:11434' # 探 ollama /api/tags,1.5s 超时
|
|
412
|
+
localProvider: ollama # 默认沿用 digestProvider
|
|
413
|
+
localModel: qwen2.5:7b-instruct # 默认沿用 digestModel
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
| 情况 | `auto` | `local` | `cloud` |
|
|
417
|
+
| --- | --- | --- | --- |
|
|
418
|
+
| 本地可用 | 走本地 | 走本地 | 走在线 |
|
|
419
|
+
| 本地挂了 · `audience=owner` | 降级在线 | 拦截(不降级) | 走在线 |
|
|
420
|
+
| 本地挂了 · `audience=group` | 拦截 | 拦截 | 拦截 |
|
|
421
|
+
|
|
422
|
+
- **群聊/多人内容永远不出本机**:`audience=group` 或不带 owner 声明的会话只走本地,本地不可用就跳过,不回退在线;这条硬规则不受 `modelRoute` 影响。
|
|
423
|
+
- 本地调用中途失败(连接错误/超时/空返回)时,**owner 内容**会降级在线一次并记 `route-fallback`;group 内容不降级。
|
|
424
|
+
- 探活只读 `/api/tags`,不跑真实生成;每次决策打一行 `route route=… audience=… provider=… model=…`,拦截时打 `route-blocked reason=…`。
|
|
425
|
+
- 改 `modelRoute` 不用重启:设置 → 插件里停用再启用即可(会重新执行 `apply`)。
|
|
426
|
+
|
|
427
|
+
### 卡死与备份顺序(v2.76.1)
|
|
428
|
+
|
|
429
|
+
- **看门狗**:每次模型调用最多 `digestTimeoutMs`(默认 120s)。超时先 `AbortController.abort()`(DSH 的 pi-ai provider 认 `options.signal`,会真的断开 HTTP → ollama 停止生成),再 `iterator.return()` 兜底,最后按失败处理:owner 内容切在线、group 内容记失败并退避重试。
|
|
430
|
+
- **熔断**:本地卡死/报错后,本地路由冷却 `digestCooldownMs`(默认 5 分钟)——冷却期内 `auto` 直接把本地当不可用(owner 走在线、group 跳过),免得下一个块又撞进去。
|
|
431
|
+
- **备份不受卡死影响**:每一轮归档先把**所有**待摘要会话的原话导出(`.memo-archive/`,幂等),再逐个调模型。所以模型卡死时,丢的只是「纪要」这一层,原话和冷备份(`~/.dsh/memo-backups`,独立定时器)都照常落盘。
|
|
432
|
+
|
|
396
433
|
## 原文归档(v2.3)
|
|
397
434
|
|
|
398
435
|
摘要再长也是单向变换。所以每次归纳时,把那段对话的**原话**一起落到工作区,纪要里只留入口:
|
package/cordis.patch.yml
CHANGED
|
@@ -37,7 +37,14 @@
|
|
|
37
37
|
# digestProvider: ollama # 想省钱/离线就指向本地
|
|
38
38
|
# digestModel: qwen2.5:7b
|
|
39
39
|
|
|
40
|
-
# ──
|
|
40
|
+
# ── 本地/在线自动切换(v2.76,留空=旧行为)────────
|
|
41
|
+
# modelRoute: 'auto' # auto=本地可用走本地;local=只用本地;cloud=只走在线
|
|
42
|
+
# localProbeUrl: 'http://127.0.0.1:11434'
|
|
43
|
+
# localProvider: ollama # 默认沿用 digestProvider
|
|
44
|
+
# localModel: qwen2.5:7b-instruct # 默认沿用 digestModel
|
|
45
|
+
# 硬规则:audience=group(群聊/多人)的内容永不出本机,本地不可用就跳过
|
|
46
|
+
|
|
47
|
+
# ── 隐私口径(接群聊/多人频道之前必看)─────────────
|
|
41
48
|
# privacyMode: 'arg' # arg=按调用方声明(旧行为);host=按会话强制
|
|
42
49
|
# ownerSessions: '' # host 模式的主人会话 id(逗号分隔或数组)
|
|
43
50
|
# defaultAudience: 'group' # 未声明时的默认受众
|
package/docs/DETAIL.md
CHANGED
|
@@ -83,4 +83,7 @@ AGENTS.md 每个会话都注入,写坏了代价最高。所以同步不是「
|
|
|
83
83
|
- **注入有预算**:目录页超过 `maxBytes`(默认 8 KB)时整条跳过,优先保留最新的条目,末尾**列出没注入的 id**(v2.69.1 起,直接 `memo_read <id>` 取)——不是坏了,是装不下。
|
|
84
84
|
- **摘要质量取决于模型**:长会话(十几万字符)可能撞输出预算,日志里是 `digest-budget-wall`;原话导出排在调模型之前,模型挂了不丢原文。
|
|
85
85
|
- **摘要不自动触发**:`autoDigest` 的 `archive` 模式只认「会话归档」;会话一直开着就不会有当天纪要,除非手动 `memo_digest` 或改成 `idle` 模式。
|
|
86
|
-
-
|
|
86
|
+
- **本地/在线自动切换(v2.76)**:`modelRoute: auto` 每 30s 探一次本地 ollama(`/api/tags`,1.5s 超时);本地挂了只让 owner 内容降级在线,`audience=group` 的内容永远不出本机、本地不可用就跳过。日志里看 `route route=…` / `route-blocked reason=…` / `route-fallback`。
|
|
87
|
+
- **日志与段索引维护(v2.76.3)**:`memo-sync.log` 超过 `logMaxBytes`(默认 2 MB)自动轮转到 `.1`,只留一代;空闲维护每 10 分钟顺手修一次过期的段索引(`index-healed=N`),`memo_index status` 不会再长期显示脏。
|
|
88
|
+
- **看门狗与备份顺序(v2.76.1/v2.76.2)**:单次模型调用超过 `digestTimeoutMs`(默认 120s)就 abort 请求(provider 认 `options.signal`,会断开 HTTP,ollama 随即停止生成)并抛 `model-timeout`,落在失败分支(owner 切在线、group 退避重试);随后本地路由冷却 `digestCooldownMs`(默认 5 分钟,日志 `route-cooling`)。归档轮询改成两段:先把本轮所有待摘要会话的原话导出(幂等),再逐个摘要——模型卡死只丢纪要,不丢原话。
|
|
89
|
+
- **手记与在场只服务单机**:接群聊/多人频道之前必须先把 `privacyMode` 切成 `host` 并配白名单,否则私密只靠调用方自觉。
|
package/index.js
CHANGED
|
@@ -63,7 +63,7 @@ function layerOf(raw) {
|
|
|
63
63
|
return LAYERS[k] ? k : '';
|
|
64
64
|
}
|
|
65
65
|
/** 构建标记:用来确认运行中的插件是不是当前这份代码。 */
|
|
66
|
-
const BUILD = '2.
|
|
66
|
+
const BUILD = '2.76.4+heal-fix';
|
|
67
67
|
|
|
68
68
|
export const inject = ['tools'];
|
|
69
69
|
|
|
@@ -278,6 +278,49 @@ function stamp() {
|
|
|
278
278
|
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
279
279
|
}
|
|
280
280
|
|
|
281
|
+
/** 备份文件名:精确到秒;同一秒里连写两次就加 -2、-3,连改不能互相覆盖。 */
|
|
282
|
+
function backupName(root, id) {
|
|
283
|
+
const d = new Date();
|
|
284
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
285
|
+
const base = `${id}-${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
|
286
|
+
let file = path.join(root, BANKUP_DIR, `${base}.md`);
|
|
287
|
+
for (let i = 2; fs.existsSync(file); i += 1) file = path.join(root, BANKUP_DIR, `${base}-${i}.md`);
|
|
288
|
+
return file;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* 给条目备份正文;和这个条目最新一份备份内容一样就不重复写(省盘、不丢信息)。
|
|
293
|
+
* 复用时把旧备份 mtime 刷新一下,免得被 pruneBackups 当成过期清掉。
|
|
294
|
+
* shortcut: 只和「最新一份」比;更早的重复不管(30 天后照常清)。
|
|
295
|
+
*/
|
|
296
|
+
function backupEntryLatest(root, id, raw) {
|
|
297
|
+
const dir = path.join(root, BANKUP_DIR);
|
|
298
|
+
let latest = '';
|
|
299
|
+
let latestMs = 0;
|
|
300
|
+
try {
|
|
301
|
+
for (const name of fs.readdirSync(dir)) {
|
|
302
|
+
if (!name.startsWith(id + '-') || !name.endsWith('.md')) continue;
|
|
303
|
+
const file = path.join(dir, name);
|
|
304
|
+
try {
|
|
305
|
+
const st = fs.statSync(file);
|
|
306
|
+
if (st.mtimeMs > latestMs) { latestMs = st.mtimeMs; latest = file; }
|
|
307
|
+
} catch {}
|
|
308
|
+
}
|
|
309
|
+
} catch {}
|
|
310
|
+
if (latest) {
|
|
311
|
+
try {
|
|
312
|
+
if (fs.readFileSync(latest, 'utf8') === raw) {
|
|
313
|
+
const now = new Date();
|
|
314
|
+
fs.utimesSync(latest, now, now);
|
|
315
|
+
return latest;
|
|
316
|
+
}
|
|
317
|
+
} catch {}
|
|
318
|
+
}
|
|
319
|
+
const file = backupName(root, id);
|
|
320
|
+
try { writeAtomic(file, raw); } catch {}
|
|
321
|
+
return file;
|
|
322
|
+
}
|
|
323
|
+
|
|
281
324
|
function slugify(text) {
|
|
282
325
|
return String(text ?? '')
|
|
283
326
|
.trim()
|
|
@@ -1238,10 +1281,7 @@ export function editEntry(options = {}) {
|
|
|
1238
1281
|
}
|
|
1239
1282
|
const replace = String(options.replace ?? '');
|
|
1240
1283
|
const root = options.root || path.dirname(memoPath);
|
|
1241
|
-
const backupFile =
|
|
1242
|
-
try {
|
|
1243
|
-
writeAtomic(backupFile, raw);
|
|
1244
|
-
} catch {}
|
|
1284
|
+
const backupFile = backupEntryLatest(root, entry.id, raw);
|
|
1245
1285
|
const next = raw.split(find).join(replace);
|
|
1246
1286
|
writeAtomic(entry.file, next);
|
|
1247
1287
|
const pruned = pruneBackups(root);
|
|
@@ -1259,6 +1299,53 @@ export function editEntry(options = {}) {
|
|
|
1259
1299
|
};
|
|
1260
1300
|
}
|
|
1261
1301
|
|
|
1302
|
+
/**
|
|
1303
|
+
* 整条覆盖:用新事实替换旧内容,而不是"再追加一条更正"。
|
|
1304
|
+
* 为什么需要:只追加会让旧结论继续被检索到,越攒越脏("已在跑"和"已暂停"同时躺在一条里)。
|
|
1305
|
+
* 行为:备份旧文件 → 重写正文 → front-matter 记 updated 日期;旧内容只在备份里,条目本身干净。
|
|
1306
|
+
* shortcut: 只认 markdown 全文件;不合并、不 diff,覆盖就是覆盖。
|
|
1307
|
+
*/
|
|
1308
|
+
export function supersedeEntry(options = {}) {
|
|
1309
|
+
const memoPath = options.memoPath || defaultMemoPath();
|
|
1310
|
+
const memoDir = options.memoDir || defaultDirFor(memoPath);
|
|
1311
|
+
const audience = String(options.audience ?? 'owner').toLowerCase() === 'group' ? 'group' : 'owner';
|
|
1312
|
+
const entries = listEntries(memoDir);
|
|
1313
|
+
const entry = resolveEntry(entries, options.query);
|
|
1314
|
+
if (!entry) return { ok: false, found: false, changed: false, reason: 'no-entry' };
|
|
1315
|
+
if (audience === 'group' && entry.visibility === 'private') {
|
|
1316
|
+
return { ok: false, found: false, changed: false, private: true, id: entry.id, title: entry.title };
|
|
1317
|
+
}
|
|
1318
|
+
const body = String(options.body ?? '').trim();
|
|
1319
|
+
if (!body) return { ok: false, found: true, changed: false, id: entry.id, title: entry.title, reason: 'body-empty' };
|
|
1320
|
+
|
|
1321
|
+
const raw = readIfExists(entry.file) ?? '';
|
|
1322
|
+
const root = options.root || path.dirname(memoPath);
|
|
1323
|
+
const backupFile = backupEntryLatest(root, entry.id, raw);
|
|
1324
|
+
|
|
1325
|
+
// 保留原 front-matter 的其余键,只换 title / updated
|
|
1326
|
+
const fmMatch = /^---\n([\s\S]*?)\n---\n?/.exec(raw);
|
|
1327
|
+
const fmLines = (fmMatch?.[1] ?? '').split('\n').filter(Boolean);
|
|
1328
|
+
const title = String(options.title ?? '').trim() || entry.title;
|
|
1329
|
+
const today = new Date();
|
|
1330
|
+
const ymd = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
|
|
1331
|
+
const kept = fmLines.filter((l) => !/^(title|updated)\s*:/.test(l));
|
|
1332
|
+
const front = ['---', `title: ${title}`, ...kept, `updated: ${ymd}`, '---', ''].join('\n');
|
|
1333
|
+
const next = `${front}# ${title}\n\n${body}\n`;
|
|
1334
|
+
writeAtomic(entry.file, next);
|
|
1335
|
+
const pruned = pruneBackups(root);
|
|
1336
|
+
return {
|
|
1337
|
+
ok: true,
|
|
1338
|
+
found: true,
|
|
1339
|
+
changed: true,
|
|
1340
|
+
id: entry.id,
|
|
1341
|
+
title,
|
|
1342
|
+
backup: (path.relative(root, backupFile) || backupFile).replace(/\\/g, '/'),
|
|
1343
|
+
bytesBefore: Buffer.byteLength(raw, 'utf8'),
|
|
1344
|
+
bytesAfter: Buffer.byteLength(next, 'utf8'),
|
|
1345
|
+
...(pruned ? { prunedBackups: pruned } : {}),
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1262
1349
|
/** 清掉过期的编辑备份(默认 30 天),避免 .memo-bankups/ 只增不减。shortcut: 只按 mtime 清理,不动非 .md。 */
|
|
1263
1350
|
export function pruneBackups(root, maxAgeMs = 30 * 86400000) {
|
|
1264
1351
|
const dir = path.join(root, BANKUP_DIR);
|
|
@@ -1459,7 +1546,7 @@ const MEMO_APPEND = {
|
|
|
1459
1546
|
text: { type: 'string', description: '一条要点,写成一句话。例如「停掉 SurfCore 桥接,开关在 ~/.dsh/surfcore/config.json 的 platforms.start.qq=false」。' },
|
|
1460
1547
|
topic: { type: 'string', description: '写进哪一条明细:用目录里的 id(如 qq / todo / paths),或一个不存在的新主题名(会自动新建一条)。默认 changelog。' },
|
|
1461
1548
|
layer: { type: 'string', description: '可选(仅新建条目时生效):core / fact / skill / daily / emotion。写「她自己的感受、关系、没解决的事」用 emotion。' },
|
|
1462
|
-
visibility: { type: 'string', description: '可选(仅新建条目时生效):private = 只给主人看,memo_recall 的 audience="group"
|
|
1549
|
+
visibility: { type: 'string', description: '可选(仅新建条目时生效):private = 只给主人看,memo_recall 的 audience="group" 会跳过它(群聊/多人频道用)。默认 shared。' },
|
|
1463
1550
|
tags: { type: 'string', description: '可选(仅新建条目时生效):关键词,逗号分隔,便于 memo_recall 命中。' },
|
|
1464
1551
|
scope: { type: 'string', description: '可选(仅新建条目时生效):world / topic:名 / file:路径 / session:会话id。file: 开头的条目只在会话碰过该文件时优先召回。' },
|
|
1465
1552
|
importance: { type: 'string', enum: ['high', 'normal'], description: '可选:high = 重要事件(行首标 ★,变更记录里一眼可分);normal = 普通流水,默认。' },
|
|
@@ -1630,6 +1717,62 @@ const MEMO_EDIT = {
|
|
|
1630
1717
|
},
|
|
1631
1718
|
};
|
|
1632
1719
|
|
|
1720
|
+
const MEMO_SUPERSEDE = {
|
|
1721
|
+
name: 'memo_supersede',
|
|
1722
|
+
description:
|
|
1723
|
+
'整条覆盖一条记忆:用现在的事实替换旧内容(不是再追加一条更正)。改前自动备份到 .memo-bankups/,旧内容只在备份里,条目本身保持干净。适合「状态变了」「结论被推翻」这类——追加会让"已停止"和"已在跑"同时留在同一条里,检索到哪个都像真的。',
|
|
1724
|
+
parameters: {
|
|
1725
|
+
type: 'object',
|
|
1726
|
+
properties: {
|
|
1727
|
+
query: { type: 'string', description: '条目 id、序号或关键词。' },
|
|
1728
|
+
title: { type: 'string', description: '新标题(省略 = 保留原标题)。' },
|
|
1729
|
+
body: { type: 'string', description: '新正文(markdown,省略标题行);会整体替换旧正文。' },
|
|
1730
|
+
audience: { type: 'string', description: 'owner(默认)/ group(组模式拒绝私密条目)。' },
|
|
1731
|
+
},
|
|
1732
|
+
required: ['query', 'body'],
|
|
1733
|
+
additionalProperties: false,
|
|
1734
|
+
},
|
|
1735
|
+
output: {
|
|
1736
|
+
schema: {
|
|
1737
|
+
type: 'object',
|
|
1738
|
+
additionalProperties: false,
|
|
1739
|
+
properties: {
|
|
1740
|
+
ok: { type: 'boolean' },
|
|
1741
|
+
found: { type: 'boolean' },
|
|
1742
|
+
changed: { type: 'boolean' },
|
|
1743
|
+
id: { type: 'string' },
|
|
1744
|
+
title: { type: 'string' },
|
|
1745
|
+
reason: { type: 'string' },
|
|
1746
|
+
backup: { type: 'string' },
|
|
1747
|
+
bytesBefore: { type: 'number' },
|
|
1748
|
+
bytesAfter: { type: 'number' },
|
|
1749
|
+
},
|
|
1750
|
+
},
|
|
1751
|
+
render: (_args, v) => {
|
|
1752
|
+
if (!v?.ok) {
|
|
1753
|
+
const why = v?.reason === 'no-entry' ? '没找到这条' : v?.reason === 'body-empty' ? 'body 不能为空' : v?.reason || '没改成';
|
|
1754
|
+
return [{ type: 'text', text: why }];
|
|
1755
|
+
}
|
|
1756
|
+
return [{ type: 'text', text: `已覆盖 ${v.id}(${v.bytesBefore} → ${v.bytesAfter} B),旧内容备份在 ${v.backup}` }];
|
|
1757
|
+
},
|
|
1758
|
+
},
|
|
1759
|
+
async execute(args, exec) {
|
|
1760
|
+
const r = supersedeEntry({
|
|
1761
|
+
query: args?.query,
|
|
1762
|
+
title: args?.title,
|
|
1763
|
+
body: args?.body,
|
|
1764
|
+
memoPath: syncRefs.memoPath,
|
|
1765
|
+
memoDir: syncRefs.memoDir,
|
|
1766
|
+
audience: resolveAudience(args, exec),
|
|
1767
|
+
});
|
|
1768
|
+
if (!r.ok) return { ok: false, found: r.found !== false, changed: false, ...(r.id ? { id: r.id } : {}), ...(r.reason ? { reason: r.reason } : {}) };
|
|
1769
|
+
syncOnce({ memoPath: syncRefs.memoPath, memoDir: syncRefs.memoDir, agentsPath: syncRefs.agentsPath, maxBytes: syncRefs.maxBytes });
|
|
1770
|
+
// 只回 schema 里有的字段(多一个宿主就判 invalid)
|
|
1771
|
+
const { prunedBackups, ...out } = r;
|
|
1772
|
+
return out;
|
|
1773
|
+
},
|
|
1774
|
+
};
|
|
1775
|
+
|
|
1633
1776
|
const MEMO_READ = {
|
|
1634
1777
|
name: 'memo_read',
|
|
1635
1778
|
description:
|
|
@@ -3223,7 +3366,7 @@ export function recallByCue({ memoDir, archiveDir, cue, limit = 3, includeArchiv
|
|
|
3223
3366
|
const MEMO_RECALL = {
|
|
3224
3367
|
name: 'memo_recall',
|
|
3225
3368
|
description:
|
|
3226
|
-
'按线索(人 / 时间 / 地点 / 话题 / 「那件事」)找回相关记忆:先查明细(标题、关键词、正文),再去 .memo-archive/ 原话里找带出处的片段。两段式:全部关键词命中记 exact,只命中一部分记 fallback(如实标注,不假装命中);7 天内推过的条目默认不再出现。audience="group" 时只返回 shared
|
|
3369
|
+
'按线索(人 / 时间 / 地点 / 话题 / 「那件事」)找回相关记忆:先查明细(标题、关键词、正文),再去 .memo-archive/ 原话里找带出处的片段。两段式:全部关键词命中记 exact,只命中一部分记 fallback(如实标注,不假装命中);7 天内推过的条目默认不再出现。audience="group" 时只返回 shared 条目、且不翻原话(群聊/多人频道用)。只返回少量候选,不整段倒出。',
|
|
3227
3370
|
parameters: {
|
|
3228
3371
|
type: 'object',
|
|
3229
3372
|
properties: {
|
|
@@ -3665,6 +3808,39 @@ export function rebuildSegIndex(memoDir, archiveDir) {
|
|
|
3665
3808
|
return { ok: true, segments: segs, indexFiles: Object.keys(idx.files).length, indexBytes: bytes };
|
|
3666
3809
|
}
|
|
3667
3810
|
|
|
3811
|
+
/**
|
|
3812
|
+
* 只修过期/缺失的段索引条目(不改别的),让 memo_index status 不再长期显示脏。
|
|
3813
|
+
* 召回时本来也会懒修,这里只是让「没有召回时」也能落到磁盘上。
|
|
3814
|
+
*/
|
|
3815
|
+
export function healSegIndex(memoDir, archiveDir) {
|
|
3816
|
+
const idx = readSegIndex(memoDir);
|
|
3817
|
+
let seen = 0;
|
|
3818
|
+
let fixed = 0;
|
|
3819
|
+
try {
|
|
3820
|
+
for (const s8 of fs.readdirSync(archiveDir)) {
|
|
3821
|
+
if (!/^[0-9a-f]{6,12}$/i.test(s8)) continue;
|
|
3822
|
+
const dir = path.join(archiveDir, s8);
|
|
3823
|
+
let names = [];
|
|
3824
|
+
try { names = fs.readdirSync(dir); } catch { continue; }
|
|
3825
|
+
for (const f of names) {
|
|
3826
|
+
if (!/^\d{2}\.md$/.test(f)) continue;
|
|
3827
|
+
const file = path.join(dir, f);
|
|
3828
|
+
let st;
|
|
3829
|
+
try { st = fs.statSync(file); } catch { continue; }
|
|
3830
|
+
seen += 1;
|
|
3831
|
+
const cur = idx.files[file];
|
|
3832
|
+
if (cur && cur.mtime === st.mtimeMs && cur.size === st.size) continue;
|
|
3833
|
+
let text = '';
|
|
3834
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { continue; }
|
|
3835
|
+
idx.files[file] = { mtime: st.mtimeMs, size: st.size, tokens: segTokens(text) };
|
|
3836
|
+
fixed += 1;
|
|
3837
|
+
}
|
|
3838
|
+
}
|
|
3839
|
+
} catch {}
|
|
3840
|
+
if (fixed) writeSegIndex(memoDir, idx);
|
|
3841
|
+
return { seen, fixed };
|
|
3842
|
+
}
|
|
3843
|
+
|
|
3668
3844
|
const MEMO_INDEX = {
|
|
3669
3845
|
name: 'memo_index',
|
|
3670
3846
|
description:
|
|
@@ -3938,6 +4114,119 @@ export function resolveDigestModel(digestCfg, sel, opts) {
|
|
|
3938
4114
|
return { provider: String(sel?.provider || '').trim(), model: String(sel?.model || '').trim(), source: 'default' };
|
|
3939
4115
|
}
|
|
3940
4116
|
|
|
4117
|
+
// ---------------------------------------------------------------- 模型路由(v2.76)
|
|
4118
|
+
/**
|
|
4119
|
+
* 本地模型 / 在线 API 自由切换。只属于本插件,不知道谁在调用(QQ 那层只是传 audience 的客户端)。
|
|
4120
|
+
* 硬规则先于配置:audience=group(别人说的话)永远不发给在线 API。
|
|
4121
|
+
* 配置:
|
|
4122
|
+
* modelRoute: ''(默认,保持旧行为:静态 digestProvider/digestModel)
|
|
4123
|
+
* | 'auto' 本地可用走本地;本地挂了只有 owner 才降级到在线
|
|
4124
|
+
* | 'local' 只用本地,本地挂了就 blocked,不降级
|
|
4125
|
+
* | 'cloud' 只走在线,group 内容 blocked
|
|
4126
|
+
* localProbeUrl 默认 http://127.0.0.1:11434(探 ollama /api/tags)
|
|
4127
|
+
* localProvider / localModel 本地模型;默认沿用 digestProvider / digestModel
|
|
4128
|
+
* shortcut: 只用 /api/tags 探活(1.5s),不跑真实生成;切 modelRoute 要重启 DSH(注册时读一次)。
|
|
4129
|
+
*/
|
|
4130
|
+
const ROUTE = { mode: '', probeUrl: 'http://127.0.0.1:11434', localProvider: '', localModel: '', timeoutMs: 120_000, cooldownMs: 300_000 };
|
|
4131
|
+
const PROBE = { url: '', at: 0, ok: false, models: [] };
|
|
4132
|
+
/** 本地模型卡死后的冷却:冷却期内 local 一律视为不可用(auto 下 owner 走在线、group 跳过)。 */
|
|
4133
|
+
const COOL = { until: 0, reason: '' };
|
|
4134
|
+
function localCooling(now = Date.now()) { return now < COOL.until; }
|
|
4135
|
+
function coolLocal(ms, reason) {
|
|
4136
|
+
COOL.until = Date.now() + ms;
|
|
4137
|
+
COOL.reason = reason;
|
|
4138
|
+
note(`route-cooling ms=${ms} reason=${reason}`);
|
|
4139
|
+
}
|
|
4140
|
+
|
|
4141
|
+
/** 路由决策(纯函数,便于自检):local / cloud / blocked。 */
|
|
4142
|
+
export function decideRoute({ mode, audience, localOk, hasLocalModel }) {
|
|
4143
|
+
const aud = String(audience || 'owner').toLowerCase() === 'group' ? 'group' : 'owner';
|
|
4144
|
+
const m = String(mode || '').toLowerCase();
|
|
4145
|
+
if (!m) return { route: 'cloud', reason: 'route-off' };
|
|
4146
|
+
const local = Boolean(localOk && hasLocalModel);
|
|
4147
|
+
if (m === 'local') return local ? { route: 'local' } : { route: 'blocked', reason: 'local-down' };
|
|
4148
|
+
if (m === 'cloud') {
|
|
4149
|
+
return aud === 'owner' ? { route: 'cloud' } : { route: 'blocked', reason: 'group-content-local-only' };
|
|
4150
|
+
}
|
|
4151
|
+
if (local) return { route: 'local' };
|
|
4152
|
+
return aud === 'owner' ? { route: 'cloud', reason: 'local-down' } : { route: 'blocked', reason: 'local-down-group-content' };
|
|
4153
|
+
}
|
|
4154
|
+
|
|
4155
|
+
/** 探本地模型:/api/tags 成功且有模型才算可用;成功缓存 30s、失败 10s。 */
|
|
4156
|
+
export async function probeLocalModel({ url = ROUTE.probeUrl, timeoutMs = 1500 } = {}) {
|
|
4157
|
+
const now = Date.now();
|
|
4158
|
+
const base = String(url || '').replace(/\/+$/, '');
|
|
4159
|
+
const ttl = PROBE.ok ? 30_000 : 10_000;
|
|
4160
|
+
if (PROBE.url === base && now - PROBE.at < ttl) return { ok: PROBE.ok, models: PROBE.models, cached: true };
|
|
4161
|
+
let models = [];
|
|
4162
|
+
let ok = false;
|
|
4163
|
+
try {
|
|
4164
|
+
const res = await fetch(base + '/api/tags', { signal: AbortSignal.timeout(timeoutMs) });
|
|
4165
|
+
if (res.ok) {
|
|
4166
|
+
const data = await res.json();
|
|
4167
|
+
models = (data?.models || []).map((m) => String(m?.name || '')).filter(Boolean);
|
|
4168
|
+
ok = models.length > 0;
|
|
4169
|
+
}
|
|
4170
|
+
} catch {}
|
|
4171
|
+
PROBE.url = base; PROBE.at = now; PROBE.ok = ok; PROBE.models = models;
|
|
4172
|
+
return { ok, models, cached: false };
|
|
4173
|
+
}
|
|
4174
|
+
|
|
4175
|
+
/** 会话归属:host 模式按 ownerSessions 判,arg 模式本机单用户一律 owner。 */
|
|
4176
|
+
export function sessionAudience(sessionId, cfg = PRIVACY) {
|
|
4177
|
+
if (String(cfg.mode || 'arg').toLowerCase() !== 'host') return 'owner';
|
|
4178
|
+
const sid = String(sessionId || '');
|
|
4179
|
+
const owners = (Array.isArray(cfg.ownerSessions) ? cfg.ownerSessions : String(cfg.ownerSessions ?? '').split(/[,\s]+/)).map(String).filter(Boolean);
|
|
4180
|
+
if (!sid) return String(cfg.defaultAudience || 'group').toLowerCase() === 'owner' ? 'owner' : 'group';
|
|
4181
|
+
return owners.some((p) => sid.startsWith(p)) ? 'owner' : 'group';
|
|
4182
|
+
}
|
|
4183
|
+
|
|
4184
|
+
/**
|
|
4185
|
+
* 把一次 llm.stream 读干:返回正文与 finish 原因;流里报错直接抛。
|
|
4186
|
+
* timeoutMs > 0 时是看门狗:超时先调 iterator.return() 让 provider 尽量 abort,再抛 model-timeout。
|
|
4187
|
+
* shortcut: provider 若不理会 return(),后台可能还在生成;靠 route-cooling 别再撞进去。
|
|
4188
|
+
*/
|
|
4189
|
+
export async function drainStream(llm, args, timeoutMs = 0) {
|
|
4190
|
+
// DSH 的 provider(pi-ai 系)认 options.signal:abort 会真的断开 HTTP,
|
|
4191
|
+
// ollama 侧看到客户端断连就停止生成(实测:断连后 6 秒内无新 token、小请求 0.2s 返回)。
|
|
4192
|
+
const controller = timeoutMs > 0 ? new AbortController() : null;
|
|
4193
|
+
const stream = llm.stream(controller ? { ...args, signal: controller.signal } : args);
|
|
4194
|
+
const it = typeof stream?.[Symbol.asyncIterator] === "function"
|
|
4195
|
+
? stream[Symbol.asyncIterator]()
|
|
4196
|
+
: { next: async () => ({ done: true, value: undefined }), return: async () => ({ done: true, value: undefined }) };
|
|
4197
|
+
let out = "";
|
|
4198
|
+
let finishKind = "";
|
|
4199
|
+
let timer = null;
|
|
4200
|
+
const timeout = timeoutMs > 0
|
|
4201
|
+
? new Promise((_, reject) => {
|
|
4202
|
+
timer = setTimeout(() => {
|
|
4203
|
+
try { controller.abort(); } catch {}
|
|
4204
|
+
try { it.return?.(); } catch {}
|
|
4205
|
+
reject(new Error(`model-timeout:${timeoutMs}ms`));
|
|
4206
|
+
}, timeoutMs);
|
|
4207
|
+
// 不 unref:事件循环空了(典型是 CLI 自检)也要让看门狗到点 fire
|
|
4208
|
+
})
|
|
4209
|
+
: null;
|
|
4210
|
+
try {
|
|
4211
|
+
while (true) {
|
|
4212
|
+
const step = await (timeout ? Promise.race([it.next(), timeout]) : it.next());
|
|
4213
|
+
if (!step || step.done) break;
|
|
4214
|
+
const chunk = step.value;
|
|
4215
|
+
if (!chunk) continue;
|
|
4216
|
+
if (chunk.type === "text-delta" && chunk.text) out += chunk.text;
|
|
4217
|
+
if (chunk.type === "finish") {
|
|
4218
|
+
finishKind = String(chunk.reason?.kind || finishKind || "");
|
|
4219
|
+
if (chunk.reason?.kind === "error") {
|
|
4220
|
+
throw new Error(chunk.reason?.failure?.message || "模型调用失败");
|
|
4221
|
+
}
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
4224
|
+
} finally {
|
|
4225
|
+
if (timer) clearTimeout(timer);
|
|
4226
|
+
}
|
|
4227
|
+
return { out, finishKind };
|
|
4228
|
+
}
|
|
4229
|
+
|
|
3941
4230
|
async function summarize(ctx, text, opts = {}) {
|
|
3942
4231
|
if (!ctx || typeof ctx.get !== "function") {
|
|
3943
4232
|
throw new Error("插件上下文不可用,无法调用模型(请直接把 summary 传进来)");
|
|
@@ -3953,8 +4242,33 @@ async function summarize(ctx, text, opts = {}) {
|
|
|
3953
4242
|
sel,
|
|
3954
4243
|
opts,
|
|
3955
4244
|
);
|
|
3956
|
-
|
|
3957
|
-
|
|
4245
|
+
let provider = picked.provider;
|
|
4246
|
+
let model = picked.model;
|
|
4247
|
+
let routeMode = '';
|
|
4248
|
+
if (ROUTE.mode) {
|
|
4249
|
+
const audience = String(opts?.audience || 'owner').toLowerCase() === 'group' ? 'group' : 'owner';
|
|
4250
|
+
const cooling = localCooling();
|
|
4251
|
+
let probe = { ok: false, models: [] };
|
|
4252
|
+
if (!cooling) { try { probe = await probeLocalModel(); } catch {} }
|
|
4253
|
+
const localModel = ROUTE.localModel || picked.model || '';
|
|
4254
|
+
const hasLocalModel = Boolean(localModel) && probe.models.includes(localModel);
|
|
4255
|
+
const decision = decideRoute({ mode: ROUTE.mode, audience, localOk: probe.ok && !cooling, hasLocalModel });
|
|
4256
|
+
if (decision.route === 'blocked') {
|
|
4257
|
+
note(`route-blocked reason=${decision.reason} audience=${audience} probe=${probe.ok} localModel=${localModel || '(未配置)'}`);
|
|
4258
|
+
throw new Error(`模型路由拦截:${decision.reason}`);
|
|
4259
|
+
}
|
|
4260
|
+
if (decision.route === 'local') {
|
|
4261
|
+
provider = ROUTE.localProvider || picked.provider;
|
|
4262
|
+
model = localModel;
|
|
4263
|
+
routeMode = 'local';
|
|
4264
|
+
} else {
|
|
4265
|
+
const cp = String(sel?.provider || '');
|
|
4266
|
+
const cm = String(sel?.model || '');
|
|
4267
|
+
if (!cp || !cm) throw new Error('在线路由需要 DSH 默认模型(设置 → 模型)');
|
|
4268
|
+
provider = cp; model = cm; routeMode = 'cloud';
|
|
4269
|
+
}
|
|
4270
|
+
note(`route route=${routeMode} audience=${audience} provider=${provider} model=${model} reason=${decision.reason || 'ok'}`);
|
|
4271
|
+
}
|
|
3958
4272
|
if (!provider || !model) {
|
|
3959
4273
|
throw new Error(
|
|
3960
4274
|
picked.source === 'config'
|
|
@@ -3984,26 +4298,30 @@ async function summarize(ctx, text, opts = {}) {
|
|
|
3984
4298
|
? text
|
|
3985
4299
|
: `${text}\n\n【提醒】上一次输出无效(不是纪要格式)。只输出【重要】/【未完成】/【无关】三段纯文本,禁止续写对话、禁止输出任何标签或命令。`;
|
|
3986
4300
|
|
|
3987
|
-
|
|
3988
|
-
let finishKind = "";
|
|
3989
|
-
const stream = llm.stream({
|
|
4301
|
+
const args = {
|
|
3990
4302
|
provider,
|
|
3991
4303
|
model,
|
|
3992
4304
|
system,
|
|
3993
4305
|
messages: [{ role: "user", content: [{ type: "text", text: input }] }],
|
|
3994
4306
|
maxTokens: budgetTokens,
|
|
3995
4307
|
temperature: formatFails === 0 ? 0.2 : 0.4,
|
|
3996
|
-
}
|
|
3997
|
-
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
if (
|
|
4001
|
-
|
|
4002
|
-
|
|
4003
|
-
|
|
4004
|
-
|
|
4005
|
-
|
|
4308
|
+
};
|
|
4309
|
+
let drained;
|
|
4310
|
+
try {
|
|
4311
|
+
drained = await drainStream(llm, args, ROUTE.timeoutMs);
|
|
4312
|
+
if (routeMode === 'local') COOL.until = 0;
|
|
4313
|
+
} catch (error) {
|
|
4314
|
+
// 本地模型中途出错 → owner 内容允许降级在线一次;group 内容不降级(硬规则)。
|
|
4315
|
+
const audience = String(opts?.audience || 'owner').toLowerCase() === 'group' ? 'group' : 'owner';
|
|
4316
|
+
if (routeMode === 'local') coolLocal(ROUTE.cooldownMs, /^model-timeout/.test(String(error?.message ?? error)) ? 'timeout' : 'error');
|
|
4317
|
+
const canFallback = routeMode === 'local' && audience === 'owner' && sel?.provider && sel?.model;
|
|
4318
|
+
if (!canFallback) throw error;
|
|
4319
|
+
note(`route-fallback from=local reason=${String(error?.message ?? error).slice(0, 80)}`);
|
|
4320
|
+
provider = String(sel.provider); model = String(sel.model); routeMode = 'cloud';
|
|
4321
|
+
drained = await drainStream(llm, { ...args, provider, model }, ROUTE.timeoutMs);
|
|
4006
4322
|
}
|
|
4323
|
+
const out = drained.out;
|
|
4324
|
+
const finishKind = drained.finishKind;
|
|
4007
4325
|
|
|
4008
4326
|
let summary = sanitizeSummary(out);
|
|
4009
4327
|
const requireImportant = opts?.requireImportant !== false;
|
|
@@ -4062,14 +4380,14 @@ export function splitDigestText(text, chunkChars = 18000, maxChunks = 8) {
|
|
|
4062
4380
|
* 18k 字一块对思考型模型太肥——reasoning 长度跟着输入走,切小之后 4000 就够。
|
|
4063
4381
|
* shortcut: 只降一级(再失败就整段失败),免得在长会话上滚雪球式烧调用。
|
|
4064
4382
|
*/
|
|
4065
|
-
async function summarizeChunk(ctx, text, depth = 0) {
|
|
4066
|
-
const part = await summarize(ctx, text, { system: CHUNK_SYSTEM, maxTokens: 4000, attempts: 2, requireImportant: false });
|
|
4383
|
+
async function summarizeChunk(ctx, text, depth = 0, opts = {}) {
|
|
4384
|
+
const part = await summarize(ctx, text, { system: CHUNK_SYSTEM, maxTokens: 4000, attempts: 2, requireImportant: false, audience: opts.audience });
|
|
4067
4385
|
if (part) return part;
|
|
4068
4386
|
if (depth >= 1 || text.length < 4000) return "";
|
|
4069
4387
|
const half = Math.ceil(text.length / 2);
|
|
4070
4388
|
note(`digest-split depth=${depth + 1} in=${text.length}`);
|
|
4071
|
-
const a = await summarizeChunk(ctx, text.slice(0, half), depth + 1);
|
|
4072
|
-
const b = await summarizeChunk(ctx, text.slice(half), depth + 1);
|
|
4389
|
+
const a = await summarizeChunk(ctx, text.slice(0, half), depth + 1, opts);
|
|
4390
|
+
const b = await summarizeChunk(ctx, text.slice(half), depth + 1, opts);
|
|
4073
4391
|
if (!a || !b) return "";
|
|
4074
4392
|
return a + "\n" + b;
|
|
4075
4393
|
}
|
|
@@ -4083,19 +4401,20 @@ export async function digestText(ctx, text, opts = {}) {
|
|
|
4083
4401
|
const maxChars = Number(opts.maxChars) > 0 ? Number(opts.maxChars) : 20000;
|
|
4084
4402
|
const chunkChars = Number(opts.chunkChars) > 0 ? Number(opts.chunkChars) : 18000;
|
|
4085
4403
|
const maxChunks = Number(opts.maxChunks) > 0 ? Number(opts.maxChunks) : 8;
|
|
4086
|
-
|
|
4404
|
+
const audience = opts?.audience;
|
|
4405
|
+
if (s.length <= maxChars) return { text: await summarize(ctx, s, { audience }), chunks: 1 };
|
|
4087
4406
|
const chunks = splitDigestText(s, chunkChars, maxChunks);
|
|
4088
|
-
if (chunks.length <= 1) return { text: await summarize(ctx, s), chunks: 1 };
|
|
4407
|
+
if (chunks.length <= 1) return { text: await summarize(ctx, s, { audience }), chunks: 1 };
|
|
4089
4408
|
note(`digest-chunked chars=${s.length} chunks=${chunks.length} chunkChars=${chunks[0].length}`);
|
|
4090
4409
|
const parts = [];
|
|
4091
4410
|
for (let i = 0; i < chunks.length; i += 1) {
|
|
4092
|
-
const part = await summarizeChunk(ctx, chunks[i]);
|
|
4411
|
+
const part = await summarizeChunk(ctx, chunks[i], 0, opts);
|
|
4093
4412
|
if (!part) throw new Error(`长会话第 ${i + 1}/${chunks.length} 段归纳失败`);
|
|
4094
4413
|
parts.push(part);
|
|
4095
4414
|
note(`digest-chunk ${i + 1}/${chunks.length} in=${chunks[i].length} out=${part.length}`);
|
|
4096
4415
|
}
|
|
4097
4416
|
const merged = parts.map((p, i) => `【第${i + 1}/${chunks.length}段】\n${p}`).join("\n\n");
|
|
4098
|
-
return { text: await summarize(ctx, merged), chunks: chunks.length };
|
|
4417
|
+
return { text: await summarize(ctx, merged, { audience }), chunks: chunks.length };
|
|
4099
4418
|
}
|
|
4100
4419
|
|
|
4101
4420
|
/** 丢掉整行看起来像工具调用 / 标签标记的内容(模型偶尔会续写记录里的标记)。 */
|
|
@@ -4516,7 +4835,7 @@ const MEMO_DIGEST = {
|
|
|
4516
4835
|
}
|
|
4517
4836
|
if (!source.text || source.count <= 0) throw new Error("这个会话没有可归纳的消息(缓冲区和会话日志都是空的)");
|
|
4518
4837
|
count = source.count;
|
|
4519
|
-
const digested = await digestText(currentCtx, source.text, autoCfg);
|
|
4838
|
+
const digested = await digestText(currentCtx, source.text, { ...autoCfg, audience: sessionAudience(sessionId) });
|
|
4520
4839
|
summary = digested.text;
|
|
4521
4840
|
if (!summary) throw new Error("模型没有返回内容");
|
|
4522
4841
|
mode = (fromLog ? "auto · 补记" : "auto") + (digested.chunks > 1 ? ` · ${digested.chunks} 段合并` : "");
|
|
@@ -4871,6 +5190,17 @@ function digestNote(sessionId, count, archive) {
|
|
|
4871
5190
|
* { status: "failed", reason }— 模型失败/返回空,不能写进 seen,留给下一轮重试
|
|
4872
5191
|
* 原文导出排在调模型之前:模型挂了也不至于连原话都没留下(exportArchive 幂等)。
|
|
4873
5192
|
*/
|
|
5193
|
+
/** 只导出原话、不调模型(幂等)。pollArchived 在摘要前先跑一遍,模型卡死也有原文。 */
|
|
5194
|
+
function exportArchivedRaw(sessionId) {
|
|
5195
|
+
const fromLog = transcriptFromLog(currentCtx, sessionId, 0, ARCHIVE_MESSAGE_CAP);
|
|
5196
|
+
const fromBuf = buildTranscript(sessionId, 0, 0);
|
|
5197
|
+
const useLog = fromLog.count >= (fromBuf.slice ?? 0);
|
|
5198
|
+
const entries = useLog
|
|
5199
|
+
? fromLog.entries
|
|
5200
|
+
: (transcript.get(sessionId) ?? []).map((m) => ({ role: m.role, text: m.text }));
|
|
5201
|
+
return exportArchive(sessionId, entries);
|
|
5202
|
+
}
|
|
5203
|
+
|
|
4874
5204
|
async function digestArchived(sessionId) {
|
|
4875
5205
|
// 取全文(0 = 不截断),分段摘要自己控制每块大小;直接截 20k 会漏掉长会话中间的内容
|
|
4876
5206
|
const fromLog = transcriptFromLog(currentCtx, sessionId, 0, ARCHIVE_MESSAGE_CAP);
|
|
@@ -4918,9 +5248,27 @@ function logPath() {
|
|
|
4918
5248
|
return process.env.DSH_MEMO_LOG || path.join(os.homedir(), '.dsh', 'memo-sync.log');
|
|
4919
5249
|
}
|
|
4920
5250
|
|
|
5251
|
+
const LOG_LIMIT = { maxBytes: 2_000_000 };
|
|
5252
|
+
|
|
5253
|
+
/** 日志超过上限就轮转一份 .1(只留一代);返回是否轮转过。 */
|
|
5254
|
+
export function rotateLogIfNeeded(file, maxBytes = LOG_LIMIT.maxBytes) {
|
|
5255
|
+
try {
|
|
5256
|
+
const st = fs.statSync(file);
|
|
5257
|
+
if (st.size < maxBytes) return false;
|
|
5258
|
+
const bak = file + '.1';
|
|
5259
|
+
try { fs.rmSync(bak, { force: true }); } catch {}
|
|
5260
|
+
fs.renameSync(file, bak);
|
|
5261
|
+
return true;
|
|
5262
|
+
} catch {
|
|
5263
|
+
return false;
|
|
5264
|
+
}
|
|
5265
|
+
}
|
|
5266
|
+
|
|
4921
5267
|
function note(line) {
|
|
4922
5268
|
try {
|
|
4923
|
-
|
|
5269
|
+
const file = logPath();
|
|
5270
|
+
rotateLogIfNeeded(file);
|
|
5271
|
+
fs.appendFileSync(file, `${new Date().toISOString()} ${line}\n`);
|
|
4924
5272
|
} catch {}
|
|
4925
5273
|
}
|
|
4926
5274
|
|
|
@@ -4955,10 +5303,23 @@ async function pollArchived() {
|
|
|
4955
5303
|
saveSeen(archivedSeen);
|
|
4956
5304
|
note(`archive-reconcile cleared=${cleared}`);
|
|
4957
5305
|
}
|
|
5306
|
+
const pending = [];
|
|
4958
5307
|
for (const id of ids) {
|
|
4959
5308
|
if (archivedSeen.has(id)) continue;
|
|
4960
5309
|
const retry = archiveRetry.get(id);
|
|
4961
5310
|
if (retry && retry.nextAt > Date.now()) continue;
|
|
5311
|
+
pending.push(id);
|
|
5312
|
+
}
|
|
5313
|
+
// 先把这一轮所有待摘要会话的原话落盘(幂等):模型卡死/超时也不耽误任何会话的原文备份
|
|
5314
|
+
for (const id of pending) {
|
|
5315
|
+
try {
|
|
5316
|
+
exportArchivedRaw(id);
|
|
5317
|
+
} catch (error) {
|
|
5318
|
+
note(`archive-export-failed session=${id} ${String(error?.message ?? error).slice(0, 120)}`);
|
|
5319
|
+
}
|
|
5320
|
+
}
|
|
5321
|
+
for (const id of pending) {
|
|
5322
|
+
const retry = archiveRetry.get(id);
|
|
4962
5323
|
let outcome;
|
|
4963
5324
|
try {
|
|
4964
5325
|
outcome = await digestArchived(id);
|
|
@@ -5151,6 +5512,16 @@ export function apply(ctx, config = {}) {
|
|
|
5151
5512
|
// 摘要单独用哪个模型:两个都填才生效;不填就跟主模型走(旧行为)
|
|
5152
5513
|
syncRefs.digestProvider = String(config?.digestProvider ?? "").trim();
|
|
5153
5514
|
syncRefs.digestModel = String(config?.digestModel ?? "").trim();
|
|
5515
|
+
// 模型路由(v2.76):mode 空 = 不启用,行为与旧版一致
|
|
5516
|
+
const routeRaw = String(config?.modelRoute ?? "").toLowerCase().trim();
|
|
5517
|
+
ROUTE.mode = ['auto', 'local', 'cloud'].includes(routeRaw) ? routeRaw : '';
|
|
5518
|
+
ROUTE.probeUrl = String(config?.localProbeUrl ?? 'http://127.0.0.1:11434').trim() || 'http://127.0.0.1:11434';
|
|
5519
|
+
ROUTE.localProvider = String(config?.localProvider ?? '').trim() || syncRefs.digestProvider || 'ollama';
|
|
5520
|
+
ROUTE.localModel = String(config?.localModel ?? '').trim() || syncRefs.digestModel;
|
|
5521
|
+
if (Number.isFinite(config?.logMaxBytes)) LOG_LIMIT.maxBytes = Math.max(100_000, config.logMaxBytes);
|
|
5522
|
+
ROUTE.timeoutMs = Number.isFinite(config?.digestTimeoutMs) ? Math.max(5_000, config.digestTimeoutMs) : 120_000;
|
|
5523
|
+
ROUTE.cooldownMs = Number.isFinite(config?.digestCooldownMs) ? Math.max(10_000, config.digestCooldownMs) : 300_000;
|
|
5524
|
+
if (ROUTE.mode) note(`model-route mode=${ROUTE.mode} probe=${ROUTE.probeUrl} local=${ROUTE.localProvider}/${ROUTE.localModel || '(未配置)'}`);
|
|
5154
5525
|
if (syncRefs.digestProvider && syncRefs.digestModel) {
|
|
5155
5526
|
note('digest-model provider=' + syncRefs.digestProvider + ' model=' + syncRefs.digestModel + '(摘要单独用这个,省钱/离线)');
|
|
5156
5527
|
}
|
|
@@ -5336,17 +5707,26 @@ export function apply(ctx, config = {}) {
|
|
|
5336
5707
|
const autoMaintain = config?.autoMaintain !== false;
|
|
5337
5708
|
const idleSyncMs = Number.isFinite(config?.idleSyncMs) ? Math.max(5000, config.idleSyncMs) : 15000;
|
|
5338
5709
|
let idleTimer = null;
|
|
5710
|
+
let lastIndexHeal = 0;
|
|
5339
5711
|
const runMaintenance = (why) => {
|
|
5340
5712
|
try {
|
|
5341
5713
|
const s0 = syncOnce({ memoPath, memoDir, agentsPath, maxBytes });
|
|
5342
5714
|
const star = refreshStarMap(memoDir);
|
|
5343
5715
|
const pruned = pruneTouch(memoDir);
|
|
5716
|
+
let healed = 0;
|
|
5717
|
+
if (Date.now() - lastIndexHeal > 10 * 60 * 1000) {
|
|
5718
|
+
lastIndexHeal = Date.now();
|
|
5719
|
+
try { healed = healSegIndex(memoDir, path.join(syncRefs.root, ARCHIVE_DIR)).fixed; } catch (error) {
|
|
5720
|
+
note('index-heal-failed ' + String(error?.message ?? error).slice(0, 120));
|
|
5721
|
+
}
|
|
5722
|
+
}
|
|
5344
5723
|
note(
|
|
5345
5724
|
'maintain ' +
|
|
5346
5725
|
why +
|
|
5347
5726
|
' sync=' + (s0.changed ? 'changed' : 'same') +
|
|
5348
5727
|
' star=' + (star ? 'rebuilt' : 'same') +
|
|
5349
5728
|
' touch-pruned=' + pruned +
|
|
5729
|
+
' index-healed=' + healed +
|
|
5350
5730
|
' entries=' + (s0.entries ?? 0),
|
|
5351
5731
|
);
|
|
5352
5732
|
} catch (error) {
|
|
@@ -5467,6 +5847,6 @@ export function apply(ctx, config = {}) {
|
|
|
5467
5847
|
});
|
|
5468
5848
|
}
|
|
5469
5849
|
|
|
5470
|
-
export const MEMO_TOOLS = [MEMO_APPEND, MEMO_EDIT, MEMO_READ, MEMO_LIST, MEMO_ARCHIVE, MEMO_STAR, MEMO_RECALL, MEMO_SYNC, MEMO_DIGEST, MEMO_DIARY, MEMO_LINT, MEMO_BOARD, MEMO_PICK, MEMO_WEIGHTS, MEMO_INDEX];
|
|
5850
|
+
export const MEMO_TOOLS = [MEMO_APPEND, MEMO_EDIT, MEMO_SUPERSEDE, MEMO_READ, MEMO_LIST, MEMO_ARCHIVE, MEMO_STAR, MEMO_RECALL, MEMO_SYNC, MEMO_DIGEST, MEMO_DIARY, MEMO_LINT, MEMO_BOARD, MEMO_PICK, MEMO_WEIGHTS, MEMO_INDEX];
|
|
5471
5851
|
|
|
5472
5852
|
export default apply;
|
package/index.json
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
{
|
|
9
9
|
"name": "dsh-memo-sync",
|
|
10
10
|
"title": "记忆(memo-sync)",
|
|
11
|
-
"description": "目录式长期记忆:一条记忆一个 markdown 文件,只把分层目录注入 AGENTS.md
|
|
11
|
+
"description": "目录式长期记忆:一条记忆一个 markdown 文件,只把分层目录注入 AGENTS.md;原话归档、按线索召回、跨会话在场、3D 星图。摘要模型可在本地模型与在线 API 间自动切换,群聊内容永不外发;默认不调用模型。",
|
|
12
12
|
"icon": "https://raw.githubusercontent.com/10110011-ling/dsh-memo-sync/main/icon.png",
|
|
13
13
|
"author": "10110011-limg",
|
|
14
14
|
"homepage": "https://github.com/10110011-ling/dsh-memo-sync#readme",
|
|
@@ -19,12 +19,14 @@
|
|
|
19
19
|
"memory",
|
|
20
20
|
"memo",
|
|
21
21
|
"context",
|
|
22
|
-
"archive"
|
|
22
|
+
"archive",
|
|
23
|
+
"local-model",
|
|
24
|
+
"privacy"
|
|
23
25
|
],
|
|
24
26
|
"versions": [
|
|
25
27
|
{
|
|
26
|
-
"version": "2.
|
|
27
|
-
"publishTimestamp":
|
|
28
|
+
"version": "2.76.4",
|
|
29
|
+
"publishTimestamp": 1796120441,
|
|
28
30
|
"source": {
|
|
29
31
|
"type": "npm"
|
|
30
32
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-memo-sync",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.76.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"bugs": {
|
|
19
19
|
"url": "https://github.com/10110011-ling/dsh-memo-sync/issues"
|
|
20
20
|
},
|
|
21
|
-
"description": "Directory-style long-term memory for DeepSeek Harness: one markdown file per topic, only an auto-generated index injected into AGENTS.md
|
|
21
|
+
"description": "Directory-style long-term memory for DeepSeek Harness: one markdown file per topic, only an auto-generated index injected into AGENTS.md; layered entries with recall counters, verbatim conversation archive, cue-based recall and a 3D star map. Optional digest auto-switches between a local model and the cloud API, and group content never leaves the machine. No model calls by default.",
|
|
22
22
|
"keywords": [
|
|
23
23
|
"dsh",
|
|
24
24
|
"dsh-plugin",
|
|
@@ -30,6 +30,8 @@
|
|
|
30
30
|
"star-map",
|
|
31
31
|
"backup",
|
|
32
32
|
"archive",
|
|
33
|
+
"local-model",
|
|
34
|
+
"privacy",
|
|
33
35
|
"session-log"
|
|
34
36
|
],
|
|
35
37
|
"engines": {
|
package/scripts/gen-index.mjs
CHANGED
|
@@ -9,12 +9,12 @@ const index = {
|
|
|
9
9
|
{
|
|
10
10
|
name: pkg.name,
|
|
11
11
|
title: '记忆(memo-sync)',
|
|
12
|
-
description: '目录式长期记忆:一条记忆一个 markdown 文件,只把分层目录注入 AGENTS.md
|
|
12
|
+
description: '目录式长期记忆:一条记忆一个 markdown 文件,只把分层目录注入 AGENTS.md;原话归档、按线索召回、跨会话在场、3D 星图。摘要模型可在本地模型与在线 API 间自动切换,群聊内容永不外发;默认不调用模型。',
|
|
13
13
|
icon: 'https://raw.githubusercontent.com/10110011-ling/dsh-memo-sync/main/icon.png',
|
|
14
14
|
author: pkg.author,
|
|
15
15
|
homepage: 'https://github.com/10110011-ling/dsh-memo-sync#readme',
|
|
16
16
|
repository: { url: 'https://github.com/10110011-ling/dsh-memo-sync' },
|
|
17
|
-
keywords: ['memory', 'memo', 'context', 'archive'],
|
|
17
|
+
keywords: ['memory', 'memo', 'context', 'archive', 'local-model', 'privacy'],
|
|
18
18
|
versions: [
|
|
19
19
|
{ version: pkg.version, publishTimestamp: Math.floor(Date.now() / 1000), source: { type: 'npm' } },
|
|
20
20
|
],
|