@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 +57 -0
- package/lib/ai/engine.d.ts +24 -4
- package/lib/ai/engine.js +248 -35
- package/lib/ai/learn.d.ts +8 -0
- package/lib/ai/learn.js +15 -0
- package/lib/ai/prompt.d.ts +0 -5
- package/lib/ai/prompt.js +0 -13
- package/lib/ai/provider.d.ts +2 -0
- package/lib/ai/provider.js +14 -2
- package/lib/ai/state.d.ts +4 -1
- package/lib/ai/state.js +8 -1
- package/lib/ai/trigger.d.ts +0 -3
- package/lib/index.d.ts +2 -24
- package/lib/index.js +2 -19
- package/lib/service.js +2 -1
- package/package.json +1 -1
- package/readme.md +20 -11
- package/src/ai/engine.ts +232 -36
- package/src/ai/learn.ts +16 -0
- package/src/ai/prompt.ts +0 -16
- package/src/ai/provider.ts +16 -2
- package/src/ai/state.ts +10 -1
- package/src/ai/trigger.ts +0 -3
- package/src/index.ts +2 -19
- package/src/service.js +2 -1
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,
|
|
@@ -24,8 +26,8 @@ import {
|
|
|
24
26
|
AUTO_MEMORY_LABEL,
|
|
25
27
|
} from './learn';
|
|
26
28
|
import { decideTrigger } from './trigger';
|
|
27
|
-
import {
|
|
28
|
-
import { ChatProvider
|
|
29
|
+
import { buildReplyPrompt, buildUserPrompt } from './prompt';
|
|
30
|
+
import { ChatProvider } from './provider';
|
|
29
31
|
import { pickImages, resolveImages } from './vision';
|
|
30
32
|
import { selectMemoryBlocks, splitMemoryBlocks, tokenizeForMatch } from './memory';
|
|
31
33
|
import { NameResolver, MemberIdentity } from '../core/names';
|
|
@@ -97,10 +99,13 @@ function usageText(usage: any): string {
|
|
|
97
99
|
const cacheHit = usage.prompt_cache_hit_tokens
|
|
98
100
|
?? usage.cached_tokens
|
|
99
101
|
?? usage.cache_read_input_tokens;
|
|
102
|
+
const reasoning = usage.completion_tokens_details?.reasoning_tokens
|
|
103
|
+
?? usage.reasoning_tokens;
|
|
100
104
|
const parts: string[] = [];
|
|
101
105
|
if (input != null) parts.push(`in=${input}`);
|
|
102
106
|
if (output != null) parts.push(`out=${output}`);
|
|
103
107
|
if (cacheHit != null) parts.push(`cache=${cacheHit}`);
|
|
108
|
+
if (reasoning != null) parts.push(`reasoning=${reasoning}`);
|
|
104
109
|
return parts.join(',');
|
|
105
110
|
}
|
|
106
111
|
|
|
@@ -139,6 +144,9 @@ export class AiEngine {
|
|
|
139
144
|
private learnDaily = new Map<string, number>();
|
|
140
145
|
/** 自动归纳:空闲兜底定时器 */
|
|
141
146
|
private learnTimer: any = null;
|
|
147
|
+
/** 状态持久化:退出/定时把上下文与待归纳桶写到 data/qqgm-ai-state.json */
|
|
148
|
+
private persistEnabled = true;
|
|
149
|
+
private persistTimer: any = null;
|
|
142
150
|
|
|
143
151
|
constructor(host: AiHost, deps: AiDeps = {}) {
|
|
144
152
|
this.host = host;
|
|
@@ -157,10 +165,215 @@ export class AiEngine {
|
|
|
157
165
|
this.now = deps.now ?? Date.now;
|
|
158
166
|
this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
|
|
159
167
|
|
|
168
|
+
// 只有配置明确为 true 才持久化。生产环境 Schema 默认就是 true;
|
|
169
|
+
// 测试里用裸对象构造引擎时不会误写/误读仓库目录下的状态文件。
|
|
170
|
+
this.persistEnabled = host.config?.persistAiState === true;
|
|
171
|
+
this.restorePersistedState();
|
|
172
|
+
|
|
160
173
|
// 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
|
|
161
174
|
this.startLearnTimer();
|
|
162
175
|
}
|
|
163
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
|
+
|
|
164
377
|
// ---------------------------------------------------------------- 配置
|
|
165
378
|
|
|
166
379
|
private groupKey(session: any): string {
|
|
@@ -315,6 +528,7 @@ export class AiEngine {
|
|
|
315
528
|
const evicted = state.push(record, contextWindow);
|
|
316
529
|
this.emitEvicted(evicted, key, session);
|
|
317
530
|
state.counter += 1;
|
|
531
|
+
this.schedulePersist();
|
|
318
532
|
return record;
|
|
319
533
|
}
|
|
320
534
|
|
|
@@ -340,6 +554,7 @@ export class AiEngine {
|
|
|
340
554
|
this.contextWindow,
|
|
341
555
|
);
|
|
342
556
|
this.emitEvicted(evicted, groupKey, session);
|
|
557
|
+
this.schedulePersist();
|
|
343
558
|
}
|
|
344
559
|
|
|
345
560
|
/** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
|
|
@@ -363,6 +578,7 @@ export class AiEngine {
|
|
|
363
578
|
this.contextWindow,
|
|
364
579
|
);
|
|
365
580
|
this.emitEvicted(evicted, key, session);
|
|
581
|
+
this.schedulePersist();
|
|
366
582
|
}
|
|
367
583
|
|
|
368
584
|
/**
|
|
@@ -423,6 +639,7 @@ export class AiEngine {
|
|
|
423
639
|
const bucket = this.learnStore.get(kind, scopeId);
|
|
424
640
|
const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
|
|
425
641
|
const fire = bucket.push(evicted, threshold, this.now());
|
|
642
|
+
this.schedulePersist();
|
|
426
643
|
if (fire) {
|
|
427
644
|
void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
|
|
428
645
|
}
|
|
@@ -449,8 +666,9 @@ export class AiEngine {
|
|
|
449
666
|
if (this.learnTimer.unref) this.learnTimer.unref();
|
|
450
667
|
}
|
|
451
668
|
|
|
452
|
-
/**
|
|
669
|
+
/** 资源清理:落盘状态、停止定时器、清空缓存 */
|
|
453
670
|
dispose(): void {
|
|
671
|
+
this.flushPersistedState();
|
|
454
672
|
if (this.learnTimer) {
|
|
455
673
|
clearInterval(this.learnTimer);
|
|
456
674
|
this.learnTimer = null;
|
|
@@ -471,6 +689,7 @@ export class AiEngine {
|
|
|
471
689
|
const cfg: any = this.config || {};
|
|
472
690
|
const records = bucket.drain();
|
|
473
691
|
if (!records.length) return;
|
|
692
|
+
this.schedulePersist();
|
|
474
693
|
|
|
475
694
|
const scope = { kind, id: scopeId } as any;
|
|
476
695
|
const saved = await this.summarizeRecords(records, kind, scope, reason);
|
|
@@ -845,8 +1064,6 @@ export class AiEngine {
|
|
|
845
1064
|
now: this.now(),
|
|
846
1065
|
lastAttemptAt: state.lastAttemptAt,
|
|
847
1066
|
minIntervalMs: Math.max(0, Number(this.setting(session, 'aiMinReplyIntervalSeconds') ?? 45)) * 1000,
|
|
848
|
-
lastReplyAt: state.lastReplyAt || 0,
|
|
849
|
-
mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
|
|
850
1067
|
inFlight: state.inFlight,
|
|
851
1068
|
mention,
|
|
852
1069
|
followup,
|
|
@@ -906,15 +1123,6 @@ export class AiEngine {
|
|
|
906
1123
|
webSearchEnabled: this.config.aiWebSearchEnabled !== false,
|
|
907
1124
|
};
|
|
908
1125
|
|
|
909
|
-
if (allowPass && this.config.aiReplyDecision === 'two-stage') {
|
|
910
|
-
const judge = await this.judge(promptInput);
|
|
911
|
-
if (!judge) {
|
|
912
|
-
state.counter = 0;
|
|
913
|
-
this.log('ai-pass', { by: 'judge', latencyMs: this.now() - startedAt }, session);
|
|
914
|
-
return;
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
|
|
918
1126
|
const prompt = buildReplyPrompt(promptInput);
|
|
919
1127
|
if (this.debugPrompt) {
|
|
920
1128
|
this.host.logger.info(`[ai-debug] system=${prompt.system}\n[ai-debug] user=${prompt.user}`);
|
|
@@ -939,6 +1147,14 @@ export class AiEngine {
|
|
|
939
1147
|
return;
|
|
940
1148
|
}
|
|
941
1149
|
|
|
1150
|
+
if (result.finishReason === 'length') {
|
|
1151
|
+
const cap = Number(this.config.aiMaxOutputTokens ?? 1500);
|
|
1152
|
+
this.host.logger?.warn?.(
|
|
1153
|
+
`[ai-budget] 输出触达 max_tokens=${cap}(思考 + 回答总上限),正文可能被截断;`
|
|
1154
|
+
+ `可在配置页调大 aiMaxOutputTokens | guild=${session.guildId ?? '?'}`,
|
|
1155
|
+
);
|
|
1156
|
+
}
|
|
1157
|
+
|
|
942
1158
|
const raw = String(result.text || '').trim();
|
|
943
1159
|
if (!raw || PASS_RE.test(raw)) {
|
|
944
1160
|
state.counter = 0;
|
|
@@ -993,7 +1209,6 @@ export class AiEngine {
|
|
|
993
1209
|
}
|
|
994
1210
|
|
|
995
1211
|
await this.host.sendReply(session, finalText);
|
|
996
|
-
state.lastReplyAt = this.now();
|
|
997
1212
|
state.counter = 0;
|
|
998
1213
|
this.recordSelf(session, finalText);
|
|
999
1214
|
|
|
@@ -1020,6 +1235,7 @@ export class AiEngine {
|
|
|
1020
1235
|
}, session);
|
|
1021
1236
|
} finally {
|
|
1022
1237
|
state.inFlight = false;
|
|
1238
|
+
this.schedulePersist();
|
|
1023
1239
|
}
|
|
1024
1240
|
}
|
|
1025
1241
|
|
|
@@ -1210,27 +1426,6 @@ export class AiEngine {
|
|
|
1210
1426
|
);
|
|
1211
1427
|
}
|
|
1212
1428
|
|
|
1213
|
-
private async judge(input: any): Promise<boolean> {
|
|
1214
|
-
const prompt = buildJudgePrompt(input);
|
|
1215
|
-
const result: ChatResult = await this.provider.chat({
|
|
1216
|
-
system: prompt.system,
|
|
1217
|
-
user: prompt.user,
|
|
1218
|
-
temperature: 0.1,
|
|
1219
|
-
maxTokens: 256,
|
|
1220
|
-
});
|
|
1221
|
-
if (!result.ok || !result.text) return false;
|
|
1222
|
-
const match = result.text.match(/\{[\s\S]*\}/);
|
|
1223
|
-
if (!match) return false;
|
|
1224
|
-
try {
|
|
1225
|
-
const parsed = JSON.parse(match[0]);
|
|
1226
|
-
const score = Number(parsed?.score) || 0;
|
|
1227
|
-
const min = Number(this.config.aiInterestMinScore ?? 60);
|
|
1228
|
-
return !!parsed?.reply && score >= min;
|
|
1229
|
-
} catch {
|
|
1230
|
-
return false;
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
|
|
1234
1429
|
private platformAllowed(platform: string): boolean {
|
|
1235
1430
|
const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
|
|
1236
1431
|
return list.includes(platform);
|
|
@@ -1254,5 +1449,6 @@ export class AiEngine {
|
|
|
1254
1449
|
clear(): void {
|
|
1255
1450
|
this.state.clear();
|
|
1256
1451
|
this.names.clear();
|
|
1452
|
+
this.flushPersistedState();
|
|
1257
1453
|
}
|
|
1258
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/prompt.ts
CHANGED
|
@@ -167,19 +167,3 @@ export function buildReplyPrompt(input: PromptInput): { system: string; user: st
|
|
|
167
167
|
user: buildUserPrompt(input),
|
|
168
168
|
};
|
|
169
169
|
}
|
|
170
|
-
|
|
171
|
-
/** 两段式模式下的判定提示词(只有显式配置 aiReplyDecision=two-stage 才会用) */
|
|
172
|
-
export function buildJudgePrompt(input: PromptInput): { system: string; user: string } {
|
|
173
|
-
const system = [
|
|
174
|
-
'你是群聊回复开关判定器。',
|
|
175
|
-
`当前群里有一个机器人,自称「${input.selfName}」。`,
|
|
176
|
-
'判断机器人现在是否应该接话。',
|
|
177
|
-
'只输出 JSON:{"reply":true|false,"score":0-100,"reason":"一句话"}。不要输出任何其它文字。',
|
|
178
|
-
'标准:与机器人无关、别人正在对话、纯刷屏 → reply=false;被点名、被追问、有明显互动价值 → reply=true。',
|
|
179
|
-
].join('\n');
|
|
180
|
-
const user = buildUserPrompt({ ...input, allowPass: false }).replace(
|
|
181
|
-
/现在只输出一条回复正文。$/,
|
|
182
|
-
'现在只输出判定 JSON。',
|
|
183
|
-
);
|
|
184
|
-
return { system, user };
|
|
185
|
-
}
|
package/src/ai/provider.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface ChatResult {
|
|
|
27
27
|
degradedToText?: boolean;
|
|
28
28
|
/** 服务端 token 用量(OpenAI: usage;Gemini: usageMetadata) */
|
|
29
29
|
usage?: any;
|
|
30
|
+
/** 停止原因:length 表示被 max_tokens / 上下文上限截断 */
|
|
31
|
+
finishReason?: string;
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
export interface ProviderConfig {
|
|
@@ -185,7 +187,13 @@ export class ChatProvider {
|
|
|
185
187
|
error: `模型返回空内容(finish=${payload?.choices?.[0]?.finish_reason || 'unknown'})`,
|
|
186
188
|
};
|
|
187
189
|
}
|
|
188
|
-
return {
|
|
190
|
+
return {
|
|
191
|
+
ok: true,
|
|
192
|
+
text,
|
|
193
|
+
status: response.status,
|
|
194
|
+
usage: payload?.usage,
|
|
195
|
+
finishReason: payload?.choices?.[0]?.finish_reason,
|
|
196
|
+
};
|
|
189
197
|
} catch (error: any) {
|
|
190
198
|
const aborted = error?.name === 'AbortError';
|
|
191
199
|
return { ok: false, error: aborted ? '请求超时' : `请求失败: ${String(error?.message || error)}` };
|
|
@@ -234,7 +242,13 @@ export class ChatProvider {
|
|
|
234
242
|
.join('')
|
|
235
243
|
.trim();
|
|
236
244
|
if (!text) return { ok: false, status: response.status, error: 'Gemini 返回空内容' };
|
|
237
|
-
return {
|
|
245
|
+
return {
|
|
246
|
+
ok: true,
|
|
247
|
+
text,
|
|
248
|
+
status: response.status,
|
|
249
|
+
usage: payload?.usageMetadata,
|
|
250
|
+
finishReason: payload?.candidates?.[0]?.finishReason,
|
|
251
|
+
};
|
|
238
252
|
} catch (error: any) {
|
|
239
253
|
const aborted = error?.name === 'AbortError';
|
|
240
254
|
return { ok: false, error: aborted ? '请求超时' : `请求失败: ${String(error?.message || error)}` };
|
package/src/ai/state.ts
CHANGED
|
@@ -41,7 +41,6 @@ export class GroupState {
|
|
|
41
41
|
records: ChatRecord[] = [];
|
|
42
42
|
/** 自上次"完整考虑"(真正调用了模型)以来累计的消息数 */
|
|
43
43
|
counter = 0;
|
|
44
|
-
lastReplyAt = 0;
|
|
45
44
|
lastAttemptAt = 0;
|
|
46
45
|
/** 上次发「冷却中」提示的时间,用于避免 @ 刷屏时反复提示 */
|
|
47
46
|
lastCooldownNoticeAt = 0;
|
|
@@ -94,6 +93,16 @@ export class AiState {
|
|
|
94
93
|
return this.groups.get(key);
|
|
95
94
|
}
|
|
96
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
|
+
|
|
97
106
|
clear(): void {
|
|
98
107
|
this.groups.clear();
|
|
99
108
|
}
|
package/src/ai/trigger.ts
CHANGED
|
@@ -17,9 +17,6 @@ export interface TriggerInput {
|
|
|
17
17
|
now: number;
|
|
18
18
|
lastAttemptAt: number;
|
|
19
19
|
minIntervalMs: number;
|
|
20
|
-
/** 兼容字段:旧版按“上次回复”计算的 @ 冷却,已合并进 minIntervalMs */
|
|
21
|
-
lastReplyAt?: number;
|
|
22
|
-
mentionCooldownMs?: number;
|
|
23
20
|
inFlight: boolean;
|
|
24
21
|
mention: boolean;
|
|
25
22
|
followup: boolean;
|
package/src/index.ts
CHANGED
|
@@ -15,10 +15,6 @@ export const Config = Schema.intersect([
|
|
|
15
15
|
cmdCustom: Schema.string().default('[custom]').description('自定义指令集前缀,用法:[custom]。未配置自定义指令时提示「目前还没有指令」。'),
|
|
16
16
|
cmdVersion: Schema.string().default('[Version]').description('插件信息指令前缀,用法:[Version]。返回当前版本、作者、GitHub 与 npm 地址。'),
|
|
17
17
|
platformFilter: Schema.array(String).default(['onebot']).description('允许启用管理功能的平台列表。'),
|
|
18
|
-
responseStyle: Schema.union([
|
|
19
|
-
Schema.const('plain').description('普通输出'),
|
|
20
|
-
Schema.const('meow').description('Meow 风格输出'),
|
|
21
|
-
]).role('radio').default('plain').description('群聊中指令返回的文本风格。'),
|
|
22
18
|
dryRun: Schema.boolean().default(false).description('演练模式:仅输出计划动作,不执行群管理操作。'),
|
|
23
19
|
}).description('基础设置'),
|
|
24
20
|
Schema.object({
|
|
@@ -130,7 +126,6 @@ export const Config = Schema.intersect([
|
|
|
130
126
|
aiBaseUrl: Schema.string().default('https://api.openai.com/v1').description('接口基础地址(OpenAI 兼容模式需以 /v1 结尾;Gemini 模式可留默认)。'),
|
|
131
127
|
aiModel: Schema.string().default('gpt-4o-mini').description('模型名称,如 gpt-4o-mini / doubao-1.5-lite / gemini-2.0-flash。'),
|
|
132
128
|
aiAgentName: Schema.string().default('bot').description('默认智能体自称(可在配置页修改)。'),
|
|
133
|
-
aiMentionCooldownSeconds: Schema.natural().min(0).max(3600).default(5).description('(兼容字段)旧的 @ 冷却;现在所有模型调用统一走 aiMinReplyIntervalSeconds。'),
|
|
134
129
|
aiCooldownNotice: Schema.boolean().default(true).description('被 @ 但处于模型调用冷却时,是否在群里提示还剩多久(纯本地消息,不调用模型)。'),
|
|
135
130
|
aiCooldownNoticeText: Schema.string().default('还在冷却,{seconds} 秒后再叫我。').description('冷却提示文案,可用 {seconds} 与 {minutes} 占位。'),
|
|
136
131
|
aiCooldownNoticeIntervalSeconds: Schema.natural().min(0).max(600).default(20).description('同一群两次冷却提示的最小间隔(秒),防止连续 @ 刷屏;0 = 不限制。'),
|
|
@@ -156,10 +151,11 @@ export const Config = Schema.intersect([
|
|
|
156
151
|
aiPseudoRandomStep: Schema.number().min(0).max(1).step(0.001).default(0.01).description('伪随机每次未命中增加的概率(默认 0.01 = 1%)。只在真正掷骰且未命中时累加,冷却/阈值跳过不算。'),
|
|
157
152
|
aiMinReplyIntervalSeconds: Schema.natural().default(45).description('同一群两次真正调用模型的最短间隔(秒)。'),
|
|
158
153
|
aiContextWindow: Schema.natural().default(30).description('参与推理的最近消息条数(建议 20~40;太小会导致模型看不到前文)。'),
|
|
154
|
+
persistAiState: Schema.boolean().default(true).description('重启插件后恢复最近上下文、未归纳的消息桶、计数与冷却(保存到 data/qqgm-ai-state.json,只存文本、不存图片)。关闭则每次重启都从头开始。'),
|
|
159
155
|
aiContextMaxChars: Schema.natural().min(0).max(20000).default(0).description('历史上下文的字数上限:超过后从最旧的消息开始丢(至少保留最近 4 条)。0 = 不限。想省 token 可设 2500~3500。'),
|
|
160
156
|
aiStyleMaxChars: Schema.natural().min(0).max(20000).default(0).description('外部插件注入的「说话风格」段每条最多保留多少字。0 = 不限。风格 skill 很长时可设 1200~1800 显著省 token。'),
|
|
161
157
|
aiTemperature: Schema.number().min(0).max(2).step(0.1).default(0.8).description('生成温度(0~2)。群聊接话建议 0.7~0.9,过高会跑题、复述、发散。'),
|
|
162
|
-
aiMaxOutputTokens: Schema.natural().default(
|
|
158
|
+
aiMaxOutputTokens: Schema.natural().min(100).max(131072).default(1500).description('思考 + 回答的总 token 上限(API 的 max_tokens,不是只限制正文)。思考模式开启时思维链也计入这里:设得太小,预算会被思考吃掉、正文被截断;设得太大则单次成本上限更高。群聊接话建议 1000~2000。'),
|
|
163
159
|
aiMaxReplyChars: Schema.natural().min(20).max(500).default(120).description('单条回复的最大字符数,超出会在句末截断。'),
|
|
164
160
|
aiQuoteReplyMode: Schema.union([
|
|
165
161
|
Schema.const('random').description('随机决定'),
|
|
@@ -169,10 +165,6 @@ export const Config = Schema.intersect([
|
|
|
169
165
|
aiQuoteReplyProbability: Schema.number().min(0).max(1).step(0.05).default(0.5).hidden().description('引用概率(仅 random 模式生效)。'),
|
|
170
166
|
aiReadForwardMessage: Schema.boolean().default(true).description('读取合并转发聊天记录的内容,作为上下文的一部分。'),
|
|
171
167
|
aiForwardMaxNodes: Schema.natural().min(1).max(50).default(20).description('单条合并转发最多读取多少条子消息。'),
|
|
172
|
-
aiReplyDecision: Schema.union([
|
|
173
|
-
Schema.const('single').description('一次调用:模型直接输出回复,或用 <pass/> 放弃(推荐)'),
|
|
174
|
-
Schema.const('two-stage').description('两次调用:先判定是否值得回复,再生成正文'),
|
|
175
|
-
]).role('radio').default('single').description('接话决策方式。single 更快、决策与正文一致;two-stage 更省生成成本但多一次延迟。'),
|
|
176
168
|
aiEnableImageRecognition: Schema.boolean().default(true).description('是否启用图片识别(支持时将图片一并发送给模型;不支持的模型会自动降级为纯文本)。'),
|
|
177
169
|
aiImageMaxCount: Schema.natural().default(2).description('每次最多发送给模型的图片数量。'),
|
|
178
170
|
aiImageBudgetMs: Schema.natural().min(500).max(20000).default(6000).description('图片下载/转换的总时间预算(毫秒)。超时直接跳过图片,避免拖慢回复。'),
|
|
@@ -188,19 +180,10 @@ export const Config = Schema.intersect([
|
|
|
188
180
|
aiWebSearchCacheMinutes: Schema.natural().min(0).max(1440).default(10).description('相同 query 的结果缓存分钟数;0=不缓存。'),
|
|
189
181
|
aiRequestTimeoutSeconds: Schema.natural().min(5).max(120).default(20).description('单次模型请求超时(秒)。'),
|
|
190
182
|
aiDebugPrompt: Schema.boolean().default(false).description('调试:把最终系统提示词与用户提示词写入日志(排查"答非所问"时打开,平时关闭)。'),
|
|
191
|
-
aiIgnoreCommandMessage: Schema.boolean().default(true).description('忽略看起来像命令的消息,避免干扰正常指令执行。'),
|
|
192
183
|
aiEnableDirectMentionTrigger: Schema.boolean().default(true).description('消息命中智能体名字时是否忽略阈值直接触发回复。'),
|
|
193
184
|
aiEnableFollowupAfterMention: Schema.boolean().default(true).description('点名触发后,是否跟随该用户一段时间继续对话。'),
|
|
194
185
|
aiFollowupWindowSeconds: Schema.natural().default(120).description('点名后跟随该用户的持续时间(秒)。'),
|
|
195
186
|
aiFollowupMaxTurns: Schema.natural().default(3).description('一次点名会话最多继续回复轮数。'),
|
|
196
|
-
aiOwnerPlatform: Schema.string().default('onebot').description('主人平台标识(用于识别主人用户,如 onebot)。'),
|
|
197
|
-
aiOwnerUserId: Schema.string().default('').description('主人平台用户 ID(如 QQ 号,用于记忆主人身份)。'),
|
|
198
|
-
aiHomePlatform: Schema.string().default('onebot').description('兼容字段:主页平台标识(建议改用 aiOwnerPlatform)。'),
|
|
199
|
-
aiHomeUserId: Schema.string().default('').description('兼容字段:主页平台用户 ID(建议改用 aiOwnerUserId)。'),
|
|
200
|
-
aiInterestMinScore: Schema.number().min(0).max(100).step(1).default(82).description('(仅 aiReplyDecision=two-stage 时生效)判定为值得回复的最低分。'),
|
|
201
|
-
aiInterestContextWindow: Schema.number().min(4).max(16).step(1).default(8).description('(仅 two-stage 生效)判定使用的上下文窗口条数。'),
|
|
202
|
-
aiInterestModel: Schema.string().default('').description('(仅 two-stage 生效)判定专用模型(留空沿用 aiModel)。'),
|
|
203
|
-
aiInterestMaxTokens: Schema.natural().min(256).max(16384).default(2048).description('(仅 two-stage 生效)判定的最大输出 token。'),
|
|
204
187
|
}).description('AI 回复'),
|
|
205
188
|
Schema.object({
|
|
206
189
|
allowedUserIds: Schema.array(String).role('table').default([]).description('允许直接使用群管理命令的账号 ID 白名单。命中即通过,不再校验群内角色。'),
|
package/src/service.js
CHANGED
|
@@ -602,7 +602,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
602
602
|
return `platform=${session.platform ?? 'unknown'} user=${session.userId ?? 'unknown'} guild=${session.guildId ?? 'private'}`;
|
|
603
603
|
}
|
|
604
604
|
styleText(text) {
|
|
605
|
-
|
|
605
|
+
// 旧的「Meow 风格」已移除:想要喵味请在 qqgm-chat-style 里加一个风格 skill。
|
|
606
|
+
return text;
|
|
606
607
|
}
|
|
607
608
|
getMessageText(session) {
|
|
608
609
|
const raw = session?.content ?? '';
|