@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/CHANGELOG.md +24 -0
- package/lib/ai/engine.d.ts +30 -1
- package/lib/ai/engine.js +218 -6
- package/lib/ai/hooks.d.ts +37 -3
- package/lib/ai/hooks.js +25 -3
- package/lib/ai/learn.d.ts +58 -0
- package/lib/ai/learn.js +200 -0
- package/lib/ai/state.d.ts +4 -2
- package/lib/ai/state.js +6 -3
- package/lib/index.d.ts +18 -0
- package/lib/index.js +12 -3
- package/lib/service.d.ts +33 -7
- package/lib/service.js +71 -21
- package/package.json +1 -1
- package/readme.md +41 -3
- package/src/ai/engine.ts +994 -771
- package/src/ai/engine.ts.bak.manual +814 -0
- package/src/ai/hooks.ts +55 -3
- package/src/ai/learn.ts +208 -0
- package/src/ai/state.ts +7 -4
- package/src/index.ts +12 -3
- package/src/service.js +3762 -3713
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
|
|
4
4
|
|
|
5
|
+
## 1.4.1
|
|
6
|
+
|
|
7
|
+
### 新增
|
|
8
|
+
|
|
9
|
+
- **AI 自动归纳记忆(内建,不需要额外插件)**:
|
|
10
|
+
上下文挤满、最老的消息即将被丢弃时,把它们累计起来;达到阈值(`aiContextWindow × memoryLearnThresholdScale`)
|
|
11
|
+
或空闲满 `memoryLearnIdleHours`(默认 8h,且期间有新消息)后,交给模型归纳成一条不超过
|
|
12
|
+
`memoryLearnMaxChars`(默认 150 字)的记忆,去重后写入对应作用域的记忆文件,并回推到原会话。
|
|
13
|
+
- 私聊发私聊、群聊发对应群,不会串台。
|
|
14
|
+
- 写入前去重(相似度阈值 `memoryLearnDuplicateThreshold`),避免同一件事反复记。
|
|
15
|
+
- 每作用域每天上限 `memoryLearnDailyLimit`(默认 30 次),防刷额度。
|
|
16
|
+
- 总开关 `memoryAutoLearn`(默认关),生效范围 `memoryAutoLearnGroups` 白名单。
|
|
17
|
+
- 系统备注(复读等)与指令消息不参与归纳。
|
|
18
|
+
|
|
19
|
+
## 1.4.0
|
|
20
|
+
|
|
21
|
+
### 新增
|
|
22
|
+
|
|
23
|
+
- **记忆按作用域分文件**:群聊写 `Memory_<群号>_群聊.md`,私聊写 `Memory_<QQ号>_私聊.md`。
|
|
24
|
+
不再把不同群、私聊的记忆混在一个文件里。可用 `memoryPerScope` 关闭以恢复旧行为。
|
|
25
|
+
`[memory]` 指令与 AI 引用都只读写当前会话对应的文件。
|
|
26
|
+
- **`registerContextEvicted` 钩子**(aiHooks 接口版本升到 2):上下文挤满时,把被挤出的消息
|
|
27
|
+
交给外部插件处理(自动归纳已内建,此钩子仅用于第三方扩展)。
|
|
28
|
+
|
|
5
29
|
## 1.3.1
|
|
6
30
|
|
|
7
31
|
### 文档
|
package/lib/ai/engine.d.ts
CHANGED
|
@@ -24,7 +24,10 @@ export interface AiHost {
|
|
|
24
24
|
fetchQuotedImages?(session: any, quote: any): Promise<RenderedImage[]>;
|
|
25
25
|
resolveImage(ref: string, session: any): Promise<string>;
|
|
26
26
|
sendReply(session: any, text: string): Promise<void>;
|
|
27
|
-
readMemoryFile(
|
|
27
|
+
readMemoryFile(scope?: {
|
|
28
|
+
kind: 'group' | 'private';
|
|
29
|
+
id: string;
|
|
30
|
+
} | null): Promise<string>;
|
|
28
31
|
}
|
|
29
32
|
export interface AiDeps {
|
|
30
33
|
provider?: ChatProvider;
|
|
@@ -47,6 +50,12 @@ export declare class AiEngine {
|
|
|
47
50
|
private searchCache;
|
|
48
51
|
private searchRate;
|
|
49
52
|
private searchUnsupportedUntil;
|
|
53
|
+
/** 自动归纳:按作用域累计被挤出的消息 */
|
|
54
|
+
private learnStore;
|
|
55
|
+
/** 自动归纳:每个作用域每天的次数,防刷额度 */
|
|
56
|
+
private learnDaily;
|
|
57
|
+
/** 自动归纳:空闲兜底定时器 */
|
|
58
|
+
private learnTimer;
|
|
50
59
|
constructor(host: AiHost, deps?: AiDeps);
|
|
51
60
|
private groupKey;
|
|
52
61
|
private ruleFor;
|
|
@@ -65,6 +74,26 @@ export declare class AiEngine {
|
|
|
65
74
|
note(text: string, groupKey?: string, session?: any): void;
|
|
66
75
|
/** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
|
|
67
76
|
recordSelf(session: any, text: string): void;
|
|
77
|
+
/**
|
|
78
|
+
* 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
|
|
79
|
+
* 失败不影响主流程。
|
|
80
|
+
*/
|
|
81
|
+
/**
|
|
82
|
+
* 上下文挤出后的两件事:
|
|
83
|
+
* 1. 交给外部插件(registerContextEvicted,可选)
|
|
84
|
+
* 2. 内建自动归纳:累计到阈值或空闲后总结成一条记忆写回
|
|
85
|
+
* 任何一步失败都不影响正常聊天。
|
|
86
|
+
*/
|
|
87
|
+
private emitEvicted;
|
|
88
|
+
/** 归纳并(可选)回推到原会话 */
|
|
89
|
+
/** 启动空闲兜底定时器;每 5 分钟检查一次 */
|
|
90
|
+
private startLearnTimer;
|
|
91
|
+
/** 资源清理:停止定时器、清空缓存 */
|
|
92
|
+
dispose(): void;
|
|
93
|
+
private learnAndReport;
|
|
94
|
+
/** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
|
|
95
|
+
private summarizeRecords;
|
|
96
|
+
private findBot;
|
|
68
97
|
private isMention;
|
|
69
98
|
private addressesOthers;
|
|
70
99
|
private shouldContinueFollowup;
|
package/lib/ai/engine.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
16
|
exports.AiEngine = void 0;
|
|
17
17
|
const state_1 = require("./state");
|
|
18
|
+
const learn_1 = require("./learn");
|
|
18
19
|
const trigger_1 = require("./trigger");
|
|
19
20
|
const prompt_1 = require("./prompt");
|
|
20
21
|
const provider_1 = require("./provider");
|
|
@@ -65,6 +66,12 @@ class AiEngine {
|
|
|
65
66
|
searchCache = new Map();
|
|
66
67
|
searchRate = new Map();
|
|
67
68
|
searchUnsupportedUntil = 0;
|
|
69
|
+
/** 自动归纳:按作用域累计被挤出的消息 */
|
|
70
|
+
learnStore = new learn_1.LearnStore();
|
|
71
|
+
/** 自动归纳:每个作用域每天的次数,防刷额度 */
|
|
72
|
+
learnDaily = new Map();
|
|
73
|
+
/** 自动归纳:空闲兜底定时器 */
|
|
74
|
+
learnTimer = null;
|
|
68
75
|
constructor(host, deps = {}) {
|
|
69
76
|
this.host = host;
|
|
70
77
|
this.config = host.config;
|
|
@@ -79,6 +86,8 @@ class AiEngine {
|
|
|
79
86
|
this.rng = deps.rng ?? Math.random;
|
|
80
87
|
this.now = deps.now ?? Date.now;
|
|
81
88
|
this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
|
|
89
|
+
// 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
|
|
90
|
+
this.startLearnTimer();
|
|
82
91
|
}
|
|
83
92
|
// ---------------------------------------------------------------- 配置
|
|
84
93
|
groupKey(session) {
|
|
@@ -179,7 +188,8 @@ class AiEngine {
|
|
|
179
188
|
self: false,
|
|
180
189
|
at: Number(session.timestamp) || this.now(),
|
|
181
190
|
};
|
|
182
|
-
state.push(record, contextWindow);
|
|
191
|
+
const evicted = state.push(record, contextWindow);
|
|
192
|
+
this.emitEvicted(evicted, key, session);
|
|
183
193
|
state.counter += 1;
|
|
184
194
|
return record;
|
|
185
195
|
}
|
|
@@ -189,7 +199,7 @@ class AiEngine {
|
|
|
189
199
|
if (!key || !text?.trim())
|
|
190
200
|
return;
|
|
191
201
|
const state = this.state.get(key);
|
|
192
|
-
state.push({
|
|
202
|
+
const evicted = state.push({
|
|
193
203
|
id: `note-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
194
204
|
userId: 'system',
|
|
195
205
|
name: '系统',
|
|
@@ -202,6 +212,7 @@ class AiEngine {
|
|
|
202
212
|
at: this.now(),
|
|
203
213
|
command: true,
|
|
204
214
|
}, this.contextWindow);
|
|
215
|
+
this.emitEvicted(evicted, groupKey, session);
|
|
205
216
|
}
|
|
206
217
|
/** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
|
|
207
218
|
recordSelf(session, text) {
|
|
@@ -209,7 +220,7 @@ class AiEngine {
|
|
|
209
220
|
if (!key || !text?.trim())
|
|
210
221
|
return;
|
|
211
222
|
const state = this.state.get(key);
|
|
212
|
-
state.push({
|
|
223
|
+
const evicted = state.push({
|
|
213
224
|
id: `self-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
214
225
|
userId: String(session.bot?.selfId ?? ''),
|
|
215
226
|
name: this.selfName,
|
|
@@ -221,6 +232,203 @@ class AiEngine {
|
|
|
221
232
|
self: true,
|
|
222
233
|
at: this.now(),
|
|
223
234
|
}, this.contextWindow);
|
|
235
|
+
this.emitEvicted(evicted, key, session);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
|
|
239
|
+
* 失败不影响主流程。
|
|
240
|
+
*/
|
|
241
|
+
/**
|
|
242
|
+
* 上下文挤出后的两件事:
|
|
243
|
+
* 1. 交给外部插件(registerContextEvicted,可选)
|
|
244
|
+
* 2. 内建自动归纳:累计到阈值或空闲后总结成一条记忆写回
|
|
245
|
+
* 任何一步失败都不影响正常聊天。
|
|
246
|
+
*/
|
|
247
|
+
emitEvicted(evicted, groupKey, session) {
|
|
248
|
+
if (!evicted || !evicted.length)
|
|
249
|
+
return;
|
|
250
|
+
const isDirect = session?.isDirect === true || !session?.guildId;
|
|
251
|
+
const guildId = String(session?.guildId || "");
|
|
252
|
+
const userId = String(session?.userId || "");
|
|
253
|
+
const kind = isDirect ? "private" : "group";
|
|
254
|
+
const scopeId = isDirect ? userId : guildId;
|
|
255
|
+
if (!scopeId)
|
|
256
|
+
return;
|
|
257
|
+
const cfg = this.config || {};
|
|
258
|
+
// ---------- 1) 分发给外部插件 ----------
|
|
259
|
+
if (this.hooks && typeof this.hooks.runContextEvicted === "function") {
|
|
260
|
+
const payload = evicted.map((item) => ({
|
|
261
|
+
id: item.id,
|
|
262
|
+
userId: item.userId,
|
|
263
|
+
name: item.name,
|
|
264
|
+
role: item.role,
|
|
265
|
+
text: item.text,
|
|
266
|
+
self: item.self,
|
|
267
|
+
at: item.at,
|
|
268
|
+
command: item.command,
|
|
269
|
+
}));
|
|
270
|
+
void this.hooks
|
|
271
|
+
.runContextEvicted({
|
|
272
|
+
groupId: guildId,
|
|
273
|
+
kind,
|
|
274
|
+
scopeId,
|
|
275
|
+
session,
|
|
276
|
+
evicted: payload,
|
|
277
|
+
window: this.contextWindow,
|
|
278
|
+
})
|
|
279
|
+
.catch((error) => {
|
|
280
|
+
this.host.logger?.warn?.(`[ai-evicted] 分发失败: ${String(error)}`);
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
// ---------- 2) 内建自动归纳 ----------
|
|
284
|
+
if (!cfg.memoryAutoLearn)
|
|
285
|
+
return;
|
|
286
|
+
if (!cfg.enableMemory || cfg.memoryAutoLearn === false)
|
|
287
|
+
return;
|
|
288
|
+
if (!this.resolveEnabled(session))
|
|
289
|
+
return;
|
|
290
|
+
const allow = Array.isArray(cfg.memoryAutoLearnGroups) ? cfg.memoryAutoLearnGroups.map(String) : [];
|
|
291
|
+
if (allow.length && !allow.includes(guildId) && !allow.includes(userId))
|
|
292
|
+
return;
|
|
293
|
+
const bucket = this.learnStore.get(kind, scopeId);
|
|
294
|
+
const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
|
|
295
|
+
const fire = bucket.push(evicted, threshold, this.now());
|
|
296
|
+
if (fire) {
|
|
297
|
+
void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** 归纳并(可选)回推到原会话 */
|
|
301
|
+
/** 启动空闲兜底定时器;每 5 分钟检查一次 */
|
|
302
|
+
startLearnTimer() {
|
|
303
|
+
if (this.learnTimer)
|
|
304
|
+
return;
|
|
305
|
+
const cfg = this.config || {};
|
|
306
|
+
if (!cfg.memoryAutoLearn)
|
|
307
|
+
return;
|
|
308
|
+
const idleHours = Math.max(1, Number(cfg.memoryLearnIdleHours) || 8);
|
|
309
|
+
const idleMs = idleHours * 60 * 60 * 1000;
|
|
310
|
+
this.learnTimer = setInterval(() => {
|
|
311
|
+
try {
|
|
312
|
+
const pending = this.learnStore.idleList(this.now(), idleMs);
|
|
313
|
+
for (const item of pending) {
|
|
314
|
+
void this.learnAndReport(item.kind, item.scopeId, item.bucket, "idle");
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
this.host.logger?.warn?.(`[memory-learn] 空闲检查失败: ${String(error)}`);
|
|
319
|
+
}
|
|
320
|
+
}, 5 * 60 * 1000);
|
|
321
|
+
if (this.learnTimer.unref)
|
|
322
|
+
this.learnTimer.unref();
|
|
323
|
+
}
|
|
324
|
+
/** 资源清理:停止定时器、清空缓存 */
|
|
325
|
+
dispose() {
|
|
326
|
+
if (this.learnTimer) {
|
|
327
|
+
clearInterval(this.learnTimer);
|
|
328
|
+
this.learnTimer = null;
|
|
329
|
+
}
|
|
330
|
+
this.learnStore.clear();
|
|
331
|
+
this.learnDaily.clear();
|
|
332
|
+
this.searchCache.clear();
|
|
333
|
+
this.searchRate.clear();
|
|
334
|
+
}
|
|
335
|
+
async learnAndReport(kind, scopeId, bucket, reason, session) {
|
|
336
|
+
const cfg = this.config || {};
|
|
337
|
+
const records = bucket.drain();
|
|
338
|
+
if (!records.length)
|
|
339
|
+
return;
|
|
340
|
+
const scope = { kind, id: scopeId };
|
|
341
|
+
const summary = await this.summarizeRecords(records, kind, scope, reason);
|
|
342
|
+
if (!summary)
|
|
343
|
+
return;
|
|
344
|
+
if (cfg.memoryLearnPushBack === false)
|
|
345
|
+
return;
|
|
346
|
+
const text = `刚记住了:${summary}`;
|
|
347
|
+
try {
|
|
348
|
+
if (kind === "private") {
|
|
349
|
+
const bot = (kind === "private" && session?.bot) || null;
|
|
350
|
+
const targetBot = bot || this.findBot();
|
|
351
|
+
if (targetBot)
|
|
352
|
+
await targetBot.sendMessage(scopeId, text, { userId: scopeId });
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
const targetBot = session?.bot || this.findBot();
|
|
356
|
+
if (targetBot)
|
|
357
|
+
await targetBot.sendMessage(scopeId, text, { guildId: scopeId, channelId: scopeId });
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
this.host.logger?.warn?.(`[memory-learn] 回推失败 ${kind}:${scopeId}: ${String(error)}`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
|
|
365
|
+
async summarizeRecords(records, kind, scope, reason) {
|
|
366
|
+
const cfg = this.config || {};
|
|
367
|
+
// 每日上限
|
|
368
|
+
const day = new Date();
|
|
369
|
+
const dayStamp = `${day.getFullYear()}-${day.getMonth() + 1}-${day.getDate()}`;
|
|
370
|
+
const dailyKey = `${kind}:${scope.id}:${dayStamp}`;
|
|
371
|
+
const limit = Math.max(1, Number(cfg.memoryLearnDailyLimit) || 30);
|
|
372
|
+
const used = this.learnDaily.get(dailyKey) || 0;
|
|
373
|
+
if (used >= limit) {
|
|
374
|
+
this.host.logger?.info?.(`[memory-learn] 已达每日上限 ${limit}(${kind}:${scope.id})`);
|
|
375
|
+
return "";
|
|
376
|
+
}
|
|
377
|
+
const prompt = (0, learn_1.buildSummaryPrompt)(records, { kind, selfName: this.selfName });
|
|
378
|
+
let raw = "";
|
|
379
|
+
try {
|
|
380
|
+
const result = await this.provider.chat({
|
|
381
|
+
system: prompt.system,
|
|
382
|
+
user: prompt.user,
|
|
383
|
+
temperature: 0.3,
|
|
384
|
+
maxTokens: 400,
|
|
385
|
+
});
|
|
386
|
+
if (!result || !result.ok) {
|
|
387
|
+
this.host.logger?.warn?.(`[memory-learn] 归纳调用失败: ${result && result.error}`);
|
|
388
|
+
return "";
|
|
389
|
+
}
|
|
390
|
+
raw = String(result.text || "");
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
this.host.logger?.warn?.(`[memory-learn] 归纳异常: ${String(error)}`);
|
|
394
|
+
return "";
|
|
395
|
+
}
|
|
396
|
+
const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
|
|
397
|
+
let text = (0, learn_1.cleanSummary)(raw, maxChars);
|
|
398
|
+
if (!text)
|
|
399
|
+
return "";
|
|
400
|
+
// 去重
|
|
401
|
+
let existing = [];
|
|
402
|
+
try {
|
|
403
|
+
const content = await this.host.readMemoryFile(scope);
|
|
404
|
+
existing = String(content || "")
|
|
405
|
+
.split(/\r?\n---\r?\n/)
|
|
406
|
+
.map((b) => b.trim())
|
|
407
|
+
.filter(Boolean)
|
|
408
|
+
.map((b) => b.split("\n").slice(1).join("\n").trim() || b);
|
|
409
|
+
}
|
|
410
|
+
catch {
|
|
411
|
+
existing = [];
|
|
412
|
+
}
|
|
413
|
+
const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
|
|
414
|
+
if ((0, learn_1.isDuplicate)(text, existing, threshold)) {
|
|
415
|
+
this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
|
|
416
|
+
return "";
|
|
417
|
+
}
|
|
418
|
+
try {
|
|
419
|
+
await this.host.saveMemoryToFile("", text, scope, "自动归纳");
|
|
420
|
+
this.learnDaily.set(dailyKey, used + 1);
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
this.host.logger?.warn?.(`[memory-learn] 写入失败: ${String(error)}`);
|
|
424
|
+
return "";
|
|
425
|
+
}
|
|
426
|
+
this.host.logger?.info?.(`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${text.length}字`);
|
|
427
|
+
return text;
|
|
428
|
+
}
|
|
429
|
+
findBot() {
|
|
430
|
+
const bots = this.host?.ctx?.bots || this.host?.bots || [];
|
|
431
|
+
return (bots || []).find((item) => item.platform === "onebot") || null;
|
|
224
432
|
}
|
|
225
433
|
// ---------------------------------------------------------------- 点名 / 跟随
|
|
226
434
|
isMention(session, record) {
|
|
@@ -319,12 +527,16 @@ class AiEngine {
|
|
|
319
527
|
return followup;
|
|
320
528
|
}
|
|
321
529
|
// ---------------------------------------------------------------- 记忆
|
|
322
|
-
async loadMemories(record, state) {
|
|
530
|
+
async loadMemories(record, state, session) {
|
|
323
531
|
if (!this.config.enableMemory || this.config.memoryInAi === false)
|
|
324
532
|
return [];
|
|
325
533
|
let content = '';
|
|
326
534
|
try {
|
|
327
|
-
|
|
535
|
+
// 按作用域读对应文件:群聊读该群,私聊读该用户
|
|
536
|
+
const scope = typeof this.host.memoryScopeOf === 'function'
|
|
537
|
+
? this.host.memoryScopeOf(session)
|
|
538
|
+
: null;
|
|
539
|
+
content = await this.host.readMemoryFile(scope);
|
|
328
540
|
}
|
|
329
541
|
catch {
|
|
330
542
|
return [];
|
|
@@ -399,7 +611,7 @@ class AiEngine {
|
|
|
399
611
|
const startedAt = this.now();
|
|
400
612
|
try {
|
|
401
613
|
const allowPass = !mention && !followup;
|
|
402
|
-
const memories = await this.loadMemories(record, state);
|
|
614
|
+
const memories = await this.loadMemories(record, state, session);
|
|
403
615
|
const hookCtx = {
|
|
404
616
|
session,
|
|
405
617
|
groupId: String(session.guildId),
|
package/lib/ai/hooks.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* AI 扩展钩子:让外部插件给提示词追加“风格段”,并在发送前过滤输出。
|
|
3
3
|
*
|
|
4
4
|
* 设计目标:
|
|
5
|
-
* -
|
|
5
|
+
* - 只暴露最小能力,不把引擎内部结构漏出去;
|
|
6
6
|
* - 任何钩子抛错都不能影响正常回复(记录日志后继续);
|
|
7
7
|
* - 输出过滤器返回 null 表示“这条不要发”(按 pass 处理);
|
|
8
8
|
* - version 用于外部插件做兼容检查。
|
|
@@ -19,22 +19,56 @@ export interface AiAfterReplyContext extends AiHookContext {
|
|
|
19
19
|
text: string;
|
|
20
20
|
}
|
|
21
21
|
export type AfterReplyHandler = (ctx: AiAfterReplyContext) => void | Promise<void>;
|
|
22
|
+
/** 一条被挤出上下文的消息。字段与 ChatRecord 对齐,但只挑外部需要的部分。 */
|
|
23
|
+
export interface EvictedRecord {
|
|
24
|
+
id: string;
|
|
25
|
+
userId: string;
|
|
26
|
+
name: string;
|
|
27
|
+
role?: string;
|
|
28
|
+
text: string;
|
|
29
|
+
self: boolean;
|
|
30
|
+
at: number;
|
|
31
|
+
command?: boolean;
|
|
32
|
+
}
|
|
33
|
+
/** 上下文挤出事件:一次可能挤掉多条。 */
|
|
34
|
+
export interface ContextEvictedContext {
|
|
35
|
+
/** 群号;私聊时为空字符串 */
|
|
36
|
+
groupId: string;
|
|
37
|
+
/** 会话类型 */
|
|
38
|
+
kind: 'group' | 'private';
|
|
39
|
+
/** 作用域 ID:群聊=群号,私聊=对方 QQ 号 */
|
|
40
|
+
scopeId: string;
|
|
41
|
+
session?: any;
|
|
42
|
+
/** 本次被挤出的消息,按时间先后排列 */
|
|
43
|
+
evicted: EvictedRecord[];
|
|
44
|
+
/** 当前上下文窗口大小 */
|
|
45
|
+
window: number;
|
|
46
|
+
}
|
|
47
|
+
export type ContextEvictedHandler = (ctx: ContextEvictedContext) => void | Promise<void>;
|
|
22
48
|
export declare class AiHookRegistry {
|
|
23
49
|
private logger?;
|
|
24
|
-
/** 钩子接口版本;外部插件应检查 >=
|
|
25
|
-
readonly version =
|
|
50
|
+
/** 钩子接口版本;外部插件应检查 >= 2 才能用 contextEvicted */
|
|
51
|
+
readonly version = 2;
|
|
26
52
|
private sections;
|
|
27
53
|
private filters;
|
|
28
54
|
private afterReplyHandlers;
|
|
55
|
+
private evictedHandlers;
|
|
29
56
|
constructor(logger?: any);
|
|
30
57
|
registerPromptSection(provider: PromptSectionProvider): () => void;
|
|
31
58
|
registerOutputFilter(filter: OutputFilter): () => void;
|
|
32
59
|
/** 文字回复已发送后触发;用于追加表情包等后续动作。 */
|
|
33
60
|
registerAfterReply(handler: AfterReplyHandler): () => void;
|
|
61
|
+
/**
|
|
62
|
+
* 上下文挤出消息时触发(2.0+)。
|
|
63
|
+
* 用于把这些即将被丢弃的消息交给外部插件做归纳、归档等。
|
|
64
|
+
*/
|
|
65
|
+
registerContextEvicted(handler: ContextEvictedHandler): () => void;
|
|
34
66
|
/** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
|
|
35
67
|
collectSections(ctx: AiHookContext): Promise<string[]>;
|
|
36
68
|
/** 依次执行输出过滤器;返回 null 表示丢弃本条回复。 */
|
|
37
69
|
applyFilters(text: string, ctx: AiHookContext): Promise<string | null>;
|
|
38
70
|
/** 文字回复发送后执行;单个 handler 失败只记日志,不影响其它。 */
|
|
39
71
|
runAfterReply(ctx: AiAfterReplyContext): Promise<void>;
|
|
72
|
+
/** 上下文挤出后执行;单个 handler 失败只记日志,不影响其它。 */
|
|
73
|
+
runContextEvicted(ctx: ContextEvictedContext): Promise<void>;
|
|
40
74
|
}
|
package/lib/ai/hooks.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* AI 扩展钩子:让外部插件给提示词追加“风格段”,并在发送前过滤输出。
|
|
4
4
|
*
|
|
5
5
|
* 设计目标:
|
|
6
|
-
* -
|
|
6
|
+
* - 只暴露最小能力,不把引擎内部结构漏出去;
|
|
7
7
|
* - 任何钩子抛错都不能影响正常回复(记录日志后继续);
|
|
8
8
|
* - 输出过滤器返回 null 表示“这条不要发”(按 pass 处理);
|
|
9
9
|
* - version 用于外部插件做兼容检查。
|
|
@@ -12,11 +12,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
12
12
|
exports.AiHookRegistry = void 0;
|
|
13
13
|
class AiHookRegistry {
|
|
14
14
|
logger;
|
|
15
|
-
/** 钩子接口版本;外部插件应检查 >=
|
|
16
|
-
version =
|
|
15
|
+
/** 钩子接口版本;外部插件应检查 >= 2 才能用 contextEvicted */
|
|
16
|
+
version = 2;
|
|
17
17
|
sections = new Set();
|
|
18
18
|
filters = new Set();
|
|
19
19
|
afterReplyHandlers = new Set();
|
|
20
|
+
evictedHandlers = new Set();
|
|
20
21
|
constructor(logger) {
|
|
21
22
|
this.logger = logger;
|
|
22
23
|
}
|
|
@@ -33,6 +34,14 @@ class AiHookRegistry {
|
|
|
33
34
|
this.afterReplyHandlers.add(handler);
|
|
34
35
|
return () => this.afterReplyHandlers.delete(handler);
|
|
35
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* 上下文挤出消息时触发(2.0+)。
|
|
39
|
+
* 用于把这些即将被丢弃的消息交给外部插件做归纳、归档等。
|
|
40
|
+
*/
|
|
41
|
+
registerContextEvicted(handler) {
|
|
42
|
+
this.evictedHandlers.add(handler);
|
|
43
|
+
return () => this.evictedHandlers.delete(handler);
|
|
44
|
+
}
|
|
36
45
|
/** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
|
|
37
46
|
async collectSections(ctx) {
|
|
38
47
|
const out = [];
|
|
@@ -75,5 +84,18 @@ class AiHookRegistry {
|
|
|
75
84
|
}
|
|
76
85
|
}
|
|
77
86
|
}
|
|
87
|
+
/** 上下文挤出后执行;单个 handler 失败只记日志,不影响其它。 */
|
|
88
|
+
async runContextEvicted(ctx) {
|
|
89
|
+
if (!this.evictedHandlers.size)
|
|
90
|
+
return;
|
|
91
|
+
for (const handler of this.evictedHandlers) {
|
|
92
|
+
try {
|
|
93
|
+
await handler(ctx);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
this.logger?.warn?.(`[ai-hooks] context-evicted failed: ${String(error)}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
78
100
|
}
|
|
79
101
|
exports.AiHookRegistry = AiHookRegistry;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆自动归纳(纯函数 + 轻量状态)。
|
|
3
|
+
*
|
|
4
|
+
* 触发时机由 engine 在上下文挤出时调用:
|
|
5
|
+
* - 累计条数达到「上下文窗口 × 倍率」
|
|
6
|
+
* - 或距最后一条消息超过 idleHours 且期间有新消息(由 idle 定时器驱动)
|
|
7
|
+
*
|
|
8
|
+
* 归纳出来的内容是一次性的一长串,150 字以内,写入对应作用域的记忆文件。
|
|
9
|
+
*/
|
|
10
|
+
export declare const MAX_SUMMARY_CHARS = 150;
|
|
11
|
+
export interface EvictedLike {
|
|
12
|
+
id?: string;
|
|
13
|
+
userId?: string;
|
|
14
|
+
name?: string;
|
|
15
|
+
text?: string;
|
|
16
|
+
self?: boolean;
|
|
17
|
+
at?: number;
|
|
18
|
+
command?: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** 正在累计的一批消息 */
|
|
21
|
+
export declare class LearnBucket {
|
|
22
|
+
records: EvictedLike[];
|
|
23
|
+
lastActivityAt: number;
|
|
24
|
+
lastLearnedAt: number;
|
|
25
|
+
push(records: EvictedLike[], threshold: number, now: number): boolean;
|
|
26
|
+
/** 距最后一条消息超过 idleMs,且确实有内容 */
|
|
27
|
+
isIdle(now: number, idleMs: number): boolean;
|
|
28
|
+
drain(): EvictedLike[];
|
|
29
|
+
get size(): number;
|
|
30
|
+
}
|
|
31
|
+
/** 按作用域保存累计桶 */
|
|
32
|
+
export declare class LearnStore {
|
|
33
|
+
private map;
|
|
34
|
+
private key;
|
|
35
|
+
get(kind: string, scopeId: string): LearnBucket;
|
|
36
|
+
idleList(now: number, idleMs: number): Array<{
|
|
37
|
+
kind: string;
|
|
38
|
+
scopeId: string;
|
|
39
|
+
bucket: LearnBucket;
|
|
40
|
+
}>;
|
|
41
|
+
clear(): void;
|
|
42
|
+
}
|
|
43
|
+
/** 把一批消息渲染成模型可读的文本 */
|
|
44
|
+
export declare function renderForSummary(records: EvictedLike[], selfName?: string): string;
|
|
45
|
+
/** 归纳提示词 */
|
|
46
|
+
export declare function buildSummaryPrompt(records: EvictedLike[], options?: {
|
|
47
|
+
kind?: string;
|
|
48
|
+
selfName?: string;
|
|
49
|
+
}): {
|
|
50
|
+
system: string;
|
|
51
|
+
user: string;
|
|
52
|
+
};
|
|
53
|
+
/** 清洗模型输出 */
|
|
54
|
+
export declare function cleanSummary(raw: string, maxChars?: number): string;
|
|
55
|
+
/** Jaccard 相似度,用于挡住重复记忆 */
|
|
56
|
+
export declare function similarityOf(a: string, b: string): number;
|
|
57
|
+
/** 判断是否与已有记忆重复 */
|
|
58
|
+
export declare function isDuplicate(candidate: string, existing: string[], threshold?: number): boolean;
|