@nestim/koishi-plugin-qq-group-manager 1.4.6 → 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/CHANGELOG.md CHANGED
@@ -2,6 +2,53 @@
2
2
 
3
3
  本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
+ ## 1.4.7
6
+
7
+ ### 新功能
8
+
9
+ - **自动记忆定期压缩**:每累计 5 条自动归纳(`memoryLearnConsolidateEvery`)就把
10
+ 「最早的 4 条 + 本次新记忆」合并成 1 条更短的记忆,压缩结果替换这一批旧条目;
11
+ 自动记忆总数默认上限 15 条(`memoryLearnMaxEntries`),超过后强制压缩。
12
+ 手动 `[memory]` 保存的内容不受影响。相关配置:
13
+
14
+ - `memoryLearnConsolidate`:总开关(默认开)
15
+ - `memoryLearnConsolidateEvery`:每多少条压缩一次(默认 5)
16
+ - `memoryLearnMaxEntries`:自动记忆条数上限(默认 15)
17
+ - `memoryLearnConsolidateMaxChars`:压缩后单条字数上限(默认 90)
18
+ - `memoryLearnModel`:归纳/压缩专用模型,留空沿用 `aiModel`,可填更便宜的模型
19
+
20
+ - **频率限制可按群单独配置**:`groupRules` 新增 `aiMessageThreshold`、
21
+ `aiRandomReplyProbability`、`aiMinReplyIntervalSeconds`、`aiCooldownNotice`,
22
+ 留空则跟随全局,填 0 表示该群不限制。
23
+
24
+ - **模型调用冷却真正生效**:之前 @ 与「点名后跟随」会直接绕过冷却,且冷却按
25
+ 「上次成功发出回复」计算,模型返回 `<pass/>`、被过滤器拦下或请求失败时不会更新,
26
+ 所以看起来像坏的。现在:
27
+
28
+ - 所有会调用模型的行为(含 @)统一受 `aiMinReplyIntervalSeconds` 约束;
29
+ - 冷却按「上一次调用模型」计算,失败与放弃也算用掉一次;
30
+ - 冷却结束后自动恢复,不需要重载插件。
31
+
32
+ - **冷却中被 @ 会提示还剩多久**:`aiCooldownNotice`(默认开)、
33
+ `aiCooldownNoticeText`(支持 `{seconds}` / `{minutes}`)、
34
+ `aiCooldownNoticeIntervalSeconds`(同一群默认 20 秒内不重复提示)。
35
+ 提示是纯本地消息,**不调用模型、不消耗 token**,也不会写进 AI 上下文。
36
+
37
+ ### 改进
38
+
39
+ - 模型调用日志新增 token 用量:`tokens=in=…,out=…,cache=…`。
40
+ 其中 `cache` 是上下文缓存命中的 token 数,可以直接判断提示词前缀有没有被缓存。
41
+ - 新增 `aiContextMaxChars`:历史上下文按字数裁剪(从最旧开始丢,至少保留最近 4 条),
42
+ 默认 0 = 不限;想省 token 可设 2500~3500。
43
+ - 新增 `aiStyleMaxChars`:限制外部插件注入的「说话风格」段长度,默认 0 = 不限;
44
+ 风格 skill 很长时可设 1200~1800,能显著降低每次调用的输入 token。
45
+ - 自动归纳/压缩的模型调用也会记录 token 用量。
46
+
47
+ ### 测试
48
+
49
+ - 新增 12 项测试:冷却顺序与剩余时间、按群覆盖阈值/冷却、冷却提示限流、
50
+ 记忆压缩(5→1、超上限强制压缩、失败回退、真实写盘替换、手动记忆保留)。
51
+
5
52
  ## 1.4.6
6
53
 
7
54
  ### 修复
