@nestim/koishi-plugin-qq-group-manager 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/readme.md CHANGED
@@ -94,7 +94,13 @@ npm i @nestim/koishi-plugin-qq-group-manager
94
94
  | `groupRules` | `[]` | 按群覆盖策略(违禁词、强关键词、白名单关键词、AI 开关、自动处罚阈值等) |
95
95
  | `memoryFileName` | `Memory.md` | 记忆库基础文件名;分作用域时作为前缀 |
96
96
  | `memoryPerScope` | `true` | 按私聊/群聊分开存:`Memory_<群号>_群聊.md` / `Memory_<QQ号>_私聊.md` |
97
- | `memoryAutoLearn` | `false` | 允许外部学习插件自动归纳(配合 qqgm-memory-learn) |
97
+ | `memoryAutoLearn` | `false` | **AI 自动归纳记忆**(内建):上下文挤满后把消息总结成记忆并回推 |
98
+ | `memoryLearnIdleHours` | `8` | 空闲兜底小时数;期间没有新消息则不触发 |
99
+ | `memoryLearnThresholdScale` | `1` | 归纳阈值 = `aiContextWindow × 该值` |
100
+ | `memoryLearnMaxChars` | `150` | 单条自动记忆字数上限 |
101
+ | `memoryLearnPushBack` | `true` | 归纳后回推原会话(私聊发私聊、群聊发对应群) |
102
+ | `memoryLearnDuplicateThreshold` | `0.55` | 相似度超此值跳过,避免重复记 |
103
+ | `memoryLearnDailyLimit` | `30` | 每作用域每天最多归纳次数 |
98
104
  | `blacklistFileName` | `banMember.md` | 黑名单文件名模板,实际为 `banMember_<群号>.md` |
99
105
  | `pendingJoinFileName` | `JoinRequests.md` | 待审入群申请落盘文件名 |
100
106
  | `enableJoinRequestReview` | `true` | 是否发起入群审核 |
@@ -161,11 +167,39 @@ npm i @nestim/koishi-plugin-qq-group-manager
161
167
  | 插件 | 作用 | 地址 |
162
168
  | --- | --- | --- |
163
169
  | `@nestim/koishi-plugin-qqgm-chat-style` | 聊天风格:一个主风格 + 多个按概率随机叠加的追加风格 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-chat-style) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-chat-style) |
164
- | `@nestim/koishi-plugin-qqgm-meme` | 表情包:AI 用 `[表情: 情绪]` 抽图,按概率补在文字后面 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-meme) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-meme) |
165
- | `@nestim/koishi-plugin-qqgm-memory-learn` | 记忆自动归纳:上下文挤满后把消息总结成记忆并回推 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-memory-learn) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-memory-learn) |
170
+ | `@nestim/koishi-plugin-qqgm-meme` | 表情包:AI 用 `[表情: 情绪]` 抽图,按概率补在文字后面 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-meme) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-meme) |
166
171
 
167
172
  定时提醒(`[提醒] 明天 8 点 开会`)**内建在本插件里**,不需要额外安装。
168
173
 
174
+ ## 记忆自动归纳(1.4.1+,内建)
175
+
176
+ 不需要额外插件。开启 `memoryAutoLearn` 后:
177
+
178
+ ```
179
+ 上下文挤满(aiContextWindow 条)
180
+ ↓ 最老的消息被挤出
181
+ 累计到阈值(aiContextWindow × memoryLearnThresholdScale)
182
+ 或空闲满 memoryLearnIdleHours(且期间有新消息)
183
+ ↓
184
+ 模型归纳成一条 ≤ memoryLearnMaxChars 的记忆
185
+ ↓ 与已有记忆去重
186
+ 写入 Memory_<群号>_群聊.md / Memory_<QQ号>_私聊.md
187
+ ↓ 回推原会话
188
+ 「刚记住了:……」
189
+ ```
190
+
191
+ 要点:
192
+
193
+ - **不会空转**:8 小时里一条新消息都没有,就不归纳。
194
+ - **不会串台**:私聊发私聊,群聊发对应群。
195
+ - **不会记废话**:提示词只允许人物关系、稳定偏好、群内黑话、反复出现的话题;
196
+ 寒暄、一次性情绪、已结束的接梗、纯表情全部丢弃。
197
+ - **不会重复记**:写入前做相似度比对,超过 `memoryLearnDuplicateThreshold` 就跳过。
198
+ - **不会刷爆额度**:每作用域每天最多 `memoryLearnDailyLimit` 次。
199
+ - **系统备注与指令消息不参与归纳**(复读、命令结果等)。
200
+
201
+ 自动写入了什么,可以直接在 Koishi 控制台「探索器」打开对应的 `Memory_*.md` 查看。
202
+ 条目带的时间戳与来源标记能让你区分手动 `[memory]` 与 AI 自动归纳。
169
203
  ## 外部插件接口(1.2.2+)
