@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/CHANGELOG.md CHANGED
@@ -2,54 +2,133 @@
2
2
 
3
3
  本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
- ## 1.4.5
6
-
7
- ### 改进
8
-
9
- - **提示词里给每个发言人带上 QQ 号,用于区分身份**。
10
-
11
- 之前只渲染「昵称(角色)」,昵称重复或改动时模型分不清谁是谁,
12
- 会出现把另一个机器人当成自己、把两个同名群友记混的情况。
13
-
14
- 现在渲染成 `昵称(角色#QQ号)`:
15
-
16
- ```
17
- [15:15] 小明(成员#10001): 你好
18
- [15:15] MeowBot(你#9999): 我说过
19
- [15:15] 冬木(管理员#2): 在吗
20
- ```
21
-
22
- - **QQ 号只作为身份参考,明确要求模型不要写进回复**;
23
- - 自己的发言标 `(你#自己QQ号)`,别人的(包括其他机器人)都不会被标成自己;
24
- - 引用消息也带上被引用者的 QQ 号(`「回复 小明#333:……」`);
25
- - `unknown` 角色用「成员」兜底,避免出现 `小明(#10001)` 这种孤立井号。
26
-
27
- 规则里新增两条约束:判断「谁是谁」必须看 #号;标着(你)的才是自己。
28
-
29
- ### 测试
30
-
31
- - 新增 9 项身份测试:QQ 号是否出现、同名用户区分、自己/其他机器人区分、
32
- 引用带号、禁止输出 QQ 号、缺 userId 时不产生空 `#`。
33
- ## 1.4.4
34
-
35
- ### 改进
36
-
37
- - **`[memory] list` 改为分页显示**。
38
-
39
- 原先固定显示「最近 10 条」,记忆攒多之后一屏刷不完,也没法往前翻。
40
-
41
- 现在:
42
-
43
- - 默认显示**最新 5 条**(第 1 页就是刚记下的内容);
44
- - 每页 5 条,序号是全局序号;
45
- - `[memory] list 1` ~ `[memory] list 9` 翻页,页码越大越往前;
46
- - 末尾固定提示「记忆库共 N 条,第 X/Y 页」和翻页用法;
47
- - 页码越界自动夹到有效范围,非法输入回落到第 1 页。
48
-
49
- ### 测试
50
-
51
- - 新增 11 项分页测试:默认页、翻页、末页、越界夹取、非法输入、空库、
52
- 整页边界、全局序号、自定义页大小。
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
+
52
+ ## 1.4.6
53
+
54
+ ### 修复
55
+
56
+ - **主插件单独重载后,配套插件(表情包 / 聊天风格 / 私聊)全部失效**。
57
+
58
+ 之前每次加载主插件都会新建一个 `AiHookRegistry`,再用
59
+ `ctx.root.set('qqgmAiHooks', ...)` 覆盖旧对象;而 qqgm-meme、
60
+ qqgm-chat-style、qqgm-private 只在启动时解析一次扩展点并长期持有。
61
+ 在控制台单独重启主插件后,新引擎拿到的是空注册表,外部插件还挂在旧对象上:
62
+
63
+ - 表情包不再追加(提示词里也没有 `[表情: 情绪]` 说明);
64
+ - 聊天风格段从 system prompt 里消失;
65
+ - 私聊继续用旧配置、旧引擎,`chat()` 走已销毁的实例。
66
+
67
+ 只有把整个 Koishi 重启一遍才能恢复。
68
+
69
+ 现在改为:
70
+
71
+ - `qqgmAiHooks` 使用 `globalThis` + `Symbol.for` 做**进程级单例**,
72
+ 模块被重新 `require`(甚至从不同路径加载两份)也拿到同一个注册表,
73
+ 重载前后对象身份不变,外部插件注册的钩子继续有效;
74
+ - `qqgmAiRuntime` 改为**稳定的门面对象**,重载只把内部 `current` 指针换到新服务,
75
+ 外部插件读到的 `config` / `hooks` / `chat` 永远是最新的;
76
+ - 旧实例的 `dispose` 会先检查是否有新实例接管,不会误清新指针。
77
+
78
+ ### 测试
79
+
80
+ - 新增跨模块重载测试:清空 `require` 缓存后重新加载,注册表身份与已注册钩子保持不变。
81
+ - 新增运行时门面测试:新实例先接管、旧实例后 `dispose` 时,指针不会被清空。
82
+ - 新增主插件重载集成测试:连续构造两个 `QQGroupManagerService`,外部钩子在重载后仍然生效。
83
+
84
+ ## 1.4.5
85
+
86
+ ### 改进
87
+
88
+ - **提示词里给每个发言人带上 QQ 号,用于区分身份**。
89
+
90
+ 之前只渲染「昵称(角色)」,昵称重复或改动时模型分不清谁是谁,
91
+ 会出现把另一个机器人当成自己、把两个同名群友记混的情况。
92
+
93
+ 现在渲染成 `昵称(角色#QQ号)`:
94
+
95
+ ```
96
+ [15:15] 小明(成员#10001): 你好
97
+ [15:15] MeowBot(你#9999): 我说过
98
+ [15:15] 冬木(管理员#2): 在吗
99
+ ```
100
+
101
+ - **QQ 号只作为身份参考,明确要求模型不要写进回复**;
102
+ - 自己的发言标 `(你#自己QQ号)`,别人的(包括其他机器人)都不会被标成自己;
103
+ - 引用消息也带上被引用者的 QQ 号(`「回复 小明#333:……」`);
104
+ - `unknown` 角色用「成员」兜底,避免出现 `小明(#10001)` 这种孤立井号。
105
+
106
+ 规则里新增两条约束:判断「谁是谁」必须看 #号;标着(你)的才是自己。
107
+
108
+ ### 测试
109
+
110
+ - 新增 9 项身份测试:QQ 号是否出现、同名用户区分、自己/其他机器人区分、
111
+ 引用带号、禁止输出 QQ 号、缺 userId 时不产生空 `#`。
112
+ ## 1.4.4
113
+
114
+ ### 改进
115
+
116
+ - **`[memory] list` 改为分页显示**。
117
+
118
+ 原先固定显示「最近 10 条」,记忆攒多之后一屏刷不完,也没法往前翻。
119
+
120
+ 现在:
121
+
122
+ - 默认显示**最新 5 条**(第 1 页就是刚记下的内容);
123
+ - 每页 5 条,序号是全局序号;
124
+ - `[memory] list 1` ~ `[memory] list 9` 翻页,页码越大越往前;
125
+ - 末尾固定提示「记忆库共 N 条,第 X/Y 页」和翻页用法;
126
+ - 页码越界自动夹到有效范围,非法输入回落到第 1 页。
127
+
128
+ ### 测试
129
+
130
+ - 新增 11 项分页测试:默认页、翻页、末页、越界夹取、非法输入、空库、
131
+ 整页边界、全局序号、自定义页大小。
53
132
  ## 1.4.3
