@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/hooks.ts CHANGED
@@ -64,6 +64,21 @@ export class AiHookRegistry {
64
64
 
65
65
  constructor(private logger?: any) {}
66
66
 
67
+ /** 主插件重载后把新实例的 logger 接到同一个注册表上。 */
68
+ setLogger(logger?: any): void {
69
+ if (logger) this.logger = logger;
70
+ }
71
+
72
+ /** 诊断用:当前已注册的钩子数量。 */
73
+ stats(): { sections: number; filters: number; afterReply: number; evicted: number } {
74
+ return {
75
+ sections: this.sections.size,
76
+ filters: this.filters.size,
77
+ afterReply: this.afterReplyHandlers.size,
78
+ evicted: this.evictedHandlers.size,
79
+ };
80
+ }
81
+
67
82
  registerPromptSection(provider: PromptSectionProvider): () => void {
68
83
  this.sections.add(provider);
69
84
  return () => this.sections.delete(provider);
@@ -141,3 +156,33 @@ export class AiHookRegistry {
141
156
  }
142
157
  }
143
158
  }
159
+
160
+ /**
161
+ * 进程级共享的钩子注册表。
162
+ *
163
+ * 背景:meme / chat-style / private 等外部插件只在启动时解析一次
164
+ * `qqgmAiHooks`,之后一直持有这个对象。如果主插件每次重载都 `new` 一个
165
+ * 新注册表,新引擎看到的是空注册表,而外部插件还挂在旧对象上——表现就是
166
+ * 主插件单独重启后表情包不发、聊天风格段消失、私聊用旧配置。
167
+ *
168
+ * 用 globalThis + Symbol.for 做单例:即使插件模块被重新 require、甚至从
169
+ * 不同路径加载了两份,拿到的也是同一个注册表,重载前后对象身份不变。
170
+ */
171
+ const SHARED_HOOKS = Symbol.for('qqgm.ai-hooks-registry');
172
+
173
+ export function getSharedAiHooks(logger?: any): AiHookRegistry {
174
+ const store = globalThis as any;
175
+ let registry: AiHookRegistry = store[SHARED_HOOKS];
176
+ if (!registry) {
177
+ registry = new AiHookRegistry(logger);
178
+ store[SHARED_HOOKS] = registry;
179
+ logger?.info?.(`[ai-hooks] v${registry.version} 注册表已创建(进程级单例)`);
180
+ } else if (logger) {
181
+ registry.setLogger(logger);
182
+ const stats = registry.stats();
183
+ logger.info?.(
184
+ `[ai-hooks] 复用进程级注册表:风格段 ${stats.sections} / 过滤器 ${stats.filters} / 后处理 ${stats.afterReply}`,
185
+ );
186
+ }
187
+ return registry;
188
+ }
package/src/ai/learn.ts CHANGED
@@ -206,3 +206,59 @@ export function isDuplicate(candidate: string, existing: string[], threshold = 0
206
206
  }
207
207
  return false;
208
208
  }
