@nestim/koishi-plugin-qq-group-manager 1.4.0 → 1.4.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.
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
+ }
@@ -76,15 +76,33 @@ export class ChatProvider {
76
76
 
77
77
  if (result.ok) return { ...result, text: stripFence(result.text || '') };
78
78
 
79
- // 图片被拒(常见于 deepseek 等不支持 vision 的模型)→ 记住并去掉图片重试一次
80
- if (images.length && (result.status === 400 || result.status === 422 || /image|vision|multimodal/i.test(result.error || ''))) {
81
- this.visionUnsupported = true;
82
- this.logger?.warn?.(`[ai] 模型不支持图片(${result.status ?? '?'}),后续自动跳过图片: ${result.error}`);
83
- const fallback = provider === 'gemini'
84
- ? await this.callGemini(request, [])
85
- : await this.callOpenAi(request, []);
86
- if (fallback.ok) return { ...fallback, text: stripFence(fallback.text || ''), degradedToText: true };
87
- return fallback;
79
+ if (images.length) {
80
+ const errorText = String(result.error || '');
81
+ const rejected = result.status === 400
82
+ || result.status === 422
83
+ || /image|vision|multimodal/i.test(errorText);
84
+
85
+ if (rejected) {
86
+ // 「格式不对」和「模型不支持视觉」是两件事,必须分开处理。
87
+ // 前者只跳过这一次,后者才记进 visionUnsupported。
88
+ const formatProblem = /unsupported image|invalid image|image format|must be|one of the following formats|too large|dimension/i.test(errorText);
89
+ if (!formatProblem) {
90
+ this.visionUnsupported = true;
91
+ this.logger?.warn?.(
92
+ `[ai] 模型不支持图片(${result.status ?? '?'}),后续自动跳过图片: ${errorText}`,
93
+ );
94
+ } else {
95
+ this.logger?.warn?.(
96
+ `[ai] 本次图片格式不被接受(${result.status ?? '?'}),仅跳过本次,不影响后续: ${errorText}`,
97
+ );
98
+ }
99
+
100
+ const fallback = provider === 'gemini'
101
+ ? await this.callGemini(request, [])
102
+ : await this.callOpenAi(request, []);
103
+ if (fallback.ok) return { ...fallback, text: stripFence(fallback.text || ''), degradedToText: true };
104
+ return fallback;
105
+ }
88
106
  }
89
107
  return result;
90
108
  }