54
133
 
55
134
  ### 修复
@@ -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;
@@ -35,6 +46,11 @@ export interface AiDeps {
35
46
  rng?: () => number;
36
47
  now?: () => number;
37
48
  fetchImpl?: typeof fetch;
49
+ /**
50
+ * 钩子注册表。主插件会传入进程级共享实例;不传则每次新建,
51
+ * 保证测试/多实例之间互不串钩子。
52
+ */
53
+ hooks?: AiHookRegistry;
38
54
  }
39
55
  export declare class AiEngine {
40
56
  readonly state: AiState;
@@ -59,6 +75,11 @@ export declare class AiEngine {
59
75
  constructor(host: AiHost, deps?: AiDeps);
60
76
  private groupKey;
61
77
  private ruleFor;
78
+ /**
79
+ * 读配置:该群 groupRules 里有同名非空值就用它,否则回落到全局。
80
+ * 这样频率限制(阈值/概率/模型调用冷却)可以按群单独设置。
81
+ */
82
+ private setting;
62
83
  resolveEnabled(session: any): boolean;
63
84
  private get contextWindow();
64
85
  private get selfName();
@@ -66,6 +87,13 @@ export declare class AiEngine {
66
87
  private get personaPrompt();
67
88
  private get maxReplyChars();
68
89
  private get debugPrompt();
90
+ /**
91
+ * 历史上下文按字数裁剪(aiContextMaxChars,0=不限)。
92
+ * 从最新往前累加,至少保留最近 4 条,避免一刀切掉当前对话。
93
+ */
94
+ private clampContext;
95
+ /** 限制外部插件注入的风格段长度(aiStyleMaxChars,0=不限) */
96
+ private clampStyle;
69
97
  /** 是否像指令(这类消息不进上下文,避免污染) */
70
98
  private isCommandLike;
71
99
  /** 记录一条群消息;返回落库后的记录(指令类返回 null) */
@@ -91,8 +119,17 @@ export declare class AiEngine {
91
119
  /** 资源清理:停止定时器、清空缓存 */
92
120
  dispose(): void;
93
121
  private learnAndReport;
94
- /** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
122
+ /** 把一批消息归纳成一条记忆并写入对应作用域;返回写入结果或 null */
95
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;
96
133
  private findBot;
97
134
  private isMention;
98
135
  private addressesOthers;
@@ -101,6 +138,13 @@ export declare class AiEngine {
101
138
  private bumpFollowup;
102
139
  private getFollowup;
103
140
  private loadMemories;
141
+ /**
142
+ * 被 @ 但处于模型调用冷却时,在群里提示还剩多久。
143
+ *
144
+ * 只发本地短句,不调用模型;同一群按 aiCooldownNoticeIntervalSeconds 限流,
145
+ * 避免有人连续 @ 时刷屏。
146
+ */
147
+ private sendCooldownNotice;
104
148
  handle(session: any): Promise<void>;
105
149
  /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
106
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)
@@ -76,7 +94,9 @@ class AiEngine {
76
94
  this.host = host;
77
95
  this.config = host.config;
78
96
  this.state = deps.state ?? new state_1.AiState();
79
- this.hooks = new hooks_1.AiHookRegistry(host.logger);
97
+ // 默认独立注册表;主插件通过 deps.hooks 注入进程级单例,
98
+ // 这样主插件重载后外部插件注册的钩子不会丢。
99
+ this.hooks = deps.hooks ?? new hooks_1.AiHookRegistry(host.logger);
80
100
  this.provider = deps.provider ?? new provider_1.ChatProvider(host.config, host.logger);
81
101
  this.names = new names_1.NameResolver({
82
102
  getOneBotApi: (session) => host.getOneBotApi(session),
@@ -100,6 +120,17 @@ class AiEngine {
100
120
  const rules = Array.isArray(this.config.groupRules) ? this.config.groupRules : [];
101
121
  return rules.find((item) => String(item?.guildId ?? '').trim() === guildId);
102
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
+ }
103
134
  resolveEnabled(session) {
104
135
  const rule = this.ruleFor(session);
105
136
  const requireRule = this.config.aiReplyRequireGroupRule !== false;
@@ -135,6 +166,40 @@ class AiEngine {
135
166
  get debugPrompt() {
136
167
  return !!this.config.aiDebugPrompt;
137
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
+ }
138
203
  // ---------------------------------------------------------------- 记录
139
204
  /** 是否像指令(这类消息不进上下文,避免污染) */
140
205
  isCommandLike(text) {
@@ -338,12 +403,12 @@ class AiEngine {
338
403
  if (!records.length)
339
404
  return;
340
405
  const scope = { kind, id: scopeId };
341
- const summary = await this.summarizeRecords(records, kind, scope, reason);
342
- if (!summary)
406
+ const saved = await this.summarizeRecords(records, kind, scope, reason);
407
+ if (!saved || !saved.text)
343
408
  return;
344
409
  if (cfg.memoryLearnPushBack === false)
345
410
  return;
346
- const text = `刚记住了:${summary}`;
411
+ const text = saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}`;
347
412
  try {
348
413
  if (kind === "private") {
349
414
  const bot = (kind === "private" && session?.bot) || null;
@@ -361,7 +426,7 @@ class AiEngine {
361
426
  this.host.logger?.warn?.(`[memory-learn] 回推失败 ${kind}:${scopeId}: ${String(error)}`);
362
427
  }
363
428
  }
364
- /** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
429
+ /** 把一批消息归纳成一条记忆并写入对应作用域;返回写入结果或 null */
365
430
  async summarizeRecords(records, kind, scope, reason) {
366
431
  const cfg = this.config || {};
367
432
  // 每日上限
@@ -372,7 +437,7 @@ class AiEngine {
372
437
  const used = this.learnDaily.get(dailyKey) || 0;
373
438
  if (used >= limit) {
374
439
  this.host.logger?.info?.(`[memory-learn] 已达每日上限 ${limit}(${kind}:${scope.id})`);
375
- return "";
440
+ return null;
376
441
  }
377
442
  const prompt = (0, learn_1.buildSummaryPrompt)(records, { kind, selfName: this.selfName });
378
443
  let raw = "";
@@ -382,21 +447,25 @@ class AiEngine {
382
447
  user: prompt.user,
383
448
  temperature: 0.3,
384
449
  maxTokens: 400,
450
+ model: String(cfg.memoryLearnModel || "").trim() || undefined,
385
451
  });
386
452
  if (!result || !result.ok) {
387
453
  this.host.logger?.warn?.(`[memory-learn] 归纳调用失败: ${result && result.error}`);
388
- return "";
454
+ return null;
389
455
  }
390
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
+ }
391
460
  }
392
461
  catch (error) {
393
462
  this.host.logger?.warn?.(`[memory-learn] 归纳异常: ${String(error)}`);
394
- return "";
463
+ return null;
395
464
  }
396
465
  const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
397
466
  let text = (0, learn_1.cleanSummary)(raw, maxChars);
398
467
  if (!text)
399
- return "";
468
+ return null;
400
469
  // 去重
401
470
  let existing = [];
402
471
  try {
@@ -413,18 +482,95 @@ class AiEngine {
413
482
  const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
414
483
  if ((0, learn_1.isDuplicate)(text, existing, threshold)) {
415
484
  this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
416
- return "";
485
+ return null;
417
486
  }
487
+ let saved;
418
488
  try {
419
- await this.host.saveMemoryToFile("", text, scope, "自动归纳");
489
+ saved = await this.saveLearnedMemory(kind, scope, text);
420
490
  this.learnDaily.set(dailyKey, used + 1);
421
491
  }
422
492
  catch (error) {
423
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"}`);
424
571
  return "";
425
572
  }
426
- this.host.logger?.info?.(`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${text.length}字`);
427
- return text;
573
+ return (0, learn_1.cleanSummary)(String(result.text || ""), maxChars);
428
574
  }
429
575
  findBot() {
430
576
  const bots = this.host?.ctx?.bots || this.host?.bots || [];
@@ -553,6 +699,40 @@ class AiEngine {
553
699
  return selected.map((item) => item.text);
554
700
  }
555
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
+ }
556
736
  async handle(session) {
557
737
  const key = this.groupKey(session);
558
738
  if (!key)
@@ -579,15 +759,15 @@ class AiEngine {
579
759
  // 用户换了话题/说的和上一轮无关时,丢掉待续话题,避免机器人追着自己上一句说
580
760
  if (followupState && !followup)
581
761
  state.followup = null;
582
- const threshold = Math.max(1, Number(this.config.aiMessageThreshold ?? 15));
762
+ const threshold = Math.max(1, Number(this.setting(session, 'aiMessageThreshold') ?? 15));
583
763
  const decision = (0, trigger_1.decideTrigger)({
584
- mode: (this.config.aiReplyMode || 'hybrid'),
764
+ mode: (this.setting(session, 'aiReplyMode') || 'hybrid'),
585
765
  counter: state.counter,
586
766
  threshold,
587
- probability: Number(this.config.aiRandomReplyProbability ?? 0.08),
767
+ probability: Number(this.setting(session, 'aiRandomReplyProbability') ?? 0.08),
588
768
  now: this.now(),
589
769
  lastAttemptAt: state.lastAttemptAt,
590
- minIntervalMs: Math.max(0, Number(this.config.aiMinReplyIntervalSeconds ?? 45)) * 1000,
770
+ minIntervalMs: Math.max(0, Number(this.setting(session, 'aiMinReplyIntervalSeconds') ?? 45)) * 1000,
591
771
  lastReplyAt: state.lastReplyAt || 0,
592
772
  mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
593
773
  inFlight: state.inFlight,
@@ -604,8 +784,12 @@ class AiEngine {
604
784
  followup,
605
785
  ctx: state.records.length,
606
786
  }, session);
607
- if (!decision.fire)
787
+ if (!decision.fire) {
788
+ if (decision.reason === 'cooldown-mention') {
789
+ await this.sendCooldownNotice(session, state, decision.remainingMs || 0);
790
+ }
608
791
  return;
792
+ }
609
793
  state.inFlight = true;
610
794
  state.lastAttemptAt = this.now();
611
795
  const startedAt = this.now();
@@ -617,13 +801,13 @@ class AiEngine {
617
801
  groupId: String(session.guildId),
618
802
  mode: 'reply',
619
803
  };
620
- const styleSections = await this.hooks.collectSections(hookCtx);
804
+ const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
621
805
  const webSearch = await this.webSearch(record, session);
622
806
  const promptInput = {
623
807
  selfName: this.selfName,
624
808
  persona: this.personaPrompt,
625
809
  groupId: String(session.guildId),
626
- records: state.records,
810
+ records: this.clampContext(state.records),
627
811
  current: record,
628
812
  mention,
629
813
  followup,
@@ -727,6 +911,7 @@ class AiEngine {
727
911
  images: images.length,
728
912
  degradedToText: !!result.degradedToText,
729
913
  chars: finalText.length,
914
+ tokens: usageText(result.usage) || undefined,
730
915
  preview: finalText.slice(0, 60),
731
916
  }, session);
732
917
  await this.hooks.runAfterReply({ ...hookCtx, text: finalText });
@@ -751,7 +936,7 @@ class AiEngine {
751
936
  const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
752
937
  let sections = [];
753
938
  try {
754
- sections = await this.hooks.collectSections({ session, groupId, mode: 'reply' });
939
+ sections = this.clampStyle(await this.hooks.collectSections({ session, groupId, mode: 'reply' }));
755
940
  }
756
941
  catch { /* ignore */ }
757
942
  const system = [
package/lib/ai/hooks.d.ts CHANGED
@@ -54,6 +54,15 @@ export declare class AiHookRegistry {
54
54
  private afterReplyHandlers;
55
55
  private evictedHandlers;
56
56
  constructor(logger?: any);
57
+ /** 主插件重载后把新实例的 logger 接到同一个注册表上。 */
58
+ setLogger(logger?: any): void;
59
+ /** 诊断用:当前已注册的钩子数量。 */
60
+ stats(): {
61
+ sections: number;
62
+ filters: number;
63
+ afterReply: number;
64
+ evicted: number;
65
+ };
57
66
  registerPromptSection(provider: PromptSectionProvider): () => void;
58
67
  registerOutputFilter(filter: OutputFilter): () => void;
59
68
  /** 文字回复已发送后触发;用于追加表情包等后续动作。 */
@@ -72,3 +81,4 @@ export declare class AiHookRegistry {
72
81
  /** 上下文挤出后执行;单个 handler 失败只记日志,不影响其它。 */
73
82
  runContextEvicted(ctx: ContextEvictedContext): Promise<void>;
74
83
  }
84
+ export declare function getSharedAiHooks(logger?: any): AiHookRegistry;