209
+
210
+ // ---------------------------------------------------------------- 记忆压缩
211
+
212
+ /** 自动归纳条目的标题标记(写进 Markdown 块首行) */
213
+ export const AUTO_MEMORY_LABEL = '自动归纳';
214
+
215
+ /** 自动归纳块首行形如 `## 2026/10/28 12:00:00 · 自动归纳` */
216
+ export function isAutoMemoryBlock(block: string): boolean {
217
+ const first = String(block || '').split('\n', 1)[0] || '';
218
+ return /·\s*自动归纳/.test(first);
219
+ }
220
+
221
+ /** 取记忆块正文(去掉 `## 时间 · 来源` 标题行) */
222
+ export function memoryBlockBody(block: string): string {
223
+ const lines = String(block || '').split('\n');
224
+ if (lines.length <= 1) return String(block || '').trim();
225
+ return lines.slice(1).join('\n').trim();
226
+ }
227
+
228
+ /**
229
+ * 记忆压缩提示词:把 N 条自动归纳合并成一条更短的。
230
+ *
231
+ * 目的不是“再总结一遍”,而是去掉重复与过时信息——群里连续几天聊同一件事时,
232
+ * 自动归纳会反复产出高度相似的条目,压缩后只保留事实差异。
233
+ */
234
+ export function buildConsolidatePrompt(
235
+ blocks: string[],
236
+ options: { maxChars?: number; kind?: string } = {},
237
+ ): { system: string; user: string } {
238
+ const maxChars = Math.max(40, Number(options.maxChars) || 90);
239
+ const label = options.kind === 'private' ? '私聊' : '群聊';
240
+ const bodies = (blocks || [])
241
+ .map((block) => memoryBlockBody(block).replace(/\s+/g, ' ').trim())
242
+ .filter(Boolean);
243
+
244
+ const system = [
245
+ `你在压缩一段${label}的长期记忆。`,
246
+ `下面有 ${bodies.length} 条已经归纳过的记忆,请合并成一条。`,
247
+ '',
248
+ '要求:',
249
+ '- 只保留互不重复的事实:人物与称呼、关系、稳定偏好、反复出现的话题;',
250
+ '- 删掉重复表述、一次性情绪、已经过时的细节;',
251
+ '- 不要编造,不要写“他们聊到”“讨论了”这类过程描述;',
252
+ `- 只输出一条纯文本,不超过 ${maxChars} 字,不要标题、编号、列表、Markdown;`,
253
+ '- 如果这些记忆里没有任何值得保留的内容,只输出一个词:NONE',
254
+ ].join('\n');
255
+
256
+ const user = [
257
+ '【待压缩的记忆】',
258
+ ...bodies.map((text, index) => `${index + 1}. ${text}`),
259
+ '',
260
+ '现在输出合并后的那一条记忆,或输出 NONE。',
261
+ ].join('\n');
262
+
263
+ return { system, user };
264
+ }
@@ -14,6 +14,8 @@ export interface ChatRequest {
14
14
  temperature?: number;
15
15
  maxTokens?: number;
16
16
  timeoutMs?: number;
17
+ /** 覆盖默认 aiModel(例如自动归纳用更便宜的模型) */
18
+ model?: string;
17
19
  }
18
20
 
