@nestim/koishi-plugin-qq-group-manager 1.4.9 → 1.4.10

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,32 @@
2
2
 
3
3
  本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
+ ## 1.4.10
6
+
7
+ ### 新功能
8
+
9
+ - **重启插件不再丢 AI 状态**(`persistAiState`,默认开)。
10
+
11
+ 之前上下文、消息计数、模型调用冷却、伪随机加成,以及「已被挤出但还没归纳」的消息
12
+ 都只在内存里。插件一重载就全部清空:机器人忘记刚聊过的内容,自动归纳重新计数,
13
+ 被挤出但没来得及总结的消息直接丢失。
14
+
15
+ 现在会持久化到 `data/qqgm-ai-state.json`:
16
+
17
+ - 每个群最近 6 小时内的上下文(条数仍受 `aiContextWindow` 限制);
18
+ - 消息计数、模型调用冷却、伪随机加成、点名跟随状态;
19
+ - 尚未归纳的消息桶与每日归纳次数(这些丢了就真丢了,全部恢复);
20
+ - 退出/重载时同步落盘,运行中每 3 秒防抖落盘一次;
21
+ - 原子写入(先写 `.tmp` 再 rename),文件损坏时静默回退为空状态;
22
+ - 只存文本、不存图片(Data URL 太大),重启后历史消息里的图片不会重发。
23
+
24
+ 关闭 `persistAiState` 则恢复旧行为:每次重启从头开始。
25
+
26
+ ### 说明
27
+
28
+ - 状态文件和记忆文件一样放在 Koishi 数据目录,可用控制台「探索器」查看;
29
+ - 这是插件自身能力,所有用户升级后默认生效,不依赖服务器脚本。
30
+
5
31
  ## 1.4.9
6
32
 
7
33
  ### 清理
@@ -72,7 +72,28 @@ export declare class AiEngine {
72
72
  private learnDaily;
73
73
  /** 自动归纳:空闲兜底定时器 */
74
74
  private learnTimer;
75
+ /** 状态持久化:退出/定时把上下文与待归纳桶写到 data/qqgm-ai-state.json */
76
+ private persistEnabled;
77
+ private persistTimer;
75
78
  constructor(host: AiHost, deps?: AiDeps);
79
+ /** 持久化文件路径(Koishi 数据目录下) */
80
+ private stateFilePath;
81
+ /** 精简一条记录用于落盘:去掉图片(Data URL 太大),文本做上限 */
82
+ private slimRecord;
83
+ private reviveRecord;
84
+ /**
85
+ * 恢复上次退出时的状态。
86
+ *
87
+ * - 最近上下文:只恢复 6 小时以内的,避免重启后把很久以前的消息当成“最近”;
88
+ * - 未归纳消息桶:全部恢复(它们还没变成记忆,丢了就真丢了);
89
+ * - 计数、模型调用冷却、伪随机加成、点名跟随:一并恢复。
90
+ */
91
+ private restorePersistedState;
92
+ /** 落盘当前状态(同步、原子替换,dispose 时调用) */
93
+ private flushPersistedState;
94
+ private snapshotState;
95
+ /** 防抖落盘:状态变化频繁,最多 3 秒写一次 */
96
+ private schedulePersist;
76
97
  private groupKey;
77
98
  private ruleFor;
78
99
  /**
@@ -116,7 +137,7 @@ export declare class AiEngine {
116
137
  /** 归纳并(可选)回推到原会话 */
117
138
  /** 启动空闲兜底定时器;每 5 分钟检查一次 */
118
139
  private startLearnTimer;
119
- /** 资源清理:停止定时器、清空缓存 */
140
+ /** 资源清理:落盘状态、停止定时器、清空缓存 */
120
141
  dispose(): void;
121
142
  private learnAndReport;
122
143
  /** 把一批消息归纳成一条记忆并写入对应作用域;返回写入结果或 null */
package/lib/ai/engine.js CHANGED
@@ -12,9 +12,34 @@
12
12
  * - 只回应当前消息,引用与回答永远一致;
13
13
  * - 允许模型用 <pass/> 主动放弃,放弃也重置计数,避免每条消息都空转调用。
14
14
  */
15
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ var desc = Object.getOwnPropertyDescriptor(m, k);
18
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
19
+ desc = { enumerable: true, get: function() { return m[k]; } };
20
+ }
21
+ Object.defineProperty(o, k2, desc);
22
+ }) : (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ o[k2] = m[k];
25
+ }));
26
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
27
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
28
+ }) : function(o, v) {
29
+ o["default"] = v;
30
+ });
31
+ var __importStar = (this && this.__importStar) || function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
15
38
  Object.defineProperty(exports, "__esModule", { value: true });
16
39
  exports.AiEngine = void 0;
17
40
  const state_1 = require("./state");
41
+ const fs = __importStar(require("node:fs"));
42
+ const path = __importStar(require("node:path"));
18
43
  const learn_1 = require("./learn");
19
44
  const trigger_1 = require("./trigger");
20
45
  const prompt_1 = require("./prompt");
