@nestim/koishi-plugin-qq-group-manager 1.4.8 → 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,63 @@
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
+
31
+ ## 1.4.9
32
+
33
+ ### 清理
34
+
35
+ - 删除一批无效或冗余配置项,配置页不再显示这些「意义不明」的开关:
36
+
37
+ - `aiReplyDecision`:`two-stage` 判定路径整体移除(判定提示词、判定函数一并删除),
38
+ 现在固定为「一次调用 + `<pass/>` 放弃」;
39
+ - `aiInterestMinScore`、`aiInterestContextWindow`、`aiInterestModel`、`aiInterestMaxTokens`:
40
+ 只服务于 two-stage,且后三个在代码里从未被读取;
41
+ - `aiMentionCooldownSeconds`:1.4.7 起模型调用冷却已统一,旧字段不再生效;
42
+ - `aiOwnerPlatform`、`aiOwnerUserId`、`aiHomePlatform`、`aiHomeUserId`、`aiIgnoreCommandMessage`:
43
+ 代码里没有任何引用,属于历史遗留;
44
+ - `responseStyle`:只会给指令回复加「喵~ 」前缀,需要喵味请在 qqgm-chat-style
45
+ 里加一个风格 skill(插件内已无引用,固定普通输出)。
46
+
47
+ 旧配置里残留的这些键会被 Schema 忽略,不影响启动。
48
+
49
+ ### 改进
50
+
51
+ - 模型调用日志补充思考 token:`tokens="in=…,out=…,cache=…,reasoning=…"`。
52
+ `out` 是 completion 总数(含思考),`reasoning` 是其中思维链的部分,
53
+ 可直接看出每次调用在思考上花了多少。
54
+
55
+ - **明确 `aiMaxOutputTokens` 的语义:它是「思考 + 回答」的总上限(API 的 `max_tokens`),
56
+ 不是只限制正文**。默认值从 400 调整为 1500(群聊接话建议 1000~2000):
57
+ 设得太小,预算会被思维链吃掉、正文被截断;设得太大,单次成本上限更高。
58
+
59
+ - 当服务端返回 `finish_reason=length`(触达 `max_tokens`)时输出一条
60
+ `[ai-budget]` 告警,提示正文可能被截断,并给出当前上限。
61
+
5
62
  ## 1.4.8
6
63
 
7
64
  ### 新功能
@@ -12,7 +12,7 @@
12
12
  * - 允许模型用 <pass/> 主动放弃,放弃也重置计数,避免每条消息都空转调用。
13
13
  */
14
14
  import { AiState, ChatRecord } from './state';
15
- import { ChatProvider, ChatResult } from './provider';
15
+ import { ChatProvider } from './provider';
16
16
  import { RenderedImage } from '../core/text';
17
17
  import { AiHookRegistry } from './hooks';
