@nestim/koishi-plugin-qq-group-manager 1.4.5 → 1.4.7

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,7 +13,16 @@
13
13
  */
14
14
 
15
15
  import { AiState, GroupState, ChatRecord, FollowupState } from './state';
16
- import { LearnBucket, LearnStore, buildSummaryPrompt, cleanSummary, isDuplicate } from './learn';
16
+ import {
17
+ LearnBucket,
18
+ LearnStore,
19
+ buildSummaryPrompt,
20
+ buildConsolidatePrompt,
21
+ cleanSummary,
22
+ isDuplicate,
23
+ isAutoMemoryBlock,
24
+ AUTO_MEMORY_LABEL,
25
+ } from './learn';
17
26
  import { decideTrigger } from './trigger';
18
27
  import { buildJudgePrompt, buildReplyPrompt, buildUserPrompt, PASS_TOKEN } from './prompt';
19
28
  import { ChatProvider, ChatResult } from './provider';
@@ -38,6 +47,14 @@ export interface AiHost {
38
47
  fetchQuotedImages?(session: any, quote: any): Promise<RenderedImage[]>;
39
48
  resolveImage(ref: string, session: any): Promise<string>;
40
49
  sendReply(session: any, text: string): Promise<void>;
50
+ /** 发送系统提示(不引用、不进入 AI 上下文),用于冷却提示等 */
51
+ sendNotice?(session: any, text: string): Promise<void>;
52
+ /** 写入自动归纳记忆:add = 新条目;remove = 需要被压缩替换掉的旧条目 */
53
+ commitAutoMemory?(scope: { kind: 'group' | 'private'; id: string } | null, payload: {
54
+ add: string;
55
+ remove?: string[];
56
+ label?: string;
57
+ }): Promise<void>;
41
58
  readMemoryFile(scope?: { kind: 'group' | 'private'; id: string } | null): Promise<string>;
42
59
  }
43
60
 
@@ -47,6 +64,11 @@ export interface AiDeps {
47
64
  rng?: () => number;
48
65
  now?: () => number;
49
66
  fetchImpl?: typeof fetch;
67
+ /**
68
+ * 钩子注册表。主插件会传入进程级共享实例;不传则每次新建,
69
+ * 保证测试/多实例之间互不串钩子。
70
+ */
71
+ hooks?: AiHookRegistry;
50
72
  }
51
73
 
52
74
  const PASS_RE = /^\s*<(?:pass\s*\/?|不回复)>/i;
@@ -67,8 +89,22 @@ function cleanReply(text: string, selfName: string): string {
67
89
  return out.replace(/\s+/g, ' ').trim();
68
90
  }
69
91
 