19
21
  export interface ChatResult {
@@ -23,6 +25,8 @@ export interface ChatResult {
23
25
  status?: number;
24
26
  /** 是否因为图片被拒而发生了降级重试 */
25
27
  degradedToText?: boolean;
28
+ /** 服务端 token 用量(OpenAI: usage;Gemini: usageMetadata) */
29
+ usage?: any;
26
30
  }
27
31
 
28
32
  export interface ProviderConfig {
@@ -65,7 +69,7 @@ export class ChatProvider {
65
69
 
66
70
  async chat(request: ChatRequest): Promise<ChatResult> {
67
71
  if (!this.apiKey) return { ok: false, error: 'AI 未配置 apiKey' };
68
- if (!this.model) return { ok: false, error: 'AI 未配置 model' };
72
+ if (!this.model && !String(request.model || '').trim()) return { ok: false, error: 'AI 未配置 model' };
69
73
 
70
74
  const provider = String(this.config.aiProvider ?? 'openai-compatible');
71
75
  const requested = (request.images ?? []).filter((item) => /^data:image\//i.test(item) || /^https?:\/\//i.test(item));
@@ -113,6 +117,7 @@ export class ChatProvider {
113
117
  options: { maxTokens?: number; retried?: boolean } = {},
114
118
  ): Promise<ChatResult> {
115
119
  const base = String(this.config.aiBaseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
120
+ const model = String(request.model || this.model).trim();
116
121
  const content: any[] = [{ type: 'text', text: request.user }];
117
122
  for (const url of images) content.push({ type: 'image_url', image_url: { url } });
118
123
  const userContent = images.length ? content : request.user;
@@ -131,7 +136,7 @@ export class ChatProvider {
131
136
  'Content-Type': 'application/json',
132
137
  },
133
138
  body: JSON.stringify({
134
- model: this.model,
139
+ model,
135
140
  temperature: request.temperature ?? this.config.aiTemperature ?? 0.8,
136
141
  max_tokens: maxTokens,
137
142
  messages: [
@@ -180,7 +185,7 @@ export class ChatProvider {
180
185
  error: `模型返回空内容(finish=${payload?.choices?.[0]?.finish_reason || 'unknown'})`,
181
186
  };
182
187
  }
183
- return { ok: true, text, status: response.status };
188
+ return { ok: true, text, status: response.status, usage: payload?.usage };
184
189
  } catch (error: any) {
185
190
  const aborted = error?.name === 'AbortError';
186
191
  return { ok: false, error: aborted ? '请求超时' : `请求失败: ${String(error?.message || error)}` };
@@ -192,7 +197,8 @@ export class ChatProvider {
192
197
  private async callGemini(request: ChatRequest, images: string[]): Promise<ChatResult> {
193
198
  const rawBase = String(this.config.aiBaseUrl || 'https://generativelanguage.googleapis.com/v1beta').replace(/\/+$/, '');
194
199
  const base = /\/v\d/i.test(rawBase) ? rawBase : `${rawBase}/v1beta`;
195
- const endpoint = `${base}/models/${encodeURIComponent(this.model)}:generateContent?key=${encodeURIComponent(this.apiKey)}`;
200
+ const model = String(request.model || this.model).trim();
201
+ const endpoint = `${base}/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(this.apiKey)}`;
196
202
  const parts: any[] = [{ text: request.user }];
197
203
  for (const url of images) {
198
204
  const match = /^data:(image\/[^;]+);base64,(.*)$/i.exec(url);
@@ -228,7 +234,7 @@ export class ChatProvider {
228
234
  .join('')
229
235
  .trim();
230
236
  if (!text) return { ok: false, status: response.status, error: 'Gemini 返回空内容' };
231
- return { ok: true, text, status: response.status };
237
+ return { ok: true, text, status: response.status, usage: payload?.usageMetadata };
232
238
  } catch (error: any) {
233
239
  const aborted = error?.name === 'AbortError';
234
240
  return { ok: false, error: aborted ? '请求超时' : `请求失败: ${String(error?.message || error)}` };
@@ -0,0 +1,63 @@
1
+ /**
2
+ * 主插件对外暴露的运行时门面(进程级单例)。
3
+ *
4
+ * 为什么需要它:
5
+ * - 外部插件(qqgm-private 等)会 `ctx.root.get('qqgmAiRuntime')` 之后长期持有该对象;
6
+ * - 如果每次主插件重载都 `set` 一个全新的 `{ config, hooks, chat }` 快照,
7
+ * 外部插件手里的旧快照就永远指向已经销毁的引擎:配置不更新、钩子对不上、
8
+ * chat() 走旧实例;
9
+ * - 这里改成稳定的门面对象,重载只是把 `current` 指针换到新服务,
10
+ * 外部插件持有的引用不变,读到的 config / hooks / chat 永远是最新的。
11
+ */
12
+
13
+ import { AiHookRegistry, getSharedAiHooks } from './hooks';
14
+
15
+ const SHARED_RUNTIME = Symbol.for('qqgm.ai-runtime-facade');
16
+
17
+ export interface AiRuntimeChatRequest {
18
+ system: string;
19
+ user: string;
20
+ temperature?: number;
21
+ maxTokens?: number;
22
+ [key: string]: any;
23
+ }
24
+
25
+ export class AiRuntimeFacade {
26
+ /** 当前存活的主插件服务;主插件卸载后为 null。 */
27
+ current: any = null;
28
+
29
+ bind(service: any): void {
30
+ this.current = service;
31
+ }
32
+
33
+ unbind(service: any): void {
34
+ if (this.current === service) this.current = null;
35
+ }
36
+
37
+ get config(): any {
38
+ return this.current ? this.current.config : {};
39
+ }
40
+
41
+ get hooks(): AiHookRegistry {
42
+ const live = this.current && this.current.ai && this.current.ai.hooks;
43
+ // 服务不在时也返回共享注册表,避免外部插件拿到 null 后直接崩掉。
44
+ return live || getSharedAiHooks();
45
+ }
46
+
47
+ chat(request: AiRuntimeChatRequest): Promise<any> {
48
+ if (!this.current || !this.current.ai) {
49
+ return Promise.resolve({ ok: false, text: '', error: 'qqgm service not loaded' });
50
+ }
51
+ return this.current.ai.chat(request);
52
+ }
53
+ }
54
+
55
+ export function getAiRuntimeFacade(): AiRuntimeFacade {
56
+ const store = globalThis as any;
57
+ let facade: AiRuntimeFacade = store[SHARED_RUNTIME];
58
+ if (!facade) {
59
+ facade = new AiRuntimeFacade();
60
+ store[SHARED_RUNTIME] = facade;
61
+ }
62
+ return facade;
63
+ }
package/src/ai/state.ts CHANGED
@@ -43,6 +43,8 @@ export class GroupState {
43
43
  counter = 0;
44
44
  lastReplyAt = 0;
45
45
  lastAttemptAt = 0;
46
+ /** 上次发「冷却中」提示的时间,用于避免 @ 刷屏时反复提示 */
47
+ lastCooldownNoticeAt = 0;
46
48
  inFlight = false;
47
49
  followup: FollowupState | null = null;
48
50
  seen = new Map<string, number>();
package/src/ai/trigger.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  /**
2
2
  * 触发放行判定(纯函数,便于单测)。
3
3
  *
4
- * 三道闸门保留,但语义收紧:
5
- * 1) 冷却:同一群两次"真正调用模型"之间至少间隔 aiMinReplyIntervalSeconds;
6
- * 2) 阈值:hybrid/threshold 下需累计够 aiMessageThreshold 条消息;
7
- * 3) 概率:random/hybrid 下每条消息掷一次骰。
8
- * 点名与"点名后跟随"直接放行(不占冷却)。
4
+ * 冷却的语义已经统一:**所有真正调用模型的行为**(含 @、点名后跟随)
5
+ * 都受同一个冷却约束,按「上一次调用模型的时刻」计算,而不是按
6
+ * 「上一次成功发出回复」——模型返回 <pass/>、被过滤器拦下、请求失败
7
+ * 都算用过一次,避免一直失败却一直重试。
8
+ *
9
+ * 被 @ 但仍在冷却里时返回 remainingMs,由引擎决定是否在群里提示还剩多久。
9
10
  */
10
11
 
11
12
  export interface TriggerInput {
@@ -16,10 +17,9 @@ export interface TriggerInput {
16
17
  now: number;
17
18
  lastAttemptAt: number;
18
19
  minIntervalMs: number;
19
- /** 上一次真正发出回复的时间(用于 @ 冷却) */
20
- lastReplyAt: number;
21
- /** 被 @ 后两次回复的最小间隔 */
22
- mentionCooldownMs: number;
20
+ /** 兼容字段:旧版按“上次回复”计算的 @ 冷却,已合并进 minIntervalMs */
21
+ lastReplyAt?: number;
22
+ mentionCooldownMs?: number;
23
23
  inFlight: boolean;
24
24
  mention: boolean;
25
25
  followup: boolean;
@@ -30,24 +30,33 @@ export interface TriggerDecision {
30
30
  fire: boolean;
31
31
  forced: boolean;
32
32
  reason: string;
33
+ /** 冷却中时距离可以再次调用模型的剩余毫秒数 */
34
+ remainingMs?: number;
33
35
  }
34
36
 
35
37
  export function decideTrigger(input: TriggerInput): TriggerDecision {
36
38
  if (input.inFlight) return { fire: false, forced: false, reason: 'in-flight' };
37
39
 
38
- if (input.mention) {
39
- const cooldown = Math.max(0, Number(input.mentionCooldownMs) || 0);
40
- if (cooldown > 0 && input.now - (Number(input.lastReplyAt) || 0) < cooldown) {
41
- return { fire: false, forced: false, reason: 'mention-cooldown' };
40
+ // ---------- 1) 模型调用冷却:@ 也不能绕过 ----------
41
+ const cooldown = Math.max(0, Number(input.minIntervalMs) || 0);
42
+ const lastAttempt = Number(input.lastAttemptAt) || 0;
43
+ if (cooldown > 0 && lastAttempt > 0) {
44
+ const elapsed = input.now - lastAttempt;
45
+ if (elapsed < cooldown) {
46
+ return {
47
+ fire: false,
48
+ forced: false,
49
+ reason: input.mention ? 'cooldown-mention' : 'cooldown',
50
+ remainingMs: Math.max(0, cooldown - elapsed),
51
+ };
42
52
  }
43
- return { fire: true, forced: true, reason: 'direct-mention' };
44
53
  }
45
- if (input.followup) return { fire: true, forced: true, reason: 'followup' };
46
54
 
47
- if (input.minIntervalMs > 0 && input.now - input.lastAttemptAt < input.minIntervalMs) {
48
- return { fire: false, forced: false, reason: 'cooldown' };
49
- }
55
+ // ---------- 2) 点名与点名后跟随:越过阈值/概率,但不越过冷却 ----------
56
+ if (input.mention) return { fire: true, forced: true, reason: 'direct-mention' };
57
+ if (input.followup) return { fire: true, forced: true, reason: 'followup' };
50
58
 
59
+ // ---------- 3) 阈值 ----------
51
60
  const needThreshold = input.mode === 'threshold' || input.mode === 'hybrid';
52
61
  if (needThreshold && input.counter < Math.max(1, input.threshold)) {
53
62
  return {
@@ -57,6 +66,7 @@ export function decideTrigger(input: TriggerInput): TriggerDecision {
57
66
  };
58
67
  }
59
68
 
69
+ // ---------- 4) 概率 ----------
60
70
  const needRandom = input.mode === 'random' || input.mode === 'hybrid';
61
71
  if (needRandom) {
62
72
  const probability = Math.max(0, Math.min(1, Number(input.probability) || 0));
package/src/index.ts CHANGED
@@ -32,6 +32,10 @@ export const Config = Schema.intersect([
32
32
  groupRules: Schema.array(Schema.object({
33
33
  guildId: Schema.string().required().description('群号。'),
34
34
  enableAiReply: Schema.boolean().description('该群是否启用 AI 回复(留空则跟随全局设置)。'),
35
+ aiMessageThreshold: Schema.natural().description('该群触发的消息数阈值(留空跟随全局 aiMessageThreshold)。'),
36
+ aiRandomReplyProbability: Schema.percent().description('该群随机触发概率(0~1,控制台按百分比显示;留空跟随全局)。'),
37
+ aiMinReplyIntervalSeconds: Schema.natural().description('该群模型调用冷却(秒;留空跟随全局 aiMinReplyIntervalSeconds)。'),
38
+ aiCooldownNotice: Schema.boolean().description('该群被 @ 但处于冷却时是否提示还剩多久(留空跟随全局)。'),
35
39
  bannedWords: Schema.array(String).role('table').default([]).description('该群专属违禁词列表(同样支持“关键词|分值”与顺序模糊匹配)。'),
36
40
  whitelistKeywords: Schema.array(String).role('table').default([]).description('该群违禁词白名单:消息只要命中其中任意一个关键词,就整条跳过违禁词评分(用于校学生会招新等允许的宣传场景)。'),
37
41
  strongKeywords: Schema.array(String).role('table').description('该群强关键词(留空则跟随全局设置)。命中后无视白名单豁免,用于堵住「附一个白名单词即可绕过管控」的漏洞。'),
@@ -64,13 +68,18 @@ export const Config = Schema.intersect([
64
68
  memoryPerScope: Schema.boolean().default(true).description('按私聊/群聊分开存储:群聊写 Memory_<群号>_群聊.md,私聊写 Memory_<QQ号>_私聊.md。关闭则所有会话共用单文件(旧行为)。'),
65
69
  memoryInAi: Schema.boolean().default(true).description('AI 回复/识图时是否参考记忆库内容(只读当前会话对应的文件)。'),
66
70
  memoryAutoLearn: Schema.boolean().default(false).description('自动归纳:上下文挤满后,把被挤出的消息交给外部学习插件总结成记忆。这里只负责抛出事件,实际归纳由 qqgm-memory-learn 完成。'),
67
- memoryAutoLearnGroups: Schema.array(String).role('table').default([]).description('自动归纳生效的群号/QQ号白名单;留空表示全部生效。'),
71
+ memoryAutoLearnGroups: Schema.array(String).role('table').default([]).description('自动归纳生效的群号/QQ号白名单;留空表示全部生效。'),
68
72
  memoryLearnIdleHours: Schema.natural().min(1).max(72).default(8).description('空闲兜底:距最后一条消息超过这么多小时且期间有新消息,就归纳一次。一直没新消息则不触发。'),
69
73
  memoryLearnThresholdScale: Schema.number().min(1).max(10).step(0.5).default(1).description('归纳阈值 = aiContextWindow × 该倍数。填 1 表示攒满一个上下文窗口就归纳。'),
70
74
  memoryLearnMaxChars: Schema.natural().min(40).max(300).default(150).description('单条自动记忆的字数上限。'),
71
75
  memoryLearnPushBack: Schema.boolean().default(true).description('归纳后把结果回推到原会话:私聊发私聊、群聊发对应群。'),
72
76
  memoryLearnDuplicateThreshold: Schema.number().min(0.3).max(0.95).step(0.05).default(0.55).description('与已有记忆相似度超过该值就跳过,避免同一件事反复记。'),
73
77
  memoryLearnDailyLimit: Schema.natural().min(1).max(200).default(30).description('每个作用域每天最多归纳几次,防止刷模型额度。'),
78
+ memoryLearnConsolidate: Schema.boolean().default(true).description('自动归纳压缩:每累计 N 条就合并成一条更短的记忆,避免记忆越堆越长、反复占用提示词。'),
79
+ memoryLearnConsolidateEvery: Schema.natural().min(2).max(20).default(5).description('每多少条自动记忆压缩一次(默认 5)。'),
80
+ memoryLearnMaxEntries: Schema.natural().min(1).max(100).default(15).description('自动归纳记忆的条数上限(不含手动 [memory] 保存的内容);超过后会强制压缩。'),
81
+ memoryLearnConsolidateMaxChars: Schema.natural().min(40).max(300).default(90).description('压缩后单条记忆的字数上限。'),
82
+ memoryLearnModel: Schema.string().default('').description('自动归纳/压缩使用的模型(留空沿用 aiModel)。可用更便宜的模型降低开销。'),
74
83
  }).description('记忆库'),
75
84
  Schema.object({
76
85
  enableBlacklist: Schema.boolean().default(true).description('全局黑名单系统开关。单个群未单独设置时跟随此值;单个群设置后以该群为准(全局关着也能为某群单独开启)。'),
@@ -119,7 +128,10 @@ export const Config = Schema.intersect([
119
128
  aiBaseUrl: Schema.string().default('https://api.openai.com/v1').description('接口基础地址(OpenAI 兼容模式需以 /v1 结尾;Gemini 模式可留默认)。'),
120
129
  aiModel: Schema.string().default('gpt-4o-mini').description('模型名称,如 gpt-4o-mini / doubao-1.5-lite / gemini-2.0-flash。'),
121
130
  aiAgentName: Schema.string().default('bot').description('默认智能体自称(可在配置页修改)。'),
122
- aiMentionCooldownSeconds: Schema.natural().min(0).max(3600).default(5).description('被 @ 后两次回复的最小间隔(秒),防止连续 @ 刷屏。'),
131
+ aiMentionCooldownSeconds: Schema.natural().min(0).max(3600).default(5).description('(兼容字段)旧的 @ 冷却;现在所有模型调用统一走 aiMinReplyIntervalSeconds。'),
132
+ aiCooldownNotice: Schema.boolean().default(true).description('被 @ 但处于模型调用冷却时,是否在群里提示还剩多久(纯本地消息,不调用模型)。'),
133
+ aiCooldownNoticeText: Schema.string().default('还在冷却,{seconds} 秒后再叫我。').description('冷却提示文案,可用 {seconds} 与 {minutes} 占位。'),
134
+ aiCooldownNoticeIntervalSeconds: Schema.natural().min(0).max(600).default(20).description('同一群两次冷却提示的最小间隔(秒),防止连续 @ 刷屏;0 = 不限制。'),
123
135
  aiIdleTopicMinutes: Schema.natural().min(0).max(1440).default(120).description('群内无消息多少分钟后主动抛话题;0=关闭。'),
124
136
  aiIdleTopicMinHour: Schema.natural().min(0).max(23).default(9).description('主动话题允许的最早小时(0-23)。'),
125
137
  aiIdleTopicMaxHour: Schema.natural().min(0).max(24).default(23).description('主动话题允许的最晚小时(不含)。'),
@@ -140,6 +152,8 @@ export const Config = Schema.intersect([
140
152
  aiRandomReplyProbability: Schema.percent().default(0.08).description('随机触发概率(每条消息掷一次骰)。random / hybrid 模式下未掷中直接跳过,不会调用 AI 接口。填 0 等同于关闭随机触发。'),
141
153
  aiMinReplyIntervalSeconds: Schema.natural().default(45).description('同一群两次真正调用模型的最短间隔(秒)。'),
142
154
  aiContextWindow: Schema.natural().default(30).description('参与推理的最近消息条数(建议 20~40;太小会导致模型看不到前文)。'),
155
+ aiContextMaxChars: Schema.natural().min(0).max(20000).default(0).description('历史上下文的字数上限:超过后从最旧的消息开始丢(至少保留最近 4 条)。0 = 不限。想省 token 可设 2500~3500。'),
156
+ aiStyleMaxChars: Schema.natural().min(0).max(20000).default(0).description('外部插件注入的「说话风格」段每条最多保留多少字。0 = 不限。风格 skill 很长时可设 1200~1800 显著省 token。'),
143
157
  aiTemperature: Schema.number().min(0).max(2).step(0.1).default(0.8).description('生成温度(0~2)。群聊接话建议 0.7~0.9,过高会跑题、复述、发散。'),
144
158
  aiMaxOutputTokens: Schema.natural().default(400).description('AI 最大输出 token 数。群聊一句话不需要太大,过大会增加延迟。'),
145
159
  aiMaxReplyChars: Schema.natural().min(20).max(500).default(120).description('单条回复的最大字符数,超出会在句末截断。'),
package/src/service.js CHANGED
@@ -8,6 +8,8 @@ const koishi_1 = require("koishi");
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const node_fs_1 = __importDefault(require("node:fs"));
10
10
  const { AiEngine } = require("./ai/engine");
11
+ const { getSharedAiHooks } = require("./ai/hooks");
12
+ const { getAiRuntimeFacade } = require("./ai/runtime");
11
13
  let PLUGIN_VERSION = 'unknown';
12
14
  try {
13
15
  PLUGIN_VERSION = require('../package.json').version || 'unknown';
@@ -284,22 +286,32 @@ class QQGroupManagerService extends koishi_1.Service {
284
286
  this.ctx = ctx;
285
287
  this.config = config;
286
288
  this._logger = ctx.logger('nestim-qq-group-manager');
287
- this.ai = new AiEngine(this);
289
+ // 进程级共享钩子:主插件重载后仍是同一个对象,外部插件注册的钩子不会丢。
290
+ const sharedHooks = getSharedAiHooks(this._logger);
291
+ this.ai = new AiEngine(this, { hooks: sharedHooks });
288
292
  // Koishi 的 Service 注册在插件 fork 作用域,兄弟插件的 inject 拿不到;
289
- // 额外把扩展点挂到 root,外部插件 inject 'qqgmAiHooks' 即可。
293
+ // 额外把扩展点挂到 root,外部插件运行时探测即可。
294
+ //
295
+ // 关键:hooks 与 runtime 都必须是「进程级稳定对象」。主插件单独重载
296
+ // 时不能换成新对象,否则 meme / chat-style / private 手里的旧引用会
297
+ // 指向已销毁的实例:新引擎看不到它们的钩子(表情包不发、风格段丢失),
298
+ // 私聊还会继续用旧配置和旧引擎。
290
299
  try {
291
- ctx.root.set('qqgmAiHooks', this.ai.hooks);
292
- const runtime = {
293
- config: this.config,
294
- hooks: this.ai.hooks,
295
- chat: (request) => this.ai.chat(request),
296
- };
297
- ctx.root.set('qqgmAiRuntime', runtime);
300
+ const hooks = sharedHooks;
301
+ const facade = getAiRuntimeFacade();
302
+ facade.bind(this);
303
+ ctx.root.set('qqgmAiHooks', hooks);
304
+ ctx.root.set('qqgmAiRuntime', facade);
298
305
  ctx.on('dispose', () => {
299
306
  try {
300
- if (ctx.root.get('qqgmAiHooks') === this.ai.hooks)
307
+ facade.unbind(this);
308
+ // 只有当前没有新实例接管时才撤掉对外暴露:旧实例的 dispose
309
+ // 可能晚于新实例的 bind,此时不能把新指针清掉。
310
+ if (facade.current)
311
+ return;
312
+ if (ctx.root.get('qqgmAiHooks') === hooks)
301
313
  ctx.root.set('qqgmAiHooks', undefined);
302
- if (ctx.root.get('qqgmAiRuntime')?.hooks === this.ai.hooks)
314
+ if (ctx.root.get('qqgmAiRuntime') === facade)
303
315
  ctx.root.set('qqgmAiRuntime', undefined);
304
316
  }
305
317
  catch { /* ignore */ }
@@ -877,6 +889,42 @@ class QQGroupManagerService extends koishi_1.Service {
877
889
  return block;
878
890
  });
879
891
  }
892
+ /**
893
+ * 自动归纳专用写入:追加一条新记忆,并可同时删掉若干旧条目。
894
+ * 用于「每 N 条压缩成 1 条」——remove 里的旧条目会被新条目替换。
895
+ */
896
+ async commitAutoMemory(scope, payload) {
897
+ const add = String(payload && payload.add || '').trim();
898
+ if (!add)
899
+ return null;
900
+ const remove = new Set((payload && payload.remove || [])
901
+ .map((item) => String(item || '').trim())
902
+ .filter(Boolean));
903
+ const label = String(payload && payload.label || '自动归纳');
904
+ return this.runMemoryWriteLocked(async () => {
905
+ const now = new Date();
906
+ const stamp = now.toLocaleString('zh-CN', { hour12: false });
907
+ const block = `## ${stamp} · ${label}\n${add}`;
908
+ const existing = (await this.readMemoryFile(scope)).trim();
909
+ const blocks = this.extractMemoryBlocks(existing);
910
+ const kept = [];
911
+ let insertAt = -1;
912
+ for (const item of blocks) {
913
+ if (remove.has(item)) {
914
+ if (insertAt < 0)
915
+ insertAt = kept.length;
916
+ continue;
917
+ }
918
+ kept.push(item);
919
+ }
920
+ if (insertAt < 0)
921
+ insertAt = kept.length;
922
+ kept.splice(insertAt, 0, block);
923
+ const next = kept.length ? `${kept.join('\n\n---\n\n')}\n` : `${block}\n`;
924
+ await this.writeMemoryFile(next, scope);
925
+ return block;
926
+ });
927
+ }
880
928
  async searchMemory(keyword, limit = 8, scope) {
881
929
  const blocks = this.extractMemoryBlocks(await this.readMemoryFile(scope));
882
930
  const kw = String(keyword || '').trim();
@@ -2162,6 +2210,12 @@ class QQGroupManagerService extends koishi_1.Service {
2162
2210
  }
2163
2211
  await session.send(koishi_1.h.text(text));
2164
2212
  }
2213
+ /** 系统提示(例如「冷却中」),不引用原消息、不写入 AI 上下文 */
2214
+ async sendNotice(session, text) {
2215
+ if (!text)
2216
+ return;
2217
+ await session.send(koishi_1.h.text(String(text)));
2218
+ }
2165
2219
  extractTextForFilter(session) {
2166
2220
  const raw = (session.content ?? '')
2167
2221
  .replace(/<[^>]+>/g, ' ')