@@ -94,6 +119,9 @@ class AiEngine {
94
119
  learnDaily = new Map();
95
120
  /** 自动归纳:空闲兜底定时器 */
96
121
  learnTimer = null;
122
+ /** 状态持久化:退出/定时把上下文与待归纳桶写到 data/qqgm-ai-state.json */
123
+ persistEnabled = true;
124
+ persistTimer = null;
97
125
  constructor(host, deps = {}) {
98
126
  this.host = host;
99
127
  this.config = host.config;
@@ -110,9 +138,211 @@ class AiEngine {
110
138
  this.rng = deps.rng ?? Math.random;
111
139
  this.now = deps.now ?? Date.now;
112
140
  this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
141
+ // 只有配置明确为 true 才持久化。生产环境 Schema 默认就是 true;
142
+ // 测试里用裸对象构造引擎时不会误写/误读仓库目录下的状态文件。
143
+ this.persistEnabled = host.config?.persistAiState === true;
144
+ this.restorePersistedState();
113
145
  // 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
114
146
  this.startLearnTimer();
115
147
  }
148
+ // ---------------------------------------------------------------- 持久化
149
+ /** 持久化文件路径(Koishi 数据目录下) */
150
+ stateFilePath() {
151
+ const base = this.host?.ctx?.baseDir || process.cwd();
152
+ return path.join(base, 'data', 'qqgm-ai-state.json');
153
+ }
154
+ /** 精简一条记录用于落盘:去掉图片(Data URL 太大),文本做上限 */
155
+ slimRecord(record) {
156
+ return {
157
+ id: String(record.id || ''),
158
+ userId: String(record.userId || ''),
159
+ name: String(record.name || ''),
160
+ role: record.role || 'unknown',
161
+ text: String(record.text || '').slice(0, 600),
162
+ quote: record.quote
163
+ ? {
164
+ name: String(record.quote.name || ''),
165
+ userId: String(record.quote.userId || ''),
166
+ text: String(record.quote.text || '').slice(0, 200),
167
+ id: String(record.quote.id || ''),
168
+ }
169
+ : undefined,
170
+ forwardText: record.forwardText ? String(record.forwardText).slice(0, 1200) : undefined,
171
+ mentions: Array.isArray(record.mentions) ? record.mentions.map(String).slice(0, 20) : [],
172
+ atBot: !!record.atBot,
173
+ self: !!record.self,
174
+ at: Number(record.at) || 0,
175
+ command: record.command ? true : undefined,
176
+ };
177
+ }
178
+ reviveRecord(raw) {
179
+ if (!raw || typeof raw !== 'object')
180
+ return null;
181
+ const text = String(raw.text || '').trim();
182
+ if (!text && !raw.command)
183
+ return null;
184
+ return {
185
+ id: String(raw.id || `restored-${Math.random().toString(36).slice(2, 8)}`),
186
+ userId: String(raw.userId || ''),
187
+ name: String(raw.name || raw.userId || ''),
188
+ role: raw.role || 'unknown',
189
+ text,
190
+ images: [],
191
+ quote: raw.quote?.text
192
+ ? {
193
+ name: String(raw.quote.name || ''),
194
+ userId: String(raw.quote.userId || ''),
195
+ text: String(raw.quote.text || ''),
196
+ id: String(raw.quote.id || ''),
197
+ images: [],
198
+ }
199
+ : undefined,
200
+ forwardText: raw.forwardText ? String(raw.forwardText) : undefined,
201
+ mentions: Array.isArray(raw.mentions) ? raw.mentions.map(String) : [],
202
+ atBot: !!raw.atBot,
203
+ self: !!raw.self,
204
+ at: Number(raw.at) || 0,
205
+ command: !!raw.command,
206
+ };
207
+ }
208
+ /**
209
+ * 恢复上次退出时的状态。
210
+ *
211
+ * - 最近上下文:只恢复 6 小时以内的,避免重启后把很久以前的消息当成“最近”;
212
+ * - 未归纳消息桶:全部恢复(它们还没变成记忆,丢了就真丢了);
213
+ * - 计数、模型调用冷却、伪随机加成、点名跟随:一并恢复。
214
+ */
215
+ restorePersistedState() {
216
+ if (!this.persistEnabled)
217
+ return;
218
+ const file = this.stateFilePath();
219
+ let data;
220
+ try {
221
+ data = JSON.parse(fs.readFileSync(file, 'utf8'));
222
+ }
223
+ catch {
224
+ return;
225
+ }
226
+ if (!data || data.version !== 1)
227
+ return;
228
+ const now = this.now();
229
+ const ttl = 6 * 60 * 60 * 1000;
230
+ let groups = 0;
231
+ let learns = 0;
232
+ for (const [key, raw] of Object.entries(data.groups || {})) {
233
+ const item = raw;
234
+ if (!item || typeof item !== 'object')
235
+ continue;
236
+ const st = new state_1.GroupState();
237
+ st.counter = Math.max(0, Number(item.counter) || 0);
238
+ st.lastAttemptAt = Math.max(0, Number(item.lastAttemptAt) || 0);
239
+ st.lastCooldownNoticeAt = Math.max(0, Number(item.lastCooldownNoticeAt) || 0);
240
+ st.randomBoost = Math.min(1, Math.max(0, Number(item.randomBoost) || 0));
241
+ const followup = item.followup;
242
+ if (followup && Number(followup.expiresAt) > now && typeof followup.userId === 'string') {
243
+ st.followup = followup;
244
+ }
245
+ st.records = (Array.isArray(item.records) ? item.records : [])
246
+ .map((record) => this.reviveRecord(record))
247
+ .filter((record) => !!record)
248
+ .filter((record) => now - record.at <= ttl);
249
+ if (st.records.length > this.contextWindow) {
250
+ st.records = st.records.slice(-this.contextWindow);
251
+ }
252
+ if (!st.records.length) {
253
+ st.counter = 0;
254
+ st.followup = null;
255
+ // 上下文过期就不恢复这个会话,避免凭空出现一个空状态
256
+ continue;
257
+ }
258
+ this.state.set(key, st);
259
+ groups += 1;
260
+ }
261
+ for (const [key, raw] of Object.entries(data.learn || {})) {
262
+ const item = raw;
263
+ const idx = key.indexOf(':');
264
+ if (idx < 0 || !item || typeof item !== 'object')
265
+ continue;
266
+ const bucket = new learn_1.LearnBucket();
267
+ bucket.records = (Array.isArray(item.records) ? item.records : [])
268
+ .map((record) => this.reviveRecord(record))
269
+ .filter((record) => !!record);
270
+ bucket.lastActivityAt = Number(item.lastActivityAt) || 0;
271
+ bucket.lastLearnedAt = Number(item.lastLearnedAt) || 0;
272
+ if (!bucket.records.length)
273
+ continue;
274
+ this.learnStore.set(key.slice(0, idx), key.slice(idx + 1), bucket);
275
+ learns += 1;
276
+ }
277
+ for (const pair of Array.isArray(data.learnDaily) ? data.learnDaily : []) {
278
+ if (Array.isArray(pair) && pair.length === 2) {
279
+ this.learnDaily.set(String(pair[0]), Math.max(0, Number(pair[1]) || 0));
280
+ }
281
+ }
282
+ if (groups || learns) {
283
+ this.host.logger?.info?.(`[ai-state] 已恢复 ${groups} 个会话、${learns} 个待归纳桶`);
284
+ }
285
+ }
286
+ /** 落盘当前状态(同步、原子替换,dispose 时调用) */
287
+ flushPersistedState() {
288
+ if (!this.persistEnabled)
289
+ return;
290
+ if (this.persistTimer) {
291
+ clearTimeout(this.persistTimer);
292
+ this.persistTimer = null;
293
+ }
294
+ try {
295
+ const file = this.stateFilePath();
296
+ fs.mkdirSync(path.dirname(file), { recursive: true });
297
+ const tmp = `${file}.tmp`;
298
+ fs.writeFileSync(tmp, JSON.stringify(this.snapshotState()), 'utf8');
299
+ fs.renameSync(tmp, file);
300
+ }
301
+ catch (error) {
302
+ this.host.logger?.warn?.(`[ai-state] 保存失败: ${String(error)}`);
303
+ }
304
+ }
305
+ snapshotState() {
306
+ const groups = {};
307
+ for (const [key, st] of this.state.entries()) {
308
+ if (!st.records.length && !st.counter && !st.randomBoost)
309
+ continue;
310
+ groups[key] = {
311
+ counter: st.counter,
312
+ lastAttemptAt: st.lastAttemptAt,
313
+ lastCooldownNoticeAt: st.lastCooldownNoticeAt,
314
+ randomBoost: st.randomBoost,
315
+ followup: st.followup,
316
+ records: st.records.map((record) => this.slimRecord(record)),
317
+ };
318
+ }
319
+ const learn = {};
320
+ for (const item of this.learnStore.entries()) {
321
+ learn[`${item.kind}:${item.scopeId}`] = {
322
+ lastActivityAt: item.bucket.lastActivityAt,
323
+ lastLearnedAt: item.bucket.lastLearnedAt,
324
+ records: item.bucket.records.map((record) => this.slimRecord(record)),
325
+ };
326
+ }
327
+ return {
328
+ version: 1,
329
+ savedAt: this.now(),
330
+ groups,
331
+ learn,
332
+ learnDaily: [...this.learnDaily.entries()],
333
+ };
334
+ }
335
+ /** 防抖落盘:状态变化频繁,最多 3 秒写一次 */
336
+ schedulePersist() {
337
+ if (!this.persistEnabled || this.persistTimer)
338
+ return;
339
+ this.persistTimer = setTimeout(() => {
340
+ this.persistTimer = null;
341
+ this.flushPersistedState();
342
+ }, 3000);
343
+ if (this.persistTimer.unref)
344
+ this.persistTimer.unref();
345
+ }
116
346
  // ---------------------------------------------------------------- 配置
117
347
  groupKey(session) {
118
348
  if (!session?.guildId)
@@ -260,6 +490,7 @@ class AiEngine {
260
490
  const evicted = state.push(record, contextWindow);
261
491
  this.emitEvicted(evicted, key, session);
262
492
  state.counter += 1;
493
+ this.schedulePersist();
263
494
  return record;
264
495
  }
265
496
  /** 追加一条系统注记(复读等),不进计数、不触发 */
@@ -282,6 +513,7 @@ class AiEngine {
282
513
  command: true,
283
514
  }, this.contextWindow);
284
515
  this.emitEvicted(evicted, groupKey, session);
516
+ this.schedulePersist();
285
517
  }
286
518
  /** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
287
519
  recordSelf(session, text) {
@@ -302,6 +534,7 @@ class AiEngine {
302
534
  at: this.now(),
303
535
  }, this.contextWindow);
304
536
  this.emitEvicted(evicted, key, session);
537
+ this.schedulePersist();
305
538
  }
306
539
  /**
307
540
  * 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
@@ -362,6 +595,7 @@ class AiEngine {
362
595
  const bucket = this.learnStore.get(kind, scopeId);
363
596
  const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
364
597
  const fire = bucket.push(evicted, threshold, this.now());
598
+ this.schedulePersist();
365
599
  if (fire) {
366
600
  void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
367
601
  }
@@ -390,8 +624,9 @@ class AiEngine {
390
624
  if (this.learnTimer.unref)
391
625
  this.learnTimer.unref();
392
626
  }
393
- /** 资源清理:停止定时器、清空缓存 */
627
+ /** 资源清理:落盘状态、停止定时器、清空缓存 */
394
628
  dispose() {
629
+ this.flushPersistedState();
395
630
  if (this.learnTimer) {
396
631
  clearInterval(this.learnTimer);
397
632
  this.learnTimer = null;
@@ -406,6 +641,7 @@ class AiEngine {
406
641
  const records = bucket.drain();
407
642
  if (!records.length)
408
643
  return;
644
+ this.schedulePersist();
409
645
  const scope = { kind, id: scopeId };
410
646
  const saved = await this.summarizeRecords(records, kind, scope, reason);
411
647
  if (!saved || !saved.text)
@@ -931,6 +1167,7 @@ class AiEngine {
931
1167
  }
932
1168
  finally {
933
1169
  state.inFlight = false;
1170
+ this.schedulePersist();
934
1171
  }
935
1172
  }
936
1173
  /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
@@ -1141,6 +1378,7 @@ class AiEngine {
1141
1378
  clear() {
1142
1379
  this.state.clear();
1143
1380
  this.names.clear();
1381
+ this.flushPersistedState();
1144
1382
  }
1145
1383
  }
1146
1384
  exports.AiEngine = AiEngine;
package/lib/ai/learn.d.ts CHANGED
@@ -38,6 +38,14 @@ export declare class LearnStore {
38
38
  scopeId: string;
39
39
  bucket: LearnBucket;
40
40
  }>;
41
+ /** 持久化用:遍历所有待归纳桶 */
42
+ entries(): Array<{
43
+ kind: string;
44
+ scopeId: string;
45
+ bucket: LearnBucket;
46
+ }>;
47
+ /** 持久化用:恢复一个待归纳桶 */
48
+ set(kind: string, scopeId: string, bucket: LearnBucket): void;
41
49
  clear(): void;
42
50
  }
43
51
  /** 把一批消息渲染成模型可读的文本 */
package/lib/ai/learn.js CHANGED
@@ -77,6 +77,21 @@ class LearnStore {
77
77
  }
78
78
  return out;
79
79
  }
80
+ /** 持久化用:遍历所有待归纳桶 */
81
+ entries() {
82
+ const out = [];
83
+ for (const [k, bucket] of this.map) {
84
+ if (!bucket.size)
85
+ continue;
86
+ const idx = k.indexOf(':');
87
+ out.push({ kind: k.slice(0, idx), scopeId: k.slice(idx + 1), bucket });
88
+ }
89
+ return out;
90
+ }
91
+ /** 持久化用:恢复一个待归纳桶 */
92
+ set(kind, scopeId, bucket) {
93
+ this.map.set(this.key(kind, scopeId), bucket);
94
+ }
80
95
  clear() {
81
96
  this.map.clear();
82
97
  }
package/lib/ai/state.d.ts CHANGED
@@ -56,5 +56,9 @@ export declare class AiState {
56
56
  private groups;
57
57
  get(key: string): GroupState;
58
58
  peek(key: string): GroupState | undefined;
59
+ /** 持久化用:遍历所有会话状态 */
60
+ entries(): Array<[string, GroupState]>;
61
+ /** 持久化用:恢复一个会话状态 */
62
+ set(key: string, state: GroupState): void;
59
63
  clear(): void;
60
64
  }
package/lib/ai/state.js CHANGED
@@ -61,6 +61,14 @@ class AiState {
61
61
  peek(key) {
62
62
  return this.groups.get(key);
63
63
  }
64
+ /** 持久化用:遍历所有会话状态 */
65
+ entries() {
66
+ return [...this.groups.entries()];
67
+ }
68
+ /** 持久化用:恢复一个会话状态 */
69
+ set(key, state) {
70
+ this.groups.set(key, state);
71
+ }
64
72
  clear() {
65
73
  this.groups.clear();
66
74
  }
package/lib/index.d.ts CHANGED
@@ -171,6 +171,7 @@ export declare const Config: Schema<Schemastery.ObjectS<{
171
171
  aiPseudoRandomStep: Schema<number, number>;
172
172
  aiMinReplyIntervalSeconds: Schema<number, number>;
173
173
  aiContextWindow: Schema<number, number>;
174
+ persistAiState: Schema<boolean, boolean>;
174
175
  aiContextMaxChars: Schema<number, number>;
175
176
  aiStyleMaxChars: Schema<number, number>;
176
177
  aiTemperature: Schema<number, number>;
@@ -337,6 +338,7 @@ export declare const Config: Schema<Schemastery.ObjectS<{
337
338
  aiPseudoRandomStep: number;
338
339
  aiMinReplyIntervalSeconds: number;
339
340
  aiContextWindow: number;
341
+ persistAiState: boolean;
340
342
  aiContextMaxChars: number;
341
343
  aiStyleMaxChars: number;
342
344
  aiTemperature: number;
package/lib/index.js CHANGED
@@ -154,6 +154,7 @@ exports.Config = koishi_1.Schema.intersect([
154
154
  aiPseudoRandomStep: koishi_1.Schema.number().min(0).max(1).step(0.001).default(0.01).description('伪随机每次未命中增加的概率(默认 0.01 = 1%)。只在真正掷骰且未命中时累加,冷却/阈值跳过不算。'),
155
155
  aiMinReplyIntervalSeconds: koishi_1.Schema.natural().default(45).description('同一群两次真正调用模型的最短间隔(秒)。'),
156
156
  aiContextWindow: koishi_1.Schema.natural().default(30).description('参与推理的最近消息条数(建议 20~40;太小会导致模型看不到前文)。'),
157
+ persistAiState: koishi_1.Schema.boolean().default(true).description('重启插件后恢复最近上下文、未归纳的消息桶、计数与冷却(保存到 data/qqgm-ai-state.json,只存文本、不存图片)。关闭则每次重启都从头开始。'),
157
158
  aiContextMaxChars: koishi_1.Schema.natural().min(0).max(20000).default(0).description('历史上下文的字数上限:超过后从最旧的消息开始丢(至少保留最近 4 条)。0 = 不限。想省 token 可设 2500~3500。'),
158
159
  aiStyleMaxChars: koishi_1.Schema.natural().min(0).max(20000).default(0).description('外部插件注入的「说话风格」段每条最多保留多少字。0 = 不限。风格 skill 很长时可设 1200~1800 显著省 token。'),
159
160
  aiTemperature: koishi_1.Schema.number().min(0).max(2).step(0.1).default(0.8).description('生成温度(0~2)。群聊接话建议 0.7~0.9,过高会跑题、复述、发散。'),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nestim/koishi-plugin-qq-group-manager",
3
3
  "description": "Koishi QQ群管理插件(OneBot/LLOneBot):群管命令、权限校验、图片菜单、状态卡片、复读、AI群聊回复、记忆库、识图与自动管控(禁言/踢人)。",
4
- "version": "1.4.9",
4
+ "version": "1.4.10",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
package/readme.md CHANGED
@@ -92,22 +92,30 @@ npm i @nestim/koishi-plugin-qq-group-manager
92
92
  | `bannedWordScoreThreshold` | `70` | 违禁词评分触发阈值(强关键词共用) |
93
93
  | `strongKeywords` | `[]` | 强关键词;命中即触发且**无视白名单豁免**,支持 `关键词\|分值` |
94
94
  | `groupRules` | `[]` | 按群覆盖策略(违禁词、强关键词、白名单关键词、AI 开关、自动处罚阈值等) |
95
- | `memoryFileName` | `Memory.md` | 记忆库基础文件名;分作用域时作为前缀 |
96
- | `memoryPerScope` | `true` | 按私聊/群聊分开存:`Memory_<群号>_群聊.md` / `Memory_<QQ号>_私聊.md` |
97
- | `memoryAutoLearn` | `false` | **AI 自动归纳记忆**(内建):上下文挤满后把消息总结成记忆并回推 |
98
- | `memoryLearnIdleHours` | `8` | 空闲兜底小时数;期间没有新消息则不触发 |
99
- | `memoryLearnThresholdScale` | `1` | 归纳阈值 = `aiContextWindow × 该值` |
100
- | `memoryLearnMaxChars` | `150` | 单条自动记忆字数上限 |
101
- | `memoryLearnPushBack` | `true` | 归纳后回推原会话(私聊发私聊、群聊发对应群) |
102
- | `memoryLearnDuplicateThreshold` | `0.55` | 相似度超此值跳过,避免重复记 |
95
+ | `memoryFileName` | `Memory.md` | 记忆库基础文件名;分作用域时作为前缀 |
96
+ | `memoryPerScope` | `true` | 按私聊/群聊分开存:`Memory_<群号>_群聊.md` / `Memory_<QQ号>_私聊.md` |
97
+ | `memoryAutoLearn` | `false` | **AI 自动归纳记忆**(内建):上下文挤满后把消息总结成记忆并回推 |
98
+ | `memoryLearnIdleHours` | `8` | 空闲兜底小时数;期间没有新消息则不触发 |
99
+ | `memoryLearnThresholdScale` | `1` | 归纳阈值 = `aiContextWindow × 该值` |
100
+ | `memoryLearnMaxChars` | `150` | 单条自动记忆字数上限 |
101
+ | `memoryLearnPushBack` | `true` | 归纳后回推原会话(私聊发私聊、群聊发对应群) |
102
+ | `memoryLearnDuplicateThreshold` | `0.55` | 相似度超此值跳过,避免重复记 |
103
103
  | `memoryLearnDailyLimit` | `30` | 每作用域每天最多归纳次数 |
104
+ | `memoryLearnConsolidate` | `true` | 自动记忆压缩:每 N 条合并成 1 条 |
105
+ | `memoryLearnConsolidateEvery` | `5` | 每多少条自动记忆压缩一次 |
106
+ | `memoryLearnMaxEntries` | `15` | 自动记忆条数上限(不含手动 `[memory]`) |
107
+ | `memoryLearnConsolidateMaxChars` | `90` | 压缩后单条记忆字数上限 |
108
+ | `memoryLearnModel` | 空 | 归纳/压缩专用模型,留空沿用 `aiModel` |
104
109
  | `blacklistFileName` | `banMember.md` | 黑名单文件名模板,实际为 `banMember_<群号>.md` |
105
110
  | `pendingJoinFileName` | `JoinRequests.md` | 待审入群申请落盘文件名 |
106
111
  | `enableJoinRequestReview` | `true` | 是否发起入群审核 |
107
112
  | `enableAiReply` | `false` | AI 回复总开关(建议配合 `aiReplyRequireGroupRule` 逐群开启) |
108
113
  | `aiReplyRequireGroupRule` | `true` | 仅对已在 `groupRules` 中单独配置的群启用 AI 回复 |
109
114
  | `aiContextWindow` | `30` | 进入提示词的消息条数(建议 20~40) |
110
- | `aiReplyDecision` | `single` | `single` 一次调用(推荐)/ `two-stage` 两次调用 |
115
+ | `persistAiState` | `true` | 重启后恢复最近上下文、未归纳消息、计数与冷却(保存到 `data/qqgm-ai-state.json`,只存文本) |
116
+ | `aiMaxOutputTokens` | `1500` | 思考 + 回答的总 token 上限(`max_tokens`),不是只限制正文 |
117
+ | `aiPseudoRandom` | `true` | 随机未命中时逐步提高概率,到 1 必定回复 |
118
+ | `aiPseudoRandomStep` | `0.01` | 每次未命中增加的概率 |
111
119
  | `aiMaxReplyChars` | `120` | 单条回复最大字符数 |
112
120
  | `aiQuoteReplyMode` | `random` | 回复是否引用触发消息:`random` / `always` / `never` |
113
121
  | `aiQuoteReplyProbability` | `0.5` | `random` 模式下的引用概率 |
@@ -167,7 +175,7 @@ npm i @nestim/koishi-plugin-qq-group-manager
167
175
  | 插件 | 作用 | 地址 |
168
176
  | --- | --- | --- |
169
177
  | `@nestim/koishi-plugin-qqgm-chat-style` | 聊天风格:一个主风格 + 多个按概率随机叠加的追加风格 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-chat-style) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-chat-style) |
170
- | `@nestim/koishi-plugin-qqgm-meme` | 表情包:AI 用 `[表情: 情绪]` 抽图,按概率补在文字后面 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-meme) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-meme) |
178
+ | `@nestim/koishi-plugin-qqgm-meme` | 表情包:AI 用 `[表情: 情绪]` 抽图,按概率补在文字后面 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-meme) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-meme) |
171
179
  | `@nestim/koishi-plugin-qqgm-private` | 私聊:AI 自动回复 + 定时主动私发 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-private) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-private) |
