@nestim/koishi-plugin-qq-group-manager 1.3.1 → 1.4.1

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