@nestim/koishi-plugin-qq-group-manager 1.4.6 → 1.4.8

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,78 @@
2
2
 
3
3
  本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
+ ## 1.4.8
6
+
7
+ ### 新功能
8
+
9
+ - **伪随机触发**:随机 / 混合模式下,每次随机未命中都会把下一次的概率按步长累加,
10
+ 加到 1 时必定回复,命中后归零。避免真随机运气差时连续很多条都不接话。
11
+
12
+ - `aiPseudoRandom`:总开关(默认开)
13
+ - `aiPseudoRandomStep`:每次未命中增加多少(默认 0.01 = 1%)
14
+ - `groupRules` 里也可以按群设置 `aiPseudoRandom` / `aiPseudoRandomStep`
15
+ (留空跟随全局,填 0 表示该群不涨概率)
16
+
17
+ 细节:
18
+
19
+ - 只有「真正掷骰且未命中」才累加;冷却中、阈值不足、点名与点名后跟随都不算;
20
+ - 点名 / 跟随仍然直接回复,不消耗也不清零加成;
21
+ - 加成到 1 时不再掷骰,直接回复;
22
+ - 触发成功(随机命中)后加成归零;
23
+ - `[ai-trigger]` 日志新增 `prob=`(本次实际概率)与 `boost=`(当前加成),方便排查。
24
+
25
+ ### 测试
26
+
27
+ - 新增 6 项:未命中累加 / 命中归零、加成到 1 必定触发且不掷骰、关闭后不累加、
28
+ 概率为 0 但已有加成仍可累计、按群覆盖步长、按群关闭。
29
+
30
+ ## 1.4.7
31
+
32
+ ### 新功能
33
+
34
+ - **自动记忆定期压缩**:每累计 5 条自动归纳(`memoryLearnConsolidateEvery`)就把
35
+ 「最早的 4 条 + 本次新记忆」合并成 1 条更短的记忆,压缩结果替换这一批旧条目;
36
+ 自动记忆总数默认上限 15 条(`memoryLearnMaxEntries`),超过后强制压缩。
37
+ 手动 `[memory]` 保存的内容不受影响。相关配置:
38
+
39
+ - `memoryLearnConsolidate`:总开关(默认开)
40
+ - `memoryLearnConsolidateEvery`:每多少条压缩一次(默认 5)
41
+ - `memoryLearnMaxEntries`:自动记忆条数上限(默认 15)
42
+ - `memoryLearnConsolidateMaxChars`:压缩后单条字数上限(默认 90)
43
+ - `memoryLearnModel`:归纳/压缩专用模型,留空沿用 `aiModel`,可填更便宜的模型
44
+
45
+ - **频率限制可按群单独配置**:`groupRules` 新增 `aiMessageThreshold`、
46
+ `aiRandomReplyProbability`、`aiMinReplyIntervalSeconds`、`aiCooldownNotice`,
47
+ 留空则跟随全局,填 0 表示该群不限制。
48
+
49
+ - **模型调用冷却真正生效**:之前 @ 与「点名后跟随」会直接绕过冷却,且冷却按
50
+ 「上次成功发出回复」计算,模型返回 `<pass/>`、被过滤器拦下或请求失败时不会更新,
51
+ 所以看起来像坏的。现在:
52
+
53
+ - 所有会调用模型的行为(含 @)统一受 `aiMinReplyIntervalSeconds` 约束;
54
+ - 冷却按「上一次调用模型」计算,失败与放弃也算用掉一次;
55
+ - 冷却结束后自动恢复,不需要重载插件。
56
+
57
+ - **冷却中被 @ 会提示还剩多久**:`aiCooldownNotice`(默认开)、
58
+ `aiCooldownNoticeText`(支持 `{seconds}` / `{minutes}`)、
59
+ `aiCooldownNoticeIntervalSeconds`(同一群默认 20 秒内不重复提示)。
60
+ 提示是纯本地消息,**不调用模型、不消耗 token**,也不会写进 AI 上下文。
61
+
62
+ ### 改进
63
+
64
+ - 模型调用日志新增 token 用量:`tokens=in=…,out=…,cache=…`。
65
+ 其中 `cache` 是上下文缓存命中的 token 数,可以直接判断提示词前缀有没有被缓存。
66
+ - 新增 `aiContextMaxChars`:历史上下文按字数裁剪(从最旧开始丢,至少保留最近 4 条),
67
+ 默认 0 = 不限;想省 token 可设 2500~3500。
68
+ - 新增 `aiStyleMaxChars`:限制外部插件注入的「说话风格」段长度,默认 0 = 不限;
69
+ 风格 skill 很长时可设 1200~1800,能显著降低每次调用的输入 token。
70
+ - 自动归纳/压缩的模型调用也会记录 token 用量。
71
+
72
+ ### 测试
73
+
74
+ - 新增 12 项测试:冷却顺序与剩余时间、按群覆盖阈值/冷却、冷却提示限流、
75
+ 记忆压缩(5→1、超上限强制压缩、失败回退、真实写盘替换、手动记忆保留)。
76
+
5
77
  ## 1.4.6