170
204
 
171
205
  主插件暴露一个很小的扩展点,第三方插件可以给 AI 追加“说话风格”,或在发送前过滤输出,
package/src/ai/engine.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import { AiState, GroupState, ChatRecord, FollowupState } from './state';
16
+ import { LearnBucket, LearnStore, buildSummaryPrompt, cleanSummary, isDuplicate } from './learn';
16
17
  import { decideTrigger } from './trigger';
17
18
  import { buildJudgePrompt, buildReplyPrompt, buildUserPrompt, PASS_TOKEN } from './prompt';
18
19
  import { ChatProvider, ChatResult } from './provider';
@@ -96,6 +97,12 @@ export class AiEngine {
96
97
  private searchCache = new Map<string, { at: number; section: string }>();
97
98
  private searchRate = new Map<string, number[]>();
98
99
  private searchUnsupportedUntil = 0;
100
+ /** 自动归纳:按作用域累计被挤出的消息 */
101
+ private learnStore = new LearnStore();
102
+ /** 自动归纳:每个作用域每天的次数,防刷额度 */
103
+ private learnDaily = new Map<string, number>();
104
+ /** 自动归纳:空闲兜底定时器 */
105
+ private learnTimer: any = null;
99
106
 
100
107
  constructor(host: AiHost, deps: AiDeps = {}) {
101
108
  this.host = host;
@@ -111,6 +118,9 @@ export class AiEngine {
111
118
  this.rng = deps.rng ?? Math.random;
112
119
  this.now = deps.now ?? Date.now;
113
120
  this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
121
+
122
+ // 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
123
+ this.startLearnTimer();
114
124
  }
115
125
 
116
126
  // ---------------------------------------------------------------- 配置
@@ -278,50 +288,207 @@ export class AiEngine {
278
288
  * 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
279
289
  * 失败不影响主流程。
280
290
  */
281
- private emitEvicted(evicted: ChatRecord[], groupKey?: string, session?: any): void {
282
- if (!evicted || !evicted.length) return;
283
- if (!this.hooks || typeof (this.hooks as any).runContextEvicted !== "function") return;
284
- // 自动归纳开关 + 生效范围白名单
285
- const cfg: any = this.config || {};
286
- if (cfg.memoryAutoLearn === false) return;
287
- const allow: string[] = Array.isArray(cfg.memoryAutoLearnGroups) ? cfg.memoryAutoLearnGroups.map(String) : [];
288
- if (allow.length) {
289
- const gid = String(session?.guildId || "");
290
- const uid = String(session?.userId || "");
291
- if (!allow.includes(gid) && !allow.includes(uid)) return;
292
- }
293
-
294
- const isDirect = session?.isDirect === true || !session?.guildId;
295
- const guildId = String(session?.guildId || "");
296
- const userId = String(session?.userId || "");
297
- const kind: "group" | "private" = isDirect ? "private" : "group";
298
- const scopeId = isDirect ? userId : guildId;
299
- if (!scopeId) return;
300
-
301
- const payload = evicted.map((item) => ({
302
- id: item.id,
303
- userId: item.userId,
304
- name: item.name,
305
- role: item.role,
306
- text: item.text,
307
- self: item.self,
308
- at: item.at,
309
- command: item.command,
310
- }));
311
-
312
- void this.hooks
313
- .runContextEvicted({
314
- groupId: guildId,
315
- kind,
316
- scopeId,
317
- session,
318
- evicted: payload,
319
- window: this.contextWindow,
320
- })
321
- .catch((error: any) => {
322
- this.host.logger?.warn?.(`[ai-evicted] 分发失败: ${String(error)}`);
323
- });
324
- }
291
+ /**
292
+ * 上下文挤出后的两件事:
293
+ * 1. 交给外部插件(registerContextEvicted,可选)
294
+ * 2. 内建自动归纳:累计到阈值或空闲后总结成一条记忆写回
295
+ * 任何一步失败都不影响正常聊天。
296
+ */
297
+ private emitEvicted(evicted: ChatRecord[], groupKey?: string, session?: any): void {
298
+ if (!evicted || !evicted.length) return;
299
+
300
+ const isDirect = session?.isDirect === true || !session?.guildId;
301
+ const guildId = String(session?.guildId || "");
302
+ const userId = String(session?.userId || "");
303
+ const kind: "group" | "private" = isDirect ? "private" : "group";
304
+ const scopeId = isDirect ? userId : guildId;
305
+ if (!scopeId) return;
306
+
307
+ const cfg: any = this.config || {};
308
+
309
+ // ---------- 1) 分发给外部插件 ----------
310
+ if (this.hooks && typeof (this.hooks as any).runContextEvicted === "function") {
311
+ const payload = evicted.map((item) => ({
312
+ id: item.id,
313
+ userId: item.userId,
314
+ name: item.name,
315
+ role: item.role,
316
+ text: item.text,
317
+ self: item.self,
318
+ at: item.at,
319
+ command: item.command,
320
+ }));
321
+ void this.hooks
322
+ .runContextEvicted({
323
+ groupId: guildId,
324
+ kind,
325
+ scopeId,
326
+ session,
327
+ evicted: payload,
328
+ window: this.contextWindow,
329
+ })
330
+ .catch((error: any) => {
331
+ this.host.logger?.warn?.(`[ai-evicted] 分发失败: ${String(error)}`);
332
+ });
333
+ }
334
+
335
+ // ---------- 2) 内建自动归纳 ----------
336
+ if (!cfg.memoryAutoLearn) return;
337
+ if (!cfg.enableMemory || cfg.memoryAutoLearn === false) return;
338
+ if (!this.resolveEnabled(session)) return;
339
+ const allow: string[] = Array.isArray(cfg.memoryAutoLearnGroups) ? cfg.memoryAutoLearnGroups.map(String) : [];
340
+ if (allow.length && !allow.includes(guildId) && !allow.includes(userId)) return;
341
+
342
+ const bucket = this.learnStore.get(kind, scopeId);
343
+ const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
344
+ const fire = bucket.push(evicted, threshold, this.now());
345
+ if (fire) {
346
+ void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
347
+ }
348
+ }
349
+
350
+ /** 归纳并(可选)回推到原会话 */
351
+ /** 启动空闲兜底定时器;每 5 分钟检查一次 */
352
+ private startLearnTimer(): void {
353
+ if (this.learnTimer) return;
354
+ const cfg: any = this.config || {};
355
+ if (!cfg.memoryAutoLearn) return;
356
+ const idleHours = Math.max(1, Number(cfg.memoryLearnIdleHours) || 8);
357
+ const idleMs = idleHours * 60 * 60 * 1000;
358
+ this.learnTimer = setInterval(() => {
359
+ try {
360
+ const pending = this.learnStore.idleList(this.now(), idleMs);
361
+ for (const item of pending) {
362
+ void this.learnAndReport(item.kind as any, item.scopeId, item.bucket, "idle");
363
+ }
364
+ } catch (error: any) {
365
+ this.host.logger?.warn?.(`[memory-learn] 空闲检查失败: ${String(error)}`);
366
+ }
367
+ }, 5 * 60 * 1000);
368
+ if (this.learnTimer.unref) this.learnTimer.unref();
369
+ }
370
+
371
+ /** 资源清理:停止定时器、清空缓存 */
372
+ dispose(): void {
373
+ if (this.learnTimer) {
374
+ clearInterval(this.learnTimer);
375
+ this.learnTimer = null;
376
+ }
377
+ this.learnStore.clear();
378
+ this.learnDaily.clear();
379
+ this.searchCache.clear();
380
+ this.searchRate.clear();
381
+ }
382
+
383
+ private async learnAndReport(
384
+ kind: "group" | "private",
385
+ scopeId: string,
386
+ bucket: LearnBucket,
387
+ reason: string,
388
+ session?: any,
389
+ ): Promise<void> {
390
+ const cfg: any = this.config || {};
391
+ const records = bucket.drain();
392
+ if (!records.length) return;
393
+
394
+ const scope = { kind, id: scopeId } as any;
395
+ const summary = await this.summarizeRecords(records, kind, scope, reason);
396
+ if (!summary) return;
397
+
398
+ if (cfg.memoryLearnPushBack === false) return;
399
+
400
+ const text = `刚记住了:${summary}`;
401
+ try {
402
+ if (kind === "private") {
403
+ const bot = (kind === "private" && session?.bot) || null;
404
+ const targetBot = bot || this.findBot();
405
+ if (targetBot) await targetBot.sendMessage(scopeId, text, { userId: scopeId });
406
+ } else {
407
+ const targetBot = session?.bot || this.findBot();
408
+ if (targetBot) await targetBot.sendMessage(scopeId, text, { guildId: scopeId, channelId: scopeId });
409
+ }
410
+ } catch (error: any) {
411
+ this.host.logger?.warn?.(`[memory-learn] 回推失败 ${kind}:${scopeId}: ${String(error)}`);
412
+ }
413
+ }
414
+
415
+ /** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
416
+ private async summarizeRecords(
417
+ records: any[],
418
+ kind: "group" | "private",
419
+ scope: any,
420
+ reason: string,
421
+ ): Promise<string> {
422
+ const cfg: any = this.config || {};
423
+
424
+ // 每日上限
425
+ const day = new Date();
426
+ const dayStamp = `${day.getFullYear()}-${day.getMonth() + 1}-${day.getDate()}`;
427
+ const dailyKey = `${kind}:${scope.id}:${dayStamp}`;
428
+ const limit = Math.max(1, Number(cfg.memoryLearnDailyLimit) || 30);
429
+ const used = this.learnDaily.get(dailyKey) || 0;
430
+ if (used >= limit) {
431
+ this.host.logger?.info?.(`[memory-learn] 已达每日上限 ${limit}(${kind}:${scope.id})`);
432
+ return "";
433
+ }
434
+
435
+ const prompt = buildSummaryPrompt(records, { kind, selfName: this.selfName });
436
+ let raw = "";
437
+ try {
438
+ const result = await this.provider.chat({
439
+ system: prompt.system,
440
+ user: prompt.user,
441
+ temperature: 0.3,
442
+ maxTokens: 400,
443
+ });
444
+ if (!result || !result.ok) {
445
+ this.host.logger?.warn?.(`[memory-learn] 归纳调用失败: ${result && result.error}`);
446
+ return "";
447
+ }
448
+ raw = String(result.text || "");
449
+ } catch (error: any) {
450
+ this.host.logger?.warn?.(`[memory-learn] 归纳异常: ${String(error)}`);
451
+ return "";
452
+ }
453
+
454
+ const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
455
+ let text = cleanSummary(raw, maxChars);
456
+ if (!text) return "";
457
+
458
+ // 去重
459
+ let existing: string[] = [];
460
+ try {
461
+ const content = await (this.host as any).readMemoryFile(scope);
462
+ existing = String(content || "")
463
+ .split(/\r?\n---\r?\n/)
464
+ .map((b: string) => b.trim())
465
+ .filter(Boolean)
466
+ .map((b: string) => b.split("\n").slice(1).join("\n").trim() || b);
467
+ } catch {
468
+ existing = [];
469
+ }
470
+ const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
471
+ if (isDuplicate(text, existing, threshold)) {
472
+ this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
473
+ return "";
474
+ }
475
+
476
+ try {
477
+ await (this.host as any).saveMemoryToFile("", text, scope, "自动归纳");
478
+ this.learnDaily.set(dailyKey, used + 1);
479
+ } catch (error: any) {
480
+ this.host.logger?.warn?.(`[memory-learn] 写入失败: ${String(error)}`);
481
+ return "";
482
+ }
483
+
484
+ this.host.logger?.info?.(`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${text.length}字`);
485
+ return text;
486
+ }
487
+
488
+ private findBot(): any {
489
+ const bots = (this.host as any)?.ctx?.bots || (this.host as any)?.bots || [];
490
+ return (bots || []).find((item: any) => item.platform === "onebot") || null;
491
+ }
325
492
 
326
493
  // ---------------------------------------------------------------- 点名 / 跟随
327
494
 
@@ -0,0 +1,208 @@
1
+ /**
2
+ * 记忆自动归纳(纯函数 + 轻量状态)。
3
+ *
4
+ * 触发时机由 engine 在上下文挤出时调用:
5
+ * - 累计条数达到「上下文窗口 × 倍率」
6
+ * - 或距最后一条消息超过 idleHours 且期间有新消息(由 idle 定时器驱动)
7
+ *
8
+ * 归纳出来的内容是一次性的一长串,150 字以内,写入对应作用域的记忆文件。
9
+ */
10
+
11
+ import { truncate } from '../core/text';
12
+
13
+ export const MAX_SUMMARY_CHARS = 150;
14
+
15
+ export interface EvictedLike {
16
+ id?: string;
17
+ userId?: string;
18
+ name?: string;
19
+ text?: string;
20
+ self?: boolean;
21
+ at?: number;
22
+ command?: boolean;
23
+ }
24
+
25
+ /** 正在累计的一批消息 */
26
+ export class LearnBucket {
27
+ records: EvictedLike[] = [];
28
+ lastActivityAt = 0;
29
+ lastLearnedAt = 0;
30
+
31
+ push(records: EvictedLike[], threshold: number, now: number): boolean {
32
+ if (!records || !records.length) return false;
33
+ this.records.push(...records);
34
+ this.lastActivityAt = now;
35
+ return this.records.length >= Math.max(1, threshold);
36
+ }
37
+
38
+ /** 距最后一条消息超过 idleMs,且确实有内容 */
39
+ isIdle(now: number, idleMs: number): boolean {
40
+ if (!this.records.length) return false;
41
+ if (!this.lastActivityAt) return false;
42
+ return now - this.lastActivityAt >= idleMs;
43
+ }
44
+
45
+ drain(): EvictedLike[] {
46
+ const out = this.records;
47
+ this.records = [];
48
+ return out;
49
+ }
50
+
51
+ get size(): number {
52
+ return this.records.length;
53
+ }
54
+ }
55
+
56
+ /** 按作用域保存累计桶 */
57
+ export class LearnStore {
58
+ private map = new Map<string, LearnBucket>();
59
+
60
+ private key(kind: string, scopeId: string): string {
61
+ return `${kind}:${scopeId}`;
62
+ }
63
+
64
+ get(kind: string, scopeId: string): LearnBucket {
65
+ const k = this.key(kind, scopeId);
66
+ let bucket = this.map.get(k);
67
+ if (!bucket) {
68
+ bucket = new LearnBucket();
69
+ this.map.set(k, bucket);
70
+ }
71
+ return bucket;
72
+ }
73
+
74
+ idleList(now: number, idleMs: number): Array<{ kind: string; scopeId: string; bucket: LearnBucket }> {
75
+ const out: Array<{ kind: string; scopeId: string; bucket: LearnBucket }> = [];
76
+ for (const [k, bucket] of this.map) {
77
+ if (!bucket.size) continue;
78
+ if (!bucket.isIdle(now, idleMs)) continue;
79
+ const idx = k.indexOf(':');
80
+ out.push({ kind: k.slice(0, idx), scopeId: k.slice(idx + 1), bucket });
81
+ }
82
+ return out;
83
+ }
84
+
85
+ clear(): void {
86
+ this.map.clear();
87
+ }
88
+ }
89
+
90
+ /** 把一批消息渲染成模型可读的文本 */
91
+ export function renderForSummary(records: EvictedLike[], selfName = 'bot'): string {
92
+ const lines: string[] = [];
93
+ for (const item of records) {
94
+ if (!item || item.command) continue;
95
+ const text = String(item.text || '').replace(/\s+/g, ' ').trim();
96
+ if (!text) continue;
97
+ const who = item.self ? selfName : String(item.name || item.userId || '某人');
98
+ lines.push(`${who}: ${truncate(text, 160)}`);
99
+ }
100
+ return lines.join('\n');
101
+ }
102
+
103
+ /** 归纳提示词 */
104
+ export function buildSummaryPrompt(
105
+ records: EvictedLike[],
106
+ options: { kind?: string; selfName?: string } = {},
107
+ ): { system: string; user: string } {
108
+ const label = options.kind === 'private' ? '私聊' : '群聊';
109
+ const body = renderForSummary(records, options.selfName || 'bot');
110
+ const system = [
111
+ `你在整理一段${label}记录,从中提炼值得长期记住的信息。`,
112
+ '',
113
+ '只保留这几类:',
114
+ '1. 人物关系与称呼(谁是谁、怎么叫、什么身份)',
115
+ '2. 稳定的偏好、立场、习惯(不是一时的情绪)',
116
+ '3. 群内或两人之间约定俗成的说法、黑话',
117
+ '4. 反复出现、以后还会聊到的话题',
118
+ '',
119
+ '必须丢掉:寒暄、打招呼、一次性的抱怨或玩笑、已经结束的接梗、纯表情。',
120
+ '',
121
+ '输出要求:',
122
+ '- 只输出一条记忆,纯文本,不要标题、不要列表、不要编号、不要 Markdown;',
123
+ `- 不超过 ${MAX_SUMMARY_CHARS} 字;`,
124
+ '- 用陈述句写事实,不要写「他们聊到」「讨论了」这类过程描述;',
125
+ '- 如果没有任何值得长期记住的内容,只输出一个词:NONE',
126
+ ].join('\n');
127
+
128
+ const user = ['【记录】', body || '(空)', '', '现在输出那一条记忆,或输出 NONE。'].join('\n');
129
+ return { system, user };
130
+ }
131
+
132
+ /** 清洗模型输出 */
133
+ export function cleanSummary(raw: string, maxChars = MAX_SUMMARY_CHARS): string {
134
+ let text = String(raw || '').trim();
135
+ if (!text) return '';
136
+ text = text
137
+ .replace(/^```[a-zA-Z0-9_-]*\s*\n?/, '')
138
+ .replace(/\n?\s*```\s*$/, '')
139
+ .replace(/^["'“”‘’「」]+|["'“”‘’「」]+$/g, '')
140
+ .trim();
141
+
142
+ text = text
143
+ .split(/\r?\n/)
144
+ .map((line) => line.replace(/^\s*(?:[-*+·]|\d+[.)、])\s*/, '').trim())
145
+ .filter(Boolean)
146
+ .join(' ')
147
+ .replace(/\s+/g, ' ')
148
+ .trim();
149
+
150
+ if (/^(?:none|无|没有|n\/a)$/i.test(text)) return '';
151
+
152
+ const limit = Math.max(20, maxChars);
153
+ if (text.length > limit) {
154
+ const slice = text.slice(0, limit);
155
+ let cut = -1;
156
+ for (const ch of ['。', '!', '?', ';']) {
157
+ cut = Math.max(cut, slice.lastIndexOf(ch));
158
+ }
159
+ text = cut >= Math.floor(limit * 0.5) ? slice.slice(0, cut + 1) : `${slice}…`;
160
+ }
161
+ return text.trim();
162
+ }
163
+
164
+ const CJK = /[\u4e00-\u9fa5]/;
165
+
166
+ function tokenize(text: string): Set<string> {
167
+ const tokens = new Set<string>();
168
+ const normalized = String(text || '')
169
+ .toLowerCase()
170
+ .replace(/[^\u4e00-\u9fa5a-z0-9]+/g, ' ')
171
+ .trim();
172
+ if (!normalized) return tokens;
173
+ for (const chunk of normalized.split(/\s+/)) {
174
+ if (!chunk) continue;
175
+ if (CJK.test(chunk)) {
176
+ const chars = [...chunk];
177
+ if (chars.length === 1) {
178
+ tokens.add(chunk);
179
+ continue;
180
+ }
181
+ for (let i = 0; i < chars.length - 1; i += 1) tokens.add(chars[i] + chars[i + 1]);
182
+ } else if (chunk.length >= 2) {
183
+ tokens.add(chunk);
184
+ }
185
+ }
186
+ return tokens;
187
+ }
188
+
189
+ /** Jaccard 相似度,用于挡住重复记忆 */
190
+ export function similarityOf(a: string, b: string): number {
191
+ const ta = tokenize(a);
192
+ const tb = tokenize(b);
193
+ if (!ta.size || !tb.size) return 0;
194
+ let inter = 0;
195
+ for (const t of ta) if (tb.has(t)) inter += 1;
196
+ const union = ta.size + tb.size - inter;
197
+ return union ? inter / union : 0;
198
+ }
199
+
200
+ /** 判断是否与已有记忆重复 */
201
+ export function isDuplicate(candidate: string, existing: string[], threshold = 0.55): boolean {
202
+ const text = String(candidate || '').trim();
203
+ if (!text) return false;
204
+ for (const item of existing || []) {
205
+ if (similarityOf(text, String(item || '')) >= threshold) return true;
206
+ }
207
+ return false;
208
+ }
package/src/index.ts CHANGED
@@ -64,7 +64,13 @@ export const Config = Schema.intersect([
64
64
  memoryPerScope: Schema.boolean().default(true).description('按私聊/群聊分开存储:群聊写 Memory_<群号>_群聊.md,私聊写 Memory_<QQ号>_私聊.md。关闭则所有会话共用单文件(旧行为)。'),
65
65
  memoryInAi: Schema.boolean().default(true).description('AI 回复/识图时是否参考记忆库内容(只读当前会话对应的文件)。'),
66
66
  memoryAutoLearn: Schema.boolean().default(false).description('自动归纳:上下文挤满后,把被挤出的消息交给外部学习插件总结成记忆。这里只负责抛出事件,实际归纳由 qqgm-memory-learn 完成。'),
67
- memoryAutoLearnGroups: Schema.array(String).role('table').default([]).description('自动归纳生效的群号/QQ号白名单;留空表示全部生效。'),
67
+ memoryAutoLearnGroups: Schema.array(String).role('table').default([]).description('自动归纳生效的群号/QQ号白名单;留空表示全部生效。'),
68
+ memoryLearnIdleHours: Schema.natural().min(1).max(72).default(8).description('空闲兜底:距最后一条消息超过这么多小时且期间有新消息,就归纳一次。一直没新消息则不触发。'),
69
+ memoryLearnThresholdScale: Schema.number().min(1).max(10).step(0.5).default(1).description('归纳阈值 = aiContextWindow × 该倍数。填 1 表示攒满一个上下文窗口就归纳。'),
70
+ memoryLearnMaxChars: Schema.natural().min(40).max(300).default(150).description('单条自动记忆的字数上限。'),
71
+ memoryLearnPushBack: Schema.boolean().default(true).description('归纳后把结果回推到原会话:私聊发私聊、群聊发对应群。'),
72
+ memoryLearnDuplicateThreshold: Schema.number().min(0.3).max(0.95).step(0.05).default(0.55).description('与已有记忆相似度超过该值就跳过,避免同一件事反复记。'),
73
+ memoryLearnDailyLimit: Schema.natural().min(1).max(200).default(30).description('每个作用域每天最多归纳几次,防止刷模型额度。'),
68
74
  }).description('记忆库'),
69
75
  Schema.object({
70
76
  enableBlacklist: Schema.boolean().default(true).description('全局黑名单系统开关。单个群未单独设置时跟随此值;单个群设置后以该群为准(全局关着也能为某群单独开启)。'),