172
180
 
173
181
  定时提醒(`[提醒] 明天 8 点 开会`)**内建在本插件里**,不需要额外安装。
@@ -237,10 +245,11 @@ export function apply(ctx) {
237
245
 
238
246
  | 文件 | 内容 |
239
247
  | --- | --- |
240
- | `Memory_<群号>_群聊.md` | 该群的记忆,条目之间以 `---` 分隔 |
248
+ | `Memory_<群号>_群聊.md` | 该群的记忆,条目之间以 `---` 分隔 |
241
249
  | `Memory_<QQ号>_私聊.md` | 与该用户的私聊记忆 |
242
250
  | `banMember_<群号>.md` | 各群黑名单,`## QQ号 · 备注` + 加入时间 |
243
251
  | `JoinRequests.md` | 待审入群申请(人类可读表格 + 机器可读区段),重启自动恢复、过期自动清理 |
252
+ | `qqgm-ai-state.json` | AI 上下文与未归纳消息的持久化快照(`persistAiState`,只存文本、不存图片) |
244
253
 
245
254
  ## 权限模型
246
255
 
package/src/ai/engine.ts CHANGED
@@ -13,6 +13,8 @@
13
13
  */
14
14
 
15
15
  import { AiState, GroupState, ChatRecord, FollowupState } from './state';
16
+ import * as fs from 'node:fs';
17
+ import * as path from 'node:path';
16
18
  import {
17
19
  LearnBucket,
18
20
  LearnStore,
@@ -142,6 +144,9 @@ export class AiEngine {
142
144
  private learnDaily = new Map<string, number>();
143
145
  /** 自动归纳:空闲兜底定时器 */
144
146
  private learnTimer: any = null;
147
+ /** 状态持久化:退出/定时把上下文与待归纳桶写到 data/qqgm-ai-state.json */
148
+ private persistEnabled = true;
149
+ private persistTimer: any = null;
145
150
 
146
151
  constructor(host: AiHost, deps: AiDeps = {}) {
147
152
  this.host = host;
@@ -160,10 +165,215 @@ export class AiEngine {
160
165
  this.now = deps.now ?? Date.now;
161
166
  this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
162
167
 
168
+ // 只有配置明确为 true 才持久化。生产环境 Schema 默认就是 true;
169
+ // 测试里用裸对象构造引擎时不会误写/误读仓库目录下的状态文件。
170
+ this.persistEnabled = host.config?.persistAiState === true;
171
+ this.restorePersistedState();
172
+
163
173
  // 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
164
174
  this.startLearnTimer();
165
175
  }
166
176
 
177
+ // ---------------------------------------------------------------- 持久化
178
+
179
+ /** 持久化文件路径(Koishi 数据目录下) */
180
+ private stateFilePath(): string {
181
+ const base = (this.host as any)?.ctx?.baseDir || process.cwd();
182
+ return path.join(base, 'data', 'qqgm-ai-state.json');
183
+ }
184
+
185
+ /** 精简一条记录用于落盘:去掉图片(Data URL 太大),文本做上限 */
186
+ private slimRecord(record: ChatRecord): any {
187
+ return {
188
+ id: String(record.id || ''),
189
+ userId: String(record.userId || ''),
190
+ name: String(record.name || ''),
191
+ role: record.role || 'unknown',
192
+ text: String(record.text || '').slice(0, 600),
193
+ quote: record.quote
194
+ ? {
195
+ name: String((record.quote as any).name || ''),
196
+ userId: String((record.quote as any).userId || ''),
197
+ text: String((record.quote as any).text || '').slice(0, 200),
198
+ id: String((record.quote as any).id || ''),
199
+ }
200
+ : undefined,
201
+ forwardText: record.forwardText ? String(record.forwardText).slice(0, 1200) : undefined,
202
+ mentions: Array.isArray(record.mentions) ? record.mentions.map(String).slice(0, 20) : [],
203
+ atBot: !!record.atBot,
204
+ self: !!record.self,
205
+ at: Number(record.at) || 0,
206
+ command: record.command ? true : undefined,
207
+ };
208
+ }
209
+
210
+ private reviveRecord(raw: any): ChatRecord | null {
211
+ if (!raw || typeof raw !== 'object') return null;
212
+ const text = String(raw.text || '').trim();
213
+ if (!text && !raw.command) return null;
214
+ return {
215
+ id: String(raw.id || `restored-${Math.random().toString(36).slice(2, 8)}`),
216
+ userId: String(raw.userId || ''),
217
+ name: String(raw.name || raw.userId || ''),
218
+ role: raw.role || 'unknown',
219
+ text,
220
+ images: [],
221
+ quote: raw.quote?.text
222
+ ? {
223
+ name: String(raw.quote.name || ''),
224
+ userId: String(raw.quote.userId || ''),
225
+ text: String(raw.quote.text || ''),
226
+ id: String(raw.quote.id || ''),
227
+ images: [],
228
+ }
229
+ : undefined,
230
+ forwardText: raw.forwardText ? String(raw.forwardText) : undefined,
231
+ mentions: Array.isArray(raw.mentions) ? raw.mentions.map(String) : [],
232
+ atBot: !!raw.atBot,
233
+ self: !!raw.self,
234
+ at: Number(raw.at) || 0,
235
+ command: !!raw.command,
236
+ };
237
+ }
238
+
239
+ /**
240
+ * 恢复上次退出时的状态。
241
+ *
242
+ * - 最近上下文:只恢复 6 小时以内的,避免重启后把很久以前的消息当成“最近”;
243
+ * - 未归纳消息桶:全部恢复(它们还没变成记忆,丢了就真丢了);
244
+ * - 计数、模型调用冷却、伪随机加成、点名跟随:一并恢复。
245
+ */
246
+ private restorePersistedState(): void {
247
+ if (!this.persistEnabled) return;
248
+ const file = this.stateFilePath();
249
+ let data: any;
250
+ try {
251
+ data = JSON.parse(fs.readFileSync(file, 'utf8'));
252
+ } catch {
253
+ return;
254
+ }
255
+ if (!data || data.version !== 1) return;
256
+
257
+ const now = this.now();
258
+ const ttl = 6 * 60 * 60 * 1000;
259
+ let groups = 0;
260
+ let learns = 0;
261
+
262
+ for (const [key, raw] of Object.entries(data.groups || {})) {
263
+ const item: any = raw;
264
+ if (!item || typeof item !== 'object') continue;
265
+ const st = new GroupState();
266
+ st.counter = Math.max(0, Number(item.counter) || 0);
267
+ st.lastAttemptAt = Math.max(0, Number(item.lastAttemptAt) || 0);
268
+ st.lastCooldownNoticeAt = Math.max(0, Number(item.lastCooldownNoticeAt) || 0);
269
+ st.randomBoost = Math.min(1, Math.max(0, Number(item.randomBoost) || 0));
270
+ const followup = item.followup;
271
+ if (followup && Number(followup.expiresAt) > now && typeof followup.userId === 'string') {
272
+ st.followup = followup as FollowupState;
273
+ }
274
+ st.records = (Array.isArray(item.records) ? item.records : [])
275
+ .map((record: any) => this.reviveRecord(record))
276
+ .filter((record: ChatRecord | null): record is ChatRecord => !!record)
277
+ .filter((record: ChatRecord) => now - record.at <= ttl);
278
+ if (st.records.length > this.contextWindow) {
279
+ st.records = st.records.slice(-this.contextWindow);
280
+ }
281
+ if (!st.records.length) {
282
+ st.counter = 0;
283
+ st.followup = null;
284
+ // 上下文过期就不恢复这个会话,避免凭空出现一个空状态
285
+ continue;
286
+ }
287
+ this.state.set(key, st);
288
+ groups += 1;
289
+ }
290
+
291
+ for (const [key, raw] of Object.entries(data.learn || {})) {
292
+ const item: any = raw;
293
+ const idx = key.indexOf(':');
294
+ if (idx < 0 || !item || typeof item !== 'object') continue;
295
+ const bucket = new LearnBucket();
296
+ bucket.records = (Array.isArray(item.records) ? item.records : [])
297
+ .map((record: any) => this.reviveRecord(record))
298
+ .filter((record: ChatRecord | null): record is ChatRecord => !!record);
299
+ bucket.lastActivityAt = Number(item.lastActivityAt) || 0;
300
+ bucket.lastLearnedAt = Number(item.lastLearnedAt) || 0;
301
+ if (!bucket.records.length) continue;
302
+ this.learnStore.set(key.slice(0, idx), key.slice(idx + 1), bucket);
303
+ learns += 1;
304
+ }
305
+
306
+ for (const pair of Array.isArray(data.learnDaily) ? data.learnDaily : []) {
307
+ if (Array.isArray(pair) && pair.length === 2) {
308
+ this.learnDaily.set(String(pair[0]), Math.max(0, Number(pair[1]) || 0));
309
+ }
310
+ }
311
+
312
+ if (groups || learns) {
313
+ this.host.logger?.info?.(`[ai-state] 已恢复 ${groups} 个会话、${learns} 个待归纳桶`);
314
+ }
315
+ }
316
+
317
+ /** 落盘当前状态(同步、原子替换,dispose 时调用) */
318
+ private flushPersistedState(): void {
319
+ if (!this.persistEnabled) return;
320
+ if (this.persistTimer) {
321
+ clearTimeout(this.persistTimer);
322
+ this.persistTimer = null;
323
+ }
324
+ try {
325
+ const file = this.stateFilePath();
326
+ fs.mkdirSync(path.dirname(file), { recursive: true });
327
+ const tmp = `${file}.tmp`;
328
+ fs.writeFileSync(tmp, JSON.stringify(this.snapshotState()), 'utf8');
329
+ fs.renameSync(tmp, file);
330
+ } catch (error: any) {
331
+ this.host.logger?.warn?.(`[ai-state] 保存失败: ${String(error)}`);
332
+ }
333
+ }
334
+
335
+ private snapshotState(): any {
336
+ const groups: Record<string, any> = {};
337
+ for (const [key, st] of this.state.entries()) {
338
+ if (!st.records.length && !st.counter && !st.randomBoost) continue;
339
+ groups[key] = {
340
+ counter: st.counter,
341
+ lastAttemptAt: st.lastAttemptAt,
342
+ lastCooldownNoticeAt: st.lastCooldownNoticeAt,
343
+ randomBoost: st.randomBoost,
344
+ followup: st.followup,
345
+ records: st.records.map((record) => this.slimRecord(record)),
346
+ };
347
+ }
348
+
349
+ const learn: Record<string, any> = {};
350
+ for (const item of this.learnStore.entries()) {
351
+ learn[`${item.kind}:${item.scopeId}`] = {
352
+ lastActivityAt: item.bucket.lastActivityAt,
353
+ lastLearnedAt: item.bucket.lastLearnedAt,
354
+ records: item.bucket.records.map((record) => this.slimRecord(record as ChatRecord)),
355
+ };
356
+ }
357
+
358
+ return {
359
+ version: 1,
360
+ savedAt: this.now(),
361
+ groups,
362
+ learn,
363
+ learnDaily: [...this.learnDaily.entries()],
364
+ };
365
+ }
366
+
367
+ /** 防抖落盘:状态变化频繁,最多 3 秒写一次 */
368
+ private schedulePersist(): void {
369
+ if (!this.persistEnabled || this.persistTimer) return;
370
+ this.persistTimer = setTimeout(() => {
371
+ this.persistTimer = null;
372
+ this.flushPersistedState();
373
+ }, 3000);
374
+ if (this.persistTimer.unref) this.persistTimer.unref();
375
+ }
376
+
167
377
  // ---------------------------------------------------------------- 配置
168
378
 
169
379
  private groupKey(session: any): string {
@@ -318,6 +528,7 @@ export class AiEngine {
318
528
  const evicted = state.push(record, contextWindow);
319
529
  this.emitEvicted(evicted, key, session);
320
530
  state.counter += 1;
531
+ this.schedulePersist();
321
532
  return record;
322
533
  }
323
534
 
@@ -343,6 +554,7 @@ export class AiEngine {
343
554
  this.contextWindow,
344
555
  );
345
556
  this.emitEvicted(evicted, groupKey, session);
557
+ this.schedulePersist();
346
558
  }
347
559
 
348
560
  /** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
@@ -366,6 +578,7 @@ export class AiEngine {
366
578
  this.contextWindow,
367
579
  );
368
580
  this.emitEvicted(evicted, key, session);
581
+ this.schedulePersist();
369
582
  }
370
583
 
371
584
  /**
@@ -426,6 +639,7 @@ export class AiEngine {
426
639
  const bucket = this.learnStore.get(kind, scopeId);
427
640
  const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
428
641
  const fire = bucket.push(evicted, threshold, this.now());
642
+ this.schedulePersist();
429
643
  if (fire) {
430
644
  void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
431
645
  }
@@ -452,8 +666,9 @@ export class AiEngine {
452
666
  if (this.learnTimer.unref) this.learnTimer.unref();
453
667
  }
454
668
 
455
- /** 资源清理:停止定时器、清空缓存 */
669
+ /** 资源清理:落盘状态、停止定时器、清空缓存 */
456
670
  dispose(): void {
671
+ this.flushPersistedState();
457
672
  if (this.learnTimer) {
458
673
  clearInterval(this.learnTimer);
459
674
  this.learnTimer = null;
@@ -474,6 +689,7 @@ export class AiEngine {
474
689
  const cfg: any = this.config || {};
475
690
  const records = bucket.drain();
476
691
  if (!records.length) return;
692
+ this.schedulePersist();
477
693
 
478
694
  const scope = { kind, id: scopeId } as any;
479
695
  const saved = await this.summarizeRecords(records, kind, scope, reason);
@@ -1019,6 +1235,7 @@ export class AiEngine {
1019
1235
  }, session);
1020
1236
  } finally {
1021
1237
  state.inFlight = false;
1238
+ this.schedulePersist();
1022
1239
  }
1023
1240
  }
1024
1241
 
@@ -1232,5 +1449,6 @@ export class AiEngine {
1232
1449
  clear(): void {
1233
1450
  this.state.clear();
1234
1451
  this.names.clear();
1452
+ this.flushPersistedState();
1235
1453
  }
1236
1454
  }
package/src/ai/learn.ts CHANGED
@@ -82,6 +82,22 @@ export class LearnStore {
82
82
  return out;
83
83
  }
84
84
 
85
+ /** 持久化用:遍历所有待归纳桶 */
86
+ entries(): Array<{ kind: string; scopeId: string; bucket: LearnBucket }> {
87
+ const out: Array<{ kind: string; scopeId: string; bucket: LearnBucket }> = [];
88
+ for (const [k, bucket] of this.map) {
89
+ if (!bucket.size) continue;
90
+ const idx = k.indexOf(':');
91
+ out.push({ kind: k.slice(0, idx), scopeId: k.slice(idx + 1), bucket });
92
+ }
93
+ return out;
94
+ }
95
+
96
+ /** 持久化用:恢复一个待归纳桶 */
97
+ set(kind: string, scopeId: string, bucket: LearnBucket): void {
98
+ this.map.set(this.key(kind, scopeId), bucket);
99
+ }
100
+
85
101
  clear(): void {
86
102
  this.map.clear();
87
103
  }
package/src/ai/state.ts CHANGED
@@ -93,6 +93,16 @@ export class AiState {
93
93
  return this.groups.get(key);
94
94
  }
95
95
 
96
+ /** 持久化用:遍历所有会话状态 */
97
+ entries(): Array<[string, GroupState]> {
98
+ return [...this.groups.entries()];
99
+ }
100
+
101
+ /** 持久化用:恢复一个会话状态 */
102
+ set(key: string, state: GroupState): void {
103
+ this.groups.set(key, state);
104
+ }
105
+
96
106
  clear(): void {
97
107
  this.groups.clear();
98
108
  }
package/src/index.ts CHANGED
@@ -151,6 +151,7 @@ export const Config = Schema.intersect([
151
151
  aiPseudoRandomStep: Schema.number().min(0).max(1).step(0.001).default(0.01).description('伪随机每次未命中增加的概率(默认 0.01 = 1%)。只在真正掷骰且未命中时累加,冷却/阈值跳过不算。'),
152
152
  aiMinReplyIntervalSeconds: Schema.natural().default(45).description('同一群两次真正调用模型的最短间隔(秒)。'),
153
153
  aiContextWindow: Schema.natural().default(30).description('参与推理的最近消息条数(建议 20~40;太小会导致模型看不到前文)。'),
154
+ persistAiState: Schema.boolean().default(true).description('重启插件后恢复最近上下文、未归纳的消息桶、计数与冷却(保存到 data/qqgm-ai-state.json,只存文本、不存图片)。关闭则每次重启都从头开始。'),
154
155
  aiContextMaxChars: Schema.natural().min(0).max(20000).default(0).description('历史上下文的字数上限:超过后从最旧的消息开始丢(至少保留最近 4 条)。0 = 不限。想省 token 可设 2500~3500。'),
155
156
  aiStyleMaxChars: Schema.natural().min(0).max(20000).default(0).description('外部插件注入的「说话风格」段每条最多保留多少字。0 = 不限。风格 skill 很长时可设 1200~1800 显著省 token。'),
156
157
  aiTemperature: Schema.number().min(0).max(2).step(0.1).default(0.8).description('生成温度(0~2)。群聊接话建议 0.7~0.9,过高会跑题、复述、发散。'),