dsh-wechat-access 0.0.0-stage → 0.0.2

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 (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +675 -0
  3. package/README.md +278 -2
  4. package/cordis.patch.yml +5 -0
  5. package/examples/config.example.json +98 -0
  6. package/index.mjs +123 -0
  7. package/lib/access.mjs +131 -0
  8. package/lib/anysearch.mjs +143 -0
  9. package/lib/capabilities.mjs +312 -0
  10. package/lib/client.js +2532 -0
  11. package/lib/config.mjs +509 -0
  12. package/lib/emotion-store.mjs +352 -0
  13. package/lib/emotion.mjs +428 -0
  14. package/lib/endocrine/LICENSE +21 -0
  15. package/lib/endocrine/README.md +39 -0
  16. package/lib/endocrine/diseases.js +791 -0
  17. package/lib/endocrine/engine.mjs +131 -0
  18. package/lib/endocrine/store.mjs +253 -0
  19. package/lib/endocrine/upstream.mjs +1230 -0
  20. package/lib/group-gate.mjs +305 -0
  21. package/lib/imagegen.mjs +360 -0
  22. package/lib/lock.mjs +204 -0
  23. package/lib/meme-classify.mjs +190 -0
  24. package/lib/memes.mjs +442 -0
  25. package/lib/memory.mjs +437 -0
  26. package/lib/normalize.mjs +230 -0
  27. package/lib/parser.mjs +602 -0
  28. package/lib/reply-settled.mjs +130 -0
  29. package/lib/runtime.mjs +3367 -0
  30. package/lib/startup.mjs +70 -0
  31. package/lib/steam-binding.mjs +144 -0
  32. package/lib/steam.mjs +334 -0
  33. package/lib/store.mjs +259 -0
  34. package/lib/thoughts.mjs +149 -0
  35. package/lib/time-context.mjs +182 -0
  36. package/lib/tools.mjs +583 -0
  37. package/lib/ui.mjs +997 -0
  38. package/lib/util.mjs +489 -0
  39. package/lib/virtual-life-generate.mjs +421 -0
  40. package/lib/virtual-life.mjs +971 -0
  41. package/lib/weather.mjs +172 -0
  42. package/lib/wechat-client.mjs +476 -0
  43. package/lib/wechat-events.mjs +269 -0
  44. package/locale/zh.json +6 -0
  45. package/package.json +77 -4
package/lib/util.mjs ADDED
@@ -0,0 +1,489 @@
1
+ import { appendFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+
7
+ export function assert(condition, message) {
8
+ if (!condition) throw new Error(message);
9
+ }
10
+
11
+ /**
12
+ * 微信会话 / 联系人标识。
13
+ *
14
+ * 微信和 QQ 的 ID 模型完全不同,不能沿用「5–12 位纯数字」那条规则:
15
+ *
16
+ * wxid_abcdefghijklmn 系统分配的 wxid
17
+ * gjchen7 自定义微信号(字母开头)
18
+ * 12345678@chatroom 群
19
+ * gh_xxxxx 公众号
20
+ * filehelper 文件传输助手
21
+ *
22
+ * 这里只做「形状合理」的校验:真正的合法性由服务端判断,
23
+ * 本地过严只会把合法的微信号拒之门外。
24
+ */
25
+ // wxid_ / gh_ 是微信保留前缀:自定义微信号不允许占用它们,
26
+ // 否则 "wxid_" 这种残缺 ID 会被当成合法微信号放过去。
27
+ const PEER_ID = /^(?:wxid_[A-Za-z0-9_-]{3,64}|gh_[A-Za-z0-9_-]{3,64}|(?!wxid_|gh_)[A-Za-z][A-Za-z0-9_-]{1,63}|\d{5,}@chatroom|filehelper)$/;
28
+
29
+ export function peerId(value, label = '微信会话 ID') {
30
+ const id = String(value ?? '').trim();
31
+ assert(PEER_ID.test(id), `${label}格式不正确:应为 wxid_xxx、微信号、xxx@chatroom 或 filehelper`);
32
+ return id;
33
+ }
34
+
35
+ /** 只是「是不是群聊」。微信群里 ID 一律以 @chatroom 结尾。 */
36
+ export function isGroupId(id) { return String(id ?? '').endsWith('@chatroom'); }
37
+
38
+ /** 兼容旧调用点:语义等同 peerId,但保留 QQ 号式的宽松数字分支。 */
39
+ export function qqId(value, label = '微信会话 ID') {
40
+ const id = String(value ?? '').trim();
41
+ assert(PEER_ID.test(id) || /^[1-9]\d{4,11}$/.test(id), `${label}格式不正确`);
42
+ return id;
43
+ }
44
+
45
+ /**
46
+ * 本地日期 YYYY-MM-DD。
47
+ *
48
+ * 不要用 `new Date().toISOString().slice(0, 10)`:那是 UTC。
49
+ * 东八区 0 点到 8 点之间,UTC 还停在前一天 ——
50
+ * 归档会写进前一天的文件,记忆的日配额要到早上 8 点才翻转。
51
+ */
52
+ export function isoDate(date = new Date()) {
53
+ const y = date.getFullYear();
54
+ const m = String(date.getMonth() + 1).padStart(2, '0');
55
+ const d = String(date.getDate()).padStart(2, '0');
56
+ return `${y}-${m}-${d}`;
57
+ }
58
+
59
+ export function integer(value, fallback, min, max, label = '参数') {
60
+ if (value === undefined) return fallback;
61
+ assert(Number.isInteger(value) && value >= min && value <= max, `${label}必须是 ${min}–${max} 的整数`);
62
+ return value;
63
+ }
64
+ /**
65
+ * 允许小数的数值校验。
66
+ *
67
+ * integer() 卡死整数,但经纬度天然是小数,用 integer 会直接拒绝合法配置。
68
+ * 和风 v1 接口最多接受小数点后两位,这里不做截断,只校验范围。
69
+ */
70
+ export function decimal(value, fallback, min, max, label = '参数') {
71
+ if (value === undefined || value === null || value === '') return fallback;
72
+ const n = Number(value);
73
+ assert(Number.isFinite(n) && n >= min && n <= max, `${label}必须是 ${min}–${max} 之间的数字`);
74
+ return n;
75
+ }
76
+
77
+ export function textArg(value, label = '文本', limit = 4000) {
78
+ assert(typeof value === 'string' && value.trim().length > 0, `${label}不能为空`);
79
+ assert([...value].length <= limit, `${label}不能超过 ${limit} 字符`);
80
+ return value;
81
+ }
82
+
83
+ export function requestId(value) {
84
+ assert(typeof value === 'string' && /^[a-zA-Z0-9:_-]{8,160}$/.test(value), 'request_id 必须是 8–160 位字母、数字、冒号、下划线或短横线');
85
+ return value;
86
+ }
87
+
88
+ export function digest(value) { return createHash('sha256').update(JSON.stringify(value)).digest('hex'); }
89
+ export function newId(prefix = 'wx') { return `${prefix}:${randomUUID()}`; }
90
+ export function jsonClone(value) { return JSON.parse(JSON.stringify(value)); }
91
+
92
+ /**
93
+ * 把宿主的模型选择压成 agentOptions。
94
+ *
95
+ * 宿主的选择是 { provider, model, reasoningEffort? } 三件套。以前这里只取前两个
96
+ * 字段,于是用户调的推理等级只对主对话生效,主动消息、情感分析、表情分类这些
97
+ * 一次性回合全部悄悄退回服务商默认,面板上写的等级和实际跑的不是一回事。
98
+ */
99
+ export function hostSelection(selection) {
100
+ if (!selection || typeof selection !== 'object') return undefined;
101
+ const provider = String(selection.provider ?? '').trim();
102
+ const model = String(selection.model ?? '').trim();
103
+ if (!provider || !model) return undefined;
104
+ const raw = selection.reasoningEffort;
105
+ const effort = raw === undefined || raw === null ? '' : String(raw).trim();
106
+ return { provider, model, ...(effort ? { reasoningEffort: effort } : {}) };
107
+ }
108
+ export function checkSignal(signal) { signal?.throwIfAborted(); }
109
+ export function combinedSignal(signal, timeoutMs) {
110
+ return signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
111
+ }
112
+
113
+ // Callers waiting for a mutex may cancel; the running operation must still settle
114
+ // before a later caller enters. This is especially important for browser profiles.
115
+ export class Mutex {
116
+ #tail = Promise.resolve();
117
+ run(task) {
118
+ const next = this.#tail.then(task);
119
+ this.#tail = next.catch(() => {});
120
+ return next;
121
+ }
122
+ }
123
+
124
+ export class Semaphore {
125
+ #active = 0;
126
+ #waiting = [];
127
+ constructor(limit) { this.limit = limit; }
128
+ async run(task) {
129
+ if (this.#active >= this.limit) await new Promise(resolve => this.#waiting.push(resolve));
130
+ else this.#active++;
131
+ try { return await task(); }
132
+ finally {
133
+ const next = this.#waiting.shift();
134
+ if (next) next(); // Transfer the occupied slot directly to the waiter.
135
+ else this.#active--;
136
+ }
137
+ }
138
+ }
139
+
140
+ export class RateLimiter {
141
+ #mutex = new Mutex();
142
+ #lastGlobal = 0;
143
+ #lastPeer = new Map();
144
+ #minute = [];
145
+ constructor({ globalGapMs, peerGapMs, maxPerMinute }) { Object.assign(this, { globalGapMs, peerGapMs, maxPerMinute }); }
146
+ /**
147
+ * Reserve the next send slot for `peer`.
148
+ *
149
+ * `paceMs` is the caller's own idea of the gap between two consecutive messages of the
150
+ * same multi-message reply. It REPLACES peerGapMs instead of being max()'d with it, so a
151
+ * user setting of 1s is honoured even though the default same-conversation gap is 3s.
152
+ * The global gap and the per-minute quota still apply as hard floors.
153
+ */
154
+ async wait(peer, signal, paceMs = 0) {
155
+ // 锁里只做「算要等多久」和「把这次发送预定到未来某个时刻」,等待放到锁外。
156
+ //
157
+ // 以前 delay 是在 mutex.run 内部 await 的:一段拆成 8 条的回复,每条之间有
158
+ // 1–10 秒的打字间隔,那几十秒里整个全局锁被占着。后果是所有会话的发送、
159
+ // 戳一戳、空间发布、甚至工具调用全部排队,一段长回复能把整机 QQ 输出卡住。
160
+ //
161
+ // 现在下一个调用进锁时看到的是「已经预定好的未来时间」,从那个时间往后算,
162
+ // 所以多人并发时的总节奏和以前一致,只是不再互相阻塞。
163
+ const ms = await this.#mutex.run(async () => {
164
+ checkSignal(signal);
165
+ const now = Date.now();
166
+ this.#minute = this.#minute.filter(t => now - t < 60_000);
167
+ const quotaWait = this.#minute.length >= this.maxPerMinute ? this.#minute[0] + 60_000 - now : 0;
168
+ const peerGap = paceMs > 0 ? paceMs : this.peerGapMs;
169
+ const wait = Math.max(0, this.#lastGlobal + this.globalGapMs - now, (this.#lastPeer.get(peer) ?? 0) + peerGap - now, quotaWait);
170
+ // 预定到未来的时间点:下一个调用看到的 lastGlobal / lastPeer 就是这里。
171
+ const at = now + wait;
172
+ this.#lastGlobal = at;
173
+ this.#lastPeer.set(peer, at);
174
+ if (this.#lastPeer.size > 10_000) this.#lastPeer.delete(this.#lastPeer.keys().next().value);
175
+ // 配额按「预定时刻」计入,否则等待期间新进来的调用会看到空配额。
176
+ this.#minute.push(at);
177
+ return wait;
178
+ });
179
+ if (ms > 0) {
180
+ // 被取消时不撤回已经预定的时间点。撤回会让两个发送挤在同一毫秒,
181
+ // 多等一次永远比发太快安全。
182
+ await delay(ms, undefined, { signal });
183
+ }
184
+ }
185
+ }
186
+
187
+ /**
188
+ * 往 debug.log 记一行纯文本,不带异常堆栈。
189
+ *
190
+ * 用途是记「本该发生却没发生」的事 —— 比如主动消息为什么没发出去。
191
+ * 这类失败原来只在返回值里,轮询直接丢掉,日志里一点痕迹都没有,
192
+ * 用户只能看到「她没说话」,查不出原因。
193
+ */
194
+ /**
195
+ * 合并一个批次里所有消息的图片**和贴纸**。
196
+ *
197
+ * 为什么需要它:批量窗口内「先发图、再补一句文字」是最常见的发图方式。
198
+ * 但 flushPending 只用批次最后一条作为触发消息,那条通常是纯文字 ——
199
+ * 于是图片全被丢掉,模型只看到 recent_messages 里的「[图片]」。
200
+ *
201
+ * **贴纸(stickers)必须一起合并**:它们在 normalizeEvent 里被单独分了一个数组,
202
+ * 以前这里只扫 images,于是「先发贴纸、再补字」的批次丢失贴纸画面,
203
+ * 和当年丢图的 bug 完全同构。
204
+ *
205
+ * 去重按 url/file;超出上限时保留**最新**的几张。
206
+ */
207
+ export function collectBatchImages(messages, limit = 4) {
208
+ const cap = Math.max(0, Number(limit) || 0);
209
+ if (!cap) return [];
210
+ const out = [];
211
+ // 图片和贴纸按消息顺序混合收集,而不是先收完图片再收贴纸 ——
212
+ // 否则「图 A → 贴纸 B → 图 C」会变成 A,C,B,截断时保留的不是真正最新的。
213
+ const push = (item) => {
214
+ if (!item) return;
215
+ const url = String(item.url ?? '');
216
+ const file = String(item.file ?? '');
217
+ if (!url && !file) return;
218
+ if (out.some((x) => (url && String(x.url ?? '') === url) || (file && String(x.file ?? '') === file))) return;
219
+ out.push(item);
220
+ };
221
+ for (const message of messages ?? []) {
222
+ // normalizeEvent 把普通图片放 images、贴纸放 stickers,
223
+ // 两个数组同属一条消息,按消息顺序一起收。
224
+ for (const item of message?.images ?? []) push(item);
225
+ for (const item of message?.stickers ?? []) push(item);
226
+ }
227
+ return out.slice(-cap);
228
+ }
229
+
230
+ /**
231
+ * 取一批消息的「触发消息」:正文用最后一条,图片用整批合并后的。
232
+ *
233
+ * 批量窗口里先发图、再补一句文字时,最后一条通常是纯文字;
234
+ * 只用最后一条会把图丢掉。返回 null 表示这批是空的。
235
+ */
236
+ export function batchTrigger(messages, limit = 4) {
237
+ const list = Array.isArray(messages) ? messages : [];
238
+ const last = list.at(-1);
239
+ if (!last) return null;
240
+ const pictures = collectBatchImages(list, limit);
241
+ if (!pictures.length) return last;
242
+ // 整批的图片和贴纸合并后,要按**原本的归属**重新分回两个字段:
243
+ // 下游用 images 判「有没有画面」、用 stickers 判「是不是表情包」,
244
+ // 全塞进 images 会让「发表情包不强制回」这条规则失效。
245
+ const fromStickers = new Set();
246
+ // B20:按**每个条目自己的来源**记,而不是按「这条消息是不是纯贴纸」判断。
247
+ //
248
+ // 以前只在「有贴纸且没有图」的消息上登记贴纸,于是同一条消息里
249
+ // 既有图又有贴纸时,那几张贴纸不会被登记 → 落到下面的 images 里。
250
+ // 后果是下游把贴纸当成照片:imageParts 会把它当普通图读(没问题),
251
+ // 但「表情包不强制回」这类按 stickers 判断的规则就失效了。
252
+ for (const message of list) {
253
+ for (const item of message?.stickers ?? []) {
254
+ fromStickers.add(String(item?.url ?? '') + '|' + String(item?.file ?? ''));
255
+ }
256
+ }
257
+ const key = (p) => String(p?.url ?? '') + '|' + String(p?.file ?? '');
258
+ const images = pictures.filter((p) => !fromStickers.has(key(p)));
259
+ const stickers = pictures.filter((p) => fromStickers.has(key(p)));
260
+ return {
261
+ ...last,
262
+ ...(images.length ? { images } : {}),
263
+ ...(stickers.length ? { stickers } : {}),
264
+ };
265
+ }
266
+
267
+ export function noteLog(label) {
268
+ try {
269
+ const dir = process.env.DSH_QQ_CONFIG ? dirname(process.env.DSH_QQ_CONFIG) : join(homedir(), '.dsh-qq-access');
270
+ appendFileSync(join(dir, 'debug.log'), `${new Date().toISOString()} ${String(label).slice(0, 2000)}\n`);
271
+ } catch { /* diagnostics must never break the plugin */ }
272
+ }
273
+
274
+ export function safeLog(logger, label, error) {
275
+ // Do not leak upstream bodies, message text, API tokens, cookies or browser paths.
276
+ const kind = error?.name ?? 'Error';
277
+ // Local diagnostic trail: the desktop host keeps plugin console output out of reach.
278
+ try {
279
+ const dir = process.env.DSH_QQ_CONFIG ? dirname(process.env.DSH_QQ_CONFIG) : join(homedir(), '.dsh-qq-access');
280
+ appendFileSync(join(dir, 'debug.log'), `${new Date().toISOString()} ${label} (${kind}) ${String(error?.stack ?? error?.message ?? error).slice(0, 4000)}\n`);
281
+ } catch { /* diagnostics must never break the plugin */ }
282
+ logger.warn?.(`${label} (${kind});详细原因可在本机 doctor 或 Harness 工具结果中查看。`);
283
+ }
284
+
285
+ /**
286
+ * 判断一段话是不是在重复已经说过的话。
287
+ *
288
+ * 模型在多轮里翻来覆去说同一句是很常见的问题:开场白、「记得早点睡」、
289
+ * 同一个梗反复用。上下文里虽然带着她说过的原话,但模型并不总会比对。
290
+ *
291
+ * 做法:把两段文字都拆成「有意义的片段」,算出重合比例。
292
+ * 用片段而不是整句哈希,是因为复述几乎总会差几个字(换个标点、加个语气词),
293
+ * 整句比对会全部漏过去。
294
+ *
295
+ * 中文不靠空格分词,所以按 2 字滑窗切:既有区分度,又不会因为分词失败而误判。
296
+ */
297
+ export function repeatRatio(text, previous) {
298
+ const norm = (s) => String(s ?? '')
299
+ .replace(/\s+/g, '')
300
+ .replace(/[,。!?、,.!?~~…;;::"'「」『』()()\[\]【】]/g, '')
301
+ .toLowerCase();
302
+ const a = norm(text);
303
+ const b = norm(previous);
304
+ if (!a || !b) return 0;
305
+ // 短句单独处理。以前这里对不足 4 个字直接返回 0,「晚安」对「晚安」永远判不出来 ——
306
+ // 而那正是最典型的口头禅复读。完全相同就是 1,包含关系按长度折算。
307
+ if (a.length < 4 || b.length < 4) {
308
+ if (a === b) return 1;
309
+ // 短句被长句包含时,按长度比折算,不能一律 0.9。
310
+ //
311
+ // 「在的」vs「在的呀」:3/4 的长度,确实是同一句,判 0.9 合理。
312
+ // 「早点睡」vs「今天辛苦了,记得早点睡哦,明天还有会」:短句只占长句的一小段,
313
+ // 那是「顺口提到」,不是复述。以前一律给 0.9 会把这种判成重复。
314
+ const shorter = a.length <= b.length ? a : b;
315
+ const longer = a.length <= b.length ? b : a;
316
+ if (shorter.length >= 2 && longer.includes(shorter)) {
317
+ const coverage = shorter.length / longer.length;
318
+ // 只有短句占长句一半以上,才算「同一句的两个版本」。
319
+ return coverage >= 0.5 ? 0.9 : 0;
320
+ }
321
+ return 0;
322
+ }
323
+ const grams = (s) => {
324
+ const set = new Set();
325
+ for (let i = 0; i + 2 <= s.length; i++) set.add(s.slice(i, i + 2));
326
+ return set;
327
+ };
328
+ const ga = grams(a);
329
+ const gb = grams(b);
330
+ if (!ga.size || !gb.size) return 0;
331
+ let hit = 0;
332
+ for (const g of ga) if (gb.has(g)) hit += 1;
333
+ // 除以「较短那一段」的片段数,而不是固定除 a。
334
+ // 复述几乎总是改写:加个语气词、换个标点、多一句尾巴。
335
+ // 拿长的那段当分母时,「嗯嗯,记得早点睡吧」对「记得早点睡哦」只有 0.57,
336
+ // 永远够不到阈值;改成除以较短段就能反映「核心内容基本一样」。
337
+ return hit / Math.min(ga.size, gb.size);
338
+ }
339
+
340
+ /**
341
+ * 在最近她说过的话里,找出与 text 最像的一条。
342
+ *
343
+ * 返回 { ratio, text } —— ratio 为 0 表示没找到明显重复。
344
+ * 只看她自己发的(direction === 'out'),别人说的话重复不算问题。
345
+ */
346
+ /**
347
+ * 抽「话题词」:连续 2–4 个汉字里,去掉虚词和代词后剩下的片段。
348
+ *
349
+ * 为什么需要它:同一件事可以换很多说法。
350
+ * 「今天下雨了,出门记得带伞」和「外面今天下雨了,别忘了带伞哦」
351
+ * 字面相似度只有 0.50,但说的明明是同一件事。
352
+ * 光比对字面会漏掉这类复述,所以再按话题词交集判一次。
353
+ */
354
+ export function topicWords(text) {
355
+ const s = String(text ?? '')
356
+ .replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ' ')
357
+ .trim();
358
+ if (!s) return [];
359
+ const STOP = new Set([
360
+ '今天', '明天', '昨天', '现在', '刚才', '已经', '还是', '就是', '这样', '那样',
361
+ '什么', '怎么', '为什么', '可以', '应该', '真的', '有点', '一下', '一个', '这个', '那个',
362
+ '我们', '你们', '他们', '自己', '东西', '事情', '时候', '地方', '感觉', '知道',
363
+ '记得', '不要', '不会', '没有', '然后', '但是', '因为', '所以', '如果',
364
+ ]);
365
+ const out = new Set();
366
+ for (const chunk of s.split(/\s+/)) {
367
+ if (!chunk || chunk.length < 2) continue;
368
+ // 英文/数字整体算一个词
369
+ if (/^[a-zA-Z0-9]+$/.test(chunk)) { out.add(chunk.toLowerCase()); continue; }
370
+ // 中文按 2–4 字滑窗取片段,再滤掉虚词
371
+ for (let n = 2; n <= 4; n++) {
372
+ for (let i = 0; i + n <= chunk.length; i++) {
373
+ const w = chunk.slice(i, i + n);
374
+ if (STOP.has(w)) continue;
375
+ if (/^[的一了是不在有个和就都也还我你他她它这那就很太更最]+$/.test(w)) continue;
376
+ out.add(w);
377
+ }
378
+ }
379
+ }
380
+ return [...out];
381
+ }
382
+
383
+ /**
384
+ * 两条文本共有的、最长的若干个话题词。
385
+ * 取最长的若干条,短片段(2 字)噪音大,长片段才真正代表「说的事」。
386
+ */
387
+ export function sharedTopics(a, b, { max = 3 } = {}) {
388
+ const share = new Set(topicWords(a));
389
+ const other = new Set(topicWords(b));
390
+ const common = [...share].filter((w) => other.has(w));
391
+ // 去掉被更长片段包含的短片段:有「下雨了」就不必再留「下雨」。
392
+ const kept = common.filter((w) => !common.some((o) => o !== w && o.includes(w) && o.length > w.length));
393
+ return kept.sort((x, y) => y.length - x.length).slice(0, max);
394
+ }
395
+
396
+ export function findRepeatedReply(text, recentOutbound, { threshold = 0.7, window = 12 } = {}) {
397
+ const mine = (Array.isArray(recentOutbound) ? recentOutbound : [])
398
+ // 只比她说过的话。别人说「记得早点睡」不算她重复。
399
+ .filter((m) => m && m.direction === 'out' && typeof m.text === 'string' && m.text.trim())
400
+ .slice(-Math.max(1, window));
401
+ let best = { ratio: 0, text: '', topics: [] };
402
+ for (const m of mine) {
403
+ const ratio = repeatRatio(text, m.text);
404
+ // 话题词只当「加权」,不能单方面把结果抬过阈值。
405
+ //
406
+ // 以前的写法是:只要有一个 3 字以上的共同片段,就把有效相似度写成
407
+ // Math.max(ratio, 0.75) —— 而默认阈值是 0.7,等于「一个三字词就直接判重」。
408
+ // 「我去吃饭了」对「你吃饭了吗」共有一个「吃饭了」就被判成复读;
409
+ // 「早点睡」对「今天辛苦了,记得早点睡哦」也是。这类日常词太常见了。
410
+ //
411
+ // 现在改成:片段只贡献有限加分(最多 +0.15),且加分后仍要跨过阈值。
412
+ // 真正同义改写的两条(字面 0.5、片段重合度高)仍然能被抓住,
413
+ // 但单个日常三字词不足以构成复读。
414
+ const topics = sharedTopics(text, m.text);
415
+ const longTopics = topics.filter((t) => t.length >= 3);
416
+ // 有几个「实质话题」重合:越多越可能是同一件事。
417
+ //
418
+ // 门槛是「至少 2 个不同的长片段」。单个三字词(吃饭了 / 早点睡 / 下雨了)
419
+ // 在中文里太常见,一个不足以说明说的是同一件事 —— 那正是之前误判的根源。
420
+ // 两个以上(今天下雨 + 带伞)才可能是真的在讲同一件事。
421
+ const bonus = longTopics.length >= 2 ? Math.min(0.30, 0.10 + longTopics.length * 0.08) : 0;
422
+ const effective = ratio + bonus;
423
+ if (effective > best.ratio) best = { ratio: effective, text: m.text, topics };
424
+ }
425
+ return best.ratio >= threshold ? best : { ratio: best.ratio, text: '', topics: [] };
426
+ }
427
+ /**
428
+ * 清掉 DSH 宿主自带的「编程 agent」提示词段。
429
+ *
430
+ * 宿主 system prompt 里有几段是给编程会话的:身份声明("You are an AI agent
431
+ * powered by DeepSeek Harness." / "You are a coding agent powered by the …
432
+ * model.")、文件交付指引、源码 checkout 说明、Web GUI 交互说明。对 QQ 聊天
433
+ * 是纯噪音,更糟的是身份声明和「真实人类女生」人设直接打架——实机上模型被
434
+ * 三层身份拉扯后吐过训练默认样板句("You are a helpful assistant.")。
435
+ *
436
+ * 宿主的 section 注册按 name 在调用方 scope 遮蔽全局段(官方 preset 行的
437
+ * 标准姿势:"Each shadows its deployment default instead of appearing beside
438
+ * it… Empty text contributes nothing"),所以这里用同名空段把它们盖掉。
439
+ * suppressRuntimeContext() 同样是 scope 级的,只抑制本会话的可选运行时上下文
440
+ * (checkout 路径、GUI URL 等),工作目录等必需上下文不受影响。
441
+ *
442
+ * 段名与 order 来自宿主源码(SystemPrompt 的 SECTION_ORDERS 与各注册处);
443
+ * 宿主升级后若改了段名,这里静默失效、退回原样,不会出错。
444
+ */
445
+ export const HOST_PROMPT_SECTIONS = Object.freeze([
446
+ ['harness:identity', -1000], // "You are an AI agent powered by DeepSeek Harness."
447
+ ['deployment:persona-prefix', 0], // "You are a coding agent powered by the {{model}} model."
448
+ ['deployment:persona-suffix', 10200], // 部署级人格尾段(默认为空)
449
+ ['ui:deliverable-file-references', 9000], // present/文件引用指引(编程交付场景)
450
+ ['harness:source', 10000], // DSH 源码 checkout 说明
451
+ ['app:web-surface', 10100], // Web GUI / pnpm dev:web 交互说明
452
+ ]);
453
+
454
+ export function stripHostPrompt(agentCtx) {
455
+ try {
456
+ for (const [name, order] of HOST_PROMPT_SECTIONS) {
457
+ agentCtx?.systemPrompt?.section?.({ name, order, text: '' });
458
+ }
459
+ agentCtx?.systemPrompt?.suppressRuntimeContext?.();
460
+ } catch { /* 老宿主缺接口时跳过;空段在任何宿主上都无害 */ }
461
+ }
462
+ /**
463
+ * 剥掉模型输出里的「系统样板句」。
464
+ *
465
+ * 实机事故:长会话里模型抽风,把训练语料的经典开头 "You are a helpful
466
+ * assistant." 当正文第一句写了出去,分条发送后对方真收到了这句英文。
467
+ * 身份声明类提示词已经清掉(见 stripHostPrompt),但模型退化是概率事件,
468
+ * 出站必须兜底:怎么抽风都行,样板句漏不出去。
469
+ *
470
+ * 只删「行首就是样板句式」的行——她的人设是中文真实女生,正常回复不可能
471
+ * 以这些句式开头;"You are a great friend" 这类正常句子不在此列。
472
+ * 剥完剩下的内容照常发送;整条被剥空返回空串,调用方应当不发。
473
+ */
474
+ const MODEL_BOILERPLATE = new RegExp([
475
+ '^you\\s+are\\s+(a|an|the)\\s+(helpful\\s+)?(ai|assistant|bot|language model|computer program|virtual)',
476
+ '^(i\\s+am|i[\\x27\\u2019]?m)\\s+(a|an)\\s+(helpful\\s+)?(ai|assistant|bot|language model|virtual)',
477
+ '^as\\s+(a|an)\\s+(ai|language model|assistant|bot|virtual)',
478
+ '^(system|assistant|ai|model|user)\\s*[::]',
479
+ '^(i[\\x27\\u2019]?m|i am)\\s+(here to|ready to)\\s+help',
480
+ '^(hello|hi)[!!。,.]?\\s*(i[\\x27\\u2019]?m|i am)\\s+(a|an)?\\s*(ai|assistant|helpful)',
481
+ ].join('|'), 'i');
482
+
483
+ export function stripModelBoilerplate(text) {
484
+ return String(text ?? '')
485
+ .split(/\r?\n/)
486
+ .filter((line) => !MODEL_BOILERPLATE.test(line.trim()))
487
+ .join('\n')
488
+ .trim();
489
+ }