dsh-qqbot-muu 0.1.20 → 0.1.21

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.
Files changed (92) hide show
  1. package/CHANGELOG.md +168 -154
  2. package/client/qqbot-settings.js +13401 -13380
  3. package/dist/config.js +573 -581
  4. package/dist/features/contextless-store.js +247 -247
  5. package/dist/features/four-source.js +338 -336
  6. package/dist/features/group-join-request.js +289 -287
  7. package/dist/features/local-models.js +1494 -1467
  8. package/dist/features/style-layer.js +501 -498
  9. package/dist/features/thinking-log.js +71 -69
  10. package/dist/gateway/bootstrap.js +1704 -1652
  11. package/dist/model/settings-reader.js +193 -102
  12. package/dist/shared/paths.js +128 -0
  13. package/dist/shared/settings-io.js +79 -83
  14. package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
  15. package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -794
  16. package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
  17. package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
  18. package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -444
  19. package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
  20. package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
  21. package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
  22. package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
  23. package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
  24. package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
  25. package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
  26. package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
  27. package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
  28. package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
  29. package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
  30. package/package.json +119 -118
  31. package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
  32. package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
  33. package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
  34. package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
  35. package/scripts/ai-toolkit.py +607 -478
  36. package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
  37. package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
  38. package/scripts/chat-archive/build-sft-v4.py +566 -0
  39. package/scripts/chat-archive/build-sft.py +390 -0
  40. package/scripts/chat-archive/eval-sft.py +155 -0
  41. package/scripts/chat-archive/extract-memory.py +143 -0
  42. package/scripts/chat-archive/inventory.py +182 -0
  43. package/scripts/chat-archive/merge-sft.py +114 -0
  44. package/scripts/chat-archive/qce-pull.py +217 -0
  45. package/scripts/chat-archive/qqheader.py +110 -0
  46. package/scripts/chat-archive/qqkey2.py +113 -0
  47. package/scripts/chat-archive/qqprobe.py +153 -0
  48. package/scripts/chat-archive/screen-collect.py +163 -0
  49. package/scripts/chat-archive/sqlcipher_probe.py +444 -0
  50. package/scripts/episode.py +529 -0
  51. package/scripts/fan-curve.py +218 -0
  52. package/scripts/fan-guard.cmd +8 -0
  53. package/scripts/fan-mode.py +380 -263
  54. package/scripts/gen-image.py +420 -413
  55. package/scripts/gen-video.py +186 -178
  56. package/scripts/hw-profile.py +175 -0
  57. package/scripts/media-enhance.py +402 -0
  58. package/scripts/memory-audit.py +581 -0
  59. package/scripts/migrate-scope.mjs +140 -139
  60. package/scripts/qq-connect-login.py +133 -0
  61. package/scripts/qq-ip-sync-hidden.vbs +5 -0
  62. package/scripts/qq-ip-sync.py +300 -0
  63. package/scripts/qq-whitelist.py +71 -0
  64. package/scripts/release-all.mjs +636 -509
  65. package/scripts/release-check.mjs +244 -226
  66. package/scripts/secure-room/index.html +334 -0
  67. package/scripts/secure-room/server.py +582 -0
  68. package/scripts/stickers/auto-tag.mjs +161 -0
  69. package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
  70. package/scripts/train/gguf-quantize.py +92 -0
  71. package/scripts/train/gguf-to-hf.py +112 -0
  72. package/scripts/train/merge-lora.py +51 -0
  73. package/scripts/train/probe-mirrors.sh +12 -0
  74. package/scripts/train/probe-mirrors2.sh +20 -0
  75. package/scripts/train/setup-wsl.sh +23 -0
  76. package/scripts/train/setup-wsl2.sh +25 -0
  77. package/scripts/train/setup-wsl3.sh +22 -0
  78. package/scripts/train/setup-wsl4.sh +22 -0
  79. package/scripts/train/train-lora.py +319 -0
  80. package/dist/_backup_ctx_20261125_183653/dist/config.d.ts +0 -473
  81. package/dist/_backup_ctx_20261125_183653/dist/config.js +0 -450
  82. package/dist/_backup_ctx_20261125_183653/dist/features/contextless-trim.js +0 -304
  83. package/dist/_backup_ctx_20261125_183653/dist/session/session-manager.js +0 -1588
  84. package/dist/_backup_ctx_20261125_183653/dist/transport/inbound.js +0 -1567
  85. package/dist/_backup_ctx_20261125_183653/dist/transport/outbound.js +0 -647
  86. package/scripts/__pycache__/ai-mode.cpython-311.pyc +0 -0
  87. package/scripts/__pycache__/ai-toolkit.cpython-311.pyc +0 -0
  88. package/scripts/__pycache__/comfy_gen.cpython-311.pyc +0 -0
  89. package/scripts/__pycache__/gen-image.cpython-311.pyc +0 -0
  90. package/scripts/__pycache__/gen-video.cpython-311.pyc +0 -0
  91. package/scripts/__pycache__/model-registry.cpython-311.pyc +0 -0
  92. package/scripts/__pycache__/purge-standby.cpython-311.pyc +0 -0
