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,1567 +0,0 @@
1
- import { createUserMessage } from '@deepseek-ai/dsh-llm';
2
- import { createHash } from 'node:crypto';
3
- import { existsSync, readFileSync } from 'node:fs';
4
- import { skipSilentAppend } from '../session/surface-guard.js';
5
- import { clearGroupHistory } from '../features/history-store.js';
6
- import { traceContextless } from '../features/contextless-store.js';
7
- import { applyInjectRules } from './inject-rules.js';
8
- import { inferMediaKind, mediaKindLabel } from './media-kind.js';
9
- import { replaceBotMention, mentionsOthers } from '../shared/mention-clean.js';
10
- import { resolveMentionNames } from '../features/chat-ledger.js';
11
- import { MK, QUOTE_BEGIN_ALL, QUOTE_END_ALL, findFirstMarker, findLastMarker, escapeBlockMarkers, stripBlockMarkers } from './markers.js';
12
- import { dataRootOf, stickerDirOf } from '../gateway/data-root.js';
13
- import { registerMsgIndex } from './msg-index.js';
14
- import { createValueScorer, appendScoreLog, OTHER_MENTION_PENALTY } from '../features/value-score.js';
15
- import { getStickerStore, computeDHash } from '../features/sticker-store.js';
16
- import { lookupImagePath, rememberImagePath } from '../features/image-path-cache.js';
17
- import { extractFaceImageUrls, slimQuoteText } from './quote-text.js';
18
- import { lookupMsgContent, rememberMsgContent } from './msg-content-cache.js';
19
- import { appendMsgHistory } from '../features/msg-history.js';
20
- import { recordImageUrl, lookupStickerIdByUrl } from '../features/image-url-ledger.js';
21
- import { pushQuote } from '../features/quote-cache.js';
22
- import { computeRelevance, touchAffinity, classifyEmo, getAffinityEntry, memoryStrength } from '../features/local-signals.js';
23
- import { touchDaily } from '../features/intimacy-ledger.js';
24
- import { noteLastSender, attitudeOf, attitudeRange, attitudeGateFor, ATTITUDE_GATE_ENABLED } from '../features/attitude.js';
25
- import { confidentEmo } from '../features/four-source.js';
26
- import { AGG_SCORE_MODE, weightedAggregate } from '../features/agg-score.js';
27
- import { recallLines, setPendingMemo, countWroteToday } from '../features/people-memo.js';
28
- import { detectSelfDisclosure, selfDisclosureHint, bumpHint } from '../features/self-disclosure.js';
29
- import { createLocalEmbedder } from '../features/local-embed.js';
30
- /** 小传注入节流(同一人 24h 内不重复): uid → 上次注入时间 */
31
- const memoInjectAt = new Map();
32
- /** 每会话"上次注入的群时间头"(同分钟不重复注入,省 token) */
33
- const lastGroupTimeHead = new Map();
34
- /**
35
- * 群消息时间头:同一会话**同一分钟内只注入一次**。
36
- *
37
- * 2026-10-01 主人要求(省 token):「同一分钟的消息或聚合消息不重复显示时间」。
38
- * 原来每轮入站都无条件在最前面加 `[YYYY-MM-DD 周X HH:MM]` —— 同一分钟里连发几轮 / 聚合一波,
39
- * 上下文里就堆出好几行一模一样的时间头(每行 ~25 字符,纯浪费)。
40
- * 现在同分钟内的后续回合不再重复注入:时间信息不变(最近那条时间头就是当前时间),信息量零损失。
41
- *
42
- * @param cache 会话 → 上次时间头(进程内缓存,重启自然清空 → 重启后第一条会重新带上)
43
- * @returns 要注入的时间行(形如 `[2026-10-01 周四 20:47]`),本次不需注入时返回 null
44
- */
45
- export function groupTimeHead(cache, scope, peerId, now = new Date()) {
46
- const p = (n) => String(n).padStart(2, '0');
47
- const wd = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][now.getDay()];
48
- const stamp = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())} ${wd} ${p(now.getHours())}:${p(now.getMinutes())}`;
49
- const key = `${scope}:${peerId}`;
50
- if (cache.get(key) === stamp)
51
- return null;
52
- cache.set(key, stamp);
53
- return `[${stamp}]`;
54
- }
55
- // ── 主处理函数 ──
56
- /**
57
- * 处理 QQ 入站消息(已经过 SDK 中间件链)
58
- */
59
- export async function handleInbound(rawMsg, manager, config, logger, state) {
60
- const msg = rawMsg;
61
- const mwState = (state ?? {});
62
- const scope = msg.kind === 'group' ? 'group' : 'c2c';
63
- const peerId = scope === 'group' ? (msg.groupOpenid ?? msg.senderId) : msg.senderId;
64
- const replyTarget = {
65
- scope,
66
- targetId: peerId,
67
- msgId: msg.messageId,
68
- };
69
- // 2026-10-20 判消息类型 + 写消息历史台账(主人定:按会话分目录 + 一天一个文件 + 保留 7 天)
70
- // ★ 为什么放这里:群消息先经 debounce 中间件攒窗口,它会 **consume**(不 next)后再调 handleInbound,
71
- // 所以写在 bot.on('message') 里根本不会执行(实测:台账里只有机器人自己的消息、自动撤回不动)。
72
- // handleInbound 才是"消息确实进来了"的唯一必经点。
73
- let _kind = 'text';
74
- let _text = '';
75
- try {
76
- const _atts = Array.isArray(msg.attachments) ? msg.attachments : [];
77
- const _ct = (a) => String(a?.content_type ?? '');
78
- _kind = _atts.length === 0
79
- ? 'text'
80
- : _atts.some((a) => /image/i.test(_ct(a))) ? 'image'
81
- : _atts.some((a) => /audio|voice|silk/i.test(_ct(a))) ? 'voice'
82
- : _atts.some((a) => /video/i.test(_ct(a))) ? 'video'
83
- : 'file';
84
- _text = _kind === 'text' ? String(msg.content ?? '') : `[${_kind}]`;
85
- appendMsgHistory(scope, String(peerId ?? ''), {
86
- id: String(msg.messageId ?? ''),
87
- s: String(msg.senderId ?? ''),
88
- n: String(msg.senderName ?? msg.senderId ?? ''),
89
- t: Date.now(),
90
- k: _kind,
91
- x: _text,
92
- });
93
- }
94
- catch { /* 台账失败不影响主流程 */ }
95
- // (自动撤回已由 middleware-setup.ts 里"debounce 之前"的中间件负责,这里不再重复)
96
- // ── 读取中间件已下载的文件(attachmentProcessor 写入 state.downloadedFiles) ──
97
- const downloaded = mwState.downloadedFiles ?? [];
98
- // ── 组装 agentBody(对齐 openclaw-qqbot body-assembler) ──
99
- // 引用消息短消息号(2026-09-13 主人定): 入站登记到本地台账({dataRoot}/.qqbot/msg-index/{peer}/refs.json),
100
- // 注入**短号**(如 #0913a)替代长 msg_id 省 token; 出站 [rf:短号] 再查表还原完整 id。
101
- const refEnabled = config.messageReference !== false;
102
- let msgRef = '';
103
- if (refEnabled && msg.messageId) {
104
- try {
105
- msgRef = registerMsgIndex(dataRootOf(config), scope, peerId, msg.messageId, {
106
- senderId: msg.senderId,
107
- senderName: msg.senderName,
108
- });
109
- }
110
- catch { /* 台账落盘失败不影响消息流 */ }
111
- }
112
- // ⚠️ 2026-09-24 修复「当前消息的图片只显示长 URL、拿不到本地路径」(主人多次反馈):
113
- // 原代码顺序是 assembleAgentBody(拼消息,其中 Layer4 会查 lookupImagePath) **之后**
114
- // 才做图片预检并 rememberImagePath —— 等于拼消息时缓存永远是空的,只能回退 QQ 长 URL;
115
- // 而缓存要到下一条消息(历史)才生效,所以"历史里有本地路径、当前消息没有"。
116
- // 这里在拼消息**之前**先补一次预检:下载 → sha1 → 查图库 → 命中就把 URL→本地路径记进缓存。
117
- // (原来的预检逻辑保持不变,重复执行是幂等的,不影响其它行为。)
118
- try {
119
- const _imgUrls = [];
120
- for (const _a of (Array.isArray(msg.attachments) ? msg.attachments : [])) {
121
- const _u = String(_a?.url ?? '').trim();
122
- const _ct = String(_a?.content_type ?? '').toLowerCase();
123
- if (_u && /image/.test(_ct) && !_imgUrls.includes(_u))
124
- _imgUrls.push(_u);
125
- }
126
- const _first = _imgUrls[0];
127
- if (_first && !lookupImagePath(_first, logger)) {
128
- const _store = getStickerStore(stickerDirOf(config));
129
- let _buf = await fetchImageBuffer(_first);
130
- if (_buf && _buf.length > 0) {
131
- const _id = createHash('sha1').update(_buf).digest('hex').slice(0, 12);
132
- const _hit = _store.get(_id);
133
- if (_hit?.id) {
134
- const _p = _store.pathOf(_hit.id);
135
- if (_p) {
136
- rememberImagePath(_first, _p);
137
- logger.info(`[img-path] 预检命中,本条消息将带本地路径: ${_p}`);
138
- }
139
- }
140
- }
141
- }
142
- }
143
- catch (e) {
144
- logger.warn(`im-qqbot: 拼消息前的图片预检失败(不影响主流程): ${e instanceof Error ? e.message : String(e)}`);
145
- }
146
- // 2026-10-01: 登记"这条消息的文本 + 图片本地路径",供**别人引用它**时还原
147
- // (QQ 引用纯图片给不出图,只能自己记;见 transport/msg-content-cache.ts)
148
- // ⚠️ 位置讲究:必须在上面那次"图片预检"(会 rememberImagePath) **之后** —— 那时查缓存才有本地路径。
149
- try {
150
- const _mi = String(msg.msgIdx ?? '').trim();
151
- if (_mi) {
152
- const _imgs = [];
153
- for (const _a of (Array.isArray(msg.attachments) ? msg.attachments : [])) {
154
- const _url = String(_a?.url ?? '').trim();
155
- if (!_url)
156
- continue;
157
- // ⚠️ 2026-10-01: 用**两级解析**(内存缓存 → 图库台账反查)——
158
- // 台账是落盘的、跨重启/超 TTL 也命中;只查内存缓存的话(TTL 1h),
159
- // 稍早的图就记不下本地路径了(主人实测:引用的图明明在图库里,却没转成本地路径)。
160
- const _lp = resolveImageLocalPath(_url, stickerDirOf(config));
161
- if (_lp && !_imgs.includes(_lp))
162
- _imgs.push(_lp);
163
- }
164
- const _txt = String(msg.content ?? '').trim();
165
- rememberMsgContent(dataRootOf(config), `${scope}:${peerId}`, _mi, {
166
- ...(_txt ? { t: _txt.slice(0, 200) } : {}),
167
- ...(_imgs.length ? { imgs: _imgs } : {}),
168
- ...(msg.messageId ? { m: String(msg.messageId) } : {}),
169
- ...(msg.senderId ? { s: String(msg.senderId) } : {}),
170
- ...(msg.senderName ? { n: String(msg.senderName) } : {}),
171
- k: _imgs.length > 0 ? 'image' : (_txt ? 'text' : 'file'),
172
- });
173
- }
174
- }
175
- catch { /* 台账失败不影响主链 */ }
176
- let agentBody = assembleAgentBody(msg, mwState, scope, logger, downloaded, refEnabled, msgRef, dataRootOf(config), stickerDirOf(config));
177
- if (!agentBody)
178
- return;
179
- // 条件注入规则(配置化): 消息含图/链接/自定义条件时追加 [系统提示]。
180
- // 含内置读图兜底(未配置 hasImage 规则时自动生效, 行为与旧写死版一致)。
181
- // ⚠️ 本地手改功能(曾被重编译冲掉),改完务必保持 src 与部署 dist 同步。
182
- agentBody = applyInjectRules(agentBody, msg, config.injectRules, logger, config.imageHint !== false);
183
- // 群友自述 → 临时提醒她"可以记一条"(2026-09-14 主人定:按关键词命中,**零常驻开销**)
184
- // 为什么不常驻:主人定过"用法不写进守则,常驻注入每轮都占 token"。
185
- // 为什么敢用关键词:误报代价极小(最多多记一条,能删;一天只有 3 条额度),漏报也无害(下次再说还会触发)。
186
- // ⚠️ 候选**不止"当前那条"**(主人 2026-09-14 问"和消息聚合什么关系"):
187
- // 消息聚合/批派发时,窗口里前面几条在 mwState.history 里 —— 群聊的 msg.content 只装**最后一条**
188
- // (私聊才是多条拼接)。所以两边都扫、取最近 5 条,与价值评分"取最高"的口径一致(见下方评分段)。
189
- // 更早的历史不进候选:否则会为几天前的老消息反复提醒同一条。
190
- try {
191
- const candidates = [
192
- { text: String(msg.content ?? ''), senderId: msg.senderId, senderName: msg.senderName },
193
- ];
194
- if ((mwState.aggregated === true || mwState.batchDispatch === true) && Array.isArray(mwState.history)) {
195
- for (const h of mwState.history.slice(-5)) {
196
- const e = h;
197
- const t = cleanTextForScore(String(e.content ?? ''));
198
- if (t && typeof e.senderId === 'string') {
199
- candidates.push({
200
- text: t,
201
- senderId: e.senderId,
202
- senderName: typeof e.senderName === 'string' ? e.senderName : undefined,
203
- });
204
- }
205
- }
206
- }
207
- for (const c of candidates) {
208
- const hit = detectSelfDisclosure(c.text);
209
- if (!hit)
210
- continue;
211
- const personKey = `person:${c.senderId}`;
212
- if (countWroteToday(personKey) > 0)
213
- continue; // 这人今天已经记过 → 不唠叨
214
- // 只有"她在意的人"才提醒(主人 2026-09-14 定):
215
- // "每个人都提醒记录会不会太耗费 token…限制只有好感度高了才提醒,其余靠模型自觉,这样才真实"。
216
- // 口径 = 好感度占其**范围**的比例 ≥ 20%(即"亲近"档;范围随熟识度变,陌生人 ±1 所以更容易达标)。
217
- // 没达标的不提醒 —— 靠她自觉(真在意的人,她本来就会留神)。
218
- const dRoot = dataRootOf(config);
219
- const att = attitudeOf(dRoot, personKey);
220
- const affEntry = getAffinityEntry(dRoot, personKey);
221
- const f = affEntry ? memoryStrength(affEntry) : 0;
222
- const ratio = (att?.a ?? 0) / attitudeRange(f);
223
- if (ratio < 0.2)
224
- continue;
225
- if (!bumpHint(personKey))
226
- continue; // 每人每天最多提醒 2 次
227
- agentBody = `${agentBody}\n\n${selfDisclosureHint(hit, c.senderName || c.senderId)}`;
228
- logger.debug(`[小传提醒] 命中"${hit.matched}": ${c.senderName || c.senderId}`);
229
- break; // 一轮最多提醒一条,别刷屏
230
- }
231
- }
232
- catch { /* 提醒失败不影响主链 */ }
233
- // 群聊时间戳(原"群守则"拼接位): 守则已迁 systemPrompt.section(session-manager 装配期注册,
234
- // 每请求进 system, 不再每轮塞 user 历史); 此处改为注入当前系统时间, 让 AI 每轮知道日期/星期/时刻。
235
- // 2026-09-15 省 token: 去掉"当前时间"四个字(上下文里一看就懂), 一条省 ~4 token。
236
- // 2026-10-01 省 token(主人要求): **同一分钟只注入一次** —— 同分钟连发几轮/聚合一波时,
237
- // 重复的时间头(每行 ~25 字符)没有信息量, 直接省掉。见 groupTimeHead()。
238
- if (scope === 'group') {
239
- const _head = groupTimeHead(lastGroupTimeHead, scope, peerId, new Date());
240
- // 2026-10-31 主人拍板「时间头垫底」:放开头会让每轮首 token 都变(prompt 缓存全废),
241
- // 放在消息末尾同样能让 AI 知道当前时间,且不破坏前缀缓存命中。
242
- if (_head)
243
- agentBody = `${agentBody}\n${_head}`;
244
- }
245
- logger.debug(`Processing: scope=${scope} peerId=${peerId} body="${agentBody.slice(0, 200)}"`);
246
- // ── 获取或创建会话 ──
247
- let record;
248
- try {
249
- record = await manager.getOrCreate(scope, peerId, msg.senderId, replyTarget);
250
- }
251
- catch (err) {
252
- const _msg1 = err instanceof Error ? err.message : String(err);
253
- logger.error(`ERROR creating session: ${_msg1}`);
254
- // 2026-10-23 修(真机 harness.log 里每条消息一次的 "already exists"):
255
- // resume 失败 → create 撞上宿主里同 id 的会话 ⇒ 抛错 ⇒ 这里原来直接 return,
256
- // 把用户刚发的整条消息静默吞掉(这就是"漏消息"的一条真因)。
257
- // 改成:换一个 sessionId 重开(forceNew)。宁可这段历史另起一档,也不丢消息。
258
- // [qqbot-mod] retry2 —— 先普通重试两次(不换 id、不丢历史),最后才 forceNew
259
- let _ok = false;
260
- for (const _wait of [300, 700]) {
261
- try {
262
- await new Promise((r) => setTimeout(r, _wait));
263
- record = await manager.getOrCreate(scope, peerId, msg.senderId, replyTarget);
264
- logger.warn(`getOrCreate 第 ${_wait}ms 普通重试成功(会话没换): ${_msg1}`);
265
- _ok = true;
266
- break;
267
- }
268
- catch (_e) {
269
- logger.warn(`getOrCreate 第 ${_wait}ms 普通重试仍失败: ${_e instanceof Error ? _e.message : String(_e)}`);
270
- }
271
- }
272
- if (!_ok) {
273
- try {
274
- record = await manager.getOrCreate(scope, peerId, msg.senderId, replyTarget, { forceNew: true });
275
- logger.warn(`getOrCreate 自愈成功(最后手段:已轮换 sessionId 重开): ${_msg1}`);
276
- }
277
- catch (err2) {
278
- logger.error(`ERROR creating session (重试也失败, 这条只能丢): ${err2 instanceof Error ? err2.message : String(err2)}`);
279
- return;
280
- }
281
- }
282
- }
283
- // ── 工具自愈:setup 竞态漏装时补注册通道工具(幂等,几乎零开销) ──
284
- try {
285
- await manager.ensureChannelTools(record);
286
- }
287
- catch (err) {
288
- logger.debug(`ensureChannelTools error: ${err instanceof Error ? err.message : String(err)}`);
289
- }
290
- // ── qqChannel 上下文自愈: 恢复会话可能没 provide, 工具按本实例路由图库/定时需要它(幂等) ──
291
- try {
292
- await manager.ensureChannelContext(record);
293
- }
294
- catch (err) {
295
- logger.debug(`ensureChannelContext error: ${err instanceof Error ? err.message : String(err)}`);
296
- }
297
- // ── 守则/身份 context 注册自愈(幂等; 重启恢复会话也覆盖, 保证 systemPrompt.context 注入生效) ──
298
- try {
299
- await manager.ensureGroupRules(record);
300
- }
301
- catch (err) {
302
- logger.debug(`ensureGroupRules error: ${err instanceof Error ? err.message : String(err)}`);
303
- }
304
- // ── 构建 UserMessage → followup / (nothink) append 不唤醒 ──
305
- // ⚠️ 2026-09-13 修(主人问"你看到了吗"): 图片预检提示是在**下面的评分段**才追加到 agentBody 的,
306
- // 而这里 message 早就创建好了(用旧文本) → 提示改了变量却没进上下文。故 message 改为 let,
307
- // 评分段若追加过提示会重建一次(见后面 `message = createUserMessage(...)`)。
308
- let content = [{ type: 'text', text: agentBody }];
309
- let message = createUserMessage({
310
- content,
311
- source: { kind: 'user' },
312
- });
313
- // ── 本地小模型价值评分(2026-09-13 主人定, 零 token) ──
314
- // 群聊消息先本地打分: log=只记录分数(观察期, 不改行为) / block=低分不唤醒(消息仍 append 进上下文, 不丢)
315
- // ⚠️ 2026-09-13 会话级(主人要求"单会话设置就得能单独设"): 先算**本会话生效值** ——
316
- // localModel.overrides["group:<gid>"] 优先, 没有则继承账号级默认。
317
- {
318
- const lmCfg = config.localModel;
319
- const ovKey = `${scope}:${peerId}`;
320
- const ovRaw = (lmCfg?.overrides && typeof lmCfg.overrides === 'object'
321
- ? lmCfg.overrides[ovKey]
322
- : undefined) || {};
323
- const gate = ovRaw.valueGate ?? lmCfg?.valueGate ?? 'log';
324
- // ⚠️ 2026-09-27 诊断(主人反馈"评分门槛失效、所有消息都放行"):
325
- // gate 不是 'block' 时 inbound 不拦任何消息(见本文件 770 行),所以必须确认这里读到了什么。
326
- try {
327
- const allKeys = (lmCfg?.overrides && typeof lmCfg.overrides === 'object')
328
- ? Object.keys(lmCfg.overrides) : [];
329
- traceContextless('[gate] ovKey=' + ovKey
330
- + ' 命中=' + (ovRaw && Object.keys(ovRaw).length > 0 ? 'yes' : 'NO')
331
- + ' → gate=' + gate
332
- + ' 账号级gate=' + String(lmCfg?.valueGate)
333
- + ' 会话级valueGate=' + String(ovRaw.valueGate)
334
- + ' | overrides里的key=' + JSON.stringify(allKeys)
335
- + ' | localModel存在=' + (lmCfg ? 'yes' : 'NO'));
336
- }
337
- catch { /* trace 失败不影响主流程 */ }
338
- const baseMin = typeof ovRaw.valueMinScore === 'number'
339
- ? ovRaw.valueMinScore
340
- : (typeof lmCfg?.valueMinScore === 'number' ? lmCfg.valueMinScore : 0.5);
341
- // ── 好感度怎么影响"叫醒判定"(2026-09-14 主人定稿:**加在分数上,不动门槛**)──
342
- // 主人原话:"是不是不应该加减门槛,而是加减消息的最终评分数值?"
343
- // 对 —— 数学上等价(score+off ≥ min ⟺ score ≥ min−off),但**语义干净得多**:
344
- // · 门槛 = 主人设的标准,保持纯粹(你设 0.9 就是 0.9,不会被偷偷改)
345
- // · 偏移加在"这句话在她眼里值多少"上:越亲近越值(正分)、越疏远越不值(负分)
346
- // · 原始分不被污染、偏移单独记,审计一目了然
347
- // ⚠️ 符号(2026-09-14 修):偏移 = **+0.1 × 好感占比** —— 亲近加分、冷淡减分。
348
- // 之前照搬"门槛版"的 −0.1×ratio,冷淡反而 [+0.06] 加分(更容易被叫醒),语义全反。
349
- // 红线:负档也只是"少理/少主动",绝不冷落 / 阴阳 / 攻击。开关 ATTITUDE_GATE_ENABLED 可一键回滚。
350
- const minScore = baseMin;
351
- let attTier;
352
- let attOff = 0;
353
- if (ATTITUDE_GATE_ENABLED) {
354
- try {
355
- const g = attitudeGateFor(dataRootOf(config), `person:${msg.senderId}`);
356
- attTier = g.tier;
357
- attOff = g.offset;
358
- }
359
- catch { /* 算不出 → 不偏移 */ }
360
- }
361
- const lmOn = (ovRaw.enabled ?? lmCfg?.enabled) !== false;
362
- if ((scope === 'group' || scope === 'c2c') && lmOn && gate !== 'off') { // ★ c2c 修复: 私聊原本被整块跳过, 从不评分/不写日志/不拦截
363
- const mentioned = mwState.mention?.wasMentioned === true;
364
- // ★ 2026-10-12:**forceWake 是入站扩展的显式覆盖**(`{dataRoot}/.qqbot-extensions/inbound/*.mjs`
365
- // 里 `ctx.forceWake()` 写的 `ctx.state.qqInboundForceWake`)。
366
- // 语义 = "这条必须进站":跳过一切"值不值得回"的判断(价值评分拦截、免@放行、群冷却等待都在内)。
367
- // 它**不伪造 @**:`mentioned` 仍如实为 false ⇒ 上下文里不会多出假的 (@you),
368
- // 聚合加权/点名豁免这些读 mentioned 的地方照旧不受影响。
369
- // 没有扩展调用 forceWake 时该值恒为 undefined ⇒ 下面三处判定与改动前**逐字一致**(零回归)。
370
- const forced = mwState.qqInboundForceWake === true || msg.forceWake === true;
371
- // 这条消息 @ 的是**别人**(不是她)吗?—— 2026-09-15 主人修正的扣分依据(判据见 mentionsOthers 的注释)
372
- const mentionedOthers = mentionsOthers(msg.mentions, mentioned);
373
- try {
374
- const scorer = createValueScorer({
375
- dataRoot: dataRootOf(config),
376
- modelDir: lmCfg?.modelDir || undefined,
377
- logger,
378
- });
379
- scorer.warmup(); // 后台预热(幂等): 首次入站不等两次加载, 之后零开销
380
- // 评分输入清洗(2026-09-13 主人定): 剥掉合并转发/引用块的结构标记, 只留真实语义。
381
- // 引用消息的**被引用原文**单独算一次分, 与当前消息取较高者(她在回应那句话 → 往往也需要她参与)。
382
- const rawContent = String(msg.content || '');
383
- // 引用块切分(认新旧标记: 新 [引]…[/引], 老 [Quoted message begins]…[ends])
384
- // ⚠️ 用"第一个 begin + 最后一个 end"(不用非贪婪) —— 否则原文里自带标记时会截错(2026-09-13 踩过)
385
- const _qb = findFirstMarker(rawContent, QUOTE_BEGIN_ALL);
386
- const _qe = findLastMarker(rawContent, QUOTE_END_ALL);
387
- const _quoteOk = Boolean(_qb && _qe && _qe.idx > _qb.idx);
388
- const quotedInner = _quoteOk ? rawContent.slice(_qb.idx + _qb.len, _qe.idx) : undefined;
389
- const quotedFull = _quoteOk ? rawContent.slice(_qb.idx, _qe.idx + _qe.len) : undefined;
390
- const currentRaw = quotedFull ? rawContent.replace(quotedFull, ' ') : rawContent;
391
- // ⚠️ 2026-09-15 修(主人:"语音转文字消息没有参与评分吗"):
392
- // 转录文字原来**只进 userContent**(给 AI 看的那份),而评分用的是 msg.content →
393
- // 语音消息在评分链里永远是"无文字"(score=无),哪怕它被清清楚楚转成了文字 ✗
394
- // 现在把转录并入评分文本:语音里说的话,跟打字说的话**一样参与"值不值得接"的判断**。
395
- const voiceForScore = extractVoiceTexts(msg.attachments, mwState.processedAttachments, logger)
396
- .map((v) => v.text)
397
- .filter((t) => t.trim() !== '')
398
- .join(' ');
399
- const plain = cleanTextForScore([currentRaw, voiceForScore].filter((s) => s !== '').join(' '));
400
- const quotedPlain = quotedInner !== undefined ? cleanTextForScore(quotedInner) : '';
401
- // ── 图片消息(2026-09-13 主人定 a+b + B预检) ──
402
- // 小模型只认文字 → 图片本身没法直接评分。三条路都用上:
403
- // a) 纯图片也**记一条**(标 📷, 不可评分, 默认不拦)
404
- // b) 图**已在库** → 借它的 tags+desc 当文字评分(零成本; 能判出"这张她会接")
405
- // B) 注入提示: 已收藏过/新图 —— ⚠️ 实测 QQ 的 fileid **也会变**(2026-09-13 主人重发同图暴露,
406
- // 两次 fileid 只有前 40 字符相同) → 唯一恒定的是**图片字节哈希**(库 id = sha1 前 12 位),
407
- // 所以预检 = 下载到临时文件 → sha1 → 查库 → 用完删。
408
- // 图片 URL 收集(2026-09-13 主人三次实测后定稿): 不再按格式逐种匹配 —— 附件/正文/历史/合并转发
409
- // 各有各的写法, 直接**认 QQ 多媒体 URL 特征**(multimedia.nt.qq.com.cn/download?...fileid=)最稳。
410
- const imgUrls = [];
411
- const collectImg = (text) => {
412
- const re = /https:\/\/multimedia\.nt\.qq\.com\.cn\/download\?[^\s\]))]+/g;
413
- let m;
414
- while ((m = re.exec(text)) !== null) {
415
- const u = m[0];
416
- if (!imgUrls.includes(u))
417
- imgUrls.push(u);
418
- }
419
- };
420
- /**
421
- * 附件按**类型**归类(2026-09-15 主人:"视频和文件不算是图片,为什么也默认唤醒了?")。
422
- *
423
- * 原来只有 `imgUrls`,收集条件是「content_type 含 image」**或**「URL 长得像 QQ 多媒体下载链接」——
424
- * 那个 `||` 让视频/语音/文件全被当成"图",一起触发了"只要带图就一律不拦" ✗
425
- * 现在分工:只有**真图片**进 imgUrls;四种类型各自记一笔,放行时按类型开关走。
426
- */
427
- const attKinds = { image: false, video: false, voice: false, file: false };
428
- // ① 当前消息的附件(分类收集:非图片不进 imgUrls)
429
- for (const a of (Array.isArray(msg.attachments) ? msg.attachments : [])) {
430
- const at = a;
431
- const u = String(at?.url ?? '').trim();
432
- const ct = String(at?.content_type ?? '').toLowerCase();
433
- if (/image/.test(ct))
434
- attKinds.image = true;
435
- else if (/video/.test(ct))
436
- attKinds.video = true;
437
- else if (/voice|audio|record|amr|silk/.test(ct))
438
- attKinds.voice = true;
439
- else if (/file/.test(ct))
440
- attKinds.file = true;
441
- if (u && /image/.test(ct) && !imgUrls.includes(u))
442
- imgUrls.push(u);
443
- }
444
- // ② 当前消息正文(合并转发/引用会把图写在文本里) —— 文本里认不出类型,按"图片"处理(历史行为)
445
- collectImg(String(msg.content || ''));
446
- // ③ 历史里(聚合把图算进 history 时)
447
- for (const h of (Array.isArray(mwState.history) ? mwState.history : [])) {
448
- collectImg(String(h?.content ?? ''));
449
- }
450
- if (imgUrls.length > 0)
451
- attKinds.image = true;
452
- const firstImg = imgUrls[0] || '';
453
- let libItem;
454
- if (firstImg) {
455
- // 内容哈希预检(2026-09-13 改): 直接 https 拿 Buffer → sha1(精确) → 不中再 dHash(容错) → 查库。
456
- // 不再走 attachment.ts 的 download()(带 SSRF 防护, 在宿主里静默失败) 也不落临时文件; 失败留日志。
457
- try {
458
- const store = getStickerStore(stickerDirOf(config));
459
- // 收藏中间件已经把图落盘了 → 直接读盘算哈希, 省掉重复下载(2026-09-13)
460
- const localP = lookupImagePath(firstImg, logger);
461
- let buf;
462
- if (localP) {
463
- try {
464
- buf = readFileSync(localP);
465
- }
466
- catch {
467
- buf = undefined;
468
- }
469
- }
470
- if (!buf || buf.length === 0)
471
- buf = await fetchImageBuffer(firstImg);
472
- if (buf && buf.length > 0) {
473
- const id = createHash('sha1').update(buf).digest('hex').slice(0, 12);
474
- let hit = store.get(id);
475
- // 逐字节不同但"看起来一样"(QQ 重压缩/改尺寸/转格式)? → 用**感知哈希**dHash 再查一次
476
- // ⚠️ 2026-09-13 主人定: 相似匹配**只看正式库(library)** ——
477
- // 候选区全是自动下载的图, 拿它们判"像不像"毫无意义还会误报。
478
- const exactId = hit?.id;
479
- if (!hit) {
480
- const dh = await computeDHash(buf);
481
- if (dh)
482
- hit = store.findByDHash(dh, 5, 'library');
483
- }
484
- libItem = hit;
485
- // 命中(这张图库里/候选区早就有) → 把它**已有的本地文件**记进缓存:
486
- // 这条消息就能直接写本地路径, 不用等这次下载, 也不用重复下(2026-09-13)
487
- if (hit?.id) {
488
- const p = store.pathOf(hit.id);
489
- if (p)
490
- rememberImagePath(firstImg, p);
491
- // 台账兜底: 只有 sha1 精确命中才刷新「id → QQ 链接」——
492
- // dHash 命中的是"看着像"的另一张, 拿它的链接会张冠李戴(保留旧链接更安全)
493
- if (hit.id === exactId)
494
- recordImageUrl(stickerDirOf(config), hit.id, firstImg);
495
- }
496
- }
497
- else {
498
- logger.warn(`im-qqbot: 图片预检下载失败(跳过判重): ${firstImg.slice(0, 70)}…`);
499
- }
500
- }
501
- catch (e) {
502
- logger.warn(`im-qqbot: 图片预检异常(跳过判重): ${e instanceof Error ? e.message : String(e)}`);
503
- }
504
- }
505
- // b) 借库标签: 无文字但有库标签 → 用标签+描述当评分文本
506
- const libText = libItem ? [...(libItem.tags ?? []), libItem.desc ?? ''].filter(Boolean).join(' ').trim() : '';
507
- // 评分: ① 当前消息正文 ② 被引用原话(取较高) ③ 都没有但图在库 → 借库标签 ④ 纯图 → 无分
508
- let sc = plain ? await scorer.score(plain) : undefined;
509
- let scText = plain;
510
- if (quotedPlain) {
511
- const qsc = await scorer.score(quotedPlain);
512
- if (qsc && (!sc || qsc.score > sc.score)) {
513
- sc = qsc;
514
- scText = `[被引用的原话] ${quotedPlain}`;
515
- }
516
- }
517
- if (!sc && libText) {
518
- sc = await scorer.score(libText);
519
- if (sc)
520
- scText = `[图片·库内: ${libText.slice(0, 60)}]`;
521
- }
522
- if (!sc && firstImg)
523
- scText = '[图片]';
524
- let aggCount = 0;
525
- /**
526
- * ★ 归因跟随(2026-09-14 主人查实"扣错人"后加):
527
- * 聚合窗口里"取最高分那条"时,**被计分的那句话可能不是最后一个人说的**。
528
- * 原来 `scText` 换成了别人的话,而下面所有归因(熟识度 / 好感度 / 语气 /
529
- * 评分日志的 sender)仍用 `msg.senderId`(窗口里**最后**发言的人)→
530
- * 实测把「大肥鱼怎么不插话了」(某位路人说的)算到了「愤怒的小鸟」头上,
531
- * 还用**那个路人的语气**当他的语气,最后扣了他 −0.12。
532
- * 现在:scText 换成谁的话,发送者就跟着换成谁。
533
- */
534
- let srcSenderId = msg.senderId;
535
- let srcSenderName = msg.senderName;
536
- let srcFromWindow = false;
537
- /** 加权综合分(只在加权模式下有值;含各条自己的好感偏移) */
538
- let aggScore;
539
- /** 2026-09-15 修回归 bug: 聚合窗口历史里任一条 @ 了她也算本轮被点名 ——
540
- * 原来豁免只看当前那条(mwState.mention), 历史里 @ 了而当前那条没 @ 时会被低估拦下。 */
541
- let aggMentioned = false;
542
- /** 加权明细(进日志,便于事后核对"这个分是怎么平均出来的") */
543
- let aggParts;
544
- // B) 预检提示: 图片消息附一句 —— ⚠️ **只在真·有信息量时才提示**(2026-09-13 主人定):
545
- // 候选区(candidate)是插件自动下载的默认状态, 每张图都会落进去 →
546
- // 提示它纯属噪音, 所以候选区/新图**一律不提示**; 只提示「已收藏过」和「在回收站」。
547
- if (firstImg) {
548
- const lb = libItem;
549
- const tg = (lb?.tags ?? []).join('/') || '无';
550
- const hint = lb?.layer === 'library'
551
- ? `\n[这张图你已收藏过(标签: ${tg}) —— 不用再收藏]`
552
- : lb?.layer === 'trash'
553
- ? '\n[这张图在回收站里(之前清掉的) —— 想用就还原它]'
554
- : '';
555
- if (hint) {
556
- agentBody = `${agentBody}${hint}`;
557
- // ⚠️ 提示是在 message 创建之后追加的 → 必须重建 message, 否则这句进不了上下文(2026-09-13 修)
558
- content = [{ type: 'text', text: agentBody }];
559
- message = createUserMessage({ content, source: { kind: 'user' } });
560
- }
561
- }
562
- // 群友小传按需注入(2026-09-13 主人定): 走**运行时上下文**(plugin 来源) ——
563
- // AI 看得到, 而聊天界面会把它当上下文过滤掉, 不打扰 web/dock 观感。
564
- // 同一人 24h 内不重复注入(防监视感); 注入失败不影响主链。
565
- try {
566
- const uid = msg.senderId;
567
- const lastAt = memoInjectAt.get(uid) ?? 0;
568
- if (scope === 'group' && uid && Date.now() - lastAt > 24 * 3600_000) {
569
- const embedder = createLocalEmbedder({
570
- modelDir: typeof lmCfg?.modelDir === 'string' ? lmCfg.modelDir : undefined,
571
- logger,
572
- });
573
- const r = await recallLines(dataRootOf(config), uid, plain || scText || '', embedder, 2);
574
- if (r.lines.length > 0) {
575
- const memoText = `[人家记得的 ${msg.senderName || '他'}: ${r.lines.map((l) => l.replace(/^-\s*/, '')).join(' / ')}]`;
576
- // 交给 systemPrompt.context(运行时上下文贡献)注入 —— 不写进用户消息, 不打扰 web/dock 观感,
577
- // 且 system prompt 保持字节级稳定 → 前缀缓存全程命中(与 @a9i5k4/dsh-auto-memory 同款姿势)
578
- setPendingMemo(memoText);
579
- memoInjectAt.set(uid, Date.now());
580
- }
581
- }
582
- }
583
- catch { /* 小传注入失败不影响主链 */ }
584
- // 聚合/批派发时"取最高"(2026-09-13 主人问): 窗口里可能有多条(如「哈哈哈」+「帮我看看这个报错」),
585
- // 只算"当前那条"会漏掉窗口里真正需要她的那条 → 对窗口内最近几条也打分, 取最高分那条为准。
586
- if ((mwState.aggregated === true || mwState.batchDispatch === true) && Array.isArray(mwState.history)) {
587
- // ⚠️ 2026-09-13 修: 这里之前直接拿 history 的**原始文本**评分 → 合并转发/引用块的格式元数据
588
- // 又混进来了(实测记录里 text 是 `[群聊的聊天记录] === 消息 1 ===…`)。统一过清洗。
589
- const extras = mwState.history
590
- .map((h) => ({
591
- text: cleanTextForScore(String(h.content ?? '')),
592
- senderId: h.senderId,
593
- senderName: h.senderName,
594
- mentioned: h.mentioned === true,
595
- }))
596
- .filter((e) => e.text !== '')
597
- .slice(-5);
598
- aggCount = extras.length;
599
- // 2026-09-15: 窗口里任一条 @ 过她 → 本轮算被点名(供下面 !mentioned 豁免与面板标记共用)
600
- if (extras.some((e) => e.mentioned))
601
- aggMentioned = true;
602
- const others = await Promise.all(extras.map((e) => scorer.score(e.text)));
603
- // 候选池 = 当前那条 + 窗口里那几条(每条都带着"是谁说的")
604
- const pool = [
605
- { text: scText, score: sc?.score, senderId: msg.senderId, senderName: msg.senderName, mention: mentioned, fromWindow: false },
606
- ...extras.map((e, i) => ({
607
- text: e.text,
608
- score: others[i]?.score,
609
- senderId: e.senderId,
610
- senderName: e.senderName,
611
- mention: e.mentioned,
612
- fromWindow: true,
613
- })),
614
- ].filter((p) => typeof p.score === 'number');
615
- if (AGG_SCORE_MODE === 'weighted' && pool.length > 1) {
616
- // 每条先补上"说话人的好感占比 / 偏移"(读台账,所以留在外面做),再交给纯函数算加权
617
- const cands = pool.map((p) => {
618
- let ratio = 0;
619
- let offset = 0;
620
- let tier;
621
- if (ATTITUDE_GATE_ENABLED) {
622
- try {
623
- const g = attitudeGateFor(dataRootOf(config), `person:${p.senderId}`);
624
- ratio = g.ratio;
625
- offset = g.offset;
626
- tier = g.tier;
627
- }
628
- catch { /* 算不出 → 按中立 */ }
629
- }
630
- return { text: p.text, score: p.score, ratio, offset, mention: p.mention, name: p.senderName, tier, senderId: p.senderId, fromWindow: p.fromWindow };
631
- });
632
- const agg = weightedAggregate(cands);
633
- if (agg) {
634
- aggScore = agg.score;
635
- aggParts = agg.parts;
636
- // ★ 主角 = 权重最大那条:文本 / 归因 / 档位全跟着它,绝不"平均出一个不存在的人"
637
- const top = cands[agg.topIndex];
638
- if (top) {
639
- scText = top.text || scText;
640
- srcSenderId = top.senderId;
641
- srcSenderName = top.name;
642
- srcFromWindow = top.fromWindow;
643
- attTier = top.tier ?? attTier;
644
- attOff = top.offset; // 只用于日志(分值里已经各自算过偏移,别再加一次)
645
- }
646
- }
647
- }
648
- else {
649
- // 旧口径:取最高
650
- others.forEach((o, i) => {
651
- if (!o)
652
- return;
653
- if (!sc || o.score > sc.score) {
654
- sc = o;
655
- scText = extras[i]?.text ?? scText;
656
- // ★ 文本换人 → 归因也换人(否则就是"用别人的语气、扣别人的分")
657
- srcSenderId = extras[i]?.senderId ?? srcSenderId;
658
- srcSenderName = extras[i]?.senderName ?? srcSenderName;
659
- srcFromWindow = true;
660
- }
661
- });
662
- }
663
- }
664
- // 记录: 有分数→正常记; 纯图片无分数→也记一条(标 img, 让"图片也在观察范围"看得见)
665
- // ⚠️ 2026-09-15 改:**任何附件**都要进这个块 —— 否则"纯视频 / 纯文件"(既没文字、又不是图)
666
- // 会整块跳过"值不值得唤醒"的判断,等于无条件放行,附件开关就形同虚设了。
667
- const hasAnyAttachment = attKinds.image || attKinds.video || attKinds.voice || attKinds.file;
668
- // 2026-09-30: 纯文字**没算出分**时也记一行(标 无分) —— 否则观察期里看不出这条到底评没评
669
- const textNoScore = !sc && !firstImg && !hasAnyAttachment && String(msg.content || '').trim() !== ''; // ⚠️ 只能用此处已在作用域内的 msg.content(scText 声明在后面, 引用会 TDZ 抛错)
670
- if (sc || firstImg || hasAnyAttachment || textNoScore) {
671
- // 会话级门槛: 用本会话算出的 minScore 判定(不是 scorer 内部的默认值); 无分(纯图)视作放行
672
- // 判定分:加权模式用**综合分**(Σ权×有效分 / Σ权,各条的好感偏移已在里面算过);
673
- // 单条模式仍是 原始分 + 好感偏移。⚠️ 别重复加偏移(加权时 attOff 只用于日志)。
674
- // 再减"**@了别人**"的惩罚(2026-09-15 主人修正:不是"没人@她"要扣分 ——
675
- // 没人@她恰恰是她该主动挑话插的常态;真正该扣的是"这句 @ 的是别人",那轮对话方向是那个人)。
676
- const mentionPen = mentionedOthers ? OTHER_MENTION_PENALTY : 0;
677
- const effScore = (aggScore !== undefined ? aggScore : (sc ? sc.score + attOff : 0)) - mentionPen;
678
- // ── 附件唤醒开关(2026-09-15 主人定:图片/视频/语音/文件**分别**决定是否无视分数唤醒)──
679
- // 现状问题:原来只要是"带图"就一律放行 —— 而"图"里混着视频/语音/文件(收集时不区分格式)。
680
- // 新规则:
681
- // · 有分数 → 够分 **或** 该类型允许放行
682
- // · 没分数(纯附件、没文字可评)→ **只有该类型允许放行**才唤醒
683
- // ↳ 这条是关键:否则"取消勾选"等于没勾(无分一律放行的话,开关形同虚设)
684
- const attP = config.localModel?.attachmentPassthrough ?? {};
685
- const mediaPass = (attKinds.image && attP.image !== false) || // 图片:默认放行(群友发图常是给她看的)
686
- (attKinds.video && attP.video === true) || // 视频:默认不放行
687
- (attKinds.voice && attP.voice === true) || // 语音:默认不放行(有转录文字就按文字评)
688
- (attKinds.file && attP.file === true); // 文件:默认不放行
689
- const worth = sc ? (effScore >= minScore || mediaPass) : mediaPass;
690
- try {
691
- traceContextless('[gate] worth=' + String(worth) + ' gate=' + gate + ' min=' + String(minScore)
692
- + ' score=' + (sc ? sc.score.toFixed(3) : '无分') + ' eff=' + String(effScore) + ' mediaPass=' + String(mediaPass));
693
- }
694
- catch { /* ignore */ }
695
- // ① 相关度(观察期, **只记录不参与判定**): 当前消息 ↔ 她上一条发言 / 群里最近 5 条(2026-09-13 主人定)
696
- const rel = await computeRelevance({
697
- gid: scope === 'group' ? (msg.groupOpenid ?? '') : 'c2c',
698
- currentText: scText || plain,
699
- history: mwState.history,
700
- modelDir: typeof lmCfg?.modelDir === 'string' ? lmCfg.modelDir : undefined,
701
- logger,
702
- }).catch(() => undefined);
703
- // ③ 情绪粗分类(观察期**只记录**): 暖/冷/中性(2026-09-14 由"夸/骂"改名)—— 同一个本地模型 + 主人给的 60 条例句库
704
- const emo = await classifyEmo(scText || plain, {
705
- modelDir: typeof lmCfg?.modelDir === 'string' ? lmCfg.modelDir : undefined,
706
- logger,
707
- }).catch(() => undefined);
708
- // ② 好感度台账(观察期, **只统计不生效**): 互动 / 被点名 / 接话(相关度≥0.6)
709
- try {
710
- // ⚠️ 2026-09-13 修(借主人截图发现): 键原来只到"会话"(scope:peerId), 于是**整群消息累加到一条**、
711
- // 名字还被最后一个发言人覆盖(截图里"愤怒的小鸟 消息85"其实是整群总数)。改成**按人分键**。
712
- touchAffinity(dataRootOf(config), `person:${srcSenderId}`, {
713
- name: srcSenderName,
714
- mention: mentioned,
715
- reply: (rel?.relReply ?? 0) >= 0.6,
716
- });
717
- // 好感度(A 值)需要知道"这一轮在跟她说话的**是谁**"——出站事件只带会话、不带发送者,
718
- // 所以这里记一下最近发言的人,出站时用(键与会话一致:<scope>:<targetId>)。
719
- // ⚠️ 用 srcSender*(= 被计分那句话的真正说话人),不是 msg.sender*。
720
- noteLastSender(scope === 'group' ? `group:${msg.groupOpenid ?? ''}` : `c2c:${srcSenderId}`, srcSenderId, srcSenderName, confidentEmo(emo));
721
- // 日报台账(2026-09-13 主人要《本周亲密度小报》): 按天分桶, 只记肉眼可核的事实
722
- if (scope === 'group' && msg.groupOpenid) {
723
- touchDaily(dataRootOf(config), msg.groupOpenid, srcSenderId, {
724
- name: srcSenderName,
725
- mention: mentioned,
726
- reply: (rel?.relReply ?? 0) >= 0.6,
727
- img: Boolean(firstImg),
728
- });
729
- }
730
- }
731
- catch { /* ignore */ }
732
- appendScoreLog(dataRootOf(config), {
733
- gid: scope === 'group' ? (msg.groupOpenid ?? '') : 'c2c',
734
- sender: srcSenderName || srcSenderId,
735
- // ★ 记下"sender 是从聚合窗口里挑出来的"(不是窗口最后那个人)—— 排查归因问题必需
736
- senderFromWindow: srcFromWindow || undefined,
737
- mention: mentioned || aggMentioned || undefined,
738
- score: sc ? Math.round(sc.score * 1000) / 1000 : undefined,
739
- // 判定真正用的分:加权模式=Σ(权×有效分)/Σ权;单条模式=原始分+好感偏移
740
- // 判定分:有原始分**或**有加权综合分,都要记。
741
- // (2026-09-14 修:原来只在 sc 存在时记 —— 纯图那条自己没分、但窗口里别人有分,
742
- // 加权综合分照样成立,结果面板显示成「📷 + [合·加权]」自相矛盾)
743
- scoreAdj: (sc || aggScore !== undefined) ? Math.round(effScore * 1000) / 1000 : undefined,
744
- worth,
745
- // 被点名 → **必回**(2026-09-14 主人:"@不是保证触发吗?")
746
- // 拦截条件三处都写着 `!mentioned`,所以被 @ 时分数再低也放行;
747
- // 但 worth 只表示"分数够不够",日志里会显示成没通过 → 单记一个字段说明白。
748
- mentionForced: (mentioned || aggMentioned) || undefined,
749
- // ★ 2026-10-12:这条是**入站扩展强制入站**(`ctx.forceWake()`)—— 与"被 @"分开记,
750
- // 排查"为什么低分还回话"时一眼能分辨是扩展显式要求的,而不是评分坏了。
751
- forceWake: forced || undefined,
752
- forceWakeWhy: forced ? (typeof mwState.qqInboundForceWakeReason === 'string' ? mwState.qqInboundForceWakeReason : undefined) : undefined,
753
- min: minScore,
754
- // 好感度档位与偏移(2026-09-14 定稿:偏移**加在分数上**,门槛保持主人设的值不动)
755
- // ⚠️ 加权模式下 attTier/attOff 是**主角那条**的(权重最大的人),分值本身已各算各的
756
- attTier,
757
- attOff: attOff || undefined,
758
- // @了别人 → 判定分扣了多少(2026-09-15 加;0/undefined = 没扣)
759
- pen: mentionPen || undefined,
760
- penWhy: mentionPen ? 'mentionOther' : undefined,
761
- // 加权明细:每条 {n:昵称, s:价值分, r:好感占比, w:权重} —— 事后能复算出综合分
762
- aggWeighted: aggParts ? true : undefined,
763
- aggParts,
764
- minBase: baseMin,
765
- gate, // 2026-09-13 加: 记下**当时生效的模式**(排查"为什么低分还回话"必需; 以前只记 min, log/block 分不出来)
766
- img: firstImg ? true : undefined,
767
- // 附件类型(2026-09-15):记下这条带的是视频/语音/文件,便于核对"开关到底生没生效"
768
- mediaKinds: hasAnyAttachment
769
- ? Object.entries(attKinds).filter(([, v]) => v).map(([k]) => k).join('+')
770
- : undefined,
771
- lib: libItem ? true : undefined,
772
- // 图在库 ≠ 能借它评分:**待整理区(candidate)的图还没打标签/描述**,
773
- // 借不到文字 → 评不了分。分开记一个字段,面板好把话说明白
774
- // (2026-09-14 主人问"怎么有时候评分变成一个 emoji 了"时发现的)
775
- libText: libText ? true : undefined,
776
- conf: sc ? Math.round(sc.confidence * 1000) / 1000 : undefined,
777
- // 相关度(观察期): relReply=接她的话 / relHist=接群里的话题 / final=期望的融合分(暂不生效)
778
- relReply: rel?.relReply,
779
- // 情绪粗分类(观察期只记录): emo=暖|冷|中性(2026-09-14 从"夸/骂"改名), 分数与差值便于事后核对准不准
780
- emo: emo?.label,
781
- emoScore: emo?.best,
782
- emoMargin: emo?.margin,
783
- relHist: rel?.relHist,
784
- final: sc ? Math.round((0.6 * sc.score + 0.25 * (rel?.relReply ?? 0) + 0.15 * (rel?.relHist ?? 0)) * 1000) / 1000 : undefined,
785
- agg: aggCount || undefined,
786
- top: sc ? sc.top.map((n) => `${n.m.slice(0, 14)}|${n.y}|${n.s.toFixed(2)}`) : undefined,
787
- text: scText.slice(0, 120),
788
- });
789
- if (sc) {
790
- logger.debug(`im-qqbot: 价值评分 ${sc.score.toFixed(3)} worth=${worth} min=${minScore} gate=${gate} conf=${sc.confidence.toFixed(2)} mention=${mentioned} agg=${aggCount} "${scText.slice(0, 40)}"`);
791
- }
792
- // block 模式: 低分 且 未被 @ 且 **不带图** → 不唤醒(append 进上下文, 消息不丢)
793
- // ⚠️ 2026-09-13 主人定稿: **取消低置信保护** —— 被 @ 的永远放行, 其余一律只看分数。
794
- //
795
- // ⚠️ 2026-09-13 三次修(主人问"图片的消息不受影响吧" —— 查记录发现**真的受影响**):
796
- // 纯图片(sc 为空)本来就不拦, 但**库里已有的图**会借库标签当评分文本 → 因此有分数,
797
- // 而且那个分数往往是低分(实测: 【表情: 微笑】+库内图 = 0.022) → 被拦掉。
798
- // 这跟"群友发图往往是给她看/求接梗"的初衷完全相反 ⇒ 现在**只要带图就一律不拦**
799
- // (分数照记, 便于主人观察; 只是不拿它做拦截判定)。
800
- // 2026-09-15 改(主人:"视频和文件不算是图片,为什么也默认唤醒了?"):
801
- // 入口条件去掉 `sc &&` 与 `!firstImg` —— 无分(纯视频/纯文件)也要能拦,
802
- // "该不该放行"全交给上面的 worth(含**附件类型开关**),这里只负责执行。
803
- // (原来"带图不拦"里那个 firstImg 是**不区分格式**的,视频/文件跟着沾光 ✗)
804
- // ★ 2026-10-12 加 `!forced`:入站扩展用 `ctx.forceWake()` 显式要求"这条必须进站"时,
805
- // 连价值评分拦截也不再适用(forceWake 的定义就是"跳过一切值不值得回的判断")。
806
- const _scCfg = (lmCfg && lmCfg.specialCare && typeof lmCfg.specialCare === 'object') ? lmCfg.specialCare : {};
807
- const _scGroups = Array.isArray(_scCfg.groups) ? _scCfg.groups.map(String) : [];
808
- const _scPeople = Array.isArray(_scCfg.people) ? _scCfg.people.map(String) : [];
809
- const specialCare = _scGroups.includes(String(peerId)) || _scGroups.includes(String(ovKey))
810
- || _scPeople.includes(String(msg.senderId)) || _scPeople.includes(String(srcSenderId));
811
- if (specialCare) {
812
- try { traceContextless('[gate] special-care=true sender=' + String(srcSenderId) + ' group=' + String(peerId)); } catch { }
813
- }
814
- if (gate === 'block' && scope === 'group' && !mentioned && !aggMentioned && !forced && !specialCare && !worth) {
815
- const ag = record.agent;
816
- const sess = ag?.session;
817
- let appended = false;
818
- // ★ 2026-10-06: 人设未落盘的新会话【绝不能】静默 append(会把会话日志写废,
819
- // 见 session/surface-guard.ts)。跳过即可:内容不丢,下次唤醒由 [历史] 段带入。
820
- if (sess && typeof sess.append === 'function' && !skipSilentAppend(ag, logger, '价值评分')) {
821
- if (typeof ag?.whenIdle === 'function') {
822
- try {
823
- await Promise.race([ag.whenIdle(), new Promise((r) => setTimeout(r, 60_000))]);
824
- }
825
- catch { /* 超时继续追加 */ }
826
- }
827
- try {
828
- sess.append('user/message', message, { surfaceOp: 'append' });
829
- appended = true;
830
- }
831
- catch (err) {
832
- logger.warn(`[价值评分] 低分 append 失败(仍然不唤醒): ${err instanceof Error ? err.message : String(err)}`);
833
- }
834
- }
835
- else {
836
- logger.warn('[价值评分] 低分但会话无 append 能力 —— 仍然不唤醒(这条可能不进上下文)');
837
- }
838
- record.lastInboundAt = Date.now();
839
- logger.debug(`[价值评分] 不唤醒 ${sc ? sc.score.toFixed(2) : `无分`}<${minScore} (gate=block, appended=${appended}): key=${scope}:${peerId} "${plain.slice(0, 30)}"`);
840
- // ⚠️ 2026-09-13(主人要求"没产生回复就别消耗回复冷却"): 上游派发时戳了一枚群冷却,
841
- // 既然这次**没唤醒=没回复**, 就把那枚冷却还回去 —— 否则一条低分闲聊会白让群里静默 90 秒。
842
- const rb = mwState.qqCooldownRollback;
843
- if (rb && typeof rb.restore === 'function') {
844
- try {
845
- rb.restore();
846
- mwState.qqCooldownRollback = undefined;
847
- logger.debug('[价值评分] 已回滚本群回复冷却(本次没产生回复)');
848
- }
849
- catch (err) {
850
- logger.warn(`[价值评分] 冷却回滚失败(忽略): ${err instanceof Error ? err.message : String(err)}`);
851
- }
852
- }
853
- clearGroupHistory(config.appId, msg.groupOpenid ?? msg.senderId);
854
- return;
855
- }
856
- // ② 附件放行(图片默认放行、或主人勾了放行的类型):只打日志,分数照记
857
- // ★ 2026-10-12 加 `!forced`:forceWake 已经无条件放行了,这条日志不该再说"附件放行"。
858
- if (gate === 'block' && !mentioned && !forced && mediaPass && (sc ? sc.score < minScore : true)) {
859
- const kinds = Object.entries(attKinds).filter(([, v]) => v).map(([k]) => k).join('+');
860
- logger.debug(`[价值评分] 附件放行(${kinds || '未知'})不看分数 ${sc ? sc.score.toFixed(2) : '无分'}<${minScore}: key=${scope}:${peerId}`);
861
- }
862
- // ★ 2026-10-12:forceWake 导致的"低分照样进站"单独留一行——排查"为什么低分还回话"时,
863
- // 看到这行就知道是**入站扩展显式要求**的(而不是模式配错/评分坏了)。
864
- if (forced && !worth) {
865
- logger.debug(`[价值评分] 强制入站(入站扩展 forceWake${String(mwState.qqInboundForceWakeReason ?? '') ? `: ${String(mwState.qqInboundForceWakeReason)}` : ''})` +
866
- ` → 跳过低分拦截 ${sc ? sc.score.toFixed(2) : '无分'}<${minScore}${aggCount ? ` agg=${aggCount}` : ''}: key=${scope}:${peerId} "${plain.slice(0, 30)}"`);
867
- }
868
- if (sc && gate !== 'block' && !mentioned && !forced && !worth) {
869
- // ⚠️ 提到 info(2026-09-13): 主人排查"低分为什么还回话"时, 一眼就能在控制台看到
870
- // "哦,是模式还在 log" —— 而不是靠猜。平时也就每次群消息一行, 可接受。
871
- logger.debug(`[价值评分] 低分放行(模式=${gate} 不是 block 所以不拦) ${sc.score.toFixed(2)}<${minScore}${aggCount ? ` agg=${aggCount}` : ''}: key=${scope}:${peerId} "${plain.slice(0, 30)}"`);
872
- }
873
- }
874
- }
875
- catch (e) {
876
- // ⚠️ 这条是**fail-open 的可见化**: 评分环节出异常 = 照旧唤醒(不能因为打分坏了把群静音),
877
- // 但必须在控制台留痕迹, 否则"低分还回话"永远查不出来。
878
- logger.warn(`im-qqbot: 价值评分异常(本次照常唤醒): ${e instanceof Error ? e.message : String(e)}`);
879
- }
880
- }
881
- }
882
- // 完全不思考(nothink, 2026-09-07 主人定): QQ 入站不唤醒 LLM, 但消息仍要进入上下文。
883
- // 组装好的完整 agentBody(含时间戳/发送者标签/历史)以 user/message append 进会话,
884
- // surfaceOp='append' 不唤醒 —— 下次 web 对话或真人消息唤醒时, AI 自然看到这段记录。
885
- if (config.outboundMode === 'nothink') {
886
- const a = record.agent;
887
- const sess = a?.session;
888
- if (sess && typeof sess.append === 'function') {
889
- // ★ 2026-10-06: 人设未落盘 ⇒ 绝不能静默 append(会把会话日志写废,见 surface-guard.ts)。
890
- // nothink 的语义是「不唤醒」,所以这里保持不唤醒并直接返回:消息不丢 ——
891
- // 它还在群历史里,下次真人消息唤醒时由 [历史] 段带入正文。
892
- if (skipSilentAppend(a, logger, 'nothink')) {
893
- record.lastInboundAt = Date.now();
894
- return;
895
- }
896
- try {
897
- // 🔒 等 LLM 回合结束再 append(主人硬约束 2026-09-09): 回合活跃时严禁 append(拆散 tool_calls 坏记录)
898
- if (typeof a.whenIdle === 'function') {
899
- try {
900
- await Promise.race([a.whenIdle(), new Promise((r) => setTimeout(r, 60_000))]);
901
- }
902
- catch { /* 超时/异常放弃写回 */ }
903
- }
904
- record.lastInboundAt = Date.now();
905
- sess.append('user/message', message, { surfaceOp: 'append' });
906
- logger.debug(`[nothink] 已 append(不唤醒): key=${scope}:${peerId}`);
907
- // append 后同样清群历史缓存: 避免下次真人触发时把这段再打包一遍(上下文不重复)
908
- if (scope === 'group') {
909
- clearGroupHistory(config.appId, msg.groupOpenid ?? msg.senderId);
910
- }
911
- return;
912
- }
913
- catch (err) {
914
- logger.warn(`[nothink] append 失败, 退回正常 followup: ${err instanceof Error ? err.message : String(err)}`);
915
- }
916
- }
917
- else {
918
- logger.warn(`[nothink] 会话无 append 能力, 退回正常 followup: key=${scope}:${peerId}`);
919
- }
920
- // 无 append 能力 → 兜底照常 followup(保证消息不丢, 但会唤醒; 罕见路径)
921
- record.lastInboundAt = Date.now();
922
- record.turnActive = true;
923
- record.agent.followup(message);
924
- logger.debug(`→ followup sent(nothink 兜底): key=${scope}:${peerId}`);
925
- return;
926
- }
927
- record.lastInboundAt = Date.now();
928
- // 置回合活跃(消息聚合, 2026-09-07): followup 发出即算回合开始, debounce 见忙攒消息; turn/end 由 outbound 复位
929
- record.turnActive = true;
930
- record.agent.followup(message);
931
- logger.debug(`→ followup sent: key=${scope}:${peerId}`);
932
- // 群消息回复后清空历史缓存(避免下次 @ 时重复组包,对齐 openclaw-qqbot dispatch)
933
- if (scope === 'group') {
934
- clearGroupHistory(config.appId, msg.groupOpenid ?? msg.senderId);
935
- }
936
- }
937
- // ══════════════════════════════════════════════════════════════
938
- // Body Assembly(对齐 openclaw-qqbot 5 层组装)
939
- // ══════════════════════════════════════════════════════════════
940
- /**
941
- * 组装 agentBody — AI 实际看到的完整上下文
942
- */
943
- function assembleAgentBody(msg, state, scope, logger, downloaded, enableRef, msgRef, dataRoot, stickerDir) {
944
- const userContentRaw = buildUserContent(msg, state, logger);
945
- // 2026-10-01 主人实测「别人 @ 别人怎么没转换成昵称,依然是 id」:
946
- // 正文里 @ 别人的 `<@openid>` 查**群成员台账**换成 `@昵称`(查不到退化成 @短id);
947
- // 顺手省 token —— `<@07B470BDA5052489D2D0532C2CC2A2EB>`(35 字符) → `@难崩`(3 字符)。
948
- let userContent = resolveMentionNames(userContentRaw, stickerDir, scope === 'group' ? msg.groupOpenid : undefined);
949
- // ★ P0-2 修复:原来这里 return null → 上游静默 return,而 debounce 早已把这条从
950
- // 窗口删掉、也打过群冷却 ⇒ 只要有人"只 @ 她、不打字",同批里排在前面的真实消息会
951
- // **一起被吞掉**,且全链路零日志。改为给一句占位正文继续走,消息不再丢。
952
- if (!userContent && (!msg.attachments || msg.attachments.length === 0)) {
953
- try { logger?.warn?.('[im-qqbot] 入站正文为空(只@未打字?) → 用占位正文继续,避免吞掉同批消息'); } catch { }
954
- userContent = '(只 @ 了你一下,没有文字)';
955
- }
956
- // ⚠️ 2026-10-01: QQ 引用**纯图片**时 msg_elements 给不出图 —— 先用本地台账补一把(见 msg-content-cache.ts)
957
- const quotePeer = `${scope}:${scope === 'group' ? (msg.groupOpenid ?? msg.senderId) : msg.senderId}`;
958
- const quote = enrichQuoteFromCache(state.quote, dataRoot, quotePeer);
959
- let quotePart = buildQuotePart(quote, stickerDir);
960
- // 引用消息(2026-09-13): SDK 中间件没解析出 quote 时, 自己从 103/msg_elements 提取被引用原文
961
- if (!quotePart && enableRef) {
962
- const quoted = extractQuotedContent(msg);
963
- // ⚠️ 2026-10-01 主人实测抓到的**漏网之鱼**:这条路(SDK 没解析出 quote 时的兜底)拿到的是
964
- // `msg_elements` 的**原串** —— `=== 消息 1 === [消息内容] … [消息类型] 引用消息 …` 模板串,
965
- // 原来没剥壳就直接塞进上下文(还会被 trimQuoteBlock 按"519 字"截断+缓存,看着莫名其妙)。
966
- // 这里跟 buildQuoteBlock 用**同一套清洗**:剥模板壳 + 只留最外层那句 + 表情转可读。
967
- const lines = [];
968
- const slim = quoted ? slimQuoteText(quoted, 0) : '';
969
- if (slim)
970
- lines.push(escapeBlockMarkers(slim));
971
- // ⚠️ 2026-10-01 补(主人问"多图+文本混合考虑了吗"时发现的缺口):
972
- // SDK 连 quote 都没解析出来时,**也要查我们自己的内容台账** —— 否则"引用一条图片表情 /
973
- // 纯图片消息"永远是空的(QQ 那边只给一个空表情标签,没有任何媒体标识)。
974
- // 被引用消息的索引藏在 `message_scene.ext` 的 `ref_msg_idx=` 里。
975
- // 台账天然支持**多图 + 文本混合**(imgs 是数组,逐张出行)。
976
- const _ext = Array.isArray(msg.message_scene?.ext) ? msg.message_scene.ext : [];
977
- const _refRaw = _ext.find((x) => typeof x === 'string' && x.startsWith('ref_msg_idx='));
978
- const refIdx = typeof _refRaw === 'string' ? _refRaw.slice('ref_msg_idx='.length).trim() : '';
979
- if (refIdx) {
980
- const hit = lookupMsgContent(dataRoot, quotePeer, refIdx);
981
- if (hit) {
982
- if (!slim && hit.t)
983
- lines.push(escapeBlockMarkers(slimQuoteText(hit.t, 0)));
984
- for (const p of hit.imgs ?? []) {
985
- const line = describeQuoteAttachment({ contentType: 'image/*', url: p }, stickerDir);
986
- if (line)
987
- lines.push(line);
988
- }
989
- }
990
- }
991
- // ⚠️ 2026-10-01:这里**不再自带** `[当前]` —— 它由 Layer 5(buildAgentBody) 统一输出,
992
- // 否则群聊带引用时会出现两个 `[当前]`,引用块被夹在中间(主人实测:"引用被塞到当前外面")。
993
- if (lines.length > 0)
994
- quotePart = `${MK.QUOTE_BEGIN}\n${lines.join('\n')}\n${MK.QUOTE_END}\n`;
995
- }
996
- // ⚠️ 2026-09-13 主人要求(省 token): 引用原文只给**前 QUOTE_KEEP 字**,
997
- // 完整原文进本地缓存(每会话最多 10 条) → AI 需要时用 `quote_view` 工具取。
998
- quotePart = trimQuoteBlock(quotePart, dataRoot, msg, logger);
999
- const isGroup = scope === 'group';
1000
- const wasMentioned = state.mention?.wasMentioned ?? false;
1001
- const batchDispatch = state.batchDispatch === true;
1002
- const aggregated = state.aggregated === true;
1003
- const userMessage = buildUserMessage(userContent, quotePart, msg.senderId, msg.senderName, isGroup, wasMentioned, msgRef);
1004
- const dynamicCtx = buildDynamicCtx(msg, downloaded);
1005
- const base = dynamicCtx ? `${dynamicCtx}${userMessage}` : userMessage;
1006
- // ⚠️ 2026-09-10 去重(主人: "图片链接重复两次"): 聚合/冷却重新派发时, 同一条消息会**既被
1007
- // mediaHistoryBuffer 记进历史、又作为当前消息出现** → 同一条消息(含媒体 URL)在上下文里出现
1008
- // 两遍: 历史里是 `[昵称] [图片: url]`(foldMedia 折叠版), 当前是 Layer4 的 `- Image: 名 → url`。
1009
- // 按 messageId 剔掉历史中与当前消息重复的那条。
1010
- const history = (state.history ?? [])
1011
- .filter(h => !h.messageId || h.messageId !== msg.messageId)
1012
- // 省 token: 历史里的 `[图片: <250 字符长链接>]` → 本地路径 / 干脆 `[图片]`
1013
- .map(h => ({ ...h, content: localizeHistoryImages(String(h.content ?? ''), stickerDir) }));
1014
- const agentBody = buildAgentBody(base, history, isGroup, wasMentioned, batchDispatch, aggregated, scope);
1015
- return agentBody;
1016
- }
1017
- /**
1018
- * Layer 1: 用户文本内容 + 语音 + 附件
1019
- */
1020
- function buildUserContent(msg, state, logger) {
1021
- const parts = [];
1022
- // 2026-09-11 主人要求: 入站 @bot 长 openid 转短标记 @bot 省 token(精确按 mentions.is_you 替换)
1023
- const text = replaceBotMention((msg.content ?? '').trim(), msg.mentions, state.mention?.wasMentioned);
1024
- if (text) {
1025
- parts.push(text);
1026
- }
1027
- const voiceTexts = extractVoiceTexts(msg.attachments, state.processedAttachments, logger);
1028
- if (voiceTexts.length > 0) {
1029
- for (const vt of voiceTexts) {
1030
- const durationTag = vt.duration ? ` (${vt.duration}s)` : '';
1031
- parts.push(`[Voice message${durationTag}] ${vt.text}`);
1032
- }
1033
- }
1034
- const otherAttachments = describeAttachments(msg.attachments, state.processedAttachments);
1035
- if (otherAttachments) {
1036
- parts.push(otherAttachments);
1037
- }
1038
- return parts.join('\n');
1039
- }
1040
- /**
1041
- * 图片预检专用下载(2026-09-13): 直接用 node:https 取 Buffer, **不经 attachment.ts 的 download()**
1042
- * —— 那个带 SSRF 防护(assertSafeHostname), 在宿主环境里会静默失败(实测: 手工 https 能下、运行时却命中不了)。
1043
- * 任何失败 → undefined(调用方当"判不了"处理, 绝不拦消息)。
1044
- */
1045
- async function fetchImageBuffer(url, maxBytes = 5 * 1024 * 1024) {
1046
- try {
1047
- const https = await import('node:https');
1048
- return await new Promise((resolve) => {
1049
- const req = https.get(url, { headers: { 'user-agent': 'dsh-qqbot' } }, (res) => {
1050
- const code = res.statusCode || 0;
1051
- if (code < 200 || code >= 300) {
1052
- res.resume();
1053
- resolve(undefined);
1054
- return;
1055
- }
1056
- const chunks = [];
1057
- let n = 0;
1058
- res.on('data', (c) => {
1059
- n += c.length;
1060
- if (n > maxBytes) {
1061
- req.destroy();
1062
- resolve(undefined);
1063
- return;
1064
- }
1065
- chunks.push(c);
1066
- });
1067
- res.on('end', () => resolve(Buffer.concat(chunks)));
1068
- res.on('error', () => resolve(undefined));
1069
- });
1070
- req.on('error', () => resolve(undefined));
1071
- req.setTimeout(15000, () => { req.destroy(); resolve(undefined); });
1072
- });
1073
- }
1074
- catch {
1075
- return undefined;
1076
- }
1077
- }
1078
- /**
1079
- * 评分前清洗(2026-09-13 主人定): 合并转发/引用块会把大量**格式元数据**混进文本,
1080
- * 直接拿去评分 → 语义被稀释(实测一条合并消息里 90% 是 `=== 消息 1 ===`/`[发送者]`/`[附件1] 类型:…`)。
1081
- * 这里只剥"结构与标记", 保留真正的消息正文。
1082
- */
1083
- function cleanTextForScore(raw) {
1084
- // 块标记(新旧两套)统一交给 markers.ts 剥 —— 别在这里再写一遍字面量
1085
- let s = stripBlockMarkers(String(raw || ''));
1086
- s = s
1087
- // @ 标记一律剥掉(2026-09-15):`<@openid>` / `@bot` 留在打分文本里会让"这条 @ 了她"
1088
- // 变成最大共同特征 → 实测「<@xx> 不知道」拿到 1.00 分。语义交给正文,点名交给 mention 特征。
1089
- .replace(/<@[!&]?\d+>/g, ' ')
1090
- .replace(/<@[0-9A-Za-z_-]{6,}>/g, ' ')
1091
- .replace(/@bot\b/gi, ' ')
1092
- .replace(/\[群聊的聊天记录\]/g, ' ')
1093
- .replace(/={2,}\s*消息\s*\d+\s*={2,}/g, ' ') // === 消息 1 ===
1094
- .replace(/---\s*第\s*\d+\s*条\s*---/g, ' ') // --- 第1条 ---
1095
- .replace(/\[发送者\][^\n]*/g, ' ')
1096
- .replace(/\[消息内容\]/g, ' ')
1097
- .replace(/\[消息类型\][^\n]*/g, ' ')
1098
- .replace(/\[关联消息\]/g, ' ')
1099
- .replace(/\[附件\d*\][^\n]*/g, ' ') // [附件1] 类型:图片 文件名:… URL:…
1100
- .replace(/\[图片:\s*https?:\/\/[^\]]*\]/g, ' ') // [图片: URL]
1101
- .replace(/\[表情:\s*[^\]]*\]/g, ' ')
1102
- .replace(/\[当前时间[^\]]*\]/g, ' ') // 旧时间行
1103
- .replace(/\[\d{4}-\d{2}-\d{2}[^\]]*\]/g, ' ') // 新时间行(2026-09-15 起不再带"当前时间"标签)
1104
- .replace(/\[系统提示\][^\n]*/g, ' ')
1105
- .replace(/^\s*[-·]\s*Image:[^\n]*/gim, ' ') // - Image: xxx.jpg (550×550) → URL
1106
- .replace(/^\s*\[[\u4e00-\u9fa5A-Za-z]{1,8}\]\s*$/gm, ' '); // 独占一行的 [标签]
1107
- return s.replace(/[ \t]+/g, ' ').replace(/\n{2,}/g, '\n').trim();
1108
- }
1109
- /**
1110
- * Layer 2: 引用消息块
1111
- *
1112
- * ⚠️ 2026-10-01 修(主人实测:群里有人**引用一张表情包**回话,AI 完全不知道引用的是哪张图 → 答非所问):
1113
- * 两个叠在一起的坑:
1114
- * ① 原判空只看 `text`/`entry.content` —— 对方引用纯图(自己没有文字)时整块引用**直接消失**;
1115
- * ② 即使非空,SDK 的 `quote-ref` 中间件把附件**降级成占位文本**(`[image]` / `[image: a.png]`,
1116
- * 见 `@tencent-connect/qqbot-nodejs/src/middleware/quote-ref.ts` 的 `buildText`)——
1117
- * **URL 被丢掉了**,模型对着 4 个字干瞪眼。
1118
- * 好在 `quote.attachments[].url` 一直都在手边(SDK 已解析,只是没人用)。
1119
- * → 现在把被引用消息的附件**内联进引用块**,图片给「**本地路径优先、URL 兜底**」的可读目标
1120
- * (本地路径模型能用视觉工具直接读图;QQ 链接又长又会过期),语音给 ASR 转写,文件给文件名+URL。
1121
- */
1122
- /**
1123
- * 用本地台账补齐 QQ 没给全的被引用内容(2026-10-01 主人实测:引用**纯图片**看不到是哪张图)。
1124
- * QQ 引用纯图时 msg_elements 可能只给个文件名、甚至什么都不给 → 按 SDK 给的 refKey(= 被引用消息的 msg_idx)
1125
- * 回查我们**入站时**记下的台账(见 msg-content-cache.ts),补出图片**本地路径**(AI 能直接读)。
1126
- * 已经够了(有正文 + 有附件)就直接原样返回,零开销。
1127
- */
1128
- function enrichQuoteFromCache(q, dataRoot, peerKey) {
1129
- if (!q)
1130
- return q;
1131
- const refKey = String(q.refKey ?? '').trim();
1132
- if (!refKey)
1133
- return q;
1134
- const rawText = String(q.text ?? q.entry?.content ?? '').trim();
1135
- const hasText = Boolean(rawText) && !isPlaceholderQuoteText(rawText);
1136
- const hasAtt = Array.isArray(q.attachments) && q.attachments.length > 0;
1137
- if (hasText && hasAtt)
1138
- return q;
1139
- const hit = lookupMsgContent(dataRoot, peerKey, refKey);
1140
- if (!hit)
1141
- return q;
1142
- const out = { ...q };
1143
- if (!hasText && hit.t)
1144
- out.text = hit.t;
1145
- if (!hasAtt && hit.imgs && hit.imgs.length) {
1146
- // 走"本机路径"分支:describeQuoteAttachment 会原样给出路径(图库/缓存查不到也不会坏)
1147
- out.attachments = hit.imgs.map((p) => ({ contentType: 'image/*', url: p }));
1148
- }
1149
- return out;
1150
- }
1151
- export function buildQuoteBlock(quote, stickerDir) {
1152
- const atts = Array.isArray(quote?.attachments) ? quote.attachments : [];
1153
- const rawText = String(quote?.text ?? quote?.entry?.content ?? '').trim();
1154
- // 2026-10-01: 表情消息(图片表情 / 收藏表情)在 msg_elements 里只给一个 `<faceType=…,ext="base64">` ——
1155
- // 先把 ext 里**可能藏着**的图片 URL 挖出来当附件用;实测常见形态 ext=`{"text":""}` 是空的,
1156
- // 那种只能靠"那条消息入站时登记的台账"回查(见 msg-content-cache.ts / enrichQuoteFromCache)。
1157
- const faceImgs = extractFaceImageUrls(rawText);
1158
- // SDK 由附件拼出的占位文本(纯 `[image]` / `[voice: xx]`…)在有附件行时不必重复一遍
1159
- const text = (atts.length > 0 || faceImgs.length > 0) && isPlaceholderQuoteText(rawText) ? '' : rawText;
1160
- if (!text && atts.length === 0 && faceImgs.length === 0)
1161
- return '';
1162
- const lines = [];
1163
- // 2026-10-01: 剥掉 QQ 的引用模板壳(`=== 消息 N === [消息内容]…[消息类型] 引用消息 …`)并压平,
1164
- // 只去噪声不限长 —— 限长交给调用方(当前消息走 trimQuoteBlock 的 60 字+缓存,历史行走媒体历史那边)
1165
- if (text) {
1166
- // 表情标签在这里转成 `【表情: 微笑】`(原样是 `<faceType=6,faceId="0",ext="…">`,谁也看不懂)
1167
- const slim = slimQuoteText(text, 0);
1168
- if (slim)
1169
- lines.push(escapeBlockMarkers(slim));
1170
- }
1171
- for (const a of atts) {
1172
- const line = describeQuoteAttachment(a, stickerDir);
1173
- if (line)
1174
- lines.push(line);
1175
- }
1176
- // 表情标签 ext 里挖到的图片 URL(图片表情的其它端形态)→ 同样给一行"被引用的图片"
1177
- for (const u of faceImgs) {
1178
- const line = describeQuoteAttachment({ contentType: 'image/*', url: u }, stickerDir);
1179
- if (line)
1180
- lines.push(line);
1181
- }
1182
- if (lines.length === 0)
1183
- return '';
1184
- // 排版(2026-10-01 专家团共识): 引用内容整体退 2 格 —— 视觉上从属, 不再和正文同权重
1185
- const indented = lines.map((l) => ' ' + l).join('\n');
1186
- return `${MK.QUOTE_BEGIN}\n${indented}\n${MK.QUOTE_END}`;
1187
- }
1188
- /**
1189
- * Layer 2 成品:引用块 + 紧随其后的 `[当前]`(短标记见 markers.ts)。
1190
- * ⚠️ 历史行请用 {@link buildQuoteBlock} —— 那边不该出现 `[当前]` 标记。
1191
- */
1192
- export function buildQuotePart(quote, stickerDir) {
1193
- const blk = buildQuoteBlock(quote, stickerDir);
1194
- // ⚠️ 2026-10-01:`[当前]` 由 Layer 5 统一输出 —— 引用块与正文都属于当前消息,
1195
- // 引用块自己再带一个会让 `[当前]` 重复、引用块看起来"在当前消息之外"(主人实测)。
1196
- return blk ? `${blk}\n` : '';
1197
- }
1198
- /** SDK 的附件占位文本(整段只有 `[image]`/`[video: x]`/`[voice: x]`/`[file: x]` 这类行) */
1199
- function isPlaceholderQuoteText(t) {
1200
- if (!t)
1201
- return true;
1202
- return t.split('\n').every((l) => /^\[(image|video|voice|file)(:\s*[^\]]*)?\]$/i.test(l.trim()));
1203
- }
1204
- /** 被引用消息的附件 → 一行可读描述(图片优先给**本地路径**,模型能直接读图) */
1205
- function describeQuoteAttachment(a, stickerDir) {
1206
- const ct = String(a?.contentType ?? '').toLowerCase();
1207
- const name = String(a?.filename ?? '').trim();
1208
- const url = String(a?.url ?? '').trim();
1209
- const ext = (name.split('.').pop() ?? '').toLowerCase();
1210
- const isImg = ct.startsWith('image/') || /^(jpe?g|png|gif|webp|bmp)$/.test(ext);
1211
- const isVoice = ct.startsWith('audio/') || ct.includes('voice') || /^(silk|amr|ogg|mp3|wav|m4a|aac|opus)$/.test(ext);
1212
- const isVideo = ct.startsWith('video/') || /^(mp4|webm|mov|m4v)$/.test(ext);
1213
- if (isVoice) {
1214
- const asr = String(a?.asrText ?? '').trim();
1215
- return asr ? `🎵 被引用的语音转写: ${asr}` : `🎵 被引用的语音${name ? ': ' + name : ''}`;
1216
- }
1217
- if (isImg) {
1218
- // 与历史图片瘦身同一条解析链(缓存 → 图库台账 → 当前真实路径); 命中就给本地路径, 否则保留 QQ 原链
1219
- const local = url ? resolveImageLocalPath(url, stickerDir) : undefined;
1220
- const target = local ?? url;
1221
- return target ? `📷 被引用的图片: ${target}` : `📷 被引用的图片${name ? ': ' + name : ''}`;
1222
- }
1223
- if (isVideo)
1224
- return `🎬 被引用的视频${name ? ': ' + name : ''}${url ? ' → ' + url : ''}`;
1225
- return `📎 被引用的文件${name ? ': ' + name : ''}${url ? ' → ' + url : ''}`;
1226
- }
1227
- /**
1228
- * (转义实现已搬到 `markers.ts` 的 `escapeBlockMarkers` —— 新旧两套标记一起转义, 见那里的注释)
1229
- */
1230
- /** 引用原文保留字数: 超出部分只进本地缓存(2026-09-13 主人定, 短引用就别折腾了) */
1231
- const QUOTE_KEEP = 60;
1232
- /**
1233
- * 历史里的图片行瘦身(2026-09-13 主人要求"把省 token 做到极致"):
1234
- * 历史中每条图片都是 `[图片: https://multimedia…fileid=…&rkey=…]`(≈250 字符!) —— 群聊图一多就是纯浪费。
1235
- * 现在改成: ①能定位到本地文件 → `[图片: <本地路径>]`(≈60 字符, 还能真去看图)
1236
- * ②定位不到 → 直接 `[图片]`(4 字符, 反正也读不了那张过期链接)
1237
- * 解析链: image-path-cache(URL→路径) → 台账反查 id → 图库当前真实路径(搬层也对)。
1238
- */
1239
- function resolveImageLocalPath(url, stickerDir) {
1240
- const cached = lookupImagePath(url);
1241
- if (cached)
1242
- return cached;
1243
- try {
1244
- const id = lookupStickerIdByUrl(stickerDir, url);
1245
- if (!id)
1246
- return undefined;
1247
- const store = getStickerStore(stickerDir);
1248
- const p = store.pathOf(id);
1249
- if (p && existsSync(p))
1250
- return p;
1251
- }
1252
- catch { /* 查不到就算了 */ }
1253
- return undefined;
1254
- }
1255
- function localizeHistoryImages(text, stickerDir) {
1256
- if (!text || text.indexOf('[图片') < 0)
1257
- return text;
1258
- return text.replace(/\[图片:\s*(https?:\/\/[^\]\s]+)\]/g, (_m, url) => {
1259
- const p = resolveImageLocalPath(url, stickerDir);
1260
- // 2026-09-24 改进(主人反馈: 历史里的图片只剩 [图片]、AI 完全读不到图):
1261
- // 找不到本地图库对应时,**保留 QQ 的原始 URL** —— 宁可多花点 token,也别让模型对着 4 个字干瞪眼。
1262
- // (本地命中仍然优先,那是省 token 的正常路径。)
1263
- return p ? `[图片: ${p}]` : `[图片: ${url}]`;
1264
- });
1265
- }
1266
- /**
1267
- * 引用块瘦身(2026-09-13 主人要求: 引用太长很吃 token) ——
1268
- * 引用原文只给**前 {@link QUOTE_KEEP} 字**, 完整原文落本地缓存
1269
- * `{dataRoot}/.qqbot/quote-cache.json`(**每会话最多 10 条**), AI 需要时用 `quote_view` 工具取。
1270
- * 短引用(≤ QUOTE_KEEP)原样不动(免得为了省几个字反而多一次工具调用);
1271
- * 缓存失败则照旧给全文(宁可费 token, 不丢信息)。
1272
- *
1273
- * ⚠️ 2026-09-13 主人实测抓到一个隐蔽 bug: 若**被引用的原文里自带** `[Quoted message begins]`
1274
- * (比如 AI 在代码块里示范过这个格式), 原来的**非贪婪正则**会先匹配到内层那个"结束"标记 →
1275
- * 截断切错位置、外层的 `[Quoted message ends]` 反而留在后面。
1276
- * 现在: ①取**第一个 begin + 最后一个 end**(认外层) ②引用原文里的标记先转义(见 escapeQuoteMarkers)。
1277
- */
1278
- /** 引用块里的"附件行"(`📷 被引用的图片: …` 等)—— 截断豁免标记,别被 60 字上限挤掉
1279
- * ⚠️ 别写成字符类 `[📷🎵🎬📎]` —— emoji 是代理对,在字符类里会被拆成单个 UTF-16 码元,匹配不上。 */
1280
- const QUOTE_ATT_LINE_RE = /^\s*(?:📷|🎵|🎬|📎)\s*被引用的/;
1281
- function trimQuoteBlock(quotePart, dataRoot, msg, logger) {
1282
- if (!quotePart)
1283
- return quotePart;
1284
- // 认**新旧两套**标记(老会话里还留着英文长标记), 取"第一个 begin + 最后一个 end"
1285
- const b = findFirstMarker(quotePart, QUOTE_BEGIN_ALL);
1286
- const e = findLastMarker(quotePart, QUOTE_END_ALL);
1287
- if (!b || !e || e.idx <= b.idx)
1288
- return quotePart;
1289
- const full = quotePart.slice(b.idx + b.len, e.idx).trim();
1290
- // ⚠️ 2026-10-01: 附件行**不参与 60 字截断** —— 那是"被引用的是哪张图"的唯一线索,
1291
- // 被前面的文字挤掉就等于白修(见 buildQuotePart 的注释)。
1292
- const allLines = full.split('\n');
1293
- const attLines = allLines.filter((l) => QUOTE_ATT_LINE_RE.test(l.trim()));
1294
- const textPart = allLines.filter((l) => !QUOTE_ATT_LINE_RE.test(l.trim())).join('\n').trim();
1295
- // 文字部分没超长 → 整块原样返回(附件行照旧留着,也不必打"已缓存"提示)
1296
- if (textPart.length <= QUOTE_KEEP)
1297
- return quotePart;
1298
- const key = `${msg.kind === 'group' ? 'group' : 'c2c'}:${(msg.kind === 'group' ? msg.groupOpenid : undefined) ?? msg.senderId}`;
1299
- try {
1300
- const hit = pushQuote(dataRoot, key, full, msg.senderName);
1301
- const head = [textPart.slice(0, QUOTE_KEEP).replace(/\s+/g, ' '), ...attLines].filter(Boolean).join('\n');
1302
- logger.debug(`[引用] 原文 ${full.length} 字 → 只给前 ${QUOTE_KEEP} 字(缓存 #${hit.id}); 附件行 ${attLines.length} 条不截断`);
1303
- return `${quotePart.slice(0, b.idx)}${quotePart.slice(b.idx, b.idx + b.len)}\n${head}…[引用#${hit.id}: 全文 ${full.length} 字已缓存, 需要时用 quote_view 查]\n${quotePart.slice(e.idx)}`;
1304
- }
1305
- catch {
1306
- return quotePart;
1307
- }
1308
- }
1309
- /**
1310
- * 引用消息原文提取(2026-09-13 主人定): 收到引用消息(message_type=103)时,
1311
- * msg_elements[] 里带被引用消息的原文; 只有标记没有内容时退化为引用索引提示。
1312
- */
1313
- function extractQuotedContent(msg) {
1314
- const els = Array.isArray(msg.msgElements) ? msg.msgElements : [];
1315
- const texts = els.map((e) => e?.content).filter((t) => Boolean(t));
1316
- if (texts.length > 0)
1317
- return texts.join('\n');
1318
- const ext = Array.isArray(msg.message_scene?.ext) ? msg.message_scene.ext : [];
1319
- const refIdx = ext.find((x) => typeof x === 'string' && x.startsWith('ref_msg_idx='));
1320
- if (refIdx)
1321
- return `(被引用消息索引: ${refIdx.slice('ref_msg_idx='.length)})`;
1322
- return '';
1323
- }
1324
- /**
1325
- * Layer 3: 带发送者标签的用户消息
1326
- * 引用消息功能开启时, 每条入站都带**短消息号**(msgRef, 形如 0913a; 群聊挂发送者标签, 私聊独立一行)
1327
- * —— AI 想引用对方时在正文写 [rf:短号](2026-09-13 主人定: 短号省 token, 台账见 msg-index.ts)。
1328
- * 群聊标签的形状(2026-09-15 定稿, 与历史行同口径):
1329
- * 没被 @ → `[昵称 #短号]` ← 不带 openid(省 token; 32 位 id 每行 20+ token)
1330
- * 被 @ 了 → `[昵称 (openid) #短号]` + 正文后 ` (@you)` ← 要回 @ 他/认人才给 id
1331
- * 短号两边都留(引用标记 + id_lookup 反查 openid 的入口, 不能省)。
1332
- */
1333
- export function buildUserMessage(userContent, quotePart, senderId, senderName, isGroup, wasMentioned, msgRef) {
1334
- if (!isGroup) {
1335
- const idPart = msgRef ? `[消息号: ${msgRef}]\n` : '';
1336
- return `${quotePart}${idPart}${userContent}`;
1337
- }
1338
- const mentionTag = wasMentioned ? ' (@you)' : '';
1339
- const displayName = senderName ?? shortSenderId(senderId);
1340
- // 省 token(2026-09-12 定, 2026-09-15 主人复查"没 @ 的只显示昵称呢?"):
1341
- // 和**群历史行**一个口径 —— 没被 @ 的消息只给昵称, 32 位 openid 只在"被 @ 了"(要回 @ 他/认人)时才给。
1342
- // ⚠️ 短消息号 `#ref` **两边都留**: 那是引用标记([rf:xxxx] 靠它), 也是 id_lookup 反查 openid 的入口 ——
1343
- // 去掉它引用功能/认人工具就都废了 (主人 2026-09-15 特别强调)。
1344
- const idPart = wasMentioned ? ` (${senderId})` : '';
1345
- const refPart = msgRef ? ` #${msgRef}` : '';
1346
- const senderTag = `[${displayName}${idPart}${refPart}]`;
1347
- // 排版: 多行正文才缩进(单行保持原样, 不徒增视觉噪声)
1348
- const body = userContent.includes('\n') ? userContent.split('\n').map((l) => ' ' + l).join('\n') : userContent;
1349
- return `${quotePart}${senderTag} ${body}${mentionTag}`;
1350
- }
1351
- /**
1352
- * Layer 4: 媒体元数据上下文
1353
- */
1354
- function buildDynamicCtx(msg, downloaded) {
1355
- const lines = [];
1356
- if (!msg.attachments || msg.attachments.length === 0)
1357
- return '';
1358
- // 本段(Layer 4)是**附件的唯一权威描述**: 一行一个附件, 含「类型 + 文件名 + 尺寸/大小 + 取值」。
1359
- // 因此 Layer 1 的 describeAttachments 对带 URL 的附件不再输出(见该函数注释), 保证一个附件只出现一次。
1360
- //
1361
- // ⚠️ 2026-09-10 根因修复(主人实测: "视频还是附件形式, 图片也变成附件了"):
1362
- // 原来按 `content_type` 分流 —— 但 QQ 群聊里**图片/视频的 content_type 实测就是 `'file'`**,
1363
- // 于是图片视频全被塞进 `- File:` 行, dock(chatAttachmentKind 见 `- File:`)渲染成 `📎 download`。
1364
- // 改为按 inferMediaKind() 推断真实类型, 用**显式类型前缀**输出:
1365
- // `- Image: 名 (850×651) → 本地路径|url` / `- Video: 名 → url` / `- Voice: 名 → url` / `- File: 名 (1.2MB) → 路径|url`
1366
- // 好处: ① AI 能分清哪个 URL 是图/视频/语音(旧的纯 URL 汇总行做不到, 主人已指出);
1367
- // ② dock 认类型前缀 → 图片直显、视频可播、语音可放;
1368
- // ③ 语音的 ASR 转录在 Layer 1 的 `[Voice message] 文本` 里, 此处只给 URL(不重复)。
1369
- for (const att of msg.attachments) {
1370
- const kind = inferMediaKind(att);
1371
- // 元信息(文件名 + 图片尺寸 / 文件大小)并入同一行 —— Layer 1 因此不必再重复描述一遍附件。
1372
- const dim = kind === 'image' && att.width && att.height ? `(${att.width}×${att.height})` : '';
1373
- const size = kind === 'file' && att.size ? `(${formatFileSize(att.size)})` : '';
1374
- const meta = [att.filename, dim, size].filter(Boolean).join(' ');
1375
- const head = meta ? `${meta} ` : '';
1376
- if (kind === 'file') {
1377
- // 文件: 有本地落盘路径就给路径(便于 AI 直接读盘), 否则回退原始 URL。
1378
- const d = downloaded.find(x => x.filename === att.filename);
1379
- const target = d?.displayPath ?? att.url;
1380
- if (target)
1381
- lines.push(`- File: ${head}→ ${target}`);
1382
- continue;
1383
- }
1384
- if (!att.url)
1385
- continue;
1386
- // ⚠️ 2026-09-13 主人要求: 图片优先给**本地路径**(收藏中间件已落盘) ——
1387
- // ① AI 要看图直接读盘, 不用再下载(QQ 的临时 URL 又长又会过期);
1388
- // ② URL 那串 fileid/rkey 很长, 换成本地路径 token 也短。
1389
- // 没落盘(采集关闭 / 下载失败 / 超预算还没回来) → 老老实实回退原始 URL。
1390
- const localImg = kind === 'image' ? lookupImagePath(att.url) : undefined;
1391
- lines.push(`- ${mediaKindLabel(kind)}: ${head}→ ${localImg ?? att.url}`);
1392
- }
1393
- if (lines.length === 0)
1394
- return '';
1395
- return lines.join('\n') + '\n\n';
1396
- }
1397
- /**
1398
- * Layer 5: 最终 agentBody 拼合
1399
- */
1400
- // ════════════════════════════════════════════════════════════
1401
- // 注入块剥离 + 稳定块置顶(2026-11-01 重建;10-31 版随回退丢失 →
1402
- // 主人贴的实盘 prompt 实锤:每条历史拖着全套 [印象]/[成长]/[记忆]/[别重复] + 时间头,
1403
- // 设定类静态块每轮重发,浪费巨大)。
1404
- // 设计:
1405
- // ① 历史条目 → 剥掉一切注入块/时间头/消息号,只留裸对话(历史里的注入已过时,
1406
- // 当前轮的注入才是有效的);
1407
- // ② 当前轮注入里的稳定块(信条/印象/成长/旧识/性格观察/约定/手边/设定/关系)→
1408
- // 按 scope 记账,内容没变就不重发(历史里那份已被剥掉,但**稳定区**里始终有
1409
- // 一份最新的 → 模型永远看得见,且稳定区字节级不变 → prompt 缓存全命中);
1410
- // ③ 稳定区固定在最前 + [历史]裸对话居中 + 当前消息/易变块垫底 + 时间头最后。
1411
- // ════════════════════════════════════════════════════════════
1412
- const _PAIRED_TAGS = ['信条', '印象', '成长', '旧识', '性格观察', '约定', '手边', '设定', '关系', '记忆', '状态'];
1413
- const _STABLE_TAGS = ['信条', '设定', '旧识', '印象', '性格观察', '成长', '约定', '手边', '关系']; // 稳定区顺序
1414
- const _stableMemo = new Map(); // scope → Map(tag → text)
1415
- const _TIME_HEAD_RE = /^\[20\d{2}-\d{2}-\d{2}[^\]]*\]\s*/gm; // 任意行首的时间头(含同行接 [历史] 与行尾独立行)
1416
- const _MSGNO_RE = /^\[消息号:\s*[^\]]+\]\s*/;
1417
- function _pairedRe(tag) {
1418
- return new RegExp(`\\n?\\[${tag}\\][\\s\\S]*?\\[/${tag}\\]\\n?`, 'g');
1419
- }
1420
- /** 把一条历史/正文里的一切注入痕迹剥成裸文本 */
1421
- function stripInjectedBlocks(text) {
1422
- let t = String(text ?? '');
1423
- t = t.replace(_MSGNO_RE, '');
1424
- t = t.replace(_TIME_HEAD_RE, ''); // 先剥时间头(它与 [历史] 同行时,后者的 ^ 锚定才能命中)
1425
- for (const tag of _PAIRED_TAGS) t = t.replace(_pairedRe(tag), '\n');
1426
- t = t.replace(/^\[别重复\][^\n]*(?:\n[^\n\[]*)*/gm, ''); // 单行块(无闭标记)
1427
- t = t.replace(/^\[历史\]\s*/gm, '');
1428
- t = t.replace(/^\[\/历史\]\s*/gm, '');
1429
- t = t.replace(/^\[当前\]\s*/gm, '');
1430
- t = t.replace(/^(以下是你上次开口之后[^)]*)\s*$/gm, ''); // 旧版长说明
1431
- t = t.replace(/^\[系统提示\][^\n]*$/gm, ''); // 聚合提示随历史过时,只在当轮加
1432
- t = t.replace(_TIME_HEAD_RE, '');
1433
- return t.replace(/\n{3,}/g, '\n\n').trim();
1434
- }
1435
- /** 从当前轮注入里抽出稳定块:{header: 置顶文本, rest: 剩余正文};scope 记账去重 */
1436
- function splitStableBlocks(base, scope) {
1437
- let rest = String(base ?? '');
1438
- const found = new Map(); // tag → text
1439
- for (const tag of _PAIRED_TAGS) {
1440
- const re = _pairedRe(tag);
1441
- rest = rest.replace(re, (m) => {
1442
- const body = m.replace(/^\n?/, '').replace(/\n?$/, '');
1443
- found.set(tag, body);
1444
- return '\n';
1445
- });
1446
- }
1447
- let memo = _stableMemo.get(scope);
1448
- if (!memo) { memo = new Map(); _stableMemo.set(scope, memo); }
1449
- const headerParts = [];
1450
- for (const tag of _STABLE_TAGS) {
1451
- const cur = found.get(tag) ?? memo.get(tag);
1452
- if (!cur) continue;
1453
- if (found.has(tag) && memo.get(tag) !== cur) memo.set(tag, cur); // 变了才记账
1454
- if (!found.has(tag) && !memo.has(tag)) continue;
1455
- headerParts.push(cur);
1456
- if (found.has(tag)) rest = rest.replace(cur, ''); // 从正文里移走(已在稳定区)
1457
- }
1458
- rest = rest.replace(/\n{3,}/g, '\n\n').trim();
1459
- return { header: headerParts.join('\n'), rest };
1460
- }
1461
- function buildAgentBody(base, history, isGroup, wasMentioned, batchDispatch = false, aggregated = false, scope = '') {
1462
- const includeHistory = isGroup && (wasMentioned || batchDispatch) && !!history && history.length > 0;
1463
- // 稳定块置顶(私聊/群聊都生效;历史里旧注入会被剥掉,稳定区永远有一份最新的)
1464
- const { header: stableHeader, rest: currentBody } = splitStableBlocks(base, scope);
1465
- // 聚合投递提示(2026-09-07 主人定): 这些消息是我上一轮回合进行中群友发的, 攒到回合结束
1466
- // 才统一入站 —— 必须显式说明, 否则 AI 会误以为它们是"我回完之后群友接着说的"。
1467
- // ⚠️ 2026-10-07 主人: "系统提示太长了, 浪费 token" → 压缩到一句。
1468
- const aggregatedNote = aggregated
1469
- ? '[系统提示] 以下是你思考/输出期间群友发的消息(非对你的回应), 通读后综合回应(如需回应)。\n\n'
1470
- : '';
1471
- if (!includeHistory) {
1472
- // 私聊等无历史打包场景: 稳定区 → 聚合提示 → 正文
1473
- return [stableHeader, aggregatedNote + currentBody].filter(Boolean).join('\n\n');
1474
- }
1475
- const historyLines = history.map((h, _hi) => {
1476
- const name = h.senderName ?? shortSenderId(h.senderId);
1477
- // 2026-09-12 token 瘦身(主人定): 历史行默认**只给昵称**; 只有"当时 @ 过 bot 的那条"带 openid。
1478
- // 2026-11-01: 历史条目剥掉一切注入块/时间头 → 裸对话(注入只活在稳定区与当前轮)。
1479
- const mentioned = h.mentioned === true;
1480
- const raw = stripInjectedBlocks(String(h.content ?? ''));
1481
- if (!raw) return ''; // 整条都是注入的消息(罕见)→ 不占编号
1482
- const c = raw.includes('\n') ? raw.split('\n').map((l) => ' ' + l).join('\n') : raw;
1483
- return mentioned && h.senderId ? `${_hi + 1}. [${name} (${h.senderId})] ${c}` : `${_hi + 1}. [${name}] ${c}`;
1484
- }).filter(Boolean);
1485
- // 2026-11-01 主人: 说明性文字精简 —— 一行说清"独立消息+编号"就够
1486
- const historyExplainer = `(群友近况 ${historyLines.length} 条,逐条独立)`;
1487
- return [
1488
- stableHeader,
1489
- aggregated ? '[系统提示] 以下是上次回复前群友所发(非对你的回应), 通读后综合回应。' : '',
1490
- MK.HISTORY_BEGIN,
1491
- historyExplainer,
1492
- ...historyLines,
1493
- '',
1494
- MK.HISTORY_END,
1495
- MK.CURRENT,
1496
- currentBody,
1497
- ].filter(Boolean).join('\n');
1498
- }
1499
- function extractVoiceTexts(attachments, processed, _logger) {
1500
- const results = [];
1501
- if (processed) {
1502
- for (const pa of processed) {
1503
- if (pa.type === 'voice' && pa.voiceText) {
1504
- results.push({
1505
- text: pa.voiceText,
1506
- duration: pa.duration,
1507
- source: pa.voiceSource ?? 'stt',
1508
- });
1509
- }
1510
- }
1511
- }
1512
- if (results.length === 0 && attachments) {
1513
- for (const att of attachments) {
1514
- if (att.content_type === 'voice' && att.asr_refer_text) {
1515
- results.push({
1516
- text: att.asr_refer_text.trim(),
1517
- source: 'asr',
1518
- });
1519
- }
1520
- }
1521
- }
1522
- return results;
1523
- }
1524
- function describeAttachments(attachments, _processed) {
1525
- if (!attachments || attachments.length === 0)
1526
- return '';
1527
- const parts = [];
1528
- // ⚠️ 2026-09-10 去重(主人: "图片链接重复两次, 那不是又回原来的长上下文咯?"):
1529
- // 带 URL 的附件已由 Layer 4 的 `- Image: 名 (850×651) → url` 一行完整描述(类型+名+尺寸+URL),
1530
- // 本层**不再重复输出** —— 只有"没有 URL"的附件才在这里兜底做文字描述(Layer 4 给不出链接时)。
1531
- // 效果: 当前消息里一个附件只占一行(此前是 `[Image: 名 尺寸]` + `- Image: 名 → url` 两行)。
1532
- for (const att of attachments) {
1533
- const kind = inferMediaKind(att);
1534
- if (kind === 'voice')
1535
- continue; // 语音正文由 `[Voice message] 转录` 承接(不含 URL, 本就不重复)
1536
- if (att.url)
1537
- continue; // 有 URL → Layer 4 已给完整一行
1538
- switch (kind) {
1539
- case 'image': {
1540
- const dim = att.width && att.height ? ` ${att.width}×${att.height}` : '';
1541
- parts.push(`[Image: ${att.filename}${dim}]`);
1542
- break;
1543
- }
1544
- case 'video':
1545
- parts.push(`[Video: ${att.filename}]`);
1546
- break;
1547
- default:
1548
- parts.push(`[File: ${att.filename} (${formatFileSize(att.size)})]`);
1549
- break;
1550
- }
1551
- }
1552
- return parts.join('\n');
1553
- }
1554
- function formatFileSize(bytes) {
1555
- if (bytes < 1024)
1556
- return `${bytes}B`;
1557
- if (bytes < 1024 * 1024)
1558
- return `${(bytes / 1024).toFixed(1)}KB`;
1559
- return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
1560
- }
1561
- /** 发送者短标识长度(openid 前 N 位,无昵称时兜底) */
1562
- const SENDER_SHORT_ID_LEN = 8;
1563
- /** 无昵称时用 openid 前 N 位作为匿名标识 */
1564
- function shortSenderId(senderId) {
1565
- return senderId.slice(0, SENDER_SHORT_ID_LEN);
1566
- }
1567
- //# sourceMappingURL=inbound.js.map