@@ -24,6 +24,17 @@ export interface AiHost {
24
24
  fetchQuotedImages?(session: any, quote: any): Promise<RenderedImage[]>;
25
25
  resolveImage(ref: string, session: any): Promise<string>;
26
26
  sendReply(session: any, text: string): Promise<void>;
27
+ /** 发送系统提示(不引用、不进入 AI 上下文),用于冷却提示等 */
28
+ sendNotice?(session: any, text: string): Promise<void>;
29
+ /** 写入自动归纳记忆:add = 新条目;remove = 需要被压缩替换掉的旧条目 */
30
+ commitAutoMemory?(scope: {
31
+ kind: 'group' | 'private';
32
+ id: string;
33
+ } | null, payload: {
34
+ add: string;
35
+ remove?: string[];
36
+ label?: string;
37
+ }): Promise<void>;
27
38
  readMemoryFile(scope?: {
28
39
  kind: 'group' | 'private';
29
40
  id: string;
@@ -64,6 +75,11 @@ export declare class AiEngine {
64
75
  constructor(host: AiHost, deps?: AiDeps);
65
76
  private groupKey;
66
77
  private ruleFor;
78
+ /**
79
+ * 读配置:该群 groupRules 里有同名非空值就用它,否则回落到全局。
80
+ * 这样频率限制(阈值/概率/模型调用冷却)可以按群单独设置。
81
+ */
82
+ private setting;
67
83
  resolveEnabled(session: any): boolean;
68
84
  private get contextWindow();
69
85
  private get selfName();
@@ -71,6 +87,13 @@ export declare class AiEngine {
71
87
  private get personaPrompt();
72
88
  private get maxReplyChars();
73
89
  private get debugPrompt();
90
+ /**
91
+ * 历史上下文按字数裁剪(aiContextMaxChars,0=不限)。
92
+ * 从最新往前累加,至少保留最近 4 条,避免一刀切掉当前对话。
93
+ */
94
+ private clampContext;
95
+ /** 限制外部插件注入的风格段长度(aiStyleMaxChars,0=不限) */
96
+ private clampStyle;
74
97
  /** 是否像指令(这类消息不进上下文,避免污染) */
75
98
  private isCommandLike;
76
99
  /** 记录一条群消息;返回落库后的记录(指令类返回 null) */
@@ -96,8 +119,17 @@ export declare class AiEngine {
96
119
  /** 资源清理:停止定时器、清空缓存 */
97
120
  dispose(): void;
98
121
  private learnAndReport;
99
- /** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
122
+ /** 把一批消息归纳成一条记忆并写入对应作用域;返回写入结果或 null */
100
123
  private summarizeRecords;
124
+ /**
125
+ * 自动归纳写入策略(1.4.7+):
126
+ * - 每累计 N 条(默认 5)就把最早的 N-1 条 + 本次新记忆压缩成 1 条;
127
+ * - 自动记忆总数超过上限(默认 15)时同样触发压缩;
128
+ * - 压缩失败时退回普通追加,不丢数据,下次归纳会再试。
129
+ */
130
+ private saveLearnedMemory;
131
+ /** 调模型把若干条自动记忆压成一条更短的 */
132
+ private consolidateMemories;
101
133
  private findBot;
102
134
  private isMention;
103
135
  private addressesOthers;
@@ -106,6 +138,13 @@ export declare class AiEngine {
106
138
  private bumpFollowup;
107
139
  private getFollowup;
108
140
  private loadMemories;
141
+ /**
142
+ * 被 @ 但处于模型调用冷却时,在群里提示还剩多久。
143
+ *
144
+ * 只发本地短句,不调用模型;同一群按 aiCooldownNoticeIntervalSeconds 限流,
145
+ * 避免有人连续 @ 时刷屏。
146
+ */
147
+ private sendCooldownNotice;
109
148
  handle(session: any): Promise<void>;
110
149
  /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
111
150
  chat(request: any): Promise<ChatResult>;
package/lib/ai/engine.js CHANGED
@@ -42,6 +42,24 @@ function cleanReply(text, selfName) {
42
42
  out = out.slice(1, -1).trim();
43
43
  return out.replace(/\s+/g, ' ').trim();
44
44
  }
45
+ /** 把服务端 usage 压成一行日志,便于观察真实 token 消耗与缓存命中 */
46
+ function usageText(usage) {
47
+ if (!usage)
48
+ return '';
49
+ const input = usage.prompt_tokens ?? usage.input_tokens;
50
+ const output = usage.completion_tokens ?? usage.output_tokens;
51
+ const cacheHit = usage.prompt_cache_hit_tokens
52
+ ?? usage.cached_tokens
53
+ ?? usage.cache_read_input_tokens;
54
+ const parts = [];
55
+ if (input != null)
56
+ parts.push(`in=${input}`);
57
+ if (output != null)
58
+ parts.push(`out=${output}`);
59
+ if (cacheHit != null)
60
+ parts.push(`cache=${cacheHit}`);
61
+ return parts.join(',');
62
+ }
45
63
  function clipReply(text, maxChars) {
46
64
  const max = Math.max(20, maxChars || 120);
47
65
  if (text.length <= max)
@@ -102,6 +120,17 @@ class AiEngine {
102
120
  const rules = Array.isArray(this.config.groupRules) ? this.config.groupRules : [];
103
121
  return rules.find((item) => String(item?.guildId ?? '').trim() === guildId);
104
122
  }
123
+ /**
124
+ * 读配置:该群 groupRules 里有同名非空值就用它,否则回落到全局。
125
+ * 这样频率限制(阈值/概率/模型调用冷却)可以按群单独设置。
126
+ */
127
+ setting(session, key) {
128
+ const rule = this.ruleFor(session);
129
+ const value = rule ? rule[key] : undefined;
130
+ if (value === undefined || value === null || value === '')
131
+ return this.config[key];
132
+ return value;
133
+ }
105
134
  resolveEnabled(session) {
106
135
  const rule = this.ruleFor(session);
107
136
  const requireRule = this.config.aiReplyRequireGroupRule !== false;
@@ -137,6 +166,40 @@ class AiEngine {
137
166
  get debugPrompt() {
138
167
  return !!this.config.aiDebugPrompt;
139
168
  }
169
+ /**
170
+ * 历史上下文按字数裁剪(aiContextMaxChars,0=不限)。
171
+ * 从最新往前累加,至少保留最近 4 条,避免一刀切掉当前对话。
172
+ */
173
+ clampContext(records) {
174
+ const limit = Math.max(0, Number(this.config.aiContextMaxChars ?? 0));
175
+ if (!limit || !records.length)
176
+ return records;
177
+ const out = [];
178
+ let total = 0;
179
+ for (let i = records.length - 1; i >= 0; i -= 1) {
180
+ const item = records[i];
181
+ const size = String(item.text || '').length
182
+ + String(item.forwardText || '').length
183
+ + 32; // 昵称 / 时间 / 角色等渲染开销
184
+ if (out.length >= 4 && total + size > limit)
185
+ break;
186
+ total += size;
187
+ out.unshift(item);
188
+ }
189
+ return out;
190
+ }
191
+ /** 限制外部插件注入的风格段长度(aiStyleMaxChars,0=不限) */
192
+ clampStyle(sections) {
193
+ const limit = Math.max(0, Number(this.config.aiStyleMaxChars ?? 0));
194
+ if (!limit || !sections.length)
195
+ return sections;
196
+ return sections.map((text) => {
197
+ const value = String(text || '');
198
+ if (value.length <= limit)
199
+ return value;
200
+ return `${value.slice(0, limit)}\n(以上风格说明过长已截断,保持已经给出的语气即可)`;
201
+ });
202
+ }
140
203
  // ---------------------------------------------------------------- 记录
141
204
  /** 是否像指令(这类消息不进上下文,避免污染) */
142
205
  isCommandLike(text) {
@@ -340,12 +403,12 @@ class AiEngine {
340
403
  if (!records.length)
341
404
  return;
342
405
  const scope = { kind, id: scopeId };
343
- const summary = await this.summarizeRecords(records, kind, scope, reason);
344
- if (!summary)
406
+ const saved = await this.summarizeRecords(records, kind, scope, reason);
407
+ if (!saved || !saved.text)
345
408
  return;
346
409
  if (cfg.memoryLearnPushBack === false)
347
410
  return;
348
- const text = `刚记住了:${summary}`;
411
+ const text = saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}`;
349
412
  try {
350
413
  if (kind === "private") {
351
414
  const bot = (kind === "private" && session?.bot) || null;
@@ -363,7 +426,7 @@ class AiEngine {
363
426
  this.host.logger?.warn?.(`[memory-learn] 回推失败 ${kind}:${scopeId}: ${String(error)}`);
364
427
  }
365
428
  }
366
- /** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
429
+ /** 把一批消息归纳成一条记忆并写入对应作用域;返回写入结果或 null */
367
430
  async summarizeRecords(records, kind, scope, reason) {
368
431
  const cfg = this.config || {};
369
432
  // 每日上限
@@ -374,7 +437,7 @@ class AiEngine {
374
437
  const used = this.learnDaily.get(dailyKey) || 0;
375
438
  if (used >= limit) {
376
439
  this.host.logger?.info?.(`[memory-learn] 已达每日上限 ${limit}(${kind}:${scope.id})`);
377
- return "";
440
+ return null;
378
441
  }
379
442
  const prompt = (0, learn_1.buildSummaryPrompt)(records, { kind, selfName: this.selfName });
380
443
  let raw = "";
@@ -384,21 +447,25 @@ class AiEngine {
384
447
  user: prompt.user,
385
448
  temperature: 0.3,
386
449
  maxTokens: 400,
450
+ model: String(cfg.memoryLearnModel || "").trim() || undefined,
387
451
  });
388
452
  if (!result || !result.ok) {
389
453
  this.host.logger?.warn?.(`[memory-learn] 归纳调用失败: ${result && result.error}`);
390
- return "";
454
+ return null;
391
455
  }
392
456
  raw = String(result.text || "");
457
+ if (usageText(result.usage)) {
458
+ this.host.logger?.info?.(`[memory-learn] 归纳 token ${usageText(result.usage)}(${kind}:${scope.id})`);
459
+ }
393
460
  }
394
461
  catch (error) {
395
462
  this.host.logger?.warn?.(`[memory-learn] 归纳异常: ${String(error)}`);
396
- return "";
463
+ return null;
397
464
  }
398
465
  const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
399
466
  let text = (0, learn_1.cleanSummary)(raw, maxChars);
400
467
  if (!text)
401
- return "";
468
+ return null;
402
469
  // 去重
403
470
  let existing = [];
404
471
  try {
@@ -415,18 +482,95 @@ class AiEngine {
415
482
  const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
416
483
  if ((0, learn_1.isDuplicate)(text, existing, threshold)) {
417
484
  this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
418
- return "";
485
+ return null;
419
486
  }
487
+ let saved;
420
488
  try {
421
- await this.host.saveMemoryToFile("", text, scope, "自动归纳");
489
+ saved = await this.saveLearnedMemory(kind, scope, text);
422
490
  this.learnDaily.set(dailyKey, used + 1);
423
491
  }
424
492
  catch (error) {
425
493
  this.host.logger?.warn?.(`[memory-learn] 写入失败: ${String(error)}`);
494
+ return null;
495
+ }
496
+ this.host.logger?.info?.(`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${saved.text.length}字`
497
+ + (saved.consolidated ? `,压缩 ${saved.removed} 条旧记忆 → 1` : ""));
498
+ return saved;
499
+ }
500
+ /**
501
+ * 自动归纳写入策略(1.4.7+):
502
+ * - 每累计 N 条(默认 5)就把最早的 N-1 条 + 本次新记忆压缩成 1 条;
503
+ * - 自动记忆总数超过上限(默认 15)时同样触发压缩;
504
+ * - 压缩失败时退回普通追加,不丢数据,下次归纳会再试。
505
+ */
506
+ async saveLearnedMemory(kind, scope, text) {
507
+ const cfg = this.config || {};
508
+ const host = this.host;
509
+ const canConsolidate = cfg.memoryLearnConsolidate !== false
510
+ && typeof host.commitAutoMemory === "function";
511
+ if (!canConsolidate) {
512
+ await host.saveMemoryToFile("", text, scope, learn_1.AUTO_MEMORY_LABEL);
513
+ return { text, consolidated: false, removed: 0 };
514
+ }
515
+ const every = Math.max(2, Number(cfg.memoryLearnConsolidateEvery) || 5);
516
+ const maxEntries = Math.max(1, Number(cfg.memoryLearnMaxEntries) || 15);
517
+ const maxChars = Math.max(40, Number(cfg.memoryLearnConsolidateMaxChars) || 90);
518
+ let autoBlocks = [];
519
+ try {
520
+ const content = await host.readMemoryFile(scope);
521
+ autoBlocks = (0, memory_1.splitMemoryBlocks)(content)
522
+ .map((item) => item.text)
523
+ .filter((item) => (0, learn_1.isAutoMemoryBlock)(item));
524
+ }
525
+ catch {
526
+ autoBlocks = [];
527
+ }
528
+ const projected = autoBlocks.length + 1;
529
+ const reachedBatch = projected >= every;
530
+ const reachedCap = projected > maxEntries && autoBlocks.length > 0;
531
+ if (!reachedBatch && !reachedCap) {
532
+ await host.commitAutoMemory(scope, { add: text, label: learn_1.AUTO_MEMORY_LABEL });
533
+ return { text, consolidated: false, removed: 0 };
534
+ }
535
+ // 常规:拿最早的 every-1 条 + 本次,正好 every 条压成 1 条
536
+ const take = Math.max(1, Math.min(every - 1, autoBlocks.length));
537
+ const remove = autoBlocks.slice(0, take);
538
+ let stored = text;
539
+ let consolidated = false;
540
+ try {
541
+ const merged = await this.consolidateMemories(kind, remove, text, maxChars);
542
+ if (merged) {
543
+ stored = merged;
544
+ consolidated = true;
545
+ }
546
+ }
547
+ catch (error) {
548
+ this.host.logger?.warn?.(`[memory-learn] 压缩异常: ${String(error)}`);
549
+ }
550
+ await host.commitAutoMemory(scope, {
551
+ add: stored,
552
+ remove: consolidated ? remove : [],
553
+ label: learn_1.AUTO_MEMORY_LABEL,
554
+ });
555
+ return { text: stored, consolidated, removed: consolidated ? remove.length : 0 };
556
+ }
557
+ /** 调模型把若干条自动记忆压成一条更短的 */
558
+ async consolidateMemories(kind, blocks, fresh, maxChars) {
559
+ const cfg = this.config || {};
560
+ const marker = `## · ${learn_1.AUTO_MEMORY_LABEL}`;
561
+ const prompt = (0, learn_1.buildConsolidatePrompt)([...blocks, `${marker}\n${fresh}`], { maxChars, kind });
562
+ const result = await this.provider.chat({
563
+ system: prompt.system,
564
+ user: prompt.user,
565
+ temperature: 0.2,
566
+ maxTokens: Math.max(200, Math.min(500, maxChars * 5)),
567
+ model: String(cfg.memoryLearnModel || "").trim() || undefined,
568
+ });
569
+ if (!result || !result.ok) {
570
+ this.host.logger?.warn?.(`[memory-learn] 压缩调用失败: ${result?.error || "unknown"}`);
426
571
  return "";
427
572
  }
428
- this.host.logger?.info?.(`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${text.length}字`);
429
- return text;
573
+ return (0, learn_1.cleanSummary)(String(result.text || ""), maxChars);
430
574
  }
431
575
  findBot() {
432
576
  const bots = this.host?.ctx?.bots || this.host?.bots || [];
@@ -555,6 +699,40 @@ class AiEngine {
555
699
  return selected.map((item) => item.text);
556
700
  }
557
701
  // ---------------------------------------------------------------- 主流程
702
+ /**
703
+ * 被 @ 但处于模型调用冷却时,在群里提示还剩多久。
704
+ *
705
+ * 只发本地短句,不调用模型;同一群按 aiCooldownNoticeIntervalSeconds 限流,
706
+ * 避免有人连续 @ 时刷屏。
707
+ */
708
+ async sendCooldownNotice(session, state, remainingMs) {
709
+ if (this.setting(session, 'aiCooldownNotice') === false)
710
+ return;
711
+ const gap = Math.max(0, Number(this.config.aiCooldownNoticeIntervalSeconds ?? 20)) * 1000;
712
+ const now = this.now();
713
+ if (gap > 0 && now - (state.lastCooldownNoticeAt || 0) < gap)
714
+ return;
715
+ const seconds = Math.max(1, Math.ceil(Math.max(0, remainingMs) / 1000));
716
+ const template = String(this.config.aiCooldownNoticeText || '还在冷却,{seconds} 秒后再叫我。');
717
+ const text = template
718
+ .replace(/\{seconds\}/g, String(seconds))
719
+ .replace(/\{minutes\}/g, String(Math.ceil(seconds / 60)));
720
+ if (!text.trim())
721
+ return;
722
+ state.lastCooldownNoticeAt = now;
723
+ try {
724
+ if (typeof this.host.sendNotice === 'function') {
725
+ await this.host.sendNotice(session, text);
726
+ }
727
+ else {
728
+ await this.host.sendReply(session, text);
729
+ }
730
+ this.log('ai-cooldown-notice', { seconds, remainingMs }, session);
731
+ }
732
+ catch (error) {
733
+ this.host.logger?.warn?.(`[ai] 冷却提示发送失败: ${String(error)}`);
734
+ }
735
+ }
558
736
  async handle(session) {
559
737
  const key = this.groupKey(session);
560
738
  if (!key)
@@ -581,15 +759,15 @@ class AiEngine {
581
759
  // 用户换了话题/说的和上一轮无关时,丢掉待续话题,避免机器人追着自己上一句说
582
760
  if (followupState && !followup)
583
761
  state.followup = null;
584
- const threshold = Math.max(1, Number(this.config.aiMessageThreshold ?? 15));
762
+ const threshold = Math.max(1, Number(this.setting(session, 'aiMessageThreshold') ?? 15));
585
763
  const decision = (0, trigger_1.decideTrigger)({
586
- mode: (this.config.aiReplyMode || 'hybrid'),
764
+ mode: (this.setting(session, 'aiReplyMode') || 'hybrid'),
587
765
  counter: state.counter,
588
766
  threshold,
589
- probability: Number(this.config.aiRandomReplyProbability ?? 0.08),
767
+ probability: Number(this.setting(session, 'aiRandomReplyProbability') ?? 0.08),
590
768
  now: this.now(),
591
769
  lastAttemptAt: state.lastAttemptAt,
592
- minIntervalMs: Math.max(0, Number(this.config.aiMinReplyIntervalSeconds ?? 45)) * 1000,
770
+ minIntervalMs: Math.max(0, Number(this.setting(session, 'aiMinReplyIntervalSeconds') ?? 45)) * 1000,
593
771
  lastReplyAt: state.lastReplyAt || 0,
594
772
  mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
595
773
  inFlight: state.inFlight,
@@ -606,8 +784,12 @@ class AiEngine {
606
784
  followup,
607
785
  ctx: state.records.length,
608
786
  }, session);
609
- if (!decision.fire)
787
+ if (!decision.fire) {
788
+ if (decision.reason === 'cooldown-mention') {
789
+ await this.sendCooldownNotice(session, state, decision.remainingMs || 0);
790
+ }
610
791
  return;
792
+ }
611
793
  state.inFlight = true;
612
794
  state.lastAttemptAt = this.now();
613
795
  const startedAt = this.now();
@@ -619,13 +801,13 @@ class AiEngine {
619
801
  groupId: String(session.guildId),
620
802
  mode: 'reply',
621
803
  };
622
- const styleSections = await this.hooks.collectSections(hookCtx);
804
+ const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
623
805
  const webSearch = await this.webSearch(record, session);
624
806
  const promptInput = {
625
807
  selfName: this.selfName,
626
808
  persona: this.personaPrompt,
627
809
  groupId: String(session.guildId),
628
- records: state.records,
810
+ records: this.clampContext(state.records),
629
811
  current: record,
630
812
  mention,
631
813
  followup,
@@ -729,6 +911,7 @@ class AiEngine {
729
911
  images: images.length,
730
912
  degradedToText: !!result.degradedToText,
731
913
  chars: finalText.length,
914
+ tokens: usageText(result.usage) || undefined,
732
915
  preview: finalText.slice(0, 60),
733
916
  }, session);
734
917
  await this.hooks.runAfterReply({ ...hookCtx, text: finalText });
@@ -753,7 +936,7 @@ class AiEngine {
753
936
  const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
754
937
  let sections = [];
755
938
  try {
756
- sections = await this.hooks.collectSections({ session, groupId, mode: 'reply' });
939
+ sections = this.clampStyle(await this.hooks.collectSections({ session, groupId, mode: 'reply' }));
757
940
  }
758
941
  catch { /* ignore */ }
759
942
  const system = [
package/lib/ai/learn.d.ts CHANGED
@@ -56,3 +56,22 @@ export declare function cleanSummary(raw: string, maxChars?: number): string;
56
56
  export declare function similarityOf(a: string, b: string): number;
57
57
  /** 判断是否与已有记忆重复 */
58
58
  export declare function isDuplicate(candidate: string, existing: string[], threshold?: number): boolean;
59
+ /** 自动归纳条目的标题标记(写进 Markdown 块首行) */
60
+ export declare const AUTO_MEMORY_LABEL = "\u81EA\u52A8\u5F52\u7EB3";
61
+ /** 自动归纳块首行形如 `## 2026/10/28 12:00:00 · 自动归纳` */
62
+ export declare function isAutoMemoryBlock(block: string): boolean;
63
+ /** 取记忆块正文(去掉 `## 时间 · 来源` 标题行) */
64
+ export declare function memoryBlockBody(block: string): string;
65
+ /**
66
+ * 记忆压缩提示词:把 N 条自动归纳合并成一条更短的。
67
+ *
68
+ * 目的不是“再总结一遍”,而是去掉重复与过时信息——群里连续几天聊同一件事时,
69
+ * 自动归纳会反复产出高度相似的条目,压缩后只保留事实差异。
70
+ */
71
+ export declare function buildConsolidatePrompt(blocks: string[], options?: {
72
+ maxChars?: number;
73
+ kind?: string;
74
+ }): {
75
+ system: string;
76
+ user: string;
77
+ };
package/lib/ai/learn.js CHANGED
@@ -9,12 +9,15 @@
9
9
  * 归纳出来的内容是一次性的一长串,150 字以内,写入对应作用域的记忆文件。
10
10
  */
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.LearnStore = exports.LearnBucket = exports.MAX_SUMMARY_CHARS = void 0;
12
+ exports.AUTO_MEMORY_LABEL = exports.LearnStore = exports.LearnBucket = exports.MAX_SUMMARY_CHARS = void 0;
13
13
  exports.renderForSummary = renderForSummary;
14
14
  exports.buildSummaryPrompt = buildSummaryPrompt;
15
15
  exports.cleanSummary = cleanSummary;
16
16
  exports.similarityOf = similarityOf;
17
17
  exports.isDuplicate = isDuplicate;
18
+ exports.isAutoMemoryBlock = isAutoMemoryBlock;
19
+ exports.memoryBlockBody = memoryBlockBody;
20
+ exports.buildConsolidatePrompt = buildConsolidatePrompt;
18
21
  const text_1 = require("../core/text");
19
22
  exports.MAX_SUMMARY_CHARS = 150;
20
23
  /** 正在累计的一批消息 */
@@ -198,3 +201,49 @@ function isDuplicate(candidate, existing, threshold = 0.55) {
198
201
  }
199
202
  return false;
200
203
  }
204
+ // ---------------------------------------------------------------- 记忆压缩
205
+ /** 自动归纳条目的标题标记(写进 Markdown 块首行) */
206
+ exports.AUTO_MEMORY_LABEL = '自动归纳';
207
+ /** 自动归纳块首行形如 `## 2026/10/28 12:00:00 · 自动归纳` */
208
+ function isAutoMemoryBlock(block) {
209
+ const first = String(block || '').split('\n', 1)[0] || '';
210
+ return /·\s*自动归纳/.test(first);
211
+ }
212
+ /** 取记忆块正文(去掉 `## 时间 · 来源` 标题行) */
213
+ function memoryBlockBody(block) {
214
+ const lines = String(block || '').split('\n');
215
+ if (lines.length <= 1)
216
+ return String(block || '').trim();
217
+ return lines.slice(1).join('\n').trim();
218
+ }
219
+ /**
220
+ * 记忆压缩提示词:把 N 条自动归纳合并成一条更短的。
221
+ *
222
+ * 目的不是“再总结一遍”,而是去掉重复与过时信息——群里连续几天聊同一件事时,
223
+ * 自动归纳会反复产出高度相似的条目,压缩后只保留事实差异。
224
+ */
225
+ function buildConsolidatePrompt(blocks, options = {}) {
226
+ const maxChars = Math.max(40, Number(options.maxChars) || 90);
227
+ const label = options.kind === 'private' ? '私聊' : '群聊';
228
+ const bodies = (blocks || [])
229
+ .map((block) => memoryBlockBody(block).replace(/\s+/g, ' ').trim())
230
+ .filter(Boolean);
231
+ const system = [
232
+ `你在压缩一段${label}的长期记忆。`,
233
+ `下面有 ${bodies.length} 条已经归纳过的记忆,请合并成一条。`,
234
+ '',
235
+ '要求:',
236
+ '- 只保留互不重复的事实:人物与称呼、关系、稳定偏好、反复出现的话题;',
237
+ '- 删掉重复表述、一次性情绪、已经过时的细节;',
238
+ '- 不要编造,不要写“他们聊到”“讨论了”这类过程描述;',
239
+ `- 只输出一条纯文本,不超过 ${maxChars} 字,不要标题、编号、列表、Markdown;`,
240
+ '- 如果这些记忆里没有任何值得保留的内容,只输出一个词:NONE',
241
+ ].join('\n');
242
+ const user = [
243
+ '【待压缩的记忆】',
244
+ ...bodies.map((text, index) => `${index + 1}. ${text}`),
245
+ '',
246
+ '现在输出合并后的那一条记忆,或输出 NONE。',
247
+ ].join('\n');
248
+ return { system, user };
249
+ }
@@ -13,6 +13,8 @@ export interface ChatRequest {
13
13
  temperature?: number;
14
14
  maxTokens?: number;
15
15
  timeoutMs?: number;
16
+ /** 覆盖默认 aiModel(例如自动归纳用更便宜的模型) */
17
+ model?: string;
16
18
  }
17
19
  export interface ChatResult {
18
20
  ok: boolean;
@@ -21,6 +23,8 @@ export interface ChatResult {
21
23
  status?: number;
22
24
  /** 是否因为图片被拒而发生了降级重试 */
23
25
  degradedToText?: boolean;
26
+ /** 服务端 token 用量(OpenAI: usage;Gemini: usageMetadata) */
27
+ usage?: any;
24
28
  }
25
29
  export interface ProviderConfig {
26
30
  aiProvider?: string;
@@ -39,7 +39,7 @@ class ChatProvider {
39
39
  async chat(request) {
40
40
  if (!this.apiKey)
41
41
  return { ok: false, error: 'AI 未配置 apiKey' };
42
- if (!this.model)
42
+ if (!this.model && !String(request.model || '').trim())
43
43
  return { ok: false, error: 'AI 未配置 model' };
44
44
  const provider = String(this.config.aiProvider ?? 'openai-compatible');
45
45
  const requested = (request.images ?? []).filter((item) => /^data:image\//i.test(item) || /^https?:\/\//i.test(item));
@@ -77,6 +77,7 @@ class ChatProvider {
77
77
  }
78
78
  async callOpenAi(request, images, options = {}) {
79
79
  const base = String(this.config.aiBaseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
80
+ const model = String(request.model || this.model).trim();
80
81
  const content = [{ type: 'text', text: request.user }];
81
82
  for (const url of images)
82
83
  content.push({ type: 'image_url', image_url: { url } });
@@ -92,7 +93,7 @@ class ChatProvider {
92
93
  'Content-Type': 'application/json',
93
94
  },
94
95
  body: JSON.stringify({
95
- model: this.model,
96
+ model,
96
97
  temperature: request.temperature ?? this.config.aiTemperature ?? 0.8,
97
98
  max_tokens: maxTokens,
98
99
  messages: [
@@ -143,7 +144,7 @@ class ChatProvider {
143
144
  error: `模型返回空内容(finish=${payload?.choices?.[0]?.finish_reason || 'unknown'})`,
144
145
  };
145
146
  }
146
- return { ok: true, text, status: response.status };
147
+ return { ok: true, text, status: response.status, usage: payload?.usage };
147
148
  }
148
149
  catch (error) {
149
150
  const aborted = error?.name === 'AbortError';
@@ -156,7 +157,8 @@ class ChatProvider {
156
157
  async callGemini(request, images) {
157
158
  const rawBase = String(this.config.aiBaseUrl || 'https://generativelanguage.googleapis.com/v1beta').replace(/\/+$/, '');
158
159
  const base = /\/v\d/i.test(rawBase) ? rawBase : `${rawBase}/v1beta`;
159
- const endpoint = `${base}/models/${encodeURIComponent(this.model)}:generateContent?key=${encodeURIComponent(this.apiKey)}`;
160
+ const model = String(request.model || this.model).trim();
161
+ const endpoint = `${base}/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(this.apiKey)}`;
160
162
  const parts = [{ text: request.user }];
161
163
  for (const url of images) {
162
164
  const match = /^data:(image\/[^;]+);base64,(.*)$/i.exec(url);
@@ -193,7 +195,7 @@ class ChatProvider {
193
195
  .trim();
194
196
  if (!text)
195
197
  return { ok: false, status: response.status, error: 'Gemini 返回空内容' };
196
- return { ok: true, text, status: response.status };
198
+ return { ok: true, text, status: response.status, usage: payload?.usageMetadata };
197
199
  }
198
200
  catch (error) {
199
201
  const aborted = error?.name === 'AbortError';
package/lib/ai/state.d.ts CHANGED
@@ -39,6 +39,8 @@ export declare class GroupState {
39
39
  counter: number;
40
40
  lastReplyAt: number;
41
41
  lastAttemptAt: number;
42
+ /** 上次发「冷却中」提示的时间,用于避免 @ 刷屏时反复提示 */
43
+ lastCooldownNoticeAt: number;
42
44
  inFlight: boolean;
43
45
  followup: FollowupState | null;
44
46
  seen: Map<string, number>;
package/lib/ai/state.js CHANGED
@@ -15,6 +15,8 @@ class GroupState {
15
15
  counter = 0;
16
16
  lastReplyAt = 0;
17
17
  lastAttemptAt = 0;
18
+ /** 上次发「冷却中」提示的时间,用于避免 @ 刷屏时反复提示 */
19
+ lastCooldownNoticeAt = 0;
18
20
  inFlight = false;
19
21
  followup = null;
20
22
  seen = new Map();