@nestim/koishi-plugin-qq-group-manager 1.3.0 → 1.4.0

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/engine.ts CHANGED
@@ -1,810 +1,866 @@
1
- /**
2
- * AI 回复引擎。
3
- *
4
- * 一次「收到消息」的完整流程:
5
- * record() 记录到上下文(所有消息都记,包括被管控/指令之外的人话)
6
- * handle() 判定是否接话 → 组装提示词 → (可选)解析图片 → 调模型
7
- * → 输出正文 / <pass/> → 发送 → 把自己的回复写回上下文
8
- *
9
- * 关键取舍:
10
- * - 决策与生成合并为一次模型调用,避免"兴趣判定答非所问、生成又挑另一条";
11
- * - 只回应当前消息,引用与回答永远一致;
12
- * - 允许模型用 <pass/> 主动放弃,放弃也重置计数,避免每条消息都空转调用。
13
- */
14
-
15
- import { AiState, GroupState, ChatRecord, FollowupState } from './state';
16
- import { decideTrigger } from './trigger';
17
- import { buildJudgePrompt, buildReplyPrompt, buildUserPrompt, PASS_TOKEN } from './prompt';
18
- import { ChatProvider, ChatResult } from './provider';
19
- import { pickImages, resolveImages } from './vision';
20
- import { selectMemoryBlocks, splitMemoryBlocks, tokenizeForMatch } from './memory';
21
- import { NameResolver, MemberIdentity } from '../core/names';
22
- import { renderMessage, RenderedImage, truncate } from '../core/text';
23
- import { AiHookRegistry, AiHookContext } from './hooks';
24
- import {
25
- buildSearchQuery,
26
- fetchWebSearch,
27
- shouldWebSearch,
28
- WebSearchMode,
29
- } from './websearch';
30
-
31
- export interface AiHost {
32
- config: any;
33
- logger: any;
34
- getOneBotApi(session: any): any;
35
- toGroupId(session: any): number | null;
36
- extractImages(session: any): RenderedImage[];
37
- fetchQuotedImages?(session: any, quote: any): Promise<RenderedImage[]>;
38
- resolveImage(ref: string, session: any): Promise<string>;
39
- sendReply(session: any, text: string): Promise<void>;
40
- readMemoryFile(): Promise<string>;
41
- }
42
-
43
- export interface AiDeps {
44
- provider?: ChatProvider;
45
- state?: AiState;
46
- rng?: () => number;
47
- now?: () => number;
48
- fetchImpl?: typeof fetch;
49
- }
50
-
51
- const PASS_RE = /^\s*<(?:pass\s*\/?|不回复)>/i;
52
-
53
- function cleanReply(text: string, selfName: string): string {
54
- let out = String(text || '')
55
- .replace(/^\s*```[a-zA-Z0-9_-]*\s*\n?/, '')
56
- .replace(/\n?\s*```\s*$/, '')
57
- // 防止模型输出被平台解析成图片/CQ 码(h.text 本身不解析,这里只是保持干净)
58
- .replace(/\[CQ:[^\]]+\]/gi, '')
59
- .replace(/<img\b[^>]*>/gi, '')
60
- .trim();
61
- // 去掉模型自作主张的「自称:」前缀
62
- const prefix = new RegExp(`^\\s*${selfName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*[::]\\s*`, 'i');
63
- out = out.replace(prefix, '');
64
- // 整句被引号包住时脱掉
65
- if (/^[“"「].*[”"」]$/.test(out)) out = out.slice(1, -1).trim();
66
- return out.replace(/\s+/g, ' ').trim();
67
- }
68
-
69
- function clipReply(text: string, maxChars: number): string {
70
- const max = Math.max(20, maxChars || 120);
71
- if (text.length <= max) return text;
72
- const slice = text.slice(0, max);
73
- const boundary = Math.max(
74
- slice.lastIndexOf('。'),
75
- slice.lastIndexOf('!'),
76
- slice.lastIndexOf('?'),
77
- slice.lastIndexOf(','),
78
- slice.lastIndexOf(';'),
79
- slice.lastIndexOf(';'),
80
- );
81
- if (boundary >= max * 0.5) return slice.slice(0, boundary + 1);
82
- return `${slice}…`;
83
- }
84
-
85
- export class AiEngine {
86
- readonly state: AiState;
87
- /** 外部插件扩展点:提示词风格段 + 输出过滤 */
88
- readonly hooks: AiHookRegistry;
89
- private provider: ChatProvider;
90
- private names: NameResolver;
91
- private rng: () => number;
92
- private now: () => number;
93
- private fetchImpl: typeof fetch;
94
- private host: AiHost;
95
- private config: any;
96
- private searchCache = new Map<string, { at: number; section: string }>();
97
- private searchRate = new Map<string, number[]>();
98
- private searchUnsupportedUntil = 0;
99
-
100
- constructor(host: AiHost, deps: AiDeps = {}) {
101
- this.host = host;
102
- this.config = host.config;
103
- this.state = deps.state ?? new AiState();
104
- this.hooks = new AiHookRegistry(host.logger);
105
- this.provider = deps.provider ?? new ChatProvider(host.config, host.logger);
106
- this.names = new NameResolver({
107
- getOneBotApi: (session) => host.getOneBotApi(session),
108
- toGroupId: (session) => host.toGroupId(session),
109
- logger: host.logger,
110
- });
111
- this.rng = deps.rng ?? Math.random;
112
- this.now = deps.now ?? Date.now;
113
- this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
114
- }
115
-
116
- // ---------------------------------------------------------------- 配置
117
-
118
- private groupKey(session: any): string {
119
- if (!session?.guildId) return '';
120
- return `${session.platform ?? 'unknown'}:${session.guildId}`;
121
- }
122
-
123
- private ruleFor(session: any): any {
124
- const guildId = String(session?.guildId ?? '');
125
- const rules: any[] = Array.isArray(this.config.groupRules) ? this.config.groupRules : [];
126
- return rules.find((item) => String(item?.guildId ?? '').trim() === guildId);
127
- }
128
-
129
- resolveEnabled(session: any): boolean {
130
- const rule = this.ruleFor(session);
131
- const requireRule = this.config.aiReplyRequireGroupRule !== false;
132
- if (requireRule && !rule) return false;
133
- if (rule && typeof rule.enableAiReply === 'boolean') return rule.enableAiReply;
134
- return !!this.config.enableAiReply;
135
- }
136
-
137
- private get contextWindow(): number {
138
- const value = Number(this.config.aiContextWindow ?? 24);
139
- return Math.max(6, Math.min(100, Number.isFinite(value) ? value : 24));
140
- }
141
-
142
- private get selfName(): string {
143
- const persona = this.activePersona();
144
- return String(persona?.selfName || this.config.aiAgentName || 'bot').trim() || 'bot';
145
- }
146
-
147
- private activePersona(): any {
148
- const id = String(this.config.aiActivePersona ?? '').trim();
149
- if (!id) return null;
150
- const list: any[] = Array.isArray(this.config.aiPersonas) ? this.config.aiPersonas : [];
151
- return list.find((item) => String(item?.id ?? '').trim() === id) ?? null;
152
- }
153
-
154
- private get personaPrompt(): string {
155
- const persona = this.activePersona();
156
- return String(persona?.prompt || this.config.aiSystemPrompt || '').trim();
157
- }
158
-
159
- private get maxReplyChars(): number {
160
- const value = Number(this.config.aiMaxReplyChars ?? 120);
161
- return Math.max(20, Math.min(500, Number.isFinite(value) ? value : 120));
162
- }
163
-
164
- private get debugPrompt(): boolean {
165
- return !!this.config.aiDebugPrompt;
166
- }
167
-
168
- // ---------------------------------------------------------------- 记录
169
-
170
- /** 是否像指令(这类消息不进上下文,避免污染) */
171
- private isCommandLike(text: string): boolean {
172
- const value = String(text || '').trim();
173
- if (!value) return false;
174
- if (/^[/.!!##]/.test(value)) return true;
175
- if (/^\[[^\]\s]+\]/.test(value)) return true;
176
- const prefixes = [this.config.command, this.config.menuCommand, 'help']
177
- .map((item: any) => String(item ?? '').trim())
178
- .filter(Boolean);
179
- return prefixes.some((prefix: string) => value === prefix || value.startsWith(`${prefix} `));
180
- }
181
-
182
- /** 记录一条群消息;返回落库后的记录(指令类返回 null) */
183
- async record(session: any): Promise<ChatRecord | null> {
184
- const key = this.groupKey(session);
185
- if (!key || !session?.userId) return null;
186
- if (String(session.userId) === String(session.bot?.selfId ?? '')) return null;
187
-
188
- const state = this.state.get(key);
189
- const messageId = String(session.messageId ?? '');
190
- if (messageId) {
191
- const existing = state.records.find((item) => item.id === messageId);
192
- if (existing) return existing;
193
- }
194
-
195
- const contextWindow = this.contextWindow;
196
-
197
- // 先排除指令,避免为指令解析 @ / 查群名片
198
- const rawText = String(session.content ?? '').trim();
199
- if (this.isCommandLike(rawText.replace(/^\s*(<at\b[^>]*\/?>|\[CQ:at,[^\]]+\])\s*/i, ''))) {
200
- return null;
201
- }
202
-
203
- const identity: MemberIdentity = await this.names.identify(session);
204
-
205
- const rendered = await renderMessage(session, this.names.resolverFor(session), {
206
- selfId: String(session.bot?.selfId ?? session.selfId ?? ''),
207
- });
208
-
209
- const record: ChatRecord = {
210
- id: messageId || `local-${this.now()}-${Math.random().toString(36).slice(2, 8)}`,
211
- userId: String(session.userId),
212
- name: identity.name || String(session.userId),
213
- role: identity.role,
214
- text: rendered.text,
215
- images: rendered.images,
216
- quote: rendered.quote,
217
- forwardText: await this.readForwards(session, rendered.forwards || []),
218
- mentions: rendered.mentions,
219
- atBot: rendered.atBot,
220
- self: false,
221
- at: Number(session.timestamp) || this.now(),
222
- };
223
-
224
- state.push(record, contextWindow);
225
- state.counter += 1;
226
- return record;
227
- }
228
-
229
- /** 追加一条系统注记(复读等),不进计数、不触发 */
230
- note(text: string, groupKey?: string, session?: any): void {
231
- const key = groupKey || (session ? this.groupKey(session) : '');
232
- if (!key || !text?.trim()) return;
233
- const state = this.state.get(key);
234
- state.push(
235
- {
236
- id: `note-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
237
- userId: 'system',
238
- name: '系统',
239
- role: 'unknown',
240
- text: String(text).trim(),
241
- images: [],
242
- mentions: [],
243
- atBot: false,
244
- self: false,
245
- at: this.now(),
246
- command: true,
247
- },
248
- this.contextWindow,
249
- );
250
- }
251
-
252
- /** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
253
- recordSelf(session: any, text: string): void {
254
- const key = this.groupKey(session);
255
- if (!key || !text?.trim()) return;
256
- const state = this.state.get(key);
257
- state.push(
258
- {
259
- id: `self-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
260
- userId: String(session.bot?.selfId ?? ''),
261
- name: this.selfName,
262
- role: 'unknown',
263
- text: String(text).trim(),
264
- images: [],
265
- mentions: [],
266
- atBot: false,
267
- self: true,
268
- at: this.now(),
269
- },
270
- this.contextWindow,
271
- );
272
- }
273
-
274
- // ---------------------------------------------------------------- 点名 / 跟随
275
-
276
- private isMention(session: any, record: ChatRecord): boolean {
277
- // 渲染阶段已经确认 @ 了 bot,不依赖 session.content 的序列化格式
278
- if (record.atBot) return true;
279
- const selfId = String(session?.bot?.selfId ?? session?.selfId ?? '');
280
- if (selfId) {
281
- const content = String(session?.content ?? '');
282
- if (content.includes(`<at id="${selfId}"`)) return true;
283
- const escaped = selfId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
284
- if (new RegExp(`\\[CQ:at,[^\\]]*(?:qq|id)=${escaped}(?:,|\\])`, 'i').test(content)) return true;
285
- }
286
- // 只叫名字(不带 @)是否算点名,交给 aiEnableDirectMentionTrigger 控制
287
- if (this.config.aiEnableDirectMentionTrigger === false) return false;
288
- const name = this.selfName.toLowerCase();
289
- if (!name) return false;
290
- return String(record.text || '').toLowerCase().includes(name);
291
- }
292
-
293
- private addressesOthers(record: ChatRecord, session: any): boolean {
294
- const selfId = String(session?.bot?.selfId ?? '');
295
- return record.mentions.length > 0 && !record.mentions.includes(selfId);
296
- }
297
-
298
- private shouldContinueFollowup(record: ChatRecord, followup: FollowupState): boolean {
299
- const text = String(record.text || '').trim();
300
- if (!text) return false;
301
- if (this.isCommandLike(text)) return false;
302
- if (/^[/.!!##]/.test(text)) return false;
303
- if (text.length <= 2) return false;
304
- if (/^[\u{1F300}-\u{1FAFF}\s~~!!.。]+$/u.test(text)) return false;
305
- if (/(换个话题|换个问题|另外|题外话|不聊这个|先不说这个|说点别的|再问个新的)/.test(text)) return false;
306
-
307
- const current = tokenizeForMatch(text);
308
- const overlap = [...current].filter((token) => followup.anchorTokens.includes(token)).length;
309
- const ratio = overlap / Math.max(1, Math.min(current.size || 1, followup.anchorTokens.length || 1));
310
- if (text.length >= 8 && overlap === 0 && !/[??]/.test(text)) return false;
311
- if (text.length >= 8 && ratio <= 0.12 && /[??]/.test(text)) return false;
312
-
313
- if (/[??]/.test(text)) return true;
314
- if (/(继续|然后|那|所以|为什么|怎么|如何|帮我|还能|可以吗|行吗|对不对|是不是|展开|多说|细说|具体|举个例子|还有呢|后来呢|说说|讲讲)/.test(text)) return true;
315
- // 没有话题交集、也不是明确的追问 → 不追着说,避免用户换话题后机器人自说自话
316
- if (overlap > 0 && ratio >= 0.18) return true;
317
- return false;
318
- }
319
-
320
- private startFollowup(state: GroupState, record: ChatRecord): void {
321
- if (this.config.aiEnableFollowupAfterMention === false) return;
322
- const seconds = Math.max(1, Number(this.config.aiFollowupWindowSeconds ?? 120));
323
- state.followup = {
324
- userId: record.userId,
325
- expiresAt: this.now() + seconds * 1000,
326
- turns: 0,
327
- anchorTokens: [...tokenizeForMatch(record.text)],
328
- lastText: record.text,
329
- };
330
- }
331
-
332
- private bumpFollowup(state: GroupState, record: ChatRecord): void {
333
- const followup = state.followup;
334
- if (!followup) return;
335
- followup.turns += 1;
336
- followup.lastText = record.text;
337
- const seconds = Math.max(1, Number(this.config.aiFollowupWindowSeconds ?? 120));
338
- followup.expiresAt = this.now() + seconds * 1000;
339
- const maxTurns = Math.max(1, Number(this.config.aiFollowupMaxTurns ?? 3));
340
- if (followup.turns >= maxTurns) state.followup = null;
341
- }
342
-
343
- private getFollowup(state: GroupState, record: ChatRecord, session: any): FollowupState | null {
344
- const followup = state.followup;
345
- if (!followup) return null;
346
- if (this.now() > followup.expiresAt) {
347
- state.followup = null;
348
- return null;
349
- }
350
- if (followup.userId !== record.userId) return null;
351
- if (this.addressesOthers(record, session)) {
352
- state.followup = null;
353
- return null;
354
- }
355
- return followup;
356
- }
357
-
358
- // ---------------------------------------------------------------- 记忆
359
-
360
- private async loadMemories(record: ChatRecord, state: GroupState): Promise<string[]> {
361
- if (!this.config.enableMemory || this.config.memoryInAi === false) return [];
362
- let content = '';
363
- try {
364
- content = await this.host.readMemoryFile();
365
- } catch {
366
- return [];
367
- }
368
- const blocks = splitMemoryBlocks(content);
369
- if (!blocks.length) return [];
370
- const recent = state.records.slice(-3).map((item) => item.text);
371
- const selected = selectMemoryBlocks(blocks, [record.text, ...recent], {
372
- limit: 3,
373
- minScore: 0.12,
374
- maxChars: 160,
375
- });
376
- return selected.map((item) => item.text);
377
- }
378
-
379
- // ---------------------------------------------------------------- 主流程
380
-
381
- async handle(session: any): Promise<void> {
382
- const key = this.groupKey(session);
383
- if (!key) return;
384
- if (!this.resolveEnabled(session)) return;
385
- if (String(session.userId) === String(session.bot?.selfId ?? '')) return;
386
- if (session.platform && !this.platformAllowed(session.platform)) return;
387
-
388
- const state = this.state.get(key);
389
- const messageId = String(session.messageId ?? '');
390
- if (messageId && state.isDuplicate(`${session.platform}:${session.guildId}:${session.userId}:${messageId}`, this.now())) {
391
- return;
392
- }
393
-
394
- let record = messageId ? state.records.find((item) => item.id === messageId) : undefined;
395
- if (!record) record = (await this.record(session)) ?? undefined;
396
- if (!record) return;
397
-
398
- const mention = this.isMention(session, record);
399
- const followupState = mention ? null : this.getFollowup(state, record, session);
400
- const followup = !!followupState && this.shouldContinueFollowup(record, followupState);
401
- // 用户换了话题/说的和上一轮无关时,丢掉待续话题,避免机器人追着自己上一句说
402
- if (followupState && !followup) state.followup = null;
403
-
404
- const threshold = Math.max(1, Number(this.config.aiMessageThreshold ?? 15));
405
- const decision = decideTrigger({
406
- mode: (this.config.aiReplyMode || 'hybrid') as any,
407
- counter: state.counter,
408
- threshold,
409
- probability: Number(this.config.aiRandomReplyProbability ?? 0.08),
410
- now: this.now(),
411
- lastAttemptAt: state.lastAttemptAt,
412
- minIntervalMs: Math.max(0, Number(this.config.aiMinReplyIntervalSeconds ?? 45)) * 1000,
413
- lastReplyAt: state.lastReplyAt || 0,
414
- mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
415
- inFlight: state.inFlight,
416
- mention,
417
- followup,
418
- rng: this.rng,
419
- });
420
-
421
- this.log('ai-trigger', {
422
- fire: decision.fire,
423
- reason: decision.reason,
424
- counter: state.counter,
425
- threshold,
426
- mention,
427
- followup,
428
- ctx: state.records.length,
429
- }, session);
430
- if (!decision.fire) return;
431
-
432
- state.inFlight = true;
433
- state.lastAttemptAt = this.now();
434
- const startedAt = this.now();
435
-
436
- try {
437
- const allowPass = !mention && !followup;
438
- const memories = await this.loadMemories(record, state);
439
- const hookCtx: AiHookContext = {
440
- session,
441
- groupId: String(session.guildId),
442
- mode: 'reply',
443
- };
444
- const styleSections = await this.hooks.collectSections(hookCtx);
445
- const webSearch = await this.webSearch(record, session);
446
- const promptInput = {
447
- selfName: this.selfName,
448
- persona: this.personaPrompt,
449
- groupId: String(session.guildId),
450
- records: state.records,
451
- current: record,
452
- mention,
453
- followup,
454
- allowPass,
455
- memories,
456
- maxReplyChars: this.maxReplyChars,
457
- styleSections,
458
- webSearch,
459
- webSearchEnabled: this.config.aiWebSearchEnabled !== false,
460
- };
461
-
462
- if (allowPass && this.config.aiReplyDecision === 'two-stage') {
463
- const judge = await this.judge(promptInput);
464
- if (!judge) {
465
- state.counter = 0;
466
- this.log('ai-pass', { by: 'judge', latencyMs: this.now() - startedAt }, session);
467
- return;
468
- }
469
- }
470
-
471
- const prompt = buildReplyPrompt(promptInput);
472
- if (this.debugPrompt) {
473
- this.host.logger.info(`[ai-debug] system=${prompt.system}\n[ai-debug] user=${prompt.user}`);
474
- }
475
-
476
- const images = await this.collectImages(session, record, state);
477
- const result = await this.provider.chat({
478
- system: prompt.system,
479
- user: prompt.user,
480
- images,
481
- temperature: Number(this.config.aiTemperature ?? 0.8),
482
- maxTokens: Number(this.config.aiMaxOutputTokens ?? 400),
483
- });
484
-
485
- if (!result.ok) {
486
- this.log('ai-reply', {
487
- ok: false,
488
- error: result.error,
489
- trigger: decision.reason,
490
- latencyMs: this.now() - startedAt,
491
- }, session);
492
- return;
493
- }
494
-
495
- const raw = String(result.text || '').trim();
496
- if (!raw || PASS_RE.test(raw)) {
497
- state.counter = 0;
498
- this.log('ai-pass', {
499
- by: 'model',
500
- trigger: decision.reason,
501
- latencyMs: this.now() - startedAt,
502
- }, session);
503
- return;
504
- }
505
-
506
- let finalRaw = raw;
507
- if (!webSearch && this.shouldReviseWithSearch(raw)) {
508
- const revisedSearch = await this.webSearch(record, session, true);
509
- if (revisedSearch) {
510
- const revisedInput = { ...promptInput, webSearch: revisedSearch };
511
- const revisedUser = `${buildUserPrompt(revisedInput)}\n\n你刚才的回答是:「${truncate(finalRaw, 120)}」。现在补上了联网搜索结果,请根据结果重写最终回复;不要提“刚才/搜索/系统”,直接给答案。`;
512
- const revised = await this.provider.chat({
513
- system: prompt.system,
514
- user: revisedUser,
515
- images,
516
- temperature: Number(this.config.aiTemperature ?? 0.8),
517
- maxTokens: Number(this.config.aiMaxOutputTokens ?? 400),
518
- });
519
- if (revised.ok && revised.text && !PASS_RE.test(revised.text.trim())) {
520
- finalRaw = revised.text.trim();
521
- this.log('web-search', { ok: true, revised: true, query: buildSearchQuery(record.text) }, session);
522
- }
523
- }
524
- }
525
-
526
- const cleaned = cleanReply(finalRaw, this.selfName); if (!cleaned) {
527
- state.counter = 0;
528
- return;
529
- }
530
-
531
- const filtered = await this.hooks.applyFilters(cleaned, hookCtx);
532
- if (filtered == null) {
533
- state.counter = 0;
534
- this.log('ai-pass', {
535
- by: 'filter',
536
- trigger: decision.reason,
537
- latencyMs: this.now() - startedAt,
538
- }, session);
539
- return;
540
- }
541
-
542
- const finalText = clipReply(filtered, this.maxReplyChars);
543
- if (!finalText) {
544
- state.counter = 0;
545
- return;
546
- }
547
-
548
- await this.host.sendReply(session, finalText);
549
- state.lastReplyAt = this.now();
550
- state.counter = 0;
551
- this.recordSelf(session, finalText);
552
-
553
- if (mention) this.startFollowup(state, record);
554
- else if (followup && state.followup) this.bumpFollowup(state, record);
555
-
556
- this.log('ai-reply', {
557
- ok: true,
558
- trigger: decision.reason,
559
- latencyMs: this.now() - startedAt,
560
- images: images.length,
561
- degradedToText: !!result.degradedToText,
562
- chars: finalText.length,
563
- preview: finalText.slice(0, 60),
564
- }, session);
565
-
566
- await this.hooks.runAfterReply({ ...hookCtx, text: finalText });
567
- } catch (error: any) {
568
- this.log('ai-reply', {
569
- ok: false,
570
- error: String(error?.message || error),
571
- trigger: decision.reason,
572
- }, session);
573
- } finally {
574
- state.inFlight = false;
575
- }
576
- }
577
-
578
- /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
579
- chat(request: any) {
580
- return this.provider.chat(request);
581
- }
582
-
583
- /** 群内长时间没人说话时,生成一条主动话题。 */
584
- async idleTopic(groupId: string): Promise<string> {
585
- const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
586
- let sections: string[] = [];
587
- try {
588
- sections = await this.hooks.collectSections({ session, groupId, mode: 'reply' });
589
- } catch { /* ignore */ }
590
- const system = [
591
- `你是 QQ 群 ${groupId} 里的一个普通成员。`,
592
- '群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
593
- '不要问“在吗”,不要提“很久没人说话”,不要自我介绍。',
594
- ...sections,
595
- ].join('\n');
596
- const result = await this.provider.chat({
597
- system,
598
- user: '现在发一条主动话题。',
599
- temperature: Number(this.config.aiTemperature ?? 0.8),
600
- maxTokens: Math.min(300, Number(this.config.aiMaxOutputTokens ?? 400)),
601
- });
602
- if (!result.ok || !result.text) return '';
603
- const raw = String(result.text).trim();
604
- if (!raw || PASS_RE.test(raw)) return '';
605
- return clipReply(cleanReply(raw, this.selfName), this.maxReplyChars)
606
- .replace(/\[表情[::][^\]]*\]/g, '')
607
- .trim();
608
- }
609
-
610
- /** 需要时调用 DeepSeek Search API;失败/不支持/没结果都返回空串,继续普通回复。 */
611
- private async webSearch(record: ChatRecord, session: any, force = false): Promise<string> {
612
- if (this.config.aiWebSearchEnabled === false) return '';
613
- const mode = (this.config.aiWebSearchMode || 'auto') as WebSearchMode;
614
- if (mode === 'off') return '';
615
- const text = String(record.text || '');
616
- if (!force && !shouldWebSearch(text, mode)) return '';
617
- const query = buildSearchQuery(text);
618
- if (!query) return '';
619
-
620
- const now = this.now();
621
- if (this.searchUnsupportedUntil > now) return '';
622
- const groupId = String(session?.guildId || '');
623
- const maxPerHour = Math.max(0, Number(this.config.aiWebSearchMaxPerHour ?? 10));
624
- if (maxPerHour > 0) {
625
- const list = (this.searchRate.get(groupId) || []).filter((t) => now - t < 3600_000);
626
- if (list.length >= maxPerHour) {
627
- this.log('web-search', { ok: false, reason: 'rate-limit', groupId }, session);
628
- return '';
629
- }
630
- list.push(now);
631
- this.searchRate.set(groupId, list);
632
- }
633
-
634
- const cacheMinutes = Math.max(0, Number(this.config.aiWebSearchCacheMinutes ?? 10));
635
- const cacheKey = `${String(this.config.aiBaseUrl || '')}|${query}`;
636
- if (cacheMinutes > 0) {
637
- const hit = this.searchCache.get(cacheKey);
638
- if (hit && now - hit.at < cacheMinutes * 60_000) return hit.section;
639
- }
640
-
641
- const startedAt = this.now();
642
- const outcome = await fetchWebSearch({
643
- query,
644
- apiKey: String(this.config.aiApiKey || ''),
645
- baseUrl: String(this.config.aiBaseUrl || 'https://api.deepseek.com'),
646
- maxResults: Number(this.config.aiWebSearchMaxResults ?? 5),
647
- timeoutMs: Number(this.config.aiWebSearchTimeoutMs ?? 4000),
648
- maxChars: 1800,
649
- }, this.fetchImpl);
650
-
651
- if (!outcome.ok) {
652
- // 400/401/403/404 通常意味着这个 API 不支持 Search;10 分钟内不再重试
653
- if (/^http-(400|401|403|404)$/.test(outcome.reason || '')) {
654
- this.searchUnsupportedUntil = now + 10 * 60_000;
655
- }
656
- this.log('web-search', {
657
- ok: false,
658
- reason: outcome.reason,
659
- query,
660
- latencyMs: this.now() - startedAt,
661
- }, session);
662
- return '';
663
- }
664
-
665
- if (cacheMinutes > 0) {
666
- this.searchCache.set(cacheKey, { at: now, section: outcome.section || '' });
667
- if (this.searchCache.size > 100) {
668
- const oldest = this.searchCache.keys().next().value;
669
- if (oldest) this.searchCache.delete(oldest);
670
- }
671
- }
672
- this.log('web-search', {
673
- ok: true,
674
- results: outcome.results?.length || 0,
675
- query,
676
- latencyMs: this.now() - startedAt,
677
- }, session);
678
- return outcome.section || '';
679
- }
680
-
681
- /** 模型自己都说不知道/搜不了时,补一次搜索再重写;只在不认识的问题上多一次调用。 */
682
- private shouldReviseWithSearch(raw: string): boolean {
683
- if (this.config.aiWebSearchEnabled === false) return false;
684
- if (String(this.config.aiWebSearchMode || 'auto') === 'off') return false;
685
- return /(不知道|记不清|记不准|记不牢|不敢乱说|说岔|没法上网|查不了|搜不了|没有联网|无法联网|不确定|不太清楚|分不清|瞎猜)/.test(raw);
686
- }
687
-
688
- /** 读取合并转发的子消息,压成一行行文本;读不到就返回空串。 */
689
- private async readForwards(session: any, forwards: any[]): Promise<string> {
690
- if (this.config.aiReadForwardMessage === false) return '';
691
- if (!Array.isArray(forwards) || !forwards.length) return '';
692
- const limit = Math.max(1, Math.min(50, Number(this.config.aiForwardMaxNodes ?? 20)));
693
- const onebot = this.host.getOneBotApi(session);
694
- if (!onebot?.getForwardMsg) return '';
695
- const blocks: string[] = [];
696
- for (const item of forwards.slice(0, 3)) {
697
- const id = String(item?.id || '').trim();
698
- if (!id) continue;
699
- try {
700
- const data = await onebot.getForwardMsg(id);
701
- const messages = Array.isArray(data?.messages) ? data.messages
702
- : (Array.isArray(data?.message) ? data.message : (Array.isArray(data) ? data : []));
703
- for (const node of messages.slice(0, limit)) {
704
- const sender = String(node?.sender?.card || node?.sender?.nickname || node?.nickname || node?.name || '').trim();
705
- const content = Array.isArray(node?.message)
706
- ? node.message.filter((seg: any) => seg?.type === 'text').map((seg: any) => String(seg?.data?.text ?? '')).join('')
707
- : String(node?.content ?? node?.raw_message ?? node?.message ?? '');
708
- const text = content.replace(/\[CQ:[^\]]+\]/g, '[图片]').replace(/\s+/g, ' ').trim();
709
- if (!text) continue;
710
- blocks.push(`${sender ? `${sender}: ` : ''}${truncate(text, 160)}`);
711
- }
712
- } catch (error) {
713
- this.log('forward', { ok: false, error: String(error) }, session);
714
- }
715
- }
716
- if (!blocks.length) return '';
717
- this.log('forward', { ok: true, nodes: blocks.length }, session);
718
- return blocks.join('\n');
719
- }
720
-
721
- private recentImageRecords(state: GroupState, record: ChatRecord, maxAgeMs = 120000): RenderedImage[] {
722
- const cutoff = Number(record.at) - maxAgeMs;
723
- const candidates = state.records
724
- .filter((item) => (
725
- !item.self
726
- && item.id !== record.id
727
- && item.userId === record.userId
728
- && item.images.length > 0
729
- && Number(item.at) >= cutoff
730
- ))
731
- .slice(-4)
732
- .reverse();
733
- const out: RenderedImage[] = [];
734
- for (const item of candidates) {
735
- for (const image of item.images) out.push(image);
736
- }
737
- return out;
738
- }
739
-
740
- private async collectImages(session: any, record: ChatRecord, state: GroupState): Promise<string[]> {
741
- if (this.config.aiEnableImageRecognition === false) return [];
742
- const maxCount = Math.max(0, Number(this.config.aiImageMaxCount ?? 2));
743
- if (!maxCount) return [];
744
-
745
- const own = record.images.length ? record.images : this.host.extractImages(session);
746
- // 用户常见的“先发图,再单独 @ 一句”:当前消息没有图,回看同一用户最近 2 分钟内的图
747
- const fallback = own.length ? [] : this.recentImageRecords(state, record);
748
- let quoted: RenderedImage[] = record.quote
749
- ? (record.quote.images?.length ? record.quote.images : this.host.extractImages(session?.quote))
750
- : [];
751
- // 引用消息里没解析到图(常见于 quote 只带 messageId):用 get_msg 回查一次
752
- if (!quoted.length && record.quote?.id && typeof this.host.fetchQuotedImages === 'function') {
753
- quoted = await this.host.fetchQuotedImages(session, record.quote);
754
- }
755
- const items = pickImages([...own, ...fallback], quoted, maxCount);
756
- if (!items.length) return [];
757
-
758
- return resolveImages(
759
- items,
760
- (ref) => this.host.resolveImage(ref, session),
761
- { maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) },
762
- );
763
- }
764
-
765
- private async judge(input: any): Promise<boolean> {
766
- const prompt = buildJudgePrompt(input);
767
- const result: ChatResult = await this.provider.chat({
768
- system: prompt.system,
769
- user: prompt.user,
770
- temperature: 0.1,
771
- maxTokens: 256,
772
- });
773
- if (!result.ok || !result.text) return false;
774
- const match = result.text.match(/\{[\s\S]*\}/);
775
- if (!match) return false;
776
- try {
777
- const parsed = JSON.parse(match[0]);
778
- const score = Number(parsed?.score) || 0;
779
- const min = Number(this.config.aiInterestMinScore ?? 60);
780
- return !!parsed?.reply && score >= min;
781
- } catch {
782
- return false;
783
- }
784
- }
785
-
786
- private platformAllowed(platform: string): boolean {
787
- const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
788
- return list.includes(platform);
789
- }
790
-
791
- private log(event: string, data: Record<string, any>, session: any): void {
792
- const extra = Object.entries(data)
793
- .filter(([, value]) => value !== undefined)
794
- .map(([key, value]) => `${key}=${typeof value === 'string' ? JSON.stringify(value) : value}`)
795
- .join(' ');
796
- this.host.logger.info(
797
- `[${event}] ${extra} | platform=${session?.platform ?? '?'} user=${session?.userId ?? '?'} guild=${session?.guildId ?? '?'}`,
798
- );
799
- }
800
-
801
- /** 供指令/调试使用 */
802
- displayNameFor(session: any, qq: string): Promise<string> {
803
- return this.names.display(session, qq);
804
- }
805
-
806
- clear(): void {
807
- this.state.clear();
808
- this.names.clear();
809
- }
810
- }
1
+ /**
2
+ * AI 回复引擎。
3
+ *
4
+ * 一次「收到消息」的完整流程:
5
+ * record() 记录到上下文(所有消息都记,包括被管控/指令之外的人话)
6
+ * handle() 判定是否接话 → 组装提示词 → (可选)解析图片 → 调模型
7
+ * → 输出正文 / <pass/> → 发送 → 把自己的回复写回上下文
8
+ *
9
+ * 关键取舍:
10
+ * - 决策与生成合并为一次模型调用,避免"兴趣判定答非所问、生成又挑另一条";
11
+ * - 只回应当前消息,引用与回答永远一致;
12
+ * - 允许模型用 <pass/> 主动放弃,放弃也重置计数,避免每条消息都空转调用。
13
+ */
14
+
15
+ import { AiState, GroupState, ChatRecord, FollowupState } from './state';
16
+ import { decideTrigger } from './trigger';
17
+ import { buildJudgePrompt, buildReplyPrompt, buildUserPrompt, PASS_TOKEN } from './prompt';
18
+ import { ChatProvider, ChatResult } from './provider';
19
+ import { pickImages, resolveImages } from './vision';
20
+ import { selectMemoryBlocks, splitMemoryBlocks, tokenizeForMatch } from './memory';
21
+ import { NameResolver, MemberIdentity } from '../core/names';
22
+ import { renderMessage, RenderedImage, truncate } from '../core/text';
23
+ import { AiHookRegistry, AiHookContext } from './hooks';
24
+ import {
25
+ buildSearchQuery,
26
+ fetchWebSearch,
27
+ shouldWebSearch,
28
+ WebSearchMode,
29
+ } from './websearch';
30
+
31
+ export interface AiHost {
32
+ config: any;
33
+ logger: any;
34
+ getOneBotApi(session: any): any;
35
+ toGroupId(session: any): number | null;
36
+ extractImages(session: any): RenderedImage[];
37
+ fetchQuotedImages?(session: any, quote: any): Promise<RenderedImage[]>;
38
+ resolveImage(ref: string, session: any): Promise<string>;
39
+ sendReply(session: any, text: string): Promise<void>;
40
+ readMemoryFile(scope?: { kind: 'group' | 'private'; id: string } | null): Promise<string>;
41
+ }
42
+
43
+ export interface AiDeps {
44
+ provider?: ChatProvider;
45
+ state?: AiState;
46
+ rng?: () => number;
47
+ now?: () => number;
48
+ fetchImpl?: typeof fetch;
49
+ }
50
+
51
+ const PASS_RE = /^\s*<(?:pass\s*\/?|不回复)>/i;
52
+
53
+ function cleanReply(text: string, selfName: string): string {
54
+ let out = String(text || '')
55
+ .replace(/^\s*```[a-zA-Z0-9_-]*\s*\n?/, '')
56
+ .replace(/\n?\s*```\s*$/, '')
57
+ // 防止模型输出被平台解析成图片/CQ 码(h.text 本身不解析,这里只是保持干净)
58
+ .replace(/\[CQ:[^\]]+\]/gi, '')
59
+ .replace(/<img\b[^>]*>/gi, '')
60
+ .trim();
61
+ // 去掉模型自作主张的「自称:」前缀
62
+ const prefix = new RegExp(`^\\s*${selfName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*[::]\\s*`, 'i');
63
+ out = out.replace(prefix, '');
64
+ // 整句被引号包住时脱掉
65
+ if (/^[“"「].*[”"」]$/.test(out)) out = out.slice(1, -1).trim();
66
+ return out.replace(/\s+/g, ' ').trim();
67
+ }
68
+
69
+ function clipReply(text: string, maxChars: number): string {
70
+ const max = Math.max(20, maxChars || 120);
71
+ if (text.length <= max) return text;
72
+ const slice = text.slice(0, max);
73
+ const boundary = Math.max(
74
+ slice.lastIndexOf('。'),
75
+ slice.lastIndexOf('!'),
76
+ slice.lastIndexOf('?'),
77
+ slice.lastIndexOf(','),
78
+ slice.lastIndexOf(';'),
79
+ slice.lastIndexOf(';'),
80
+ );
81
+ if (boundary >= max * 0.5) return slice.slice(0, boundary + 1);
82
+ return `${slice}…`;
83
+ }
84
+
85
+ export class AiEngine {
86
+ readonly state: AiState;
87
+ /** 外部插件扩展点:提示词风格段 + 输出过滤 */
88
+ readonly hooks: AiHookRegistry;
89
+ private provider: ChatProvider;
90
+ private names: NameResolver;
91
+ private rng: () => number;
92
+ private now: () => number;
93
+ private fetchImpl: typeof fetch;
94
+ private host: AiHost;
95
+ private config: any;
96
+ private searchCache = new Map<string, { at: number; section: string }>();
97
+ private searchRate = new Map<string, number[]>();
98
+ private searchUnsupportedUntil = 0;
99
+
100
+ constructor(host: AiHost, deps: AiDeps = {}) {
101
+ this.host = host;
102
+ this.config = host.config;
103
+ this.state = deps.state ?? new AiState();
104
+ this.hooks = new AiHookRegistry(host.logger);
105
+ this.provider = deps.provider ?? new ChatProvider(host.config, host.logger);
106
+ this.names = new NameResolver({
107
+ getOneBotApi: (session) => host.getOneBotApi(session),
108
+ toGroupId: (session) => host.toGroupId(session),
109
+ logger: host.logger,
110
+ });
111
+ this.rng = deps.rng ?? Math.random;
112
+ this.now = deps.now ?? Date.now;
113
+ this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
114
+ }
115
+
116
+ // ---------------------------------------------------------------- 配置
117
+
118
+ private groupKey(session: any): string {
119
+ if (!session?.guildId) return '';
120
+ return `${session.platform ?? 'unknown'}:${session.guildId}`;
121
+ }
122
+
123
+ private ruleFor(session: any): any {
124
+ const guildId = String(session?.guildId ?? '');
125
+ const rules: any[] = Array.isArray(this.config.groupRules) ? this.config.groupRules : [];
126
+ return rules.find((item) => String(item?.guildId ?? '').trim() === guildId);
127
+ }
128
+
129
+ resolveEnabled(session: any): boolean {
130
+ const rule = this.ruleFor(session);
131
+ const requireRule = this.config.aiReplyRequireGroupRule !== false;
132
+ if (requireRule && !rule) return false;
133
+ if (rule && typeof rule.enableAiReply === 'boolean') return rule.enableAiReply;
134
+ return !!this.config.enableAiReply;
135
+ }
136
+
137
+ private get contextWindow(): number {
138
+ const value = Number(this.config.aiContextWindow ?? 24);
139
+ return Math.max(6, Math.min(100, Number.isFinite(value) ? value : 24));
140
+ }
141
+
142
+ private get selfName(): string {
143
+ const persona = this.activePersona();
144
+ return String(persona?.selfName || this.config.aiAgentName || 'bot').trim() || 'bot';
145
+ }
146
+
147
+ private activePersona(): any {
148
+ const id = String(this.config.aiActivePersona ?? '').trim();
149
+ if (!id) return null;
150
+ const list: any[] = Array.isArray(this.config.aiPersonas) ? this.config.aiPersonas : [];
151
+ return list.find((item) => String(item?.id ?? '').trim() === id) ?? null;
152
+ }
153
+
154
+ private get personaPrompt(): string {
155
+ const persona = this.activePersona();
156
+ return String(persona?.prompt || this.config.aiSystemPrompt || '').trim();
157
+ }
158
+
159
+ private get maxReplyChars(): number {
160
+ const value = Number(this.config.aiMaxReplyChars ?? 120);
161
+ return Math.max(20, Math.min(500, Number.isFinite(value) ? value : 120));
162
+ }
163
+
164
+ private get debugPrompt(): boolean {
165
+ return !!this.config.aiDebugPrompt;
166
+ }
167
+
168
+ // ---------------------------------------------------------------- 记录
169
+
170
+ /** 是否像指令(这类消息不进上下文,避免污染) */
171
+ private isCommandLike(text: string): boolean {
172
+ const value = String(text || '').trim();
173
+ if (!value) return false;
174
+ if (/^[/.!!##]/.test(value)) return true;
175
+ if (/^\[[^\]\s]+\]/.test(value)) return true;
176
+ const prefixes = [this.config.command, this.config.menuCommand, 'help']
177
+ .map((item: any) => String(item ?? '').trim())
178
+ .filter(Boolean);
179
+ return prefixes.some((prefix: string) => value === prefix || value.startsWith(`${prefix} `));
180
+ }
181
+
182
+ /** 记录一条群消息;返回落库后的记录(指令类返回 null) */
183
+ async record(session: any): Promise<ChatRecord | null> {
184
+ const key = this.groupKey(session);
185
+ if (!key || !session?.userId) return null;
186
+ if (String(session.userId) === String(session.bot?.selfId ?? '')) return null;
187
+
188
+ const state = this.state.get(key);
189
+ const messageId = String(session.messageId ?? '');
190
+ if (messageId) {
191
+ const existing = state.records.find((item) => item.id === messageId);
192
+ if (existing) return existing;
193
+ }
194
+
195
+ const contextWindow = this.contextWindow;
196
+
197
+ // 先排除指令,避免为指令解析 @ / 查群名片
198
+ const rawText = String(session.content ?? '').trim();
199
+ if (this.isCommandLike(rawText.replace(/^\s*(<at\b[^>]*\/?>|\[CQ:at,[^\]]+\])\s*/i, ''))) {
200
+ return null;
201
+ }
202
+
203
+ const identity: MemberIdentity = await this.names.identify(session);
204
+
205
+ const rendered = await renderMessage(session, this.names.resolverFor(session), {
206
+ selfId: String(session.bot?.selfId ?? session.selfId ?? ''),
207
+ });
208
+
209
+ const record: ChatRecord = {
210
+ id: messageId || `local-${this.now()}-${Math.random().toString(36).slice(2, 8)}`,
211
+ userId: String(session.userId),
212
+ name: identity.name || String(session.userId),
213
+ role: identity.role,
214
+ text: rendered.text,
215
+ images: rendered.images,
216
+ quote: rendered.quote,
217
+ forwardText: await this.readForwards(session, rendered.forwards || []),
218
+ mentions: rendered.mentions,
219
+ atBot: rendered.atBot,
220
+ self: false,
221
+ at: Number(session.timestamp) || this.now(),
222
+ };
223
+
224
+ const evicted = state.push(record, contextWindow);
225
+ this.emitEvicted(evicted, key, session);
226
+ state.counter += 1;
227
+ return record;
228
+ }
229
+
230
+ /** 追加一条系统注记(复读等),不进计数、不触发 */
231
+ note(text: string, groupKey?: string, session?: any): void {
232
+ const key = groupKey || (session ? this.groupKey(session) : '');
233
+ if (!key || !text?.trim()) return;
234
+ const state = this.state.get(key);
235
+ const evicted = state.push(
236
+ {
237
+ id: `note-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
238
+ userId: 'system',
239
+ name: '系统',
240
+ role: 'unknown',
241
+ text: String(text).trim(),
242
+ images: [],
243
+ mentions: [],
244
+ atBot: false,
245
+ self: false,
246
+ at: this.now(),
247
+ command: true,
248
+ },
249
+ this.contextWindow,
250
+ );
251
+ this.emitEvicted(evicted, groupKey, session);
252
+ }
253
+
254
+ /** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
255
+ recordSelf(session: any, text: string): void {
256
+ const key = this.groupKey(session);
257
+ if (!key || !text?.trim()) return;
258
+ const state = this.state.get(key);
259
+ const evicted = state.push(
260
+ {
261
+ id: `self-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
262
+ userId: String(session.bot?.selfId ?? ''),
263
+ name: this.selfName,
264
+ role: 'unknown',
265
+ text: String(text).trim(),
266
+ images: [],
267
+ mentions: [],
268
+ atBot: false,
269
+ self: true,
270
+ at: this.now(),
271
+ },
272
+ this.contextWindow,
273
+ );
274
+ this.emitEvicted(evicted, key, session);
275
+ }
276
+
277
+ /**
278
+ * 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
279
+ * 失败不影响主流程。
280
+ */
281
+ private emitEvicted(evicted: ChatRecord[], groupKey?: string, session?: any): void {
282
+ if (!evicted || !evicted.length) return;
283
+ if (!this.hooks || typeof (this.hooks as any).runContextEvicted !== "function") return;
284
+ // 自动归纳开关 + 生效范围白名单
285
+ const cfg: any = this.config || {};
286
+ if (cfg.memoryAutoLearn === false) return;
287
+ const allow: string[] = Array.isArray(cfg.memoryAutoLearnGroups) ? cfg.memoryAutoLearnGroups.map(String) : [];
288
+ if (allow.length) {
289
+ const gid = String(session?.guildId || "");
290
+ const uid = String(session?.userId || "");
291
+ if (!allow.includes(gid) && !allow.includes(uid)) return;
292
+ }
293
+
294
+ const isDirect = session?.isDirect === true || !session?.guildId;
295
+ const guildId = String(session?.guildId || "");
296
+ const userId = String(session?.userId || "");
297
+ const kind: "group" | "private" = isDirect ? "private" : "group";
298
+ const scopeId = isDirect ? userId : guildId;
299
+ if (!scopeId) return;
300
+
301
+ const payload = evicted.map((item) => ({
302
+ id: item.id,
303
+ userId: item.userId,
304
+ name: item.name,
305
+ role: item.role,
306
+ text: item.text,
307
+ self: item.self,
308
+ at: item.at,
309
+ command: item.command,
310
+ }));
311
+
312
+ void this.hooks
313
+ .runContextEvicted({
314
+ groupId: guildId,
315
+ kind,
316
+ scopeId,
317
+ session,
318
+ evicted: payload,
319
+ window: this.contextWindow,
320
+ })
321
+ .catch((error: any) => {
322
+ this.host.logger?.warn?.(`[ai-evicted] 分发失败: ${String(error)}`);
323
+ });
324
+ }
325
+
326
+ // ---------------------------------------------------------------- 点名 / 跟随
327
+
328
+ private isMention(session: any, record: ChatRecord): boolean {
329
+ // 渲染阶段已经确认 @ 了 bot,不依赖 session.content 的序列化格式
330
+ if (record.atBot) return true;
331
+ const selfId = String(session?.bot?.selfId ?? session?.selfId ?? '');
332
+ if (selfId) {
333
+ const content = String(session?.content ?? '');
334
+ if (content.includes(`<at id="${selfId}"`)) return true;
335
+ const escaped = selfId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
336
+ if (new RegExp(`\\[CQ:at,[^\\]]*(?:qq|id)=${escaped}(?:,|\\])`, 'i').test(content)) return true;
337
+ }
338
+ // 只叫名字(不带 @)是否算点名,交给 aiEnableDirectMentionTrigger 控制
339
+ if (this.config.aiEnableDirectMentionTrigger === false) return false;
340
+ const name = this.selfName.toLowerCase();
341
+ if (!name) return false;
342
+ return String(record.text || '').toLowerCase().includes(name);
343
+ }
344
+
345
+ private addressesOthers(record: ChatRecord, session: any): boolean {
346
+ const selfId = String(session?.bot?.selfId ?? '');
347
+ return record.mentions.length > 0 && !record.mentions.includes(selfId);
348
+ }
349
+
350
+ private shouldContinueFollowup(record: ChatRecord, followup: FollowupState): boolean {
351
+ const text = String(record.text || '').trim();
352
+ if (!text) return false;
353
+ if (this.isCommandLike(text)) return false;
354
+ if (/^[/.!!##]/.test(text)) return false;
355
+ if (text.length <= 2) return false;
356
+ if (/^[\u{1F300}-\u{1FAFF}\s~~!!.。]+$/u.test(text)) return false;
357
+ if (/(换个话题|换个问题|另外|题外话|不聊这个|先不说这个|说点别的|再问个新的)/.test(text)) return false;
358
+
359
+ const current = tokenizeForMatch(text);
360
+ const overlap = [...current].filter((token) => followup.anchorTokens.includes(token)).length;
361
+ const ratio = overlap / Math.max(1, Math.min(current.size || 1, followup.anchorTokens.length || 1));
362
+ if (text.length >= 8 && overlap === 0 && !/[??]/.test(text)) return false;
363
+ if (text.length >= 8 && ratio <= 0.12 && /[??]/.test(text)) return false;
364
+
365
+ if (/[??]/.test(text)) return true;
366
+ if (/(继续|然后|那|所以|为什么|怎么|如何|帮我|还能|可以吗|行吗|对不对|是不是|展开|多说|细说|具体|举个例子|还有呢|后来呢|说说|讲讲)/.test(text)) return true;
367
+ // 没有话题交集、也不是明确的追问 → 不追着说,避免用户换话题后机器人自说自话
368
+ if (overlap > 0 && ratio >= 0.18) return true;
369
+ return false;
370
+ }
371
+
372
+ private startFollowup(state: GroupState, record: ChatRecord): void {
373
+ if (this.config.aiEnableFollowupAfterMention === false) return;
374
+ const seconds = Math.max(1, Number(this.config.aiFollowupWindowSeconds ?? 120));
375
+ state.followup = {
376
+ userId: record.userId,
377
+ expiresAt: this.now() + seconds * 1000,
378
+ turns: 0,
379
+ anchorTokens: [...tokenizeForMatch(record.text)],
380
+ lastText: record.text,
381
+ };
382
+ }
383
+
384
+ private bumpFollowup(state: GroupState, record: ChatRecord): void {
385
+ const followup = state.followup;
386
+ if (!followup) return;
387
+ followup.turns += 1;
388
+ followup.lastText = record.text;
389
+ const seconds = Math.max(1, Number(this.config.aiFollowupWindowSeconds ?? 120));
390
+ followup.expiresAt = this.now() + seconds * 1000;
391
+ const maxTurns = Math.max(1, Number(this.config.aiFollowupMaxTurns ?? 3));
392
+ if (followup.turns >= maxTurns) state.followup = null;
393
+ }
394
+
395
+ private getFollowup(state: GroupState, record: ChatRecord, session: any): FollowupState | null {
396
+ const followup = state.followup;
397
+ if (!followup) return null;
398
+ if (this.now() > followup.expiresAt) {
399
+ state.followup = null;
400
+ return null;
401
+ }
402
+ if (followup.userId !== record.userId) return null;
403
+ if (this.addressesOthers(record, session)) {
404
+ state.followup = null;
405
+ return null;
406
+ }
407
+ return followup;
408
+ }
409
+
410
+ // ---------------------------------------------------------------- 记忆
411
+
412
+ private async loadMemories(record: ChatRecord, state: GroupState, session?: any): Promise<string[]> {
413
+ if (!this.config.enableMemory || this.config.memoryInAi === false) return [];
414
+ let content = '';
415
+ try {
416
+ // 按作用域读对应文件:群聊读该群,私聊读该用户
417
+ const scope = typeof (this.host as any).memoryScopeOf === 'function'
418
+ ? (this.host as any).memoryScopeOf(session)
419
+ : null;
420
+ content = await this.host.readMemoryFile(scope);
421
+ } catch {
422
+ return [];
423
+ }
424
+ const blocks = splitMemoryBlocks(content);
425
+ if (!blocks.length) return [];
426
+ const recent = state.records.slice(-3).map((item) => item.text);
427
+ const selected = selectMemoryBlocks(blocks, [record.text, ...recent], {
428
+ limit: 3,
429
+ minScore: 0.12,
430
+ maxChars: 160,
431
+ });
432
+ return selected.map((item) => item.text);
433
+ }
434
+
435
+ // ---------------------------------------------------------------- 主流程
436
+
437
+ async handle(session: any): Promise<void> {
438
+ const key = this.groupKey(session);
439
+ if (!key) return;
440
+ if (!this.resolveEnabled(session)) return;
441
+ if (String(session.userId) === String(session.bot?.selfId ?? '')) return;
442
+ if (session.platform && !this.platformAllowed(session.platform)) return;
443
+
444
+ const state = this.state.get(key);
445
+ const messageId = String(session.messageId ?? '');
446
+ if (messageId && state.isDuplicate(`${session.platform}:${session.guildId}:${session.userId}:${messageId}`, this.now())) {
447
+ return;
448
+ }
449
+
450
+ let record = messageId ? state.records.find((item) => item.id === messageId) : undefined;
451
+ if (!record) record = (await this.record(session)) ?? undefined;
452
+ if (!record) return;
453
+
454
+ const mention = this.isMention(session, record);
455
+ const followupState = mention ? null : this.getFollowup(state, record, session);
456
+ const followup = !!followupState && this.shouldContinueFollowup(record, followupState);
457
+ // 用户换了话题/说的和上一轮无关时,丢掉待续话题,避免机器人追着自己上一句说
458
+ if (followupState && !followup) state.followup = null;
459
+
460
+ const threshold = Math.max(1, Number(this.config.aiMessageThreshold ?? 15));
461
+ const decision = decideTrigger({
462
+ mode: (this.config.aiReplyMode || 'hybrid') as any,
463
+ counter: state.counter,
464
+ threshold,
465
+ probability: Number(this.config.aiRandomReplyProbability ?? 0.08),
466
+ now: this.now(),
467
+ lastAttemptAt: state.lastAttemptAt,
468
+ minIntervalMs: Math.max(0, Number(this.config.aiMinReplyIntervalSeconds ?? 45)) * 1000,
469
+ lastReplyAt: state.lastReplyAt || 0,
470
+ mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
471
+ inFlight: state.inFlight,
472
+ mention,
473
+ followup,
474
+ rng: this.rng,
475
+ });
476
+
477
+ this.log('ai-trigger', {
478
+ fire: decision.fire,
479
+ reason: decision.reason,
480
+ counter: state.counter,
481
+ threshold,
482
+ mention,
483
+ followup,
484
+ ctx: state.records.length,
485
+ }, session);
486
+ if (!decision.fire) return;
487
+
488
+ state.inFlight = true;
489
+ state.lastAttemptAt = this.now();
490
+ const startedAt = this.now();
491
+
492
+ try {
493
+ const allowPass = !mention && !followup;
494
+ const memories = await this.loadMemories(record, state, session);
495
+ const hookCtx: AiHookContext = {
496
+ session,
497
+ groupId: String(session.guildId),
498
+ mode: 'reply',
499
+ };
500
+ const styleSections = await this.hooks.collectSections(hookCtx);
501
+ const webSearch = await this.webSearch(record, session);
502
+ const promptInput = {
503
+ selfName: this.selfName,
504
+ persona: this.personaPrompt,
505
+ groupId: String(session.guildId),
506
+ records: state.records,
507
+ current: record,
508
+ mention,
509
+ followup,
510
+ allowPass,
511
+ memories,
512
+ maxReplyChars: this.maxReplyChars,
513
+ styleSections,
514
+ webSearch,
515
+ webSearchEnabled: this.config.aiWebSearchEnabled !== false,
516
+ };
517
+
518
+ if (allowPass && this.config.aiReplyDecision === 'two-stage') {
519
+ const judge = await this.judge(promptInput);
520
+ if (!judge) {
521
+ state.counter = 0;
522
+ this.log('ai-pass', { by: 'judge', latencyMs: this.now() - startedAt }, session);
523
+ return;
524
+ }
525
+ }
526
+
527
+ const prompt = buildReplyPrompt(promptInput);
528
+ if (this.debugPrompt) {
529
+ this.host.logger.info(`[ai-debug] system=${prompt.system}\n[ai-debug] user=${prompt.user}`);
530
+ }
531
+
532
+ const images = await this.collectImages(session, record, state);
533
+ const result = await this.provider.chat({
534
+ system: prompt.system,
535
+ user: prompt.user,
536
+ images,
537
+ temperature: Number(this.config.aiTemperature ?? 0.8),
538
+ maxTokens: Number(this.config.aiMaxOutputTokens ?? 400),
539
+ });
540
+
541
+ if (!result.ok) {
542
+ this.log('ai-reply', {
543
+ ok: false,
544
+ error: result.error,
545
+ trigger: decision.reason,
546
+ latencyMs: this.now() - startedAt,
547
+ }, session);
548
+ return;
549
+ }
550
+
551
+ const raw = String(result.text || '').trim();
552
+ if (!raw || PASS_RE.test(raw)) {
553
+ state.counter = 0;
554
+ this.log('ai-pass', {
555
+ by: 'model',
556
+ trigger: decision.reason,
557
+ latencyMs: this.now() - startedAt,
558
+ }, session);
559
+ return;
560
+ }
561
+
562
+ let finalRaw = raw;
563
+ if (!webSearch && this.shouldReviseWithSearch(raw)) {
564
+ const revisedSearch = await this.webSearch(record, session, true);
565
+ if (revisedSearch) {
566
+ const revisedInput = { ...promptInput, webSearch: revisedSearch };
567
+ const revisedUser = `${buildUserPrompt(revisedInput)}\n\n你刚才的回答是:「${truncate(finalRaw, 120)}」。现在补上了联网搜索结果,请根据结果重写最终回复;不要提“刚才/搜索/系统”,直接给答案。`;
568
+ const revised = await this.provider.chat({
569
+ system: prompt.system,
570
+ user: revisedUser,
571
+ images,
572
+ temperature: Number(this.config.aiTemperature ?? 0.8),
573
+ maxTokens: Number(this.config.aiMaxOutputTokens ?? 400),
574
+ });
575
+ if (revised.ok && revised.text && !PASS_RE.test(revised.text.trim())) {
576
+ finalRaw = revised.text.trim();
577
+ this.log('web-search', { ok: true, revised: true, query: buildSearchQuery(record.text) }, session);
578
+ }
579
+ }
580
+ }
581
+
582
+ const cleaned = cleanReply(finalRaw, this.selfName); if (!cleaned) {
583
+ state.counter = 0;
584
+ return;
585
+ }
586
+
587
+ const filtered = await this.hooks.applyFilters(cleaned, hookCtx);
588
+ if (filtered == null) {
589
+ state.counter = 0;
590
+ this.log('ai-pass', {
591
+ by: 'filter',
592
+ trigger: decision.reason,
593
+ latencyMs: this.now() - startedAt,
594
+ }, session);
595
+ return;
596
+ }
597
+
598
+ const finalText = clipReply(filtered, this.maxReplyChars);
599
+ if (!finalText) {
600
+ state.counter = 0;
601
+ return;
602
+ }
603
+
604
+ await this.host.sendReply(session, finalText);
605
+ state.lastReplyAt = this.now();
606
+ state.counter = 0;
607
+ this.recordSelf(session, finalText);
608
+
609
+ if (mention) this.startFollowup(state, record);
610
+ else if (followup && state.followup) this.bumpFollowup(state, record);
611
+
612
+ this.log('ai-reply', {
613
+ ok: true,
614
+ trigger: decision.reason,
615
+ latencyMs: this.now() - startedAt,
616
+ images: images.length,
617
+ degradedToText: !!result.degradedToText,
618
+ chars: finalText.length,
619
+ preview: finalText.slice(0, 60),
620
+ }, session);
621
+
622
+ await this.hooks.runAfterReply({ ...hookCtx, text: finalText });
623
+ } catch (error: any) {
624
+ this.log('ai-reply', {
625
+ ok: false,
626
+ error: String(error?.message || error),
627
+ trigger: decision.reason,
628
+ }, session);
629
+ } finally {
630
+ state.inFlight = false;
631
+ }
632
+ }
633
+
634
+ /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
635
+ chat(request: any) {
636
+ return this.provider.chat(request);
637
+ }
638
+
639
+ /** 群内长时间没人说话时,生成一条主动话题。 */
640
+ async idleTopic(groupId: string): Promise<string> {
641
+ const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
642
+ let sections: string[] = [];
643
+ try {
644
+ sections = await this.hooks.collectSections({ session, groupId, mode: 'reply' });
645
+ } catch { /* ignore */ }
646
+ const system = [
647
+ `你是 QQ 群 ${groupId} 里的一个普通成员。`,
648
+ '群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
649
+ '不要问“在吗”,不要提“很久没人说话”,不要自我介绍。',
650
+ ...sections,
651
+ ].join('\n');
652
+ const result = await this.provider.chat({
653
+ system,
654
+ user: '现在发一条主动话题。',
655
+ temperature: Number(this.config.aiTemperature ?? 0.8),
656
+ maxTokens: Math.min(300, Number(this.config.aiMaxOutputTokens ?? 400)),
657
+ });
658
+ if (!result.ok || !result.text) return '';
659
+ const raw = String(result.text).trim();
660
+ if (!raw || PASS_RE.test(raw)) return '';
661
+ return clipReply(cleanReply(raw, this.selfName), this.maxReplyChars)
662
+ .replace(/\[表情[::][^\]]*\]/g, '')
663
+ .trim();
664
+ }
665
+
666
+ /** 需要时调用 DeepSeek Search API;失败/不支持/没结果都返回空串,继续普通回复。 */
667
+ private async webSearch(record: ChatRecord, session: any, force = false): Promise<string> {
668
+ if (this.config.aiWebSearchEnabled === false) return '';
669
+ const mode = (this.config.aiWebSearchMode || 'auto') as WebSearchMode;
670
+ if (mode === 'off') return '';
671
+ const text = String(record.text || '');
672
+ if (!force && !shouldWebSearch(text, mode)) return '';
673
+ const query = buildSearchQuery(text);
674
+ if (!query) return '';
675
+
676
+ const now = this.now();
677
+ if (this.searchUnsupportedUntil > now) return '';
678
+ const groupId = String(session?.guildId || '');
679
+ const maxPerHour = Math.max(0, Number(this.config.aiWebSearchMaxPerHour ?? 10));
680
+ if (maxPerHour > 0) {
681
+ const list = (this.searchRate.get(groupId) || []).filter((t) => now - t < 3600_000);
682
+ if (list.length >= maxPerHour) {
683
+ this.log('web-search', { ok: false, reason: 'rate-limit', groupId }, session);
684
+ return '';
685
+ }
686
+ list.push(now);
687
+ this.searchRate.set(groupId, list);
688
+ }
689
+
690
+ const cacheMinutes = Math.max(0, Number(this.config.aiWebSearchCacheMinutes ?? 10));
691
+ const cacheKey = `${String(this.config.aiBaseUrl || '')}|${query}`;
692
+ if (cacheMinutes > 0) {
693
+ const hit = this.searchCache.get(cacheKey);
694
+ if (hit && now - hit.at < cacheMinutes * 60_000) return hit.section;
695
+ }
696
+
697
+ const startedAt = this.now();
698
+ const outcome = await fetchWebSearch({
699
+ query,
700
+ apiKey: String(this.config.aiApiKey || ''),
701
+ baseUrl: String(this.config.aiBaseUrl || 'https://api.deepseek.com'),
702
+ maxResults: Number(this.config.aiWebSearchMaxResults ?? 5),
703
+ timeoutMs: Number(this.config.aiWebSearchTimeoutMs ?? 4000),
704
+ maxChars: 1800,
705
+ }, this.fetchImpl);
706
+
707
+ if (!outcome.ok) {
708
+ // 400/401/403/404 通常意味着这个 API 不支持 Search;10 分钟内不再重试
709
+ if (/^http-(400|401|403|404)$/.test(outcome.reason || '')) {
710
+ this.searchUnsupportedUntil = now + 10 * 60_000;
711
+ }
712
+ this.log('web-search', {
713
+ ok: false,
714
+ reason: outcome.reason,
715
+ query,
716
+ latencyMs: this.now() - startedAt,
717
+ }, session);
718
+ return '';
719
+ }
720
+
721
+ if (cacheMinutes > 0) {
722
+ this.searchCache.set(cacheKey, { at: now, section: outcome.section || '' });
723
+ if (this.searchCache.size > 100) {
724
+ const oldest = this.searchCache.keys().next().value;
725
+ if (oldest) this.searchCache.delete(oldest);
726
+ }
727
+ }
728
+ this.log('web-search', {
729
+ ok: true,
730
+ results: outcome.results?.length || 0,
731
+ query,
732
+ latencyMs: this.now() - startedAt,
733
+ }, session);
734
+ return outcome.section || '';
735
+ }
736
+
737
+ /** 模型自己都说不知道/搜不了时,补一次搜索再重写;只在不认识的问题上多一次调用。 */
738
+ private shouldReviseWithSearch(raw: string): boolean {
739
+ if (this.config.aiWebSearchEnabled === false) return false;
740
+ if (String(this.config.aiWebSearchMode || 'auto') === 'off') return false;
741
+ return /(不知道|记不清|记不准|记不牢|不敢乱说|说岔|没法上网|查不了|搜不了|没有联网|无法联网|不确定|不太清楚|分不清|瞎猜)/.test(raw);
742
+ }
743
+
744
+ /** 读取合并转发的子消息,压成一行行文本;读不到就返回空串。 */
745
+ private async readForwards(session: any, forwards: any[]): Promise<string> {
746
+ if (this.config.aiReadForwardMessage === false) return '';
747
+ if (!Array.isArray(forwards) || !forwards.length) return '';
748
+ const limit = Math.max(1, Math.min(50, Number(this.config.aiForwardMaxNodes ?? 20)));
749
+ const onebot = this.host.getOneBotApi(session);
750
+ if (!onebot?.getForwardMsg) return '';
751
+ const blocks: string[] = [];
752
+ for (const item of forwards.slice(0, 3)) {
753
+ const id = String(item?.id || '').trim();
754
+ if (!id) continue;
755
+ try {
756
+ const data = await onebot.getForwardMsg(id);
757
+ const messages = Array.isArray(data?.messages) ? data.messages
758
+ : (Array.isArray(data?.message) ? data.message : (Array.isArray(data) ? data : []));
759
+ for (const node of messages.slice(0, limit)) {
760
+ const sender = String(node?.sender?.card || node?.sender?.nickname || node?.nickname || node?.name || '').trim();
761
+ const content = Array.isArray(node?.message)
762
+ ? node.message.filter((seg: any) => seg?.type === 'text').map((seg: any) => String(seg?.data?.text ?? '')).join('')
763
+ : String(node?.content ?? node?.raw_message ?? node?.message ?? '');
764
+ const text = content.replace(/\[CQ:[^\]]+\]/g, '[图片]').replace(/\s+/g, ' ').trim();
765
+ if (!text) continue;
766
+ blocks.push(`${sender ? `${sender}: ` : ''}${truncate(text, 160)}`);
767
+ }
768
+ } catch (error) {
769
+ this.log('forward', { ok: false, error: String(error) }, session);
770
+ }
771
+ }
772
+ if (!blocks.length) return '';
773
+ this.log('forward', { ok: true, nodes: blocks.length }, session);
774
+ return blocks.join('\n');
775
+ }
776
+
777
+ private recentImageRecords(state: GroupState, record: ChatRecord, maxAgeMs = 120000): RenderedImage[] {
778
+ const cutoff = Number(record.at) - maxAgeMs;
779
+ const candidates = state.records
780
+ .filter((item) => (
781
+ !item.self
782
+ && item.id !== record.id
783
+ && item.userId === record.userId
784
+ && item.images.length > 0
785
+ && Number(item.at) >= cutoff
786
+ ))
787
+ .slice(-4)
788
+ .reverse();
789
+ const out: RenderedImage[] = [];
790
+ for (const item of candidates) {
791
+ for (const image of item.images) out.push(image);
792
+ }
793
+ return out;
794
+ }
795
+
796
+ private async collectImages(session: any, record: ChatRecord, state: GroupState): Promise<string[]> {
797
+ if (this.config.aiEnableImageRecognition === false) return [];
798
+ const maxCount = Math.max(0, Number(this.config.aiImageMaxCount ?? 2));
799
+ if (!maxCount) return [];
800
+
801
+ const own = record.images.length ? record.images : this.host.extractImages(session);
802
+ // 用户常见的“先发图,再单独 @ 一句”:当前消息没有图,回看同一用户最近 2 分钟内的图
803
+ const fallback = own.length ? [] : this.recentImageRecords(state, record);
804
+ let quoted: RenderedImage[] = record.quote
805
+ ? (record.quote.images?.length ? record.quote.images : this.host.extractImages(session?.quote))
806
+ : [];
807
+ // 引用消息里没解析到图(常见于 quote 只带 messageId):用 get_msg 回查一次
808
+ if (!quoted.length && record.quote?.id && typeof this.host.fetchQuotedImages === 'function') {
809
+ quoted = await this.host.fetchQuotedImages(session, record.quote);
810
+ }
811
+ const items = pickImages([...own, ...fallback], quoted, maxCount);
812
+ if (!items.length) return [];
813
+
814
+ return resolveImages(
815
+ items,
816
+ (ref) => this.host.resolveImage(ref, session),
817
+ { maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) },
818
+ );
819
+ }
820
+
821
+ private async judge(input: any): Promise<boolean> {
822
+ const prompt = buildJudgePrompt(input);
823
+ const result: ChatResult = await this.provider.chat({
824
+ system: prompt.system,
825
+ user: prompt.user,
826
+ temperature: 0.1,
827
+ maxTokens: 256,
828
+ });
829
+ if (!result.ok || !result.text) return false;
830
+ const match = result.text.match(/\{[\s\S]*\}/);
831
+ if (!match) return false;
832
+ try {
833
+ const parsed = JSON.parse(match[0]);
834
+ const score = Number(parsed?.score) || 0;
835
+ const min = Number(this.config.aiInterestMinScore ?? 60);
836
+ return !!parsed?.reply && score >= min;
837
+ } catch {
838
+ return false;
839
+ }
840
+ }
841
+
842
+ private platformAllowed(platform: string): boolean {
843
+ const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
844
+ return list.includes(platform);
845
+ }
846
+
847
+ private log(event: string, data: Record<string, any>, session: any): void {
848
+ const extra = Object.entries(data)
849
+ .filter(([, value]) => value !== undefined)
850
+ .map(([key, value]) => `${key}=${typeof value === 'string' ? JSON.stringify(value) : value}`)
851
+ .join(' ');
852
+ this.host.logger.info(
853
+ `[${event}] ${extra} | platform=${session?.platform ?? '?'} user=${session?.userId ?? '?'} guild=${session?.guildId ?? '?'}`,
854
+ );
855
+ }
856
+
857
+ /** 供指令/调试使用 */
858
+ displayNameFor(session: any, qq: string): Promise<string> {
859
+ return this.names.display(session, qq);
860
+ }
861
+
862
+ clear(): void {
863
+ this.state.clear();
864
+ this.names.clear();
865
+ }
866
+ }