70
- function clipReply(text: string, maxChars: number): string {
71
- const max = Math.max(20, maxChars || 120);
92
+ /** 把服务端 usage 压成一行日志,便于观察真实 token 消耗与缓存命中 */
93
+ function usageText(usage: any): string {
94
+ if (!usage) return '';
95
+ const input = usage.prompt_tokens ?? usage.input_tokens;
96
+ const output = usage.completion_tokens ?? usage.output_tokens;
97
+ const cacheHit = usage.prompt_cache_hit_tokens
98
+ ?? usage.cached_tokens
99
+ ?? usage.cache_read_input_tokens;
100
+ const parts: string[] = [];
101
+ if (input != null) parts.push(`in=${input}`);
102
+ if (output != null) parts.push(`out=${output}`);
103
+ if (cacheHit != null) parts.push(`cache=${cacheHit}`);
104
+ return parts.join(',');
105
+ }
106
+
107
+ function clipReply(text: string, maxChars: number): string { const max = Math.max(20, maxChars || 120);
72
108
  if (text.length <= max) return text;
73
109
  const slice = text.slice(0, max);
74
110
  const boundary = Math.max(
@@ -97,18 +133,20 @@ export class AiEngine {
97
133
  private searchCache = new Map<string, { at: number; section: string }>();
98
134
  private searchRate = new Map<string, number[]>();
99
135
  private searchUnsupportedUntil = 0;
100
- /** 自动归纳:按作用域累计被挤出的消息 */
101
- private learnStore = new LearnStore();
102
- /** 自动归纳:每个作用域每天的次数,防刷额度 */
103
- private learnDaily = new Map<string, number>();
104
- /** 自动归纳:空闲兜底定时器 */
105
- private learnTimer: any = null;
136
+ /** 自动归纳:按作用域累计被挤出的消息 */
137
+ private learnStore = new LearnStore();
138
+ /** 自动归纳:每个作用域每天的次数,防刷额度 */
139
+ private learnDaily = new Map<string, number>();
140
+ /** 自动归纳:空闲兜底定时器 */
141
+ private learnTimer: any = null;
106
142
 
107
143
  constructor(host: AiHost, deps: AiDeps = {}) {
108
144
  this.host = host;
109
145
  this.config = host.config;
110
146
  this.state = deps.state ?? new AiState();
111
- this.hooks = new AiHookRegistry(host.logger);
147
+ // 默认独立注册表;主插件通过 deps.hooks 注入进程级单例,
148
+ // 这样主插件重载后外部插件注册的钩子不会丢。
149
+ this.hooks = deps.hooks ?? new AiHookRegistry(host.logger);
112
150
  this.provider = deps.provider ?? new ChatProvider(host.config, host.logger);
113
151
  this.names = new NameResolver({
114
152
  getOneBotApi: (session) => host.getOneBotApi(session),
@@ -118,9 +156,9 @@ export class AiEngine {
118
156
  this.rng = deps.rng ?? Math.random;
119
157
  this.now = deps.now ?? Date.now;
120
158
  this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
121
-
122
- // 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
123
- this.startLearnTimer();
159
+
160
+ // 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
161
+ this.startLearnTimer();
124
162
  }
125
163
 
126
164
  // ---------------------------------------------------------------- 配置
@@ -136,6 +174,17 @@ export class AiEngine {
136
174
  return rules.find((item) => String(item?.guildId ?? '').trim() === guildId);
137
175
  }
138
176
 
177
+ /**
178
+ * 读配置:该群 groupRules 里有同名非空值就用它,否则回落到全局。
179
+ * 这样频率限制(阈值/概率/模型调用冷却)可以按群单独设置。
180
+ */
181
+ private setting(session: any, key: string): any {
182
+ const rule = this.ruleFor(session);
183
+ const value = rule ? rule[key] : undefined;
184
+ if (value === undefined || value === null || value === '') return this.config[key];
185
+ return value;
186
+ }
187
+
139
188
  resolveEnabled(session: any): boolean {
140
189
  const rule = this.ruleFor(session);
141
190
  const requireRule = this.config.aiReplyRequireGroupRule !== false;
@@ -175,6 +224,38 @@ export class AiEngine {
175
224
  return !!this.config.aiDebugPrompt;
176
225
  }
177
226
 
227
+ /**
228
+ * 历史上下文按字数裁剪(aiContextMaxChars,0=不限)。
229
+ * 从最新往前累加,至少保留最近 4 条,避免一刀切掉当前对话。
230
+ */
231
+ private clampContext(records: ChatRecord[]): ChatRecord[] {
232
+ const limit = Math.max(0, Number(this.config.aiContextMaxChars ?? 0));
233
+ if (!limit || !records.length) return records;
234
+ const out: ChatRecord[] = [];
235
+ let total = 0;
236
+ for (let i = records.length - 1; i >= 0; i -= 1) {
237
+ const item = records[i];
238
+ const size = String(item.text || '').length
239
+ + String(item.forwardText || '').length
240
+ + 32; // 昵称 / 时间 / 角色等渲染开销
241
+ if (out.length >= 4 && total + size > limit) break;
242
+ total += size;
243
+ out.unshift(item);
244
+ }
245
+ return out;
246
+ }
247
+
248
+ /** 限制外部插件注入的风格段长度(aiStyleMaxChars,0=不限) */
249
+ private clampStyle(sections: string[]): string[] {
250
+ const limit = Math.max(0, Number(this.config.aiStyleMaxChars ?? 0));
251
+ if (!limit || !sections.length) return sections;
252
+ return sections.map((text) => {
253
+ const value = String(text || '');
254
+ if (value.length <= limit) return value;
255
+ return `${value.slice(0, limit)}\n(以上风格说明过长已截断,保持已经给出的语气即可)`;
256
+ });
257
+ }
258
+
178
259
  // ---------------------------------------------------------------- 记录
179
260
 
180
261
  /** 是否像指令(这类消息不进上下文,避免污染) */
@@ -288,207 +369,306 @@ export class AiEngine {
288
369
  * 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
289
370
  * 失败不影响主流程。
290
371
  */
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
- }
372
+ /**
373
+ * 上下文挤出后的两件事:
374
+ * 1. 交给外部插件(registerContextEvicted,可选)
375
+ * 2. 内建自动归纳:累计到阈值或空闲后总结成一条记忆写回
376
+ * 任何一步失败都不影响正常聊天。
377
+ */
378
+ private emitEvicted(evicted: ChatRecord[], groupKey?: string, session?: any): void {
379
+ if (!evicted || !evicted.length) return;
380
+
381
+ const isDirect = session?.isDirect === true || !session?.guildId;
382
+ const guildId = String(session?.guildId || "");
383
+ const userId = String(session?.userId || "");
384
+ const kind: "group" | "private" = isDirect ? "private" : "group";
385
+ const scopeId = isDirect ? userId : guildId;
386
+ if (!scopeId) return;
387
+
388
+ const cfg: any = this.config || {};
389
+
390
+ // ---------- 1) 分发给外部插件 ----------
391
+ if (this.hooks && typeof (this.hooks as any).runContextEvicted === "function") {
392
+ const payload = evicted.map((item) => ({
393
+ id: item.id,
394
+ userId: item.userId,
395
+ name: item.name,
396
+ role: item.role,
397
+ text: item.text,
398
+ self: item.self,
399
+ at: item.at,
400
+ command: item.command,
401
+ }));
402
+ void this.hooks
403
+ .runContextEvicted({
404
+ groupId: guildId,
405
+ kind,
406
+ scopeId,
407
+ session,
408
+ evicted: payload,
409
+ window: this.contextWindow,
410
+ })
411
+ .catch((error: any) => {
412
+ this.host.logger?.warn?.(`[ai-evicted] 分发失败: ${String(error)}`);
413
+ });
414
+ }
415
+
416
+ // ---------- 2) 内建自动归纳 ----------
417
+ if (!cfg.memoryAutoLearn) return;
418
+ if (!cfg.enableMemory || cfg.memoryAutoLearn === false) return;
419
+ if (!this.resolveEnabled(session)) return;
420
+ const allow: string[] = Array.isArray(cfg.memoryAutoLearnGroups) ? cfg.memoryAutoLearnGroups.map(String) : [];
421
+ if (allow.length && !allow.includes(guildId) && !allow.includes(userId)) return;
422
+
423
+ const bucket = this.learnStore.get(kind, scopeId);
424
+ const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
425
+ const fire = bucket.push(evicted, threshold, this.now());
426
+ if (fire) {
427
+ void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
428
+ }
429
+ }
430
+
431
+ /** 归纳并(可选)回推到原会话 */
432
+ /** 启动空闲兜底定时器;每 5 分钟检查一次 */
433
+ private startLearnTimer(): void {
434
+ if (this.learnTimer) return;
435
+ const cfg: any = this.config || {};
436
+ if (!cfg.memoryAutoLearn) return;
437
+ const idleHours = Math.max(1, Number(cfg.memoryLearnIdleHours) || 8);
438
+ const idleMs = idleHours * 60 * 60 * 1000;
439
+ this.learnTimer = setInterval(() => {
440
+ try {
441
+ const pending = this.learnStore.idleList(this.now(), idleMs);
442
+ for (const item of pending) {
443
+ void this.learnAndReport(item.kind as any, item.scopeId, item.bucket, "idle");
444
+ }
445
+ } catch (error: any) {
446
+ this.host.logger?.warn?.(`[memory-learn] 空闲检查失败: ${String(error)}`);
447
+ }
448
+ }, 5 * 60 * 1000);
449
+ if (this.learnTimer.unref) this.learnTimer.unref();
450
+ }
451
+
452
+ /** 资源清理:停止定时器、清空缓存 */
453
+ dispose(): void {
454
+ if (this.learnTimer) {
455
+ clearInterval(this.learnTimer);
456
+ this.learnTimer = null;
457
+ }
458
+ this.learnStore.clear();
459
+ this.learnDaily.clear();
460
+ this.searchCache.clear();
461
+ this.searchRate.clear();
462
+ }
463
+
464
+ private async learnAndReport(
465
+ kind: "group" | "private",
466
+ scopeId: string,
467
+ bucket: LearnBucket,
468
+ reason: string,
469
+ session?: any,
470
+ ): Promise<void> {
471
+ const cfg: any = this.config || {};
472
+ const records = bucket.drain();
473
+ if (!records.length) return;
474
+
475
+ const scope = { kind, id: scopeId } as any;
476
+ const saved = await this.summarizeRecords(records, kind, scope, reason);
477
+ if (!saved || !saved.text) return;
478
+
479
+ if (cfg.memoryLearnPushBack === false) return;
480
+
481
+ const text = saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}`;
482
+ try {
483
+ if (kind === "private") {
484
+ const bot = (kind === "private" && session?.bot) || null;
485
+ const targetBot = bot || this.findBot();
486
+ if (targetBot) await targetBot.sendMessage(scopeId, text, { userId: scopeId });
487
+ } else {
488
+ const targetBot = session?.bot || this.findBot();
489
+ if (targetBot) await targetBot.sendMessage(scopeId, text, { guildId: scopeId, channelId: scopeId });
490
+ }
491
+ } catch (error: any) {
492
+ this.host.logger?.warn?.(`[memory-learn] 回推失败 ${kind}:${scopeId}: ${String(error)}`);
493
+ }
494
+ }
495
+
496
+ /** 把一批消息归纳成一条记忆并写入对应作用域;返回写入结果或 null */
497
+ private async summarizeRecords(
498
+ records: any[],
499
+ kind: "group" | "private",
500
+ scope: any,
501
+ reason: string,
502
+ ): Promise<{ text: string; consolidated: boolean; removed: number } | null> {
503
+ const cfg: any = this.config || {};
504
+
505
+ // 每日上限
506
+ const day = new Date();
507
+ const dayStamp = `${day.getFullYear()}-${day.getMonth() + 1}-${day.getDate()}`;
508
+ const dailyKey = `${kind}:${scope.id}:${dayStamp}`;
509
+ const limit = Math.max(1, Number(cfg.memoryLearnDailyLimit) || 30);
510
+ const used = this.learnDaily.get(dailyKey) || 0;
511
+ if (used >= limit) {
512
+ this.host.logger?.info?.(`[memory-learn] 已达每日上限 ${limit}(${kind}:${scope.id})`);
513
+ return null;
514
+ }
515
+
516
+ const prompt = buildSummaryPrompt(records, { kind, selfName: this.selfName });
517
+ let raw = "";
518
+ try {
519
+ const result = await this.provider.chat({
520
+ system: prompt.system,
521
+ user: prompt.user,
522
+ temperature: 0.3,
523
+ maxTokens: 400,
524
+ model: String(cfg.memoryLearnModel || "").trim() || undefined,
525
+ });
526
+ if (!result || !result.ok) {
527
+ this.host.logger?.warn?.(`[memory-learn] 归纳调用失败: ${result && result.error}`);
528
+ return null;
529
+ }
530
+ raw = String(result.text || "");
531
+ if (usageText(result.usage)) {
532
+ this.host.logger?.info?.(`[memory-learn] 归纳 token ${usageText(result.usage)}(${kind}:${scope.id})`);
533
+ }
534
+ } catch (error: any) {
535
+ this.host.logger?.warn?.(`[memory-learn] 归纳异常: ${String(error)}`);
536
+ return null;
537
+ }
538
+
539
+ const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
540
+ let text = cleanSummary(raw, maxChars);
541
+ if (!text) return null;
542
+
543
+ // 去重
544
+ let existing: string[] = [];
545
+ try {
546
+ const content = await (this.host as any).readMemoryFile(scope);
547
+ existing = String(content || "")
548
+ .split(/\r?\n---\r?\n/)
549
+ .map((b: string) => b.trim())
550
+ .filter(Boolean)
551
+ .map((b: string) => b.split("\n").slice(1).join("\n").trim() || b);
552
+ } catch {
553
+ existing = [];
554
+ }
555
+ const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
556
+ if (isDuplicate(text, existing, threshold)) {
557
+ this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
558
+ return null;
559
+ }
560
+
561
+ let saved: { text: string; consolidated: boolean; removed: number };
562
+ try {
563
+ saved = await this.saveLearnedMemory(kind, scope, text);
564
+ this.learnDaily.set(dailyKey, used + 1);
565
+ } catch (error: any) {
566
+ this.host.logger?.warn?.(`[memory-learn] 写入失败: ${String(error)}`);
567
+ return null;
568
+ }
569
+
570
+ this.host.logger?.info?.(
571
+ `[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${saved.text.length}字`
572
+ + (saved.consolidated ? `,压缩 ${saved.removed} 条旧记忆 → 1` : ""),
573
+ );
574
+ return saved;
575
+ }
576
+
577
+ /**
578
+ * 自动归纳写入策略(1.4.7+):
579
+ * - 每累计 N 条(默认 5)就把最早的 N-1 条 + 本次新记忆压缩成 1 条;
580
+ * - 自动记忆总数超过上限(默认 15)时同样触发压缩;
581
+ * - 压缩失败时退回普通追加,不丢数据,下次归纳会再试。
582
+ */
583
+ private async saveLearnedMemory(
584
+ kind: "group" | "private",
585
+ scope: any,
586
+ text: string,
587
+ ): Promise<{ text: string; consolidated: boolean; removed: number }> {
588
+ const cfg: any = this.config || {};
589
+ const host: any = this.host;
590
+ const canConsolidate = cfg.memoryLearnConsolidate !== false
591
+ && typeof host.commitAutoMemory === "function";
592
+
593
+ if (!canConsolidate) {
594
+ await host.saveMemoryToFile("", text, scope, AUTO_MEMORY_LABEL);
595
+ return { text, consolidated: false, removed: 0 };
596
+ }
597
+
598
+ const every = Math.max(2, Number(cfg.memoryLearnConsolidateEvery) || 5);
599
+ const maxEntries = Math.max(1, Number(cfg.memoryLearnMaxEntries) || 15);
600
+ const maxChars = Math.max(40, Number(cfg.memoryLearnConsolidateMaxChars) || 90);
601
+
602
+ let autoBlocks: string[] = [];
603
+ try {
604
+ const content = await host.readMemoryFile(scope);
605
+ autoBlocks = splitMemoryBlocks(content)
606
+ .map((item) => item.text)
607
+ .filter((item) => isAutoMemoryBlock(item));
608
+ } catch {
609
+ autoBlocks = [];
610
+ }
611
+
612
+ const projected = autoBlocks.length + 1;
613
+ const reachedBatch = projected >= every;
614
+ const reachedCap = projected > maxEntries && autoBlocks.length > 0;
615
+ if (!reachedBatch && !reachedCap) {
616
+ await host.commitAutoMemory(scope, { add: text, label: AUTO_MEMORY_LABEL });
617
+ return { text, consolidated: false, removed: 0 };
618
+ }
619
+
620
+ // 常规:拿最早的 every-1 条 + 本次,正好 every 条压成 1 条
621
+ const take = Math.max(1, Math.min(every - 1, autoBlocks.length));
622
+ const remove = autoBlocks.slice(0, take);
623
+
624
+ let stored = text;
625
+ let consolidated = false;
626
+ try {
627
+ const merged = await this.consolidateMemories(kind, remove, text, maxChars);
628
+ if (merged) {
629
+ stored = merged;
630
+ consolidated = true;
631
+ }
632
+ } catch (error: any) {
633
+ this.host.logger?.warn?.(`[memory-learn] 压缩异常: ${String(error)}`);
634
+ }
635
+
636
+ await host.commitAutoMemory(scope, {
637
+ add: stored,
638
+ remove: consolidated ? remove : [],
639
+ label: AUTO_MEMORY_LABEL,
640
+ });
641
+ return { text: stored, consolidated, removed: consolidated ? remove.length : 0 };
642
+ }
643
+
644
+ /** 调模型把若干条自动记忆压成一条更短的 */
645
+ private async consolidateMemories(
646
+ kind: "group" | "private",
647
+ blocks: string[],
648
+ fresh: string,
649
+ maxChars: number,
650
+ ): Promise<string> {
651
+ const cfg: any = this.config || {};
652
+ const marker = `## · ${AUTO_MEMORY_LABEL}`;
653
+ const prompt = buildConsolidatePrompt([...blocks, `${marker}\n${fresh}`], { maxChars, kind });
654
+ const result = await this.provider.chat({
655
+ system: prompt.system,
656
+ user: prompt.user,
657
+ temperature: 0.2,
658
+ maxTokens: Math.max(200, Math.min(500, maxChars * 5)),
659
+ model: String(cfg.memoryLearnModel || "").trim() || undefined,
660
+ });
661
+ if (!result || !result.ok) {
662
+ this.host.logger?.warn?.(`[memory-learn] 压缩调用失败: ${result?.error || "unknown"}`);
663
+ return "";
664
+ }
665
+ return cleanSummary(String(result.text || ""), maxChars);
666
+ }
667
+
668
+ private findBot(): any {
669
+ const bots = (this.host as any)?.ctx?.bots || (this.host as any)?.bots || [];
670
+ return (bots || []).find((item: any) => item.platform === "onebot") || null;
671
+ }
492
672
 
493
673
  // ---------------------------------------------------------------- 点名 / 跟随
494
674
 
@@ -601,6 +781,38 @@ export class AiEngine {
601
781
 
602
782
  // ---------------------------------------------------------------- 主流程
603
783
 
784
+ /**
785
+ * 被 @ 但处于模型调用冷却时,在群里提示还剩多久。
786
+ *
787
+ * 只发本地短句,不调用模型;同一群按 aiCooldownNoticeIntervalSeconds 限流,
788
+ * 避免有人连续 @ 时刷屏。
789
+ */
790
+ private async sendCooldownNotice(session: any, state: GroupState, remainingMs: number): Promise<void> {
791
+ if (this.setting(session, 'aiCooldownNotice') === false) return;
792
+ const gap = Math.max(0, Number(this.config.aiCooldownNoticeIntervalSeconds ?? 20)) * 1000;
793
+ const now = this.now();
794
+ if (gap > 0 && now - (state.lastCooldownNoticeAt || 0) < gap) return;
795
+
796
+ const seconds = Math.max(1, Math.ceil(Math.max(0, remainingMs) / 1000));
797
+ const template = String(this.config.aiCooldownNoticeText || '还在冷却,{seconds} 秒后再叫我。');
798
+ const text = template
799
+ .replace(/\{seconds\}/g, String(seconds))
800
+ .replace(/\{minutes\}/g, String(Math.ceil(seconds / 60)));
801
+ if (!text.trim()) return;
802
+
803
+ state.lastCooldownNoticeAt = now;
804
+ try {
805
+ if (typeof (this.host as any).sendNotice === 'function') {
806
+ await (this.host as any).sendNotice(session, text);
807
+ } else {
808
+ await this.host.sendReply(session, text);
809
+ }
810
+ this.log('ai-cooldown-notice', { seconds, remainingMs }, session);
811
+ } catch (error: any) {
812
+ this.host.logger?.warn?.(`[ai] 冷却提示发送失败: ${String(error)}`);
813
+ }
814
+ }
815
+
604
816
  async handle(session: any): Promise<void> {
605
817
  const key = this.groupKey(session);
606
818
  if (!key) return;
@@ -624,15 +836,15 @@ export class AiEngine {
624
836
  // 用户换了话题/说的和上一轮无关时,丢掉待续话题,避免机器人追着自己上一句说
625
837
  if (followupState && !followup) state.followup = null;
626
838
 
627
- const threshold = Math.max(1, Number(this.config.aiMessageThreshold ?? 15));
839
+ const threshold = Math.max(1, Number(this.setting(session, 'aiMessageThreshold') ?? 15));
628
840
  const decision = decideTrigger({
629
- mode: (this.config.aiReplyMode || 'hybrid') as any,
841
+ mode: (this.setting(session, 'aiReplyMode') || 'hybrid') as any,
630
842
  counter: state.counter,
631
843
  threshold,
632
- probability: Number(this.config.aiRandomReplyProbability ?? 0.08),
844
+ probability: Number(this.setting(session, 'aiRandomReplyProbability') ?? 0.08),
633
845
  now: this.now(),
634
846
  lastAttemptAt: state.lastAttemptAt,
635
- minIntervalMs: Math.max(0, Number(this.config.aiMinReplyIntervalSeconds ?? 45)) * 1000,
847
+ minIntervalMs: Math.max(0, Number(this.setting(session, 'aiMinReplyIntervalSeconds') ?? 45)) * 1000,
636
848
  lastReplyAt: state.lastReplyAt || 0,
637
849
  mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
638
850
  inFlight: state.inFlight,
@@ -650,7 +862,12 @@ export class AiEngine {
650
862
  followup,
651
863
  ctx: state.records.length,
652
864
  }, session);
653
- if (!decision.fire) return;
865
+ if (!decision.fire) {
866
+ if (decision.reason === 'cooldown-mention') {
867
+ await this.sendCooldownNotice(session, state, decision.remainingMs || 0);
868
+ }
869
+ return;
870
+ }
654
871
 
655
872
  state.inFlight = true;
656
873
  state.lastAttemptAt = this.now();
@@ -664,13 +881,13 @@ export class AiEngine {
664
881
  groupId: String(session.guildId),
665
882
  mode: 'reply',
666
883
  };
667
- const styleSections = await this.hooks.collectSections(hookCtx);
884
+ const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
668
885
  const webSearch = await this.webSearch(record, session);
669
886
  const promptInput = {
670
887
  selfName: this.selfName,
671
888
  persona: this.personaPrompt,
672
889
  groupId: String(session.guildId),
673
- records: state.records,
890
+ records: this.clampContext(state.records),
674
891
  current: record,
675
892
  mention,
676
893
  followup,
@@ -783,6 +1000,7 @@ export class AiEngine {
783
1000
  images: images.length,
784
1001
  degradedToText: !!result.degradedToText,
785
1002
  chars: finalText.length,
1003
+ tokens: usageText(result.usage) || undefined,
786
1004
  preview: finalText.slice(0, 60),
787
1005
  }, session);
788
1006
 
@@ -808,7 +1026,7 @@ export class AiEngine {
808
1026
  const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
809
1027
  let sections: string[] = [];
810
1028
  try {
811
- sections = await this.hooks.collectSections({ session, groupId, mode: 'reply' });
1029
+ sections = this.clampStyle(await this.hooks.collectSections({ session, groupId, mode: 'reply' }));
812
1030
  } catch { /* ignore */ }
813
1031
  const system = [
814
1032
  `你是 QQ 群 ${groupId} 里的一个普通成员。`,