6
78
 
7
79
  ### 修复
@@ -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,22 +759,28 @@ 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,
596
774
  mention,
597
775
  followup,
598
776
  rng: this.rng,
777
+ pseudoRandom: this.setting(session, 'aiPseudoRandom') !== false,
778
+ randomBoost: state.randomBoost,
779
+ pseudoRandomStep: Math.max(0, Number(this.setting(session, 'aiPseudoRandomStep') ?? 0.01)),
599
780
  });
781
+ // 伪随机加成只由「随机掷骰」更新:冷却/阈值跳过时保持不变
782
+ if (typeof decision.nextBoost === 'number')
783
+ state.randomBoost = decision.nextBoost;
600
784
  this.log('ai-trigger', {
601
785
  fire: decision.fire,
602
786
  reason: decision.reason,
@@ -604,10 +788,16 @@ class AiEngine {
604
788
  threshold,
605
789
  mention,
606
790
  followup,
791
+ prob: decision.effectiveProbability,
792
+ boost: state.randomBoost,
607
793
  ctx: state.records.length,
608
794
  }, session);
609
- if (!decision.fire)
795
+ if (!decision.fire) {
796
+ if (decision.reason === 'cooldown-mention') {
797
+ await this.sendCooldownNotice(session, state, decision.remainingMs || 0);
798
+ }
610
799
  return;
800
+ }
611
801
  state.inFlight = true;
612
802
  state.lastAttemptAt = this.now();
613
803
  const startedAt = this.now();
@@ -619,13 +809,13 @@ class AiEngine {
619
809
  groupId: String(session.guildId),
620
810
  mode: 'reply',
621
811
  };
622
- const styleSections = await this.hooks.collectSections(hookCtx);
812
+ const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
623
813
  const webSearch = await this.webSearch(record, session);
624
814
  const promptInput = {
625
815
  selfName: this.selfName,
626
816
  persona: this.personaPrompt,
627
817
  groupId: String(session.guildId),
628
- records: state.records,
818
+ records: this.clampContext(state.records),
629
819
  current: record,
630
820
  mention,
631
821
  followup,
@@ -729,6 +919,7 @@ class AiEngine {
729
919
  images: images.length,
730
920
  degradedToText: !!result.degradedToText,
731
921
  chars: finalText.length,
922
+ tokens: usageText(result.usage) || undefined,
732
923
  preview: finalText.slice(0, 60),
733
924
  }, session);
734
925
  await this.hooks.runAfterReply({ ...hookCtx, text: finalText });
@@ -753,7 +944,7 @@ class AiEngine {
753
944
  const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
754
945
  let sections = [];
755
946
  try {
756
- sections = await this.hooks.collectSections({ session, groupId, mode: 'reply' });
947
+ sections = this.clampStyle(await this.hooks.collectSections({ session, groupId, mode: 'reply' }));
757
948
  }
758
949
  catch { /* ignore */ }
759
950
  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;