@@ -1,154 +1,158 @@
1
- /**
2
- * outbound/aa-sanitize.mjs — 出站第一道闸:把不该让群友看到的东西剥掉
3
- *
4
- * 真机踩到的(2026-10-31 主人贴实锤):她把**整段注入回显**原样发了出来 ——
5
- * 「[消息号: 11018] …好。[信条]…[/信条][状态]…[/状态][别重复]刚说过:…」
6
- * 旧清单只盖了 6 种块,[信条]/[消息号]/[旧识]/[成长]/[性格观察]/[情绪回响]/[约定]/[手边]
7
- * 全部漏网。v2(2026-10-31):块清单与入站 stripMemoryBlock 对齐 + 三道兜底:
8
- * ① 成对块([x]…[/x])逐个剥;
9
- * ② 单行块([别重复]/[手边]/[消息号: N])整行剥;
10
- * ③ 截断回显兜底:剥完还残留开块标记(后面没有闭块,模型回显常被截断)→ 从标记剥到结尾。
11
- * 文件名 aa- 开头 = 出站链里排最前,先洗干净再让别的扩展改写。
12
- */
13
- import { createHash } from 'node:crypto';
14
- import { getChatState, setChatState } from '../lib/chatlog-db.mjs';
15
-
16
- export const name = 'sanitize-out';
17
-
18
- // 成对块:与 inbound/aa-memory-recall.mjs stripMemoryBlock 同一清单(两处增删要同步)
19
- const PAIRED = [
20
- '记忆', '信条', '设定', '印象', '旧识', '性格观察', '成长',
21
- '关系', '状态', 'B站', '学', '情绪回响', '约定', '听懂',
22
- ];
23
- // 单行块:没有闭标记,一行就是一块
24
- const LINE_TAGS = ['别重复', '手边'];
25
-
26
- const PATTERNS = [
27
- // ① 成对注入块
28
- ...PAIRED.map((t) => [new RegExp(`\\[${t}\\][\\s\\S]*?\\[/${t}\\]`, 'g'), '']),
29
- // ② 单行块
30
- ...LINE_TAGS.map((t) => [new RegExp(`\\n?\\[${t}\\][^\\n]*`, 'g'), '']),
31
- // [消息号: 11018] 头(入站 msgRef,模型有时会原样念出来)
32
- [/\[消息号[^\]\n]{0,24}\]\n?/g, ''],
33
- [/\[消息号(?!\])[^\n]{0,30}\n?/g, ''],
34
- // 内部消息号:m01013b / m001f / m01013 这类(真实聊天里不会出现)
35
- [/\b[mM][0-9a-fA-F]{4,8}\b/g, ''],
36
- // 形如 #0913a 的裸消息号([rf:…] 里的不动,因为那是引用语法)
37
- [/(^|[\s,。!?、])#([0-9a-fA-F]{5})(?=$|[\s,。!?、])/g, '$1'],
38
- // ③ 截断回显兜底(必须放最后:成对块先剥完,剩下的开标记 = 没有闭块的残段)
39
- [new RegExp(`\\[(?:${PAIRED.join('|')})\\][\\s\\S]*$`), ''],
40
- ];
41
-
42
- export function sanitize(text) {
43
- let t = String(text == null ? '' : text);
44
- for (const [re, to] of PATTERNS) t = t.replace(re, to);
45
- t = t.replace(/[ \t]{2,}/g, ' ').replace(/\n{3,}/g, '\n\n').trim();
46
- return t;
47
- }
48
-
49
- // ── 同文重复发送拦截(2026-10-31 主人反馈「容易把同一消息反复发送」)──
50
- // 短窗口内(120s)与刚发出去的正文完全相同(去标点/空白归一后)→ 消灭这条,不再出站。
51
- // 只拦整句重复: Length≥8 才算(「嗯」「6」这种短句自然重复不拦);主人让她「再说一遍」
52
- // 时隔得久,不受影响。
53
- const _lastSent = new Map(); // key: target → { norm, h, at }(内存快路径)
54
- const DUP_META_PREFIX = 'dup:'; // chat_meta 键前缀(实际落盘为 state:dup:<target>)
55
- function normForDup(s) {
56
- return String(s || '').replace(/[\s\u3000]+/g, '').replace(/[^\u4e00-\u9fa5A-Za-z0-9]/g, '').toLowerCase();
57
- }
58
- function hashOf(norm) {
59
- try { return createHash('sha1').update(String(norm || '')).digest('hex').slice(0, 16); } catch { return ''; }
60
- }
61
- function dupKeyOf(ctx) {
62
- try {
63
- const t = ctx?.target;
64
- if (t && typeof t === 'object') return String(t.openid || t.id || t.chatId || JSON.stringify(t));
65
- } catch { /* ignore */ }
66
- return String(ctx?.target ?? 'unknown');
67
- }
68
- function rootOf(ctx) {
69
- try { return String(ctx?.dataRoot || process.env.QQBOT_MEMORY_DATA_ROOT || ''); } catch { return ''; }
70
- }
71
- // 读「上次发过什么」:内存优先,未命中再读 chat_meta(重启后继续生效)
72
- function readLast(ctx, key) {
73
- const mem = _lastSent.get(key);
74
- if (mem) return mem;
75
- const root = rootOf(ctx);
76
- if (!root) return null;
77
- try {
78
- const st = getChatState(root, DUP_META_PREFIX + key);
79
- const at = Number(st?.at);
80
- const h = String(st?.h || '');
81
- if (!h || !Number.isFinite(at) || at <= 0) return null;
82
- return { norm: '', h, at };
83
- } catch { return null; }
84
- }
85
- // 「发送失败」:删掉内存账并把持久化写空(chatlog-db 没有删除 API)
86
- function forgetLast(ctx, key) {
87
- try { _lastSent.delete(key); } catch { /* ignore */ }
88
- const root = rootOf(ctx);
89
- if (!root) return;
90
- try { setChatState(root, DUP_META_PREFIX + key, { h: '', at: 0 }); } catch { /* ignore */ }
91
- }
92
-
93
- export async function onOutbound(ctx, next) {
94
- if (!ctx || ctx.phase !== 'send' || ctx.kind !== 'text') return next();
95
- const before = String(ctx.text || '');
96
- if (!before) return next();
97
- let after = sanitize(before);
98
- if (!after) after = '……';
99
-
100
- const key = dupKeyOf(ctx);
101
- const norm = normForDup(after);
102
- const isDupCandidate = Boolean(norm && norm.length >= 8);
103
-
104
- // 同文重复拦截(剥完块再比,免得被剥掉的前后缀造成假差异)
105
- try {
106
- if (isDupCandidate) {
107
- const now = Date.now();
108
- const last = readLast(ctx, key);
109
- const same = Boolean(last && (last.norm ? last.norm === norm : last.h === hashOf(norm)));
110
- if (same && now - last.at < 120_000) {
111
- try { ctx.logger?.warn?.(`[sanitize] 同文重复发送已拦截(${Math.round((now - last.at) / 1000)}s 前发过同一句)`); } catch {}
112
- try { ctx.note && ctx.note('sanitize: 拦截同文重复'); } catch {}
113
- ctx.annihilate?.('重复发送拦截');
114
- return; // 已被消灭,链不必再走
115
- }
116
- }
117
- } catch { /* 判重失败不拦正常发送 */ }
118
-
119
- if (after !== before) {
120
- try {
121
- ctx.note && ctx.note('sanitize: 剥掉了内部标记');
122
- } catch {}
123
- try {
124
- ctx.rewrite(after);
125
- } catch {}
126
- }
127
-
128
- // 2026-11-08(P1-5):记账挪到 next() 之后 —— 下游失败时不留"已发过"的假账。
129
- // 边界:出站链是「发送前改写链」,真正网络发送由 transport 在链后执行,
130
- // 本闸只能观测「链内抛错 / 明确返回 false」,观察不到 transport 的发送结果。
131
- let ret;
132
- try {
133
- ret = await next();
134
- } catch (err) {
135
- if (isDupCandidate) forgetLast(ctx, key); // 失败删除该键,允许立刻重试同句
136
- throw err;
137
- }
138
- if (ret === false) {
139
- if (isDupCandidate) forgetLast(ctx, key);
140
- return ret;
141
- }
142
- // 记录「已发出去的正文」供下一条判重(内存 + chat_meta:target + hash + 时间,不落正文)
143
- try {
144
- if (isDupCandidate) {
145
- const at = Date.now();
146
- _lastSent.set(key, { norm, h: hashOf(norm), at });
147
- const root = rootOf(ctx);
148
- if (root) setChatState(root, DUP_META_PREFIX + key, { h: hashOf(norm), at });
149
- }
150
- } catch { /* 记账失败不影响发送 */ }
151
- return ret;
152
- }
153
-
154
- export default onOutbound;
1
+ /**
2
+ * outbound/aa-sanitize.mjs — 出站第一道闸:把不该让群友看到的东西剥掉
3
+ *
4
+ * 真机踩到的(2026-10-31 主人贴实锤):她把**整段注入回显**原样发了出来 ——
5
+ * 「[消息号: 11018] …好。[信条]…[/信条][状态]…[/状态][别重复]刚说过:…」
6
+ * 旧清单只盖了 6 种块,[信条]/[消息号]/[旧识]/[成长]/[性格观察]/[情绪回响]/[约定]/[手边]
7
+ * 全部漏网。v2(2026-10-31):块清单与入站 stripMemoryBlock 对齐 + 三道兜底:
8
+ * ① 成对块([x]…[/x])逐个剥;
9
+ * ② 单行块([别重复]/[手边]/[消息号: N])整行剥;
10
+ * ③ 截断回显兜底:剥完还残留开块标记(后面没有闭块,模型回显常被截断)→ 从标记剥到结尾。
11
+ * 文件名 aa- 开头 = 出站链里排最前,先洗干净再让别的扩展改写。
12
+ */
13
+ import { createHash } from 'node:crypto';
14
+ import { getChatState, setChatState } from '../lib/chatlog-db.mjs';
15
+
16
+ export const name = 'sanitize-out';
17
+
18
+ // 成对块:与 inbound/aa-memory-recall.mjs stripMemoryBlock 同一清单(两处增删要同步)
19
+ const PAIRED = [
20
+ '记忆', '信条', '设定', '印象', '旧识', '性格观察', '成长',
21
+ '关系', '状态', 'B站', '学', '情绪回响', '约定', '听懂',
22
+ ];
23
+ // 单行块:没有闭标记,一行就是一块
24
+ const LINE_TAGS = ['别重复', '手边'];
25
+
26
+ const PATTERNS = [
27
+ // ① 成对注入块
28
+ ...PAIRED.map((t) => [new RegExp(`\\[${t}\\][\\s\\S]*?\\[/${t}\\]`, 'g'), '']),
29
+ // ② 单行块
30
+ ...LINE_TAGS.map((t) => [new RegExp(`\\n?\\[${t}\\][^\\n]*`, 'g'), '']),
31
+ // [消息号: 11018] 头(入站 msgRef,模型有时会原样念出来)
32
+ [/\[消息号[^\]\n]{0,24}\]\n?/g, ''],
33
+ [/\[消息号(?!\])[^\n]{0,30}\n?/g, ''],
34
+ // QQ 引用标记 `[回复]`:训练语料里自带的(2026-12-04 实测模型会开口就念),纯标记,剥掉留正文
35
+ [/\[回复\]\s*/g, ''],
36
+ // 媒体占位符([图片]/[表情]…):真人不会打字打出来,模型念出来只显得像机器
37
+ [/\[(?:图片|视频|语音|文件|表情|动画表情|位置|音乐|表情包|卡片|转发)\]\s*/g, ''],
38
+ // 内部消息号:m01013b / m001f / m01013 这类(真实聊天里不会出现)
39
+ [/\b[mM][0-9a-fA-F]{4,8}\b/g, ''],
40
+ // 形如 #0913a 的裸消息号([rf:…] 里的不动,因为那是引用语法)
41
+ [/(^|[\s,。!?、])#([0-9a-fA-F]{5})(?=$|[\s,。!?、])/g, '$1'],
42
+ // ③ 截断回显兜底(必须放最后:成对块先剥完,剩下的开标记 = 没有闭块的残段)
43
+ [new RegExp(`\\[(?:${PAIRED.join('|')})\\][\\s\\S]*$`), ''],
44
+ ];
45
+
46
+ export function sanitize(text) {
47
+ let t = String(text == null ? '' : text);
48
+ for (const [re, to] of PATTERNS) t = t.replace(re, to);
49
+ t = t.replace(/[ \t]{2,}/g, ' ').replace(/\n{3,}/g, '\n\n').trim();
50
+ return t;
51
+ }
52
+
53
+ // ── 同文重复发送拦截(2026-10-31 主人反馈「容易把同一消息反复发送」)──
54
+ // 短窗口内(120s)与刚发出去的正文完全相同(去标点/空白归一后)→ 消灭这条,不再出站。
55
+ // 只拦整句重复: Length≥8 才算(「嗯」「6」这种短句自然重复不拦);主人让她「再说一遍」
56
+ // 时隔得久,不受影响。
57
+ const _lastSent = new Map(); // key: target → { norm, h, at }(内存快路径)
58
+ const DUP_META_PREFIX = 'dup:'; // chat_meta 键前缀(实际落盘为 state:dup:<target>)
59
+ function normForDup(s) {
60
+ return String(s || '').replace(/[\s\u3000]+/g, '').replace(/[^\u4e00-\u9fa5A-Za-z0-9]/g, '').toLowerCase();
61
+ }
62
+ function hashOf(norm) {
63
+ try { return createHash('sha1').update(String(norm || '')).digest('hex').slice(0, 16); } catch { return ''; }
64
+ }
65
+ function dupKeyOf(ctx) {
66
+ try {
67
+ const t = ctx?.target;
68
+ if (t && typeof t === 'object') return String(t.openid || t.id || t.chatId || JSON.stringify(t));
69
+ } catch { /* ignore */ }
70
+ return String(ctx?.target ?? 'unknown');
71
+ }
72
+ function rootOf(ctx) {
73
+ try { return String(ctx?.dataRoot || process.env.QQBOT_MEMORY_DATA_ROOT || ''); } catch { return ''; }
74
+ }
75
+ // 读「上次发过什么」:内存优先,未命中再读 chat_meta(重启后继续生效)
76
+ function readLast(ctx, key) {
77
+ const mem = _lastSent.get(key);
78
+ if (mem) return mem;
79
+ const root = rootOf(ctx);
80
+ if (!root) return null;
81
+ try {
82
+ const st = getChatState(root, DUP_META_PREFIX + key);
83
+ const at = Number(st?.at);
84
+ const h = String(st?.h || '');
85
+ if (!h || !Number.isFinite(at) || at <= 0) return null;
86
+ return { norm: '', h, at };
87
+ } catch { return null; }
88
+ }
89
+ // 「发送失败」:删掉内存账并把持久化写空(chatlog-db 没有删除 API)
90
+ function forgetLast(ctx, key) {
91
+ try { _lastSent.delete(key); } catch { /* ignore */ }
92
+ const root = rootOf(ctx);
93
+ if (!root) return;
94
+ try { setChatState(root, DUP_META_PREFIX + key, { h: '', at: 0 }); } catch { /* ignore */ }
95
+ }
96
+
97
+ export async function onOutbound(ctx, next) {
98
+ if (!ctx || ctx.phase !== 'send' || ctx.kind !== 'text') return next();
99
+ const before = String(ctx.text || '');
100
+ if (!before) return next();
101
+ let after = sanitize(before);
102
+ if (!after) after = '……';
103
+
104
+ const key = dupKeyOf(ctx);
105
+ const norm = normForDup(after);
106
+ const isDupCandidate = Boolean(norm && norm.length >= 8);
107
+
108
+ // 同文重复拦截(剥完块再比,免得被剥掉的前后缀造成假差异)
109
+ try {
110
+ if (isDupCandidate) {
111
+ const now = Date.now();
112
+ const last = readLast(ctx, key);
113
+ const same = Boolean(last && (last.norm ? last.norm === norm : last.h === hashOf(norm)));
114
+ if (same && now - last.at < 120_000) {
115
+ try { ctx.logger?.warn?.(`[sanitize] 同文重复发送已拦截(${Math.round((now - last.at) / 1000)}s 前发过同一句)`); } catch {}
116
+ try { ctx.note && ctx.note('sanitize: 拦截同文重复'); } catch {}
117
+ ctx.annihilate?.('重复发送拦截');
118
+ return; // 已被消灭,链不必再走
119
+ }
120
+ }
121
+ } catch { /* 判重失败不拦正常发送 */ }
122
+
123
+ if (after !== before) {
124
+ try {
125
+ ctx.note && ctx.note('sanitize: 剥掉了内部标记');
126
+ } catch {}
127
+ try {
128
+ ctx.rewrite(after);
129
+ } catch {}
130
+ }
131
+
132
+ // 2026-11-08(P1-5):记账挪到 next() 之后 —— 下游失败时不留"已发过"的假账。
133
+ // 边界:出站链是「发送前改写链」,真正网络发送由 transport 在链后执行,
134
+ // 本闸只能观测「链内抛错 / 明确返回 false」,观察不到 transport 的发送结果。
135
+ let ret;
136
+ try {
137
+ ret = await next();
138
+ } catch (err) {
139
+ if (isDupCandidate) forgetLast(ctx, key); // 失败删除该键,允许立刻重试同句
140
+ throw err;
141
+ }
142
+ if (ret === false) {
143
+ if (isDupCandidate) forgetLast(ctx, key);
144
+ return ret;
145
+ }
146
+ // 记录「已发出去的正文」供下一条判重(内存 + chat_meta:target + hash + 时间,不落正文)
147
+ try {
148
+ if (isDupCandidate) {
149
+ const at = Date.now();
150
+ _lastSent.set(key, { norm, h: hashOf(norm), at });
151
+ const root = rootOf(ctx);
152
+ if (root) setChatState(root, DUP_META_PREFIX + key, { h: hashOf(norm), at });
153
+ }
154
+ } catch { /* 记账失败不影响发送 */ }
155
+ return ret;
156
+ }
157
+
158
+ export default onOutbound;
@@ -1,130 +1,121 @@
1
- /**
2
- * outbound/memory-agent.mjs — 回合收尾时唤一次「记忆分身」
3
- *
4
- * 为什么放在 outbound/turnEnd:
5
- * · 此时她刚说完,最近对话最完整(含她自己的回复);
6
- * · 正文块已经发完,不会挡用户看到回复;
7
- * · 和 turn-memory 一样只在 turnEnd 触发,天然一回合一次。
8
- *
9
- * 行为:
10
- * 1) 同步补一次聊天台账(新增行才写,成本 ≈ 读几个 KB);
11
- * 2) 把「整理这段对话」丢给 lib/memory-agent.mjs,**不 await**;
12
- * 3) 同一 scope 正在整理时直接跳过,避免堆积并发小模型请求。
13
- *
14
- * 关闭方式:memory-config.json → "memoryAgent": { "enabled": false }
15
- * 或整个记忆关掉("enabled": false)。任何异常都静默降级。
16
- */
17
-
18
- import { dirname } from 'node:path';
19
- import { fileURLToPath } from 'node:url';
20
-
21
- export const name = 'memory-agent';
22
-
23
- const HERE = dirname(fileURLToPath(import.meta.url));
24
- const _running = new Set();
25
-
26
- /**
27
- * 历史印象(高维卡)的自动更新。
28
- *
29
- * 之前这套只有面板里手动点才会跑,配置里 `digest.perDayMs`("每天最多重建一次")
30
- * 等于一句空话——导入再多历史,那张"这个人是谁"的卡也不会自己长出来。
31
- *
32
- * 三处限流,任何一处不满足就不跑:
33
- * · 只做 c2c:群里的卡要按发言人做,出站钩子拿不到稳定的发言人 id;
34
- * · 进程内 12h/人:模型离线反复失败时不至于每回合撞一次 60s 超时;
35
- * · digestPerson 内部的 perDayMs:跨进程重启也不会重复重建。
36
- */
37
- const DIGEST_EVERY_MS = 12 * 3600 * 1000;
38
- const _lastDigest = new Map();
39
-
40
- async function maybeDigest(root, scope, cfg, ok) {
41
- if (!ok) return null;
42
- if (cfg?.digest?.auto === false) return null;
43
- if (!scope.startsWith('c2c:')) return null;
44
- const sid = scope.slice(4);
45
- if (!sid) return null;
46
- const k = root + '|' + sid;
47
- if (Date.now() - (Number(_lastDigest.get(k)) || 0) < DIGEST_EVERY_MS) return null;
48
- _lastDigest.set(k, Date.now());
49
- const { digestPerson } = await import('../lib/profile-digest.mjs');
50
- return digestPerson({ dataRoot: root, senderId: sid, scope: '', cfg });
51
- }
52
-
53
- /**
54
- * 印象「保鲜」(主人 2026-10-27):
55
- * · 卡片长期不更新,面板上的印象就会和目标偏移;
56
- * · 自我卡("我自己是谁")以前是每次面板临时合成的,库里那张停在 10-26,从不变。
57
- * 所以每 N 小时做一次轻量保养:
58
- * 1) 重写自我卡(纯读 character.json + growth,不花 token);
59
- * 2) 挑最多 1 个"有新切片没消化 / 太旧"的人重建卡(digestPerson 自带 22h 节流)。
60
- * 进程内 6h 一次;异常静默。
61
- */
62
- const FRESH_EVERY_MS = 6 * 3600 * 1000;
63
- const _lastFresh = new Map();
64
-
65
- async function maybeFresh(root, cfg) {
66
- if (cfg?.personaFresh?.enabled === false) return null;
67
- const k = root;
68
- if (Date.now() - (Number(_lastFresh.get(k)) || 0) < FRESH_EVERY_MS) return null;
69
- _lastFresh.set(k, Date.now());
70
- const { refresh } = await import('../lib/persona-fresh.mjs');
71
- return refresh(root, { mode: 'stale', budget: 1, force: false, cfg });
72
- }
73
-
74
- function dataRootOf(ctx) {
75
- const env = String(process.env.QQBOT_MEMORY_DATA_ROOT || '').trim();
76
- if (env) return env;
77
- if (ctx && typeof ctx.dataRoot === 'string' && ctx.dataRoot) return ctx.dataRoot;
78
- return dirname(dirname(HERE)); // .../{dataRoot}/.qqbot-extensions/outbound/
79
- }
80
-
81
- function scopeOfTarget(target) {
82
- if (!target) return '';
83
- // 真机 ctx.target = { scope, targetId }(不是 peerId);两个都认,否则永远拿不到会话
84
- const peer = String(target.peerId || target.targetId || '');
85
- if (!peer) return '';
86
- const kind = String(target.scope || '');
87
- if (kind === 'c2c' || kind === 'user' || kind === 'private') return 'c2c:' + peer;
88
- return 'group:' + peer;
89
- }
90
-
91
- export async function onOutbound(ctx, next) {
92
- if (ctx?.phase !== 'turnEnd') return next();
93
-
94
- try {
95
- const root = dataRootOf(ctx);
96
- const scope = scopeOfTarget(ctx?.target);
97
- if (!scope || _running.has(scope)) return next();
98
-
99
- const mem = await import('../lib/memory.mjs');
100
- const cfg = mem.loadConfig(root);
101
- if (cfg.enabled === false) return next();
102
-
103
- const { runTurnAgent, loadAgentCfg } = await import('../lib/memory-agent.mjs');
104
- const acfg = loadAgentCfg(cfg);
105
- if (acfg.enabled === false) return next();
106
-
107
- _running.add(scope);
108
- // 故意不 await:整理要调本地模型(几百 ms ~ 几秒),不能拖慢收尾
109
- Promise.resolve()
110
- .then(async () => {
111
- let llmCfg = null;
112
- try {
113
- const llm = await import('../lib/local-llm.mjs');
114
- llmCfg = llm.loadConfig(root);
115
- } catch { /* 没有本地模型就交给 runTurnAgent 自己判 */ }
116
- const r = await runTurnAgent({ dataRoot: root, scope, cfg, llmCfg, reply: String(ctx?.text || '') });
117
- // 回合整理成功 = 这段对话真的在推进,顺手看一眼"这个人的历史印象"要不要重建。
118
- // 慢(本地模型几十秒),所以继续往后扔,不阻塞收尾。
119
- maybeDigest(root, scope, cfg, !!(r && r.ok)).catch(() => { /* 卡片没更新不影响聊天 */ });
120
- maybeFresh(root, cfg).catch(() => { /* 保鲜失败不影响聊天 */ });
121
- return r;
122
- })
123
- .catch(() => { /* 整理失败不影响任何链路 */ })
124
- .finally(() => { _running.delete(scope); });
125
- } catch { /* ignore */ }
126
-
127
- return next();
128
- }
129
-
130
- export default onOutbound;
1
+ /**
2
+ * outbound/memory-agent.mjs — 回合收尾时唤一次「记忆分身」
3
+ *
4
+ * 为什么放在 outbound/turnEnd:
5
+ * · 此时她刚说完,最近对话最完整(含她自己的回复);
6
+ * · 正文块已经发完,不会挡用户看到回复;
7
+ * · 和 turn-memory 一样只在 turnEnd 触发,天然一回合一次。
8
+ *
9
+ * 行为:
10
+ * 1) 同步补一次聊天台账(新增行才写,成本 ≈ 读几个 KB);
11
+ * 2) 把「整理这段对话」丢给 lib/memory-agent.mjs,**不 await**;
12
+ * 3) 同一 scope 正在整理时直接跳过,避免堆积并发小模型请求。
13
+ *
14
+ * 关闭方式:memory-config.json → "memoryAgent": { "enabled": false }
15
+ * 或整个记忆关掉("enabled": false)。任何异常都静默降级。
16
+ */
17
+
18
+ import { dirname } from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { scopeOfTarget } from '../lib/scope-util.mjs';
21
+
22
+ export const name = 'memory-agent';
23
+
24
+ const HERE = dirname(fileURLToPath(import.meta.url));
25
+ const _running = new Set();
26
+
27
+ /**
28
+ * 历史印象(高维卡)的自动更新。
29
+ *
30
+ * 之前这套只有面板里手动点才会跑,配置里 `digest.perDayMs`("每天最多重建一次")
31
+ * 等于一句空话——导入再多历史,那张"这个人是谁"的卡也不会自己长出来。
32
+ *
33
+ * 三处限流,任何一处不满足就不跑:
34
+ * · 只做 c2c:群里的卡要按发言人做,出站钩子拿不到稳定的发言人 id;
35
+ * · 进程内 12h/人:模型离线反复失败时不至于每回合撞一次 60s 超时;
36
+ * · digestPerson 内部的 perDayMs:跨进程重启也不会重复重建。
37
+ */
38
+ const DIGEST_EVERY_MS = 12 * 3600 * 1000;
39
+ const _lastDigest = new Map();
40
+
41
+ async function maybeDigest(root, scope, cfg, ok) {
42
+ if (!ok) return null;
43
+ if (cfg?.digest?.auto === false) return null;
44
+ if (!scope.startsWith('c2c:')) return null;
45
+ const sid = scope.slice(4);
46
+ if (!sid) return null;
47
+ const k = root + '|' + sid;
48
+ if (Date.now() - (Number(_lastDigest.get(k)) || 0) < DIGEST_EVERY_MS) return null;
49
+ _lastDigest.set(k, Date.now());
50
+ const { digestPerson } = await import('../lib/profile-digest.mjs');
51
+ return digestPerson({ dataRoot: root, senderId: sid, scope: '', cfg });
52
+ }
53
+
54
+ /**
55
+ * 印象「保鲜」(主人 2026-10-27):
56
+ * · 卡片长期不更新,面板上的印象就会和目标偏移;
57
+ * · 自我卡("我自己是谁")以前是每次面板临时合成的,库里那张停在 10-26,从不变。
58
+ * 所以每 N 小时做一次轻量保养:
59
+ * 1) 重写自我卡(纯读 character.json + growth,不花 token);
60
+ * 2) 挑最多 1 个"有新切片没消化 / 太旧"的人重建卡(digestPerson 自带 22h 节流)。
61
+ * 进程内 6h 一次;异常静默。
62
+ */
63
+ const FRESH_EVERY_MS = 6 * 3600 * 1000;
64
+ const _lastFresh = new Map();
65
+
66
+ async function maybeFresh(root, cfg) {
67
+ if (cfg?.personaFresh?.enabled === false) return null;
68
+ const k = root;
69
+ if (Date.now() - (Number(_lastFresh.get(k)) || 0) < FRESH_EVERY_MS) return null;
70
+ _lastFresh.set(k, Date.now());
71
+ const { refresh } = await import('../lib/persona-fresh.mjs');
72
+ return refresh(root, { mode: 'stale', budget: 1, force: false, cfg });
73
+ }
74
+
75
+ function dataRootOf(ctx) {
76
+ const env = String(process.env.QQBOT_MEMORY_DATA_ROOT || '').trim();
77
+ if (env) return env;
78
+ if (ctx && typeof ctx.dataRoot === 'string' && ctx.dataRoot) return ctx.dataRoot;
79
+ return dirname(dirname(HERE)); // .../{dataRoot}/.qqbot-extensions/outbound/
80
+ }
81
+
82
+ export async function onOutbound(ctx, next) {
83
+ if (ctx?.phase !== 'turnEnd') return next();
84
+
85
+ try {
86
+ const root = dataRootOf(ctx);
87
+ const scope = scopeOfTarget(ctx?.target);
88
+ if (!scope || _running.has(scope)) return next();
89
+
90
+ const mem = await import('../lib/memory.mjs');
91
+ const cfg = mem.loadConfig(root);
92
+ if (cfg.enabled === false) return next();
93
+
94
+ const { runTurnAgent, loadAgentCfg } = await import('../lib/memory-agent.mjs');
95
+ const acfg = loadAgentCfg(cfg);
96
+ if (acfg.enabled === false) return next();
97
+
98
+ _running.add(scope);
99
+ // 故意不 await:整理要调本地模型(几百 ms ~ 几秒),不能拖慢收尾
100
+ Promise.resolve()
101
+ .then(async () => {
102
+ let llmCfg = null;
103
+ try {
104
+ const llm = await import('../lib/local-llm.mjs');
105
+ llmCfg = llm.loadConfig(root);
106
+ } catch { /* 没有本地模型就交给 runTurnAgent 自己判 */ }
107
+ const r = await runTurnAgent({ dataRoot: root, scope, cfg, llmCfg, reply: String(ctx?.text || '') });
108
+ // 回合整理成功 = 这段对话真的在推进,顺手看一眼"这个人的历史印象"要不要重建。
109
+ // 慢(本地模型几十秒),所以继续往后扔,不阻塞收尾。
110
+ maybeDigest(root, scope, cfg, !!(r && r.ok)).catch(() => { /* 卡片没更新不影响聊天 */ });
111
+ maybeFresh(root, cfg).catch(() => { /* 保鲜失败不影响聊天 */ });
112
+ return r;
113
+ })
114
+ .catch(() => { /* 整理失败不影响任何链路 */ })
115
+ .finally(() => { _running.delete(scope); });
116
+ } catch { /* ignore */ }
117
+
118
+ return next();
119
+ }
120
+
121
+ export default onOutbound;