@nestim/koishi-plugin-qq-group-manager 1.1.3 → 1.2.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/CHANGELOG.md +299 -0
- package/lib/ai/engine.d.ts +74 -0
- package/lib/ai/engine.js +525 -0
- package/lib/ai/memory.d.ts +30 -0
- package/lib/ai/memory.js +89 -0
- package/lib/ai/prompt.d.ts +36 -0
- package/lib/ai/prompt.js +125 -0
- package/lib/ai/provider.d.ts +48 -0
- package/lib/ai/provider.js +194 -0
- package/lib/ai/state.d.ts +53 -0
- package/lib/ai/state.js +62 -0
- package/lib/ai/trigger.d.ts +28 -0
- package/lib/ai/trigger.js +41 -0
- package/lib/ai/vision.d.ts +15 -0
- package/lib/ai/vision.js +64 -0
- package/lib/core/names.d.ts +48 -0
- package/lib/core/names.js +144 -0
- package/lib/core/text.d.ts +47 -0
- package/lib/core/text.js +284 -0
- package/lib/index.d.ts +263 -54
- package/lib/index.js +19 -13
- package/lib/service.d.ts +574 -153
- package/lib/service.js +56 -1221
- package/package.json +20 -7
- package/readme.md +149 -11
- package/src/ai/engine.ts +568 -0
- package/src/ai/memory.ts +104 -0
- package/src/ai/prompt.ts +142 -0
- package/src/ai/provider.ts +221 -0
- package/src/ai/state.ts +91 -0
- package/src/ai/trigger.ts +60 -0
- package/src/ai/vision.ts +81 -0
- package/src/core/names.ts +158 -0
- package/src/core/text.ts +332 -0
- package/src/index.ts +186 -0
- package/src/service.js +3327 -0
- package/tsconfig.json +24 -0
- package/lib/commands.d.ts +0 -4
- package/lib/commands.js +0 -18
- package/lib/types.d.ts +0 -23
- package/lib/types.js +0 -2
package/lib/ai/engine.js
ADDED
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* AI 回复引擎。
|
|
4
|
+
*
|
|
5
|
+
* 一次「收到消息」的完整流程:
|
|
6
|
+
* record() 记录到上下文(所有消息都记,包括被管控/指令之外的人话)
|
|
7
|
+
* handle() 判定是否接话 → 组装提示词 → (可选)解析图片 → 调模型
|
|
8
|
+
* → 输出正文 / <pass/> → 发送 → 把自己的回复写回上下文
|
|
9
|
+
*
|
|
10
|
+
* 关键取舍:
|
|
11
|
+
* - 决策与生成合并为一次模型调用,避免"兴趣判定答非所问、生成又挑另一条";
|
|
12
|
+
* - 只回应当前消息,引用与回答永远一致;
|
|
13
|
+
* - 允许模型用 <pass/> 主动放弃,放弃也重置计数,避免每条消息都空转调用。
|
|
14
|
+
*/
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.AiEngine = void 0;
|
|
17
|
+
const state_1 = require("./state");
|
|
18
|
+
const trigger_1 = require("./trigger");
|
|
19
|
+
const prompt_1 = require("./prompt");
|
|
20
|
+
const provider_1 = require("./provider");
|
|
21
|
+
const vision_1 = require("./vision");
|
|
22
|
+
const memory_1 = require("./memory");
|
|
23
|
+
const names_1 = require("../core/names");
|
|
24
|
+
const text_1 = require("../core/text");
|
|
25
|
+
const PASS_RE = /^\s*<(?:pass\s*\/?|不回复)>/i;
|
|
26
|
+
function cleanReply(text, selfName) {
|
|
27
|
+
let out = String(text || '')
|
|
28
|
+
.replace(/^\s*```[a-zA-Z0-9_-]*\s*\n?/, '')
|
|
29
|
+
.replace(/\n?\s*```\s*$/, '')
|
|
30
|
+
// 防止模型输出被平台解析成图片/CQ 码(h.text 本身不解析,这里只是保持干净)
|
|
31
|
+
.replace(/\[CQ:[^\]]+\]/gi, '')
|
|
32
|
+
.replace(/<img\b[^>]*>/gi, '')
|
|
33
|
+
.trim();
|
|
34
|
+
// 去掉模型自作主张的「自称:」前缀
|
|
35
|
+
const prefix = new RegExp(`^\\s*${selfName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*[::]\\s*`, 'i');
|
|
36
|
+
out = out.replace(prefix, '');
|
|
37
|
+
// 整句被引号包住时脱掉
|
|
38
|
+
if (/^[“"「].*[”"」]$/.test(out))
|
|
39
|
+
out = out.slice(1, -1).trim();
|
|
40
|
+
return out.replace(/\s+/g, ' ').trim();
|
|
41
|
+
}
|
|
42
|
+
function clipReply(text, maxChars) {
|
|
43
|
+
const max = Math.max(20, maxChars || 120);
|
|
44
|
+
if (text.length <= max)
|
|
45
|
+
return text;
|
|
46
|
+
const slice = text.slice(0, max);
|
|
47
|
+
const boundary = Math.max(slice.lastIndexOf('。'), slice.lastIndexOf('!'), slice.lastIndexOf('?'), slice.lastIndexOf(','), slice.lastIndexOf(';'), slice.lastIndexOf(';'));
|
|
48
|
+
if (boundary >= max * 0.5)
|
|
49
|
+
return slice.slice(0, boundary + 1);
|
|
50
|
+
return `${slice}…`;
|
|
51
|
+
}
|
|
52
|
+
class AiEngine {
|
|
53
|
+
state;
|
|
54
|
+
provider;
|
|
55
|
+
names;
|
|
56
|
+
rng;
|
|
57
|
+
now;
|
|
58
|
+
host;
|
|
59
|
+
config;
|
|
60
|
+
constructor(host, deps = {}) {
|
|
61
|
+
this.host = host;
|
|
62
|
+
this.config = host.config;
|
|
63
|
+
this.state = deps.state ?? new state_1.AiState();
|
|
64
|
+
this.provider = deps.provider ?? new provider_1.ChatProvider(host.config, host.logger);
|
|
65
|
+
this.names = new names_1.NameResolver({
|
|
66
|
+
getOneBotApi: (session) => host.getOneBotApi(session),
|
|
67
|
+
toGroupId: (session) => host.toGroupId(session),
|
|
68
|
+
logger: host.logger,
|
|
69
|
+
});
|
|
70
|
+
this.rng = deps.rng ?? Math.random;
|
|
71
|
+
this.now = deps.now ?? Date.now;
|
|
72
|
+
}
|
|
73
|
+
// ---------------------------------------------------------------- 配置
|
|
74
|
+
groupKey(session) {
|
|
75
|
+
if (!session?.guildId)
|
|
76
|
+
return '';
|
|
77
|
+
return `${session.platform ?? 'unknown'}:${session.guildId}`;
|
|
78
|
+
}
|
|
79
|
+
ruleFor(session) {
|
|
80
|
+
const guildId = String(session?.guildId ?? '');
|
|
81
|
+
const rules = Array.isArray(this.config.groupRules) ? this.config.groupRules : [];
|
|
82
|
+
return rules.find((item) => String(item?.guildId ?? '').trim() === guildId);
|
|
83
|
+
}
|
|
84
|
+
resolveEnabled(session) {
|
|
85
|
+
const rule = this.ruleFor(session);
|
|
86
|
+
const requireRule = this.config.aiReplyRequireGroupRule !== false;
|
|
87
|
+
if (requireRule && !rule)
|
|
88
|
+
return false;
|
|
89
|
+
if (rule && typeof rule.enableAiReply === 'boolean')
|
|
90
|
+
return rule.enableAiReply;
|
|
91
|
+
return !!this.config.enableAiReply;
|
|
92
|
+
}
|
|
93
|
+
get contextWindow() {
|
|
94
|
+
const value = Number(this.config.aiContextWindow ?? 24);
|
|
95
|
+
return Math.max(6, Math.min(100, Number.isFinite(value) ? value : 24));
|
|
96
|
+
}
|
|
97
|
+
get selfName() {
|
|
98
|
+
const persona = this.activePersona();
|
|
99
|
+
return String(persona?.selfName || this.config.aiAgentName || 'MeowBot').trim() || 'MeowBot';
|
|
100
|
+
}
|
|
101
|
+
activePersona() {
|
|
102
|
+
const id = String(this.config.aiActivePersona ?? '').trim();
|
|
103
|
+
if (!id)
|
|
104
|
+
return null;
|
|
105
|
+
const list = Array.isArray(this.config.aiPersonas) ? this.config.aiPersonas : [];
|
|
106
|
+
return list.find((item) => String(item?.id ?? '').trim() === id) ?? null;
|
|
107
|
+
}
|
|
108
|
+
get personaPrompt() {
|
|
109
|
+
const persona = this.activePersona();
|
|
110
|
+
return String(persona?.prompt || this.config.aiSystemPrompt || '').trim();
|
|
111
|
+
}
|
|
112
|
+
get maxReplyChars() {
|
|
113
|
+
const value = Number(this.config.aiMaxReplyChars ?? 120);
|
|
114
|
+
return Math.max(20, Math.min(500, Number.isFinite(value) ? value : 120));
|
|
115
|
+
}
|
|
116
|
+
get debugPrompt() {
|
|
117
|
+
return !!this.config.aiDebugPrompt;
|
|
118
|
+
}
|
|
119
|
+
// ---------------------------------------------------------------- 记录
|
|
120
|
+
/** 是否像指令(这类消息不进上下文,避免污染) */
|
|
121
|
+
isCommandLike(text) {
|
|
122
|
+
const value = String(text || '').trim();
|
|
123
|
+
if (!value)
|
|
124
|
+
return false;
|
|
125
|
+
if (/^[/.!!##]/.test(value))
|
|
126
|
+
return true;
|
|
127
|
+
if (/^\[[^\]\s]+\]/.test(value))
|
|
128
|
+
return true;
|
|
129
|
+
const prefixes = [this.config.command, this.config.menuCommand, 'help']
|
|
130
|
+
.map((item) => String(item ?? '').trim())
|
|
131
|
+
.filter(Boolean);
|
|
132
|
+
return prefixes.some((prefix) => value === prefix || value.startsWith(`${prefix} `));
|
|
133
|
+
}
|
|
134
|
+
/** 记录一条群消息;返回落库后的记录(指令类返回 null) */
|
|
135
|
+
async record(session) {
|
|
136
|
+
const key = this.groupKey(session);
|
|
137
|
+
if (!key || !session?.userId)
|
|
138
|
+
return null;
|
|
139
|
+
if (String(session.userId) === String(session.bot?.selfId ?? ''))
|
|
140
|
+
return null;
|
|
141
|
+
const state = this.state.get(key);
|
|
142
|
+
const messageId = String(session.messageId ?? '');
|
|
143
|
+
if (messageId) {
|
|
144
|
+
const existing = state.records.find((item) => item.id === messageId);
|
|
145
|
+
if (existing)
|
|
146
|
+
return existing;
|
|
147
|
+
}
|
|
148
|
+
const contextWindow = this.contextWindow;
|
|
149
|
+
// 先排除指令,避免为指令解析 @ / 查群名片
|
|
150
|
+
const rawText = String(session.content ?? '').trim();
|
|
151
|
+
if (this.isCommandLike(rawText.replace(/^\s*(<at\b[^>]*\/?>|\[CQ:at,[^\]]+\])\s*/i, ''))) {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
const identity = await this.names.identify(session);
|
|
155
|
+
const rendered = await (0, text_1.renderMessage)(session, this.names.resolverFor(session), {
|
|
156
|
+
selfId: String(session.bot?.selfId ?? session.selfId ?? ''),
|
|
157
|
+
});
|
|
158
|
+
const record = {
|
|
159
|
+
id: messageId || `local-${this.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
|
160
|
+
userId: String(session.userId),
|
|
161
|
+
name: identity.name || String(session.userId),
|
|
162
|
+
role: identity.role,
|
|
163
|
+
text: rendered.text,
|
|
164
|
+
images: rendered.images,
|
|
165
|
+
quote: rendered.quote,
|
|
166
|
+
mentions: rendered.mentions,
|
|
167
|
+
atBot: rendered.atBot,
|
|
168
|
+
self: false,
|
|
169
|
+
at: Number(session.timestamp) || this.now(),
|
|
170
|
+
};
|
|
171
|
+
state.push(record, contextWindow);
|
|
172
|
+
state.counter += 1;
|
|
173
|
+
return record;
|
|
174
|
+
}
|
|
175
|
+
/** 追加一条系统注记(复读等),不进计数、不触发 */
|
|
176
|
+
note(text, groupKey, session) {
|
|
177
|
+
const key = groupKey || (session ? this.groupKey(session) : '');
|
|
178
|
+
if (!key || !text?.trim())
|
|
179
|
+
return;
|
|
180
|
+
const state = this.state.get(key);
|
|
181
|
+
state.push({
|
|
182
|
+
id: `note-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
183
|
+
userId: 'system',
|
|
184
|
+
name: '系统',
|
|
185
|
+
role: 'unknown',
|
|
186
|
+
text: String(text).trim(),
|
|
187
|
+
images: [],
|
|
188
|
+
mentions: [],
|
|
189
|
+
atBot: false,
|
|
190
|
+
self: false,
|
|
191
|
+
at: this.now(),
|
|
192
|
+
command: true,
|
|
193
|
+
}, this.contextWindow);
|
|
194
|
+
}
|
|
195
|
+
/** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
|
|
196
|
+
recordSelf(session, text) {
|
|
197
|
+
const key = this.groupKey(session);
|
|
198
|
+
if (!key || !text?.trim())
|
|
199
|
+
return;
|
|
200
|
+
const state = this.state.get(key);
|
|
201
|
+
state.push({
|
|
202
|
+
id: `self-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
203
|
+
userId: String(session.bot?.selfId ?? ''),
|
|
204
|
+
name: this.selfName,
|
|
205
|
+
role: 'unknown',
|
|
206
|
+
text: String(text).trim(),
|
|
207
|
+
images: [],
|
|
208
|
+
mentions: [],
|
|
209
|
+
atBot: false,
|
|
210
|
+
self: true,
|
|
211
|
+
at: this.now(),
|
|
212
|
+
}, this.contextWindow);
|
|
213
|
+
}
|
|
214
|
+
// ---------------------------------------------------------------- 点名 / 跟随
|
|
215
|
+
isMention(session, record) {
|
|
216
|
+
// 渲染阶段已经确认 @ 了 bot,不依赖 session.content 的序列化格式
|
|
217
|
+
if (record.atBot)
|
|
218
|
+
return true;
|
|
219
|
+
const selfId = String(session?.bot?.selfId ?? session?.selfId ?? '');
|
|
220
|
+
if (selfId) {
|
|
221
|
+
const content = String(session?.content ?? '');
|
|
222
|
+
if (content.includes(`<at id="${selfId}"`))
|
|
223
|
+
return true;
|
|
224
|
+
const escaped = selfId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
225
|
+
if (new RegExp(`\\[CQ:at,[^\\]]*(?:qq|id)=${escaped}(?:,|\\])`, 'i').test(content))
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
// 只叫名字(不带 @)是否算点名,交给 aiEnableDirectMentionTrigger 控制
|
|
229
|
+
if (this.config.aiEnableDirectMentionTrigger === false)
|
|
230
|
+
return false;
|
|
231
|
+
const name = this.selfName.toLowerCase();
|
|
232
|
+
if (!name)
|
|
233
|
+
return false;
|
|
234
|
+
return String(record.text || '').toLowerCase().includes(name);
|
|
235
|
+
}
|
|
236
|
+
addressesOthers(record, session) {
|
|
237
|
+
const selfId = String(session?.bot?.selfId ?? '');
|
|
238
|
+
return record.mentions.length > 0 && !record.mentions.includes(selfId);
|
|
239
|
+
}
|
|
240
|
+
shouldContinueFollowup(record, followup) {
|
|
241
|
+
const text = String(record.text || '').trim();
|
|
242
|
+
if (!text)
|
|
243
|
+
return false;
|
|
244
|
+
if (this.isCommandLike(text))
|
|
245
|
+
return false;
|
|
246
|
+
if (/^[/.!!##]/.test(text))
|
|
247
|
+
return false;
|
|
248
|
+
if (text.length <= 2)
|
|
249
|
+
return false;
|
|
250
|
+
if (/^[\u{1F300}-\u{1FAFF}\s~~!!.。]+$/u.test(text))
|
|
251
|
+
return false;
|
|
252
|
+
if (/(换个话题|换个问题|另外|题外话|不聊这个|先不说这个|说点别的|再问个新的)/.test(text))
|
|
253
|
+
return false;
|
|
254
|
+
const current = (0, memory_1.tokenizeForMatch)(text);
|
|
255
|
+
const overlap = [...current].filter((token) => followup.anchorTokens.includes(token)).length;
|
|
256
|
+
const ratio = overlap / Math.max(1, Math.min(current.size || 1, followup.anchorTokens.length || 1));
|
|
257
|
+
if (text.length >= 8 && overlap === 0 && !/[??]/.test(text))
|
|
258
|
+
return false;
|
|
259
|
+
if (text.length >= 8 && ratio <= 0.12 && /[??]/.test(text))
|
|
260
|
+
return false;
|
|
261
|
+
if (/[??]/.test(text))
|
|
262
|
+
return true;
|
|
263
|
+
if (/(继续|然后|那|所以|为什么|怎么|如何|帮我|还能|可以吗|行吗|对不对|是不是)/.test(text))
|
|
264
|
+
return true;
|
|
265
|
+
return text.length >= 6;
|
|
266
|
+
}
|
|
267
|
+
startFollowup(state, record) {
|
|
268
|
+
if (this.config.aiEnableFollowupAfterMention === false)
|
|
269
|
+
return;
|
|
270
|
+
const seconds = Math.max(1, Number(this.config.aiFollowupWindowSeconds ?? 120));
|
|
271
|
+
state.followup = {
|
|
272
|
+
userId: record.userId,
|
|
273
|
+
expiresAt: this.now() + seconds * 1000,
|
|
274
|
+
turns: 0,
|
|
275
|
+
anchorTokens: [...(0, memory_1.tokenizeForMatch)(record.text)],
|
|
276
|
+
lastText: record.text,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
bumpFollowup(state, record) {
|
|
280
|
+
const followup = state.followup;
|
|
281
|
+
if (!followup)
|
|
282
|
+
return;
|
|
283
|
+
followup.turns += 1;
|
|
284
|
+
followup.lastText = record.text;
|
|
285
|
+
const seconds = Math.max(1, Number(this.config.aiFollowupWindowSeconds ?? 120));
|
|
286
|
+
followup.expiresAt = this.now() + seconds * 1000;
|
|
287
|
+
const maxTurns = Math.max(1, Number(this.config.aiFollowupMaxTurns ?? 3));
|
|
288
|
+
if (followup.turns >= maxTurns)
|
|
289
|
+
state.followup = null;
|
|
290
|
+
}
|
|
291
|
+
getFollowup(state, record, session) {
|
|
292
|
+
const followup = state.followup;
|
|
293
|
+
if (!followup)
|
|
294
|
+
return null;
|
|
295
|
+
if (this.now() > followup.expiresAt) {
|
|
296
|
+
state.followup = null;
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
if (followup.userId !== record.userId)
|
|
300
|
+
return null;
|
|
301
|
+
if (this.addressesOthers(record, session)) {
|
|
302
|
+
state.followup = null;
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
return followup;
|
|
306
|
+
}
|
|
307
|
+
// ---------------------------------------------------------------- 记忆
|
|
308
|
+
async loadMemories(record, state) {
|
|
309
|
+
if (!this.config.enableMemory || this.config.memoryInAi === false)
|
|
310
|
+
return [];
|
|
311
|
+
let content = '';
|
|
312
|
+
try {
|
|
313
|
+
content = await this.host.readMemoryFile();
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return [];
|
|
317
|
+
}
|
|
318
|
+
const blocks = (0, memory_1.splitMemoryBlocks)(content);
|
|
319
|
+
if (!blocks.length)
|
|
320
|
+
return [];
|
|
321
|
+
const recent = state.records.slice(-3).map((item) => item.text);
|
|
322
|
+
const selected = (0, memory_1.selectMemoryBlocks)(blocks, [record.text, ...recent], {
|
|
323
|
+
limit: 3,
|
|
324
|
+
minScore: 0.12,
|
|
325
|
+
maxChars: 160,
|
|
326
|
+
});
|
|
327
|
+
return selected.map((item) => item.text);
|
|
328
|
+
}
|
|
329
|
+
// ---------------------------------------------------------------- 主流程
|
|
330
|
+
async handle(session) {
|
|
331
|
+
const key = this.groupKey(session);
|
|
332
|
+
if (!key)
|
|
333
|
+
return;
|
|
334
|
+
if (!this.resolveEnabled(session))
|
|
335
|
+
return;
|
|
336
|
+
if (String(session.userId) === String(session.bot?.selfId ?? ''))
|
|
337
|
+
return;
|
|
338
|
+
if (session.platform && !this.platformAllowed(session.platform))
|
|
339
|
+
return;
|
|
340
|
+
const state = this.state.get(key);
|
|
341
|
+
const messageId = String(session.messageId ?? '');
|
|
342
|
+
if (messageId && state.isDuplicate(`${session.platform}:${session.guildId}:${session.userId}:${messageId}`, this.now())) {
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
let record = messageId ? state.records.find((item) => item.id === messageId) : undefined;
|
|
346
|
+
if (!record)
|
|
347
|
+
record = (await this.record(session)) ?? undefined;
|
|
348
|
+
if (!record)
|
|
349
|
+
return;
|
|
350
|
+
const mention = this.isMention(session, record);
|
|
351
|
+
const followupState = mention ? null : this.getFollowup(state, record, session);
|
|
352
|
+
const followup = !!followupState && this.shouldContinueFollowup(record, followupState);
|
|
353
|
+
const threshold = Math.max(1, Number(this.config.aiMessageThreshold ?? 15));
|
|
354
|
+
const decision = (0, trigger_1.decideTrigger)({
|
|
355
|
+
mode: (this.config.aiReplyMode || 'hybrid'),
|
|
356
|
+
counter: state.counter,
|
|
357
|
+
threshold,
|
|
358
|
+
probability: Number(this.config.aiRandomReplyProbability ?? 0.08),
|
|
359
|
+
now: this.now(),
|
|
360
|
+
lastAttemptAt: state.lastAttemptAt,
|
|
361
|
+
minIntervalMs: Math.max(0, Number(this.config.aiMinReplyIntervalSeconds ?? 45)) * 1000,
|
|
362
|
+
inFlight: state.inFlight,
|
|
363
|
+
mention,
|
|
364
|
+
followup,
|
|
365
|
+
rng: this.rng,
|
|
366
|
+
});
|
|
367
|
+
this.log('ai-trigger', {
|
|
368
|
+
fire: decision.fire,
|
|
369
|
+
reason: decision.reason,
|
|
370
|
+
counter: state.counter,
|
|
371
|
+
threshold,
|
|
372
|
+
mention,
|
|
373
|
+
followup,
|
|
374
|
+
ctx: state.records.length,
|
|
375
|
+
}, session);
|
|
376
|
+
if (!decision.fire)
|
|
377
|
+
return;
|
|
378
|
+
state.inFlight = true;
|
|
379
|
+
state.lastAttemptAt = this.now();
|
|
380
|
+
const startedAt = this.now();
|
|
381
|
+
try {
|
|
382
|
+
const allowPass = !mention && !followup;
|
|
383
|
+
const memories = await this.loadMemories(record, state);
|
|
384
|
+
const promptInput = {
|
|
385
|
+
selfName: this.selfName,
|
|
386
|
+
persona: this.personaPrompt,
|
|
387
|
+
groupId: String(session.guildId),
|
|
388
|
+
records: state.records,
|
|
389
|
+
current: record,
|
|
390
|
+
mention,
|
|
391
|
+
followup,
|
|
392
|
+
allowPass,
|
|
393
|
+
memories,
|
|
394
|
+
maxReplyChars: this.maxReplyChars,
|
|
395
|
+
};
|
|
396
|
+
if (allowPass && this.config.aiReplyDecision === 'two-stage') {
|
|
397
|
+
const judge = await this.judge(promptInput);
|
|
398
|
+
if (!judge) {
|
|
399
|
+
state.counter = 0;
|
|
400
|
+
this.log('ai-pass', { by: 'judge', latencyMs: this.now() - startedAt }, session);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const prompt = (0, prompt_1.buildReplyPrompt)(promptInput);
|
|
405
|
+
if (this.debugPrompt) {
|
|
406
|
+
this.host.logger.info(`[ai-debug] system=${prompt.system}\n[ai-debug] user=${prompt.user}`);
|
|
407
|
+
}
|
|
408
|
+
const images = await this.collectImages(session, record);
|
|
409
|
+
const result = await this.provider.chat({
|
|
410
|
+
system: prompt.system,
|
|
411
|
+
user: prompt.user,
|
|
412
|
+
images,
|
|
413
|
+
temperature: Number(this.config.aiTemperature ?? 0.8),
|
|
414
|
+
maxTokens: Number(this.config.aiMaxOutputTokens ?? 400),
|
|
415
|
+
});
|
|
416
|
+
if (!result.ok) {
|
|
417
|
+
this.log('ai-reply', {
|
|
418
|
+
ok: false,
|
|
419
|
+
error: result.error,
|
|
420
|
+
trigger: decision.reason,
|
|
421
|
+
latencyMs: this.now() - startedAt,
|
|
422
|
+
}, session);
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
const raw = String(result.text || '').trim();
|
|
426
|
+
if (!raw || PASS_RE.test(raw)) {
|
|
427
|
+
state.counter = 0;
|
|
428
|
+
this.log('ai-pass', {
|
|
429
|
+
by: 'model',
|
|
430
|
+
trigger: decision.reason,
|
|
431
|
+
latencyMs: this.now() - startedAt,
|
|
432
|
+
}, session);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const cleaned = clipReply(cleanReply(raw, this.selfName), this.maxReplyChars);
|
|
436
|
+
if (!cleaned) {
|
|
437
|
+
state.counter = 0;
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
await this.host.sendReply(session, cleaned);
|
|
441
|
+
state.lastReplyAt = this.now();
|
|
442
|
+
state.counter = 0;
|
|
443
|
+
this.recordSelf(session, cleaned);
|
|
444
|
+
if (mention)
|
|
445
|
+
this.startFollowup(state, record);
|
|
446
|
+
else if (followup && state.followup)
|
|
447
|
+
this.bumpFollowup(state, record);
|
|
448
|
+
this.log('ai-reply', {
|
|
449
|
+
ok: true,
|
|
450
|
+
trigger: decision.reason,
|
|
451
|
+
latencyMs: this.now() - startedAt,
|
|
452
|
+
images: images.length,
|
|
453
|
+
degradedToText: !!result.degradedToText,
|
|
454
|
+
chars: cleaned.length,
|
|
455
|
+
preview: cleaned.slice(0, 60),
|
|
456
|
+
}, session);
|
|
457
|
+
}
|
|
458
|
+
catch (error) {
|
|
459
|
+
this.log('ai-reply', {
|
|
460
|
+
ok: false,
|
|
461
|
+
error: String(error?.message || error),
|
|
462
|
+
trigger: decision.reason,
|
|
463
|
+
}, session);
|
|
464
|
+
}
|
|
465
|
+
finally {
|
|
466
|
+
state.inFlight = false;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
async collectImages(session, record) {
|
|
470
|
+
if (this.config.aiEnableImageRecognition === false)
|
|
471
|
+
return [];
|
|
472
|
+
const maxCount = Math.max(0, Number(this.config.aiImageMaxCount ?? 2));
|
|
473
|
+
if (!maxCount)
|
|
474
|
+
return [];
|
|
475
|
+
const own = record.images.length ? record.images : this.host.extractImages(session);
|
|
476
|
+
const quoted = record.quote ? this.host.extractImages(session?.quote) : [];
|
|
477
|
+
const items = (0, vision_1.pickImages)(own, quoted, maxCount);
|
|
478
|
+
if (!items.length)
|
|
479
|
+
return [];
|
|
480
|
+
return (0, vision_1.resolveImages)(items, (ref) => this.host.resolveImage(ref, session), { maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) });
|
|
481
|
+
}
|
|
482
|
+
async judge(input) {
|
|
483
|
+
const prompt = (0, prompt_1.buildJudgePrompt)(input);
|
|
484
|
+
const result = await this.provider.chat({
|
|
485
|
+
system: prompt.system,
|
|
486
|
+
user: prompt.user,
|
|
487
|
+
temperature: 0.1,
|
|
488
|
+
maxTokens: 256,
|
|
489
|
+
});
|
|
490
|
+
if (!result.ok || !result.text)
|
|
491
|
+
return false;
|
|
492
|
+
const match = result.text.match(/\{[\s\S]*\}/);
|
|
493
|
+
if (!match)
|
|
494
|
+
return false;
|
|
495
|
+
try {
|
|
496
|
+
const parsed = JSON.parse(match[0]);
|
|
497
|
+
const score = Number(parsed?.score) || 0;
|
|
498
|
+
const min = Number(this.config.aiInterestMinScore ?? 60);
|
|
499
|
+
return !!parsed?.reply && score >= min;
|
|
500
|
+
}
|
|
501
|
+
catch {
|
|
502
|
+
return false;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
platformAllowed(platform) {
|
|
506
|
+
const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
|
|
507
|
+
return list.includes(platform);
|
|
508
|
+
}
|
|
509
|
+
log(event, data, session) {
|
|
510
|
+
const extra = Object.entries(data)
|
|
511
|
+
.filter(([, value]) => value !== undefined)
|
|
512
|
+
.map(([key, value]) => `${key}=${typeof value === 'string' ? JSON.stringify(value) : value}`)
|
|
513
|
+
.join(' ');
|
|
514
|
+
this.host.logger.info(`[${event}] ${extra} | platform=${session?.platform ?? '?'} user=${session?.userId ?? '?'} guild=${session?.guildId ?? '?'}`);
|
|
515
|
+
}
|
|
516
|
+
/** 供指令/调试使用 */
|
|
517
|
+
displayNameFor(session, qq) {
|
|
518
|
+
return this.names.display(session, qq);
|
|
519
|
+
}
|
|
520
|
+
clear() {
|
|
521
|
+
this.state.clear();
|
|
522
|
+
this.names.clear();
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
exports.AiEngine = AiEngine;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆检索(纯函数)。
|
|
3
|
+
*
|
|
4
|
+
* 旧实现用「整句 includes」匹配,中文整句几乎永远匹配不到,于是每次 fallback
|
|
5
|
+
* 注入最近 6 条记忆——不管群里在聊什么,模型都会被喂"星野爱"。
|
|
6
|
+
*
|
|
7
|
+
* 这里改成字级 n-gram 重叠打分:只有真正和当前消息/最近两三条消息有交集的
|
|
8
|
+
* 记忆才会被注入;没有交集就一条都不给。
|
|
9
|
+
*/
|
|
10
|
+
/** 中文按二元组切,英文/数字按词切 */
|
|
11
|
+
export declare function tokenizeForMatch(text: string): Set<string>;
|
|
12
|
+
export interface MemoryBlock {
|
|
13
|
+
text: string;
|
|
14
|
+
/** 原始下标,用于稳定排序 */
|
|
15
|
+
index: number;
|
|
16
|
+
}
|
|
17
|
+
export declare function splitMemoryBlocks(content: string): MemoryBlock[];
|
|
18
|
+
export interface SelectOptions {
|
|
19
|
+
limit?: number;
|
|
20
|
+
/** 命中率门槛:命中 token 数 / min(查询 token 数, 24) */
|
|
21
|
+
minScore?: number;
|
|
22
|
+
/** 单条注入的最大字符数 */
|
|
23
|
+
maxChars?: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* 选出与当前话题相关的记忆。
|
|
27
|
+
* @param blocks 记忆条目
|
|
28
|
+
* @param queryTexts 当前消息 + 最近几条上下文(按重要性从高到低)
|
|
29
|
+
*/
|
|
30
|
+
export declare function selectMemoryBlocks(blocks: MemoryBlock[], queryTexts: string[], options?: SelectOptions): MemoryBlock[];
|
package/lib/ai/memory.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* 记忆检索(纯函数)。
|
|
4
|
+
*
|
|
5
|
+
* 旧实现用「整句 includes」匹配,中文整句几乎永远匹配不到,于是每次 fallback
|
|
6
|
+
* 注入最近 6 条记忆——不管群里在聊什么,模型都会被喂"星野爱"。
|
|
7
|
+
*
|
|
8
|
+
* 这里改成字级 n-gram 重叠打分:只有真正和当前消息/最近两三条消息有交集的
|
|
9
|
+
* 记忆才会被注入;没有交集就一条都不给。
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.tokenizeForMatch = tokenizeForMatch;
|
|
13
|
+
exports.splitMemoryBlocks = splitMemoryBlocks;
|
|
14
|
+
exports.selectMemoryBlocks = selectMemoryBlocks;
|
|
15
|
+
const CJK = /[\u4e00-\u9fa5]/;
|
|
16
|
+
/** 中文按二元组切,英文/数字按词切 */
|
|
17
|
+
function tokenizeForMatch(text) {
|
|
18
|
+
const tokens = new Set();
|
|
19
|
+
const normalized = String(text || '')
|
|
20
|
+
.toLowerCase()
|
|
21
|
+
.replace(/[^\u4e00-\u9fa5a-z0-9]+/g, ' ')
|
|
22
|
+
.trim();
|
|
23
|
+
if (!normalized)
|
|
24
|
+
return tokens;
|
|
25
|
+
for (const chunk of normalized.split(/\s+/)) {
|
|
26
|
+
if (!chunk)
|
|
27
|
+
continue;
|
|
28
|
+
if (CJK.test(chunk)) {
|
|
29
|
+
const chars = [...chunk];
|
|
30
|
+
if (chars.length === 1) {
|
|
31
|
+
tokens.add(chunk);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
for (let i = 0; i < chars.length - 1; i += 1) {
|
|
35
|
+
tokens.add(chars[i] + chars[i + 1]);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else if (chunk.length >= 2) {
|
|
39
|
+
tokens.add(chunk);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return tokens;
|
|
43
|
+
}
|
|
44
|
+
function splitMemoryBlocks(content) {
|
|
45
|
+
return String(content || '')
|
|
46
|
+
.split(/\r?\n---\r?\n/)
|
|
47
|
+
.map((item) => item.trim())
|
|
48
|
+
.filter(Boolean)
|
|
49
|
+
.map((text, index) => ({ text, index }));
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* 选出与当前话题相关的记忆。
|
|
53
|
+
* @param blocks 记忆条目
|
|
54
|
+
* @param queryTexts 当前消息 + 最近几条上下文(按重要性从高到低)
|
|
55
|
+
*/
|
|
56
|
+
function selectMemoryBlocks(blocks, queryTexts, options = {}) {
|
|
57
|
+
const limit = Math.max(0, options.limit ?? 3);
|
|
58
|
+
const minScore = options.minScore ?? 0.12;
|
|
59
|
+
const maxChars = options.maxChars ?? 160;
|
|
60
|
+
if (!limit || !blocks.length)
|
|
61
|
+
return [];
|
|
62
|
+
const queryTokens = new Set();
|
|
63
|
+
for (const text of queryTexts) {
|
|
64
|
+
for (const token of tokenizeForMatch(text))
|
|
65
|
+
queryTokens.add(token);
|
|
66
|
+
}
|
|
67
|
+
if (!queryTokens.size)
|
|
68
|
+
return [];
|
|
69
|
+
const denominator = Math.max(1, Math.min(queryTokens.size, 24));
|
|
70
|
+
const scored = blocks.map((block) => {
|
|
71
|
+
const tokens = tokenizeForMatch(block.text);
|
|
72
|
+
let hits = 0;
|
|
73
|
+
for (const token of tokens) {
|
|
74
|
+
if (queryTokens.has(token))
|
|
75
|
+
hits += 1;
|
|
76
|
+
}
|
|
77
|
+
// 至少命中 2 个二元组才算相关,避免"的""了"这类碎片误命中
|
|
78
|
+
const score = hits >= 2 ? hits / denominator : 0;
|
|
79
|
+
return { block, hits, score };
|
|
80
|
+
});
|
|
81
|
+
return scored
|
|
82
|
+
.filter((item) => item.score >= minScore)
|
|
83
|
+
.sort((a, b) => b.score - a.score || a.block.index - b.block.index)
|
|
84
|
+
.slice(0, limit)
|
|
85
|
+
.map((item) => ({
|
|
86
|
+
...item.block,
|
|
87
|
+
text: item.block.text.length > maxChars ? `${item.block.text.slice(0, maxChars)}…` : item.block.text,
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 提示词组装(纯函数)。
|
|
3
|
+
*
|
|
4
|
+
* 设计要点(对应旧版的四个病灶):
|
|
5
|
+
* - 上下文严格按时间顺序,不按关键词重排,不出现"不要回复最后一条";
|
|
6
|
+
* - 明确「只回应当前消息」,引用与回答永远指向同一条;
|
|
7
|
+
* - 机器人自己的历史发言以「你」出现,前后文能接上;
|
|
8
|
+
* - 记忆只在检索命中时注入,并且明确允许忽略;
|
|
9
|
+
* - 非点名场景允许模型输出 <pass/> 放弃接话(决策与生成合一,不再两次调用)。
|
|
10
|
+
*/
|
|
11
|
+
import type { ChatRecord } from './state';
|
|
12
|
+
export interface PromptInput {
|
|
13
|
+
selfName: string;
|
|
14
|
+
persona: string;
|
|
15
|
+
groupId: string;
|
|
16
|
+
records: ChatRecord[];
|
|
17
|
+
current: ChatRecord;
|
|
18
|
+
mention: boolean;
|
|
19
|
+
followup: boolean;
|
|
20
|
+
allowPass: boolean;
|
|
21
|
+
memories: string[];
|
|
22
|
+
maxReplyChars: number;
|
|
23
|
+
}
|
|
24
|
+
export declare const PASS_TOKEN = "<pass/>";
|
|
25
|
+
export declare function renderRecordLine(record: ChatRecord, selfName: string): string;
|
|
26
|
+
export declare function buildSystemPrompt(input: PromptInput): string;
|
|
27
|
+
export declare function buildUserPrompt(input: PromptInput): string;
|
|
28
|
+
export declare function buildReplyPrompt(input: PromptInput): {
|
|
29
|
+
system: string;
|
|
30
|
+
user: string;
|
|
31
|
+
};
|
|
32
|
+
/** 两段式模式下的判定提示词(只有显式配置 aiReplyDecision=two-stage 才会用) */
|
|
33
|
+
export declare function buildJudgePrompt(input: PromptInput): {
|
|
34
|
+
system: string;
|
|
35
|
+
user: string;
|
|
36
|
+
};
|