18
18
  export interface AiHost {
@@ -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 */
@@ -147,7 +168,7 @@ export declare class AiEngine {
147
168
  private sendCooldownNotice;
148
169
  handle(session: any): Promise<void>;
149
170
  /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
150
- chat(request: any): Promise<ChatResult>;
171
+ chat(request: any): Promise<import("./provider").ChatResult>;
151
172
  /** 群内长时间没人说话时,生成一条主动话题。 */
152
173
  idleTopic(groupId: string): Promise<string>;
153
174
  /** 需要时调用 DeepSeek Search API;失败/不支持/没结果都返回空串,继续普通回复。 */
@@ -158,7 +179,6 @@ export declare class AiEngine {
158
179
  private readForwards;
159
180
  private recentImageRecords;
160
181
  private collectImages;
161
- private judge;
162
182
  private platformAllowed;
163
183
  private log;
164
184
  /** 供指令/调试使用 */
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");
@@ -51,6 +76,8 @@ function usageText(usage) {
51
76
  const cacheHit = usage.prompt_cache_hit_tokens
52
77
  ?? usage.cached_tokens
53
78
  ?? usage.cache_read_input_tokens;
79
+ const reasoning = usage.completion_tokens_details?.reasoning_tokens
80
+ ?? usage.reasoning_tokens;
54
81
  const parts = [];
55
82
  if (input != null)
56
83
  parts.push(`in=${input}`);
@@ -58,6 +85,8 @@ function usageText(usage) {
58
85
  parts.push(`out=${output}`);
59
86
  if (cacheHit != null)
60
87
  parts.push(`cache=${cacheHit}`);
88
+ if (reasoning != null)
89
+ parts.push(`reasoning=${reasoning}`);
61
90
  return parts.join(',');
62
91
  }
63
92
  function clipReply(text, maxChars) {
@@ -90,6 +119,9 @@ class AiEngine {
90
119
  learnDaily = new Map();
91
120
  /** 自动归纳:空闲兜底定时器 */
92
121
  learnTimer = null;
122
+ /** 状态持久化:退出/定时把上下文与待归纳桶写到 data/qqgm-ai-state.json */
123
+ persistEnabled = true;
124
+ persistTimer = null;
93
125
  constructor(host, deps = {}) {
94
126
  this.host = host;
95
127
  this.config = host.config;
@@ -106,9 +138,211 @@ class AiEngine {
106
138
  this.rng = deps.rng ?? Math.random;
107
139
  this.now = deps.now ?? Date.now;
108
140
  this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
141
+ // 只有配置明确为 true 才持久化。生产环境 Schema 默认就是 true;
142
+ // 测试里用裸对象构造引擎时不会误写/误读仓库目录下的状态文件。
143
+ this.persistEnabled = host.config?.persistAiState === true;
144
+ this.restorePersistedState();
109
145
  // 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
110
146
  this.startLearnTimer();
111
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
+ }
112
346
  // ---------------------------------------------------------------- 配置
113
347
  groupKey(session) {
114
348
  if (!session?.guildId)
@@ -256,6 +490,7 @@ class AiEngine {
256
490
  const evicted = state.push(record, contextWindow);
257
491
  this.emitEvicted(evicted, key, session);
258
492
  state.counter += 1;
493
+ this.schedulePersist();
259
494
  return record;
260
495
  }
261
496
  /** 追加一条系统注记(复读等),不进计数、不触发 */
@@ -278,6 +513,7 @@ class AiEngine {
278
513
  command: true,
279
514
  }, this.contextWindow);
280
515
  this.emitEvicted(evicted, groupKey, session);
516
+ this.schedulePersist();
281
517
  }
282
518
  /** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
283
519
  recordSelf(session, text) {
@@ -298,6 +534,7 @@ class AiEngine {
298
534
  at: this.now(),
299
535
  }, this.contextWindow);
300
536
  this.emitEvicted(evicted, key, session);
537
+ this.schedulePersist();
301
538
  }
302
539
  /**
303
540
  * 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
@@ -358,6 +595,7 @@ class AiEngine {
358
595
  const bucket = this.learnStore.get(kind, scopeId);
359
596
  const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
360
597
  const fire = bucket.push(evicted, threshold, this.now());
598
+ this.schedulePersist();
361
599
  if (fire) {
362
600
  void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
363
601
  }
@@ -386,8 +624,9 @@ class AiEngine {
386
624
  if (this.learnTimer.unref)
387
625
  this.learnTimer.unref();
388
626
  }
389
- /** 资源清理:停止定时器、清空缓存 */
627
+ /** 资源清理:落盘状态、停止定时器、清空缓存 */
390
628
  dispose() {
629
+ this.flushPersistedState();
391
630
  if (this.learnTimer) {
392
631
  clearInterval(this.learnTimer);
393
632
  this.learnTimer = null;
@@ -402,6 +641,7 @@ class AiEngine {
402
641
  const records = bucket.drain();
403
642
  if (!records.length)
404
643
  return;
644
+ this.schedulePersist();
405
645
  const scope = { kind, id: scopeId };
406
646
  const saved = await this.summarizeRecords(records, kind, scope, reason);
407
647
  if (!saved || !saved.text)
@@ -768,8 +1008,6 @@ class AiEngine {
768
1008
  now: this.now(),
769
1009
  lastAttemptAt: state.lastAttemptAt,
770
1010
  minIntervalMs: Math.max(0, Number(this.setting(session, 'aiMinReplyIntervalSeconds') ?? 45)) * 1000,
771
- lastReplyAt: state.lastReplyAt || 0,
772
- mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
773
1011
  inFlight: state.inFlight,
774
1012
  mention,
775
1013
  followup,
@@ -826,14 +1064,6 @@ class AiEngine {
826
1064
  webSearch,
827
1065
  webSearchEnabled: this.config.aiWebSearchEnabled !== false,
828
1066
  };
829
- if (allowPass && this.config.aiReplyDecision === 'two-stage') {
830
- const judge = await this.judge(promptInput);
831
- if (!judge) {
832
- state.counter = 0;
833
- this.log('ai-pass', { by: 'judge', latencyMs: this.now() - startedAt }, session);
834
- return;
835
- }
836
- }
837
1067
  const prompt = (0, prompt_1.buildReplyPrompt)(promptInput);
838
1068
  if (this.debugPrompt) {
839
1069
  this.host.logger.info(`[ai-debug] system=${prompt.system}\n[ai-debug] user=${prompt.user}`);
@@ -855,6 +1085,11 @@ class AiEngine {
855
1085
  }, session);
856
1086
  return;
857
1087
  }
1088
+ if (result.finishReason === 'length') {
1089
+ const cap = Number(this.config.aiMaxOutputTokens ?? 1500);
1090
+ this.host.logger?.warn?.(`[ai-budget] 输出触达 max_tokens=${cap}(思考 + 回答总上限),正文可能被截断;`
1091
+ + `可在配置页调大 aiMaxOutputTokens | guild=${session.guildId ?? '?'}`);
1092
+ }
858
1093
  const raw = String(result.text || '').trim();
859
1094
  if (!raw || PASS_RE.test(raw)) {
860
1095
  state.counter = 0;
@@ -905,7 +1140,6 @@ class AiEngine {
905
1140
  return;
906
1141
  }
907
1142
  await this.host.sendReply(session, finalText);
908
- state.lastReplyAt = this.now();
909
1143
  state.counter = 0;
910
1144
  this.recordSelf(session, finalText);
911
1145
  if (mention)
@@ -933,6 +1167,7 @@ class AiEngine {
933
1167
  }
934
1168
  finally {
935
1169
  state.inFlight = false;
1170
+ this.schedulePersist();
936
1171
  }
937
1172
  }
938
1173
  /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
@@ -1125,29 +1360,6 @@ class AiEngine {
1125
1360
  return [];
1126
1361
  return (0, vision_1.resolveImages)(items, (ref) => this.host.resolveImage(ref, session), { maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) });
1127
1362
  }
1128
- async judge(input) {
1129
- const prompt = (0, prompt_1.buildJudgePrompt)(input);
1130
- const result = await this.provider.chat({
1131
- system: prompt.system,
1132
- user: prompt.user,
1133
- temperature: 0.1,
1134
- maxTokens: 256,
1135
- });
1136
- if (!result.ok || !result.text)
1137
- return false;
1138
- const match = result.text.match(/\{[\s\S]*\}/);
1139
- if (!match)
1140
- return false;
1141
- try {
1142
- const parsed = JSON.parse(match[0]);
1143
- const score = Number(parsed?.score) || 0;
1144
- const min = Number(this.config.aiInterestMinScore ?? 60);
1145
- return !!parsed?.reply && score >= min;
1146
- }
1147
- catch {
1148
- return false;
1149
- }
1150
- }
1151
1363
  platformAllowed(platform) {
1152
1364
  const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
1153
1365
  return list.includes(platform);
@@ -1166,6 +1378,7 @@ class AiEngine {
1166
1378
  clear() {
1167
1379
  this.state.clear();
1168
1380
  this.names.clear();
1381
+ this.flushPersistedState();
1169
1382
  }
1170
1383
  }
1171
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
  }
@@ -35,8 +35,3 @@ export declare function buildReplyPrompt(input: PromptInput): {
35
35
  system: string;
36
36
  user: string;
37
37
  };
38
- /** 两段式模式下的判定提示词(只有显式配置 aiReplyDecision=two-stage 才会用) */
39
- export declare function buildJudgePrompt(input: PromptInput): {
40
- system: string;
41
- user: string;
42
- };
package/lib/ai/prompt.js CHANGED
@@ -15,7 +15,6 @@ exports.renderRecordLine = renderRecordLine;
15
15
  exports.buildSystemPrompt = buildSystemPrompt;
16
16
  exports.buildUserPrompt = buildUserPrompt;
17
17
  exports.buildReplyPrompt = buildReplyPrompt;
18
- exports.buildJudgePrompt = buildJudgePrompt;
19
18
  const names_1 = require("../core/names");
20
19
  const text_1 = require("../core/text");
21
20
  exports.PASS_TOKEN = '<pass/>';
@@ -146,15 +145,3 @@ function buildReplyPrompt(input) {
146
145
  user: buildUserPrompt(input),
147
146
  };
148
147
  }
149
- /** 两段式模式下的判定提示词(只有显式配置 aiReplyDecision=two-stage 才会用) */
150
- function buildJudgePrompt(input) {
151
- const system = [
152
- '你是群聊回复开关判定器。',
153
- `当前群里有一个机器人,自称「${input.selfName}」。`,
154
- '判断机器人现在是否应该接话。',
155
- '只输出 JSON:{"reply":true|false,"score":0-100,"reason":"一句话"}。不要输出任何其它文字。',
156
- '标准:与机器人无关、别人正在对话、纯刷屏 → reply=false;被点名、被追问、有明显互动价值 → reply=true。',
157
- ].join('\n');
158
- const user = buildUserPrompt({ ...input, allowPass: false }).replace(/现在只输出一条回复正文。$/, '现在只输出判定 JSON。');
159
- return { system, user };
160
- }
@@ -25,6 +25,8 @@ export interface ChatResult {
25
25
  degradedToText?: boolean;
26
26
  /** 服务端 token 用量(OpenAI: usage;Gemini: usageMetadata) */
27
27
  usage?: any;
28
+ /** 停止原因:length 表示被 max_tokens / 上下文上限截断 */
29
+ finishReason?: string;
28
30
  }
29
31
  export interface ProviderConfig {
30
32
  aiProvider?: string;
@@ -144,7 +144,13 @@ class ChatProvider {
144
144
  error: `模型返回空内容(finish=${payload?.choices?.[0]?.finish_reason || 'unknown'})`,
145
145
  };
146
146
  }
147
- return { ok: true, text, status: response.status, usage: payload?.usage };
147
+ return {
148
+ ok: true,
149
+ text,
150
+ status: response.status,
151
+ usage: payload?.usage,
152
+ finishReason: payload?.choices?.[0]?.finish_reason,
153
+ };
148
154
  }
149
155
  catch (error) {
150
156
  const aborted = error?.name === 'AbortError';
@@ -195,7 +201,13 @@ class ChatProvider {
195
201
  .trim();
196
202
  if (!text)
197
203
  return { ok: false, status: response.status, error: 'Gemini 返回空内容' };
198
- return { ok: true, text, status: response.status, usage: payload?.usageMetadata };
204
+ return {
205
+ ok: true,
206
+ text,
207
+ status: response.status,
208
+ usage: payload?.usageMetadata,
209
+ finishReason: payload?.candidates?.[0]?.finishReason,
210
+ };
199
211
  }
200
212
  catch (error) {
201
213
  const aborted = error?.name === 'AbortError';
package/lib/ai/state.d.ts CHANGED
@@ -37,7 +37,6 @@ export declare class GroupState {
37
37
  records: ChatRecord[];
38
38
  /** 自上次"完整考虑"(真正调用了模型)以来累计的消息数 */
39
39
  counter: number;
40
- lastReplyAt: number;
41
40
  lastAttemptAt: number;
42
41
  /** 上次发「冷却中」提示的时间,用于避免 @ 刷屏时反复提示 */
43
42
  lastCooldownNoticeAt: number;
@@ -57,5 +56,9 @@ export declare class AiState {
57
56
  private groups;
58
57
  get(key: string): GroupState;
59
58
  peek(key: string): GroupState | undefined;
59
+ /** 持久化用:遍历所有会话状态 */
60
+ entries(): Array<[string, GroupState]>;
61
+ /** 持久化用:恢复一个会话状态 */
62
+ set(key: string, state: GroupState): void;
60
63
  clear(): void;
61
64
  }