@nestim/koishi-plugin-qq-group-manager 1.4.0 → 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 +15 -6
- package/lib/ai/engine.d.ts +21 -0
- package/lib/ai/engine.js +190 -35
- package/lib/ai/learn.d.ts +58 -0
- package/lib/ai/learn.js +200 -0
- package/lib/index.d.ts +12 -0
- package/lib/index.js +6 -0
- package/lib/service.d.ts +1 -1
- package/lib/service.js +7 -0
- package/package.json +1 -1
- package/readme.md +37 -3
- package/src/ai/engine.ts +211 -44
- package/src/ai/learn.ts +208 -0
- package/src/index.ts +7 -1
- package/src/service.js +3762 -3755
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,20 @@
|
|
|
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
|
+
|
|
5
19
|
## 1.4.0
|
|
6
20
|
|
|
7
21
|
### 新增
|
|
@@ -10,12 +24,7 @@
|
|
|
10
24
|
不再把不同群、私聊的记忆混在一个文件里。可用 `memoryPerScope` 关闭以恢复旧行为。
|
|
11
25
|
`[memory]` 指令与 AI 引用都只读写当前会话对应的文件。
|
|
12
26
|
- **`registerContextEvicted` 钩子**(aiHooks 接口版本升到 2):上下文挤满时,把被挤出的消息
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
### 配套插件
|
|
16
|
-
|
|
17
|
-
- 新增 [`@nestim/koishi-plugin-qqgm-memory-learn`](https://github.com/Miseat/koishi-plugin-qqgm-memory-learn):
|
|
18
|
-
把挤出的消息累计起来,达到阈值或空闲 8 小时后交给模型归纳成一条记忆并写回,再回推到原会话。
|
|
27
|
+
交给外部插件处理(自动归纳已内建,此钩子仅用于第三方扩展)。
|
|
19
28
|
|
|
20
29
|
## 1.3.1
|
|
21
30
|
|
package/lib/ai/engine.d.ts
CHANGED
|
@@ -50,6 +50,12 @@ export declare class AiEngine {
|
|
|
50
50
|
private searchCache;
|
|
51
51
|
private searchRate;
|
|
52
52
|
private searchUnsupportedUntil;
|
|
53
|
+
/** 自动归纳:按作用域累计被挤出的消息 */
|
|
54
|
+
private learnStore;
|
|
55
|
+
/** 自动归纳:每个作用域每天的次数,防刷额度 */
|
|
56
|
+
private learnDaily;
|
|
57
|
+
/** 自动归纳:空闲兜底定时器 */
|
|
58
|
+
private learnTimer;
|
|
53
59
|
constructor(host: AiHost, deps?: AiDeps);
|
|
54
60
|
private groupKey;
|
|
55
61
|
private ruleFor;
|
|
@@ -72,7 +78,22 @@ export declare class AiEngine {
|
|
|
72
78
|
* 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
|
|
73
79
|
* 失败不影响主流程。
|
|
74
80
|
*/
|
|
81
|
+
/**
|
|
82
|
+
* 上下文挤出后的两件事:
|
|
83
|
+
* 1. 交给外部插件(registerContextEvicted,可选)
|
|
84
|
+
* 2. 内建自动归纳:累计到阈值或空闲后总结成一条记忆写回
|
|
85
|
+
* 任何一步失败都不影响正常聊天。
|
|
86
|
+
*/
|
|
75
87
|
private emitEvicted;
|
|
88
|
+
/** 归纳并(可选)回推到原会话 */
|
|
89
|
+
/** 启动空闲兜底定时器;每 5 分钟检查一次 */
|
|
90
|
+
private startLearnTimer;
|
|
91
|
+
/** 资源清理:停止定时器、清空缓存 */
|
|
92
|
+
dispose(): void;
|
|
93
|
+
private learnAndReport;
|
|
94
|
+
/** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
|
|
95
|
+
private summarizeRecords;
|
|
96
|
+
private findBot;
|
|
76
97
|
private isMention;
|
|
77
98
|
private addressesOthers;
|
|
78
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) {
|
|
@@ -229,22 +238,15 @@ class AiEngine {
|
|
|
229
238
|
* 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
|
|
230
239
|
* 失败不影响主流程。
|
|
231
240
|
*/
|
|
241
|
+
/**
|
|
242
|
+
* 上下文挤出后的两件事:
|
|
243
|
+
* 1. 交给外部插件(registerContextEvicted,可选)
|
|
244
|
+
* 2. 内建自动归纳:累计到阈值或空闲后总结成一条记忆写回
|
|
245
|
+
* 任何一步失败都不影响正常聊天。
|
|
246
|
+
*/
|
|
232
247
|
emitEvicted(evicted, groupKey, session) {
|
|
233
248
|
if (!evicted || !evicted.length)
|
|
234
249
|
return;
|
|
235
|
-
if (!this.hooks || typeof this.hooks.runContextEvicted !== "function")
|
|
236
|
-
return;
|
|
237
|
-
// 自动归纳开关 + 生效范围白名单
|
|
238
|
-
const cfg = this.config || {};
|
|
239
|
-
if (cfg.memoryAutoLearn === false)
|
|
240
|
-
return;
|
|
241
|
-
const allow = Array.isArray(cfg.memoryAutoLearnGroups) ? cfg.memoryAutoLearnGroups.map(String) : [];
|
|
242
|
-
if (allow.length) {
|
|
243
|
-
const gid = String(session?.guildId || "");
|
|
244
|
-
const uid = String(session?.userId || "");
|
|
245
|
-
if (!allow.includes(gid) && !allow.includes(uid))
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
250
|
const isDirect = session?.isDirect === true || !session?.guildId;
|
|
249
251
|
const guildId = String(session?.guildId || "");
|
|
250
252
|
const userId = String(session?.userId || "");
|
|
@@ -252,28 +254,181 @@ class AiEngine {
|
|
|
252
254
|
const scopeId = isDirect ? userId : guildId;
|
|
253
255
|
if (!scopeId)
|
|
254
256
|
return;
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
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;
|
|
277
432
|
}
|
|
278
433
|
// ---------------------------------------------------------------- 点名 / 跟随
|
|
279
434
|
isMention(session, record) {
|
|
@@ -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;
|
package/lib/ai/learn.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* 记忆自动归纳(纯函数 + 轻量状态)。
|
|
4
|
+
*
|
|
5
|
+
* 触发时机由 engine 在上下文挤出时调用:
|
|
6
|
+
* - 累计条数达到「上下文窗口 × 倍率」
|
|
7
|
+
* - 或距最后一条消息超过 idleHours 且期间有新消息(由 idle 定时器驱动)
|
|
8
|
+
*
|
|
9
|
+
* 归纳出来的内容是一次性的一长串,150 字以内,写入对应作用域的记忆文件。
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.LearnStore = exports.LearnBucket = exports.MAX_SUMMARY_CHARS = void 0;
|
|
13
|
+
exports.renderForSummary = renderForSummary;
|
|
14
|
+
exports.buildSummaryPrompt = buildSummaryPrompt;
|
|
15
|
+
exports.cleanSummary = cleanSummary;
|
|
16
|
+
exports.similarityOf = similarityOf;
|
|
17
|
+
exports.isDuplicate = isDuplicate;
|
|
18
|
+
const text_1 = require("../core/text");
|
|
19
|
+
exports.MAX_SUMMARY_CHARS = 150;
|
|
20
|
+
/** 正在累计的一批消息 */
|
|
21
|
+
class LearnBucket {
|
|
22
|
+
records = [];
|
|
23
|
+
lastActivityAt = 0;
|
|
24
|
+
lastLearnedAt = 0;
|
|
25
|
+
push(records, threshold, now) {
|
|
26
|
+
if (!records || !records.length)
|
|
27
|
+
return false;
|
|
28
|
+
this.records.push(...records);
|
|
29
|
+
this.lastActivityAt = now;
|
|
30
|
+
return this.records.length >= Math.max(1, threshold);
|
|
31
|
+
}
|
|
32
|
+
/** 距最后一条消息超过 idleMs,且确实有内容 */
|
|
33
|
+
isIdle(now, idleMs) {
|
|
34
|
+
if (!this.records.length)
|
|
35
|
+
return false;
|
|
36
|
+
if (!this.lastActivityAt)
|
|
37
|
+
return false;
|
|
38
|
+
return now - this.lastActivityAt >= idleMs;
|
|
39
|
+
}
|
|
40
|
+
drain() {
|
|
41
|
+
const out = this.records;
|
|
42
|
+
this.records = [];
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
get size() {
|
|
46
|
+
return this.records.length;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
exports.LearnBucket = LearnBucket;
|
|
50
|
+
/** 按作用域保存累计桶 */
|
|
51
|
+
class LearnStore {
|
|
52
|
+
map = new Map();
|
|
53
|
+
key(kind, scopeId) {
|
|
54
|
+
return `${kind}:${scopeId}`;
|
|
55
|
+
}
|
|
56
|
+
get(kind, scopeId) {
|
|
57
|
+
const k = this.key(kind, scopeId);
|
|
58
|
+
let bucket = this.map.get(k);
|
|
59
|
+
if (!bucket) {
|
|
60
|
+
bucket = new LearnBucket();
|
|
61
|
+
this.map.set(k, bucket);
|
|
62
|
+
}
|
|
63
|
+
return bucket;
|
|
64
|
+
}
|
|
65
|
+
idleList(now, idleMs) {
|
|
66
|
+
const out = [];
|
|
67
|
+
for (const [k, bucket] of this.map) {
|
|
68
|
+
if (!bucket.size)
|
|
69
|
+
continue;
|
|
70
|
+
if (!bucket.isIdle(now, idleMs))
|
|
71
|
+
continue;
|
|
72
|
+
const idx = k.indexOf(':');
|
|
73
|
+
out.push({ kind: k.slice(0, idx), scopeId: k.slice(idx + 1), bucket });
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
clear() {
|
|
78
|
+
this.map.clear();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
exports.LearnStore = LearnStore;
|
|
82
|
+
/** 把一批消息渲染成模型可读的文本 */
|
|
83
|
+
function renderForSummary(records, selfName = 'bot') {
|
|
84
|
+
const lines = [];
|
|
85
|
+
for (const item of records) {
|
|
86
|
+
if (!item || item.command)
|
|
87
|
+
continue;
|
|
88
|
+
const text = String(item.text || '').replace(/\s+/g, ' ').trim();
|
|
89
|
+
if (!text)
|
|
90
|
+
continue;
|
|
91
|
+
const who = item.self ? selfName : String(item.name || item.userId || '某人');
|
|
92
|
+
lines.push(`${who}: ${(0, text_1.truncate)(text, 160)}`);
|
|
93
|
+
}
|
|
94
|
+
return lines.join('\n');
|
|
95
|
+
}
|
|
96
|
+
/** 归纳提示词 */
|
|
97
|
+
function buildSummaryPrompt(records, options = {}) {
|
|
98
|
+
const label = options.kind === 'private' ? '私聊' : '群聊';
|
|
99
|
+
const body = renderForSummary(records, options.selfName || 'bot');
|
|
100
|
+
const system = [
|
|
101
|
+
`你在整理一段${label}记录,从中提炼值得长期记住的信息。`,
|
|
102
|
+
'',
|
|
103
|
+
'只保留这几类:',
|
|
104
|
+
'1. 人物关系与称呼(谁是谁、怎么叫、什么身份)',
|
|
105
|
+
'2. 稳定的偏好、立场、习惯(不是一时的情绪)',
|
|
106
|
+
'3. 群内或两人之间约定俗成的说法、黑话',
|
|
107
|
+
'4. 反复出现、以后还会聊到的话题',
|
|
108
|
+
'',
|
|
109
|
+
'必须丢掉:寒暄、打招呼、一次性的抱怨或玩笑、已经结束的接梗、纯表情。',
|
|
110
|
+
'',
|
|
111
|
+
'输出要求:',
|
|
112
|
+
'- 只输出一条记忆,纯文本,不要标题、不要列表、不要编号、不要 Markdown;',
|
|
113
|
+
`- 不超过 ${exports.MAX_SUMMARY_CHARS} 字;`,
|
|
114
|
+
'- 用陈述句写事实,不要写「他们聊到」「讨论了」这类过程描述;',
|
|
115
|
+
'- 如果没有任何值得长期记住的内容,只输出一个词:NONE',
|
|
116
|
+
].join('\n');
|
|
117
|
+
const user = ['【记录】', body || '(空)', '', '现在输出那一条记忆,或输出 NONE。'].join('\n');
|
|
118
|
+
return { system, user };
|
|
119
|
+
}
|
|
120
|
+
/** 清洗模型输出 */
|
|
121
|
+
function cleanSummary(raw, maxChars = exports.MAX_SUMMARY_CHARS) {
|
|
122
|
+
let text = String(raw || '').trim();
|
|
123
|
+
if (!text)
|
|
124
|
+
return '';
|
|
125
|
+
text = text
|
|
126
|
+
.replace(/^```[a-zA-Z0-9_-]*\s*\n?/, '')
|
|
127
|
+
.replace(/\n?\s*```\s*$/, '')
|
|
128
|
+
.replace(/^["'“”‘’「」]+|["'“”‘’「」]+$/g, '')
|
|
129
|
+
.trim();
|
|
130
|
+
text = text
|
|
131
|
+
.split(/\r?\n/)
|
|
132
|
+
.map((line) => line.replace(/^\s*(?:[-*+·]|\d+[.)、])\s*/, '').trim())
|
|
133
|
+
.filter(Boolean)
|
|
134
|
+
.join(' ')
|
|
135
|
+
.replace(/\s+/g, ' ')
|
|
136
|
+
.trim();
|
|
137
|
+
if (/^(?:none|无|没有|n\/a)$/i.test(text))
|
|
138
|
+
return '';
|
|
139
|
+
const limit = Math.max(20, maxChars);
|
|
140
|
+
if (text.length > limit) {
|
|
141
|
+
const slice = text.slice(0, limit);
|
|
142
|
+
let cut = -1;
|
|
143
|
+
for (const ch of ['。', '!', '?', ';']) {
|
|
144
|
+
cut = Math.max(cut, slice.lastIndexOf(ch));
|
|
145
|
+
}
|
|
146
|
+
text = cut >= Math.floor(limit * 0.5) ? slice.slice(0, cut + 1) : `${slice}…`;
|
|
147
|
+
}
|
|
148
|
+
return text.trim();
|
|
149
|
+
}
|
|
150
|
+
const CJK = /[\u4e00-\u9fa5]/;
|
|
151
|
+
function tokenize(text) {
|
|
152
|
+
const tokens = new Set();
|
|
153
|
+
const normalized = String(text || '')
|
|
154
|
+
.toLowerCase()
|
|
155
|
+
.replace(/[^\u4e00-\u9fa5a-z0-9]+/g, ' ')
|
|
156
|
+
.trim();
|
|
157
|
+
if (!normalized)
|
|
158
|
+
return tokens;
|
|
159
|
+
for (const chunk of normalized.split(/\s+/)) {
|
|
160
|
+
if (!chunk)
|
|
161
|
+
continue;
|
|
162
|
+
if (CJK.test(chunk)) {
|
|
163
|
+
const chars = [...chunk];
|
|
164
|
+
if (chars.length === 1) {
|
|
165
|
+
tokens.add(chunk);
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
for (let i = 0; i < chars.length - 1; i += 1)
|
|
169
|
+
tokens.add(chars[i] + chars[i + 1]);
|
|
170
|
+
}
|
|
171
|
+
else if (chunk.length >= 2) {
|
|
172
|
+
tokens.add(chunk);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return tokens;
|
|
176
|
+
}
|
|
177
|
+
/** Jaccard 相似度,用于挡住重复记忆 */
|
|
178
|
+
function similarityOf(a, b) {
|
|
179
|
+
const ta = tokenize(a);
|
|
180
|
+
const tb = tokenize(b);
|
|
181
|
+
if (!ta.size || !tb.size)
|
|
182
|
+
return 0;
|
|
183
|
+
let inter = 0;
|
|
184
|
+
for (const t of ta)
|
|
185
|
+
if (tb.has(t))
|
|
186
|
+
inter += 1;
|
|
187
|
+
const union = ta.size + tb.size - inter;
|
|
188
|
+
return union ? inter / union : 0;
|
|
189
|
+
}
|
|
190
|
+
/** 判断是否与已有记忆重复 */
|
|
191
|
+
function isDuplicate(candidate, existing, threshold = 0.55) {
|
|
192
|
+
const text = String(candidate || '').trim();
|
|
193
|
+
if (!text)
|
|
194
|
+
return false;
|
|
195
|
+
for (const item of existing || []) {
|
|
196
|
+
if (similarityOf(text, String(item || '')) >= threshold)
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
return false;
|
|
200
|
+
}
|
package/lib/index.d.ts
CHANGED
|
@@ -75,6 +75,12 @@ export declare const Config: Schema<Schemastery.ObjectS<{
|
|
|
75
75
|
memoryInAi: Schema<boolean, boolean>;
|
|
76
76
|
memoryAutoLearn: Schema<boolean, boolean>;
|
|
77
77
|
memoryAutoLearnGroups: Schema<string[], string[]>;
|
|
78
|
+
memoryLearnIdleHours: Schema<number, number>;
|
|
79
|
+
memoryLearnThresholdScale: Schema<number, number>;
|
|
80
|
+
memoryLearnMaxChars: Schema<number, number>;
|
|
81
|
+
memoryLearnPushBack: Schema<boolean, boolean>;
|
|
82
|
+
memoryLearnDuplicateThreshold: Schema<number, number>;
|
|
83
|
+
memoryLearnDailyLimit: Schema<number, number>;
|
|
78
84
|
}> | Schemastery.ObjectS<{
|
|
79
85
|
enableBlacklist: Schema<boolean, boolean>;
|
|
80
86
|
blacklistFileName: Schema<string, string>;
|
|
@@ -242,6 +248,12 @@ export declare const Config: Schema<Schemastery.ObjectS<{
|
|
|
242
248
|
memoryInAi: boolean;
|
|
243
249
|
memoryAutoLearn: boolean;
|
|
244
250
|
memoryAutoLearnGroups: string[];
|
|
251
|
+
memoryLearnIdleHours: number;
|
|
252
|
+
memoryLearnThresholdScale: number;
|
|
253
|
+
memoryLearnMaxChars: number;
|
|
254
|
+
memoryLearnPushBack: boolean;
|
|
255
|
+
memoryLearnDuplicateThreshold: number;
|
|
256
|
+
memoryLearnDailyLimit: number;
|
|
245
257
|
} & {
|
|
246
258
|
enableBlacklist: boolean;
|
|
247
259
|
blacklistFileName: string;
|
package/lib/index.js
CHANGED
|
@@ -68,6 +68,12 @@ exports.Config = koishi_1.Schema.intersect([
|
|
|
68
68
|
memoryInAi: koishi_1.Schema.boolean().default(true).description('AI 回复/识图时是否参考记忆库内容(只读当前会话对应的文件)。'),
|
|
69
69
|
memoryAutoLearn: koishi_1.Schema.boolean().default(false).description('自动归纳:上下文挤满后,把被挤出的消息交给外部学习插件总结成记忆。这里只负责抛出事件,实际归纳由 qqgm-memory-learn 完成。'),
|
|
70
70
|
memoryAutoLearnGroups: koishi_1.Schema.array(String).role('table').default([]).description('自动归纳生效的群号/QQ号白名单;留空表示全部生效。'),
|
|
71
|
+
memoryLearnIdleHours: koishi_1.Schema.natural().min(1).max(72).default(8).description('空闲兜底:距最后一条消息超过这么多小时且期间有新消息,就归纳一次。一直没新消息则不触发。'),
|
|
72
|
+
memoryLearnThresholdScale: koishi_1.Schema.number().min(1).max(10).step(0.5).default(1).description('归纳阈值 = aiContextWindow × 该倍数。填 1 表示攒满一个上下文窗口就归纳。'),
|
|
73
|
+
memoryLearnMaxChars: koishi_1.Schema.natural().min(40).max(300).default(150).description('单条自动记忆的字数上限。'),
|
|
74
|
+
memoryLearnPushBack: koishi_1.Schema.boolean().default(true).description('归纳后把结果回推到原会话:私聊发私聊、群聊发对应群。'),
|
|
75
|
+
memoryLearnDuplicateThreshold: koishi_1.Schema.number().min(0.3).max(0.95).step(0.05).default(0.55).description('与已有记忆相似度超过该值就跳过,避免同一件事反复记。'),
|
|
76
|
+
memoryLearnDailyLimit: koishi_1.Schema.natural().min(1).max(200).default(30).description('每个作用域每天最多归纳几次,防止刷模型额度。'),
|
|
71
77
|
}).description('记忆库'),
|
|
72
78
|
koishi_1.Schema.object({
|
|
73
79
|
enableBlacklist: koishi_1.Schema.boolean().default(true).description('全局黑名单系统开关。单个群未单独设置时跟随此值;单个群设置后以该群为准(全局关着也能为某群单独开启)。'),
|
package/lib/service.d.ts
CHANGED
|
@@ -386,7 +386,7 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
|
|
|
386
386
|
* 短关键词(2~4 字)极易被无关文本凑齐(如「领导说…红色包装袋」凑出「领红包」),
|
|
387
387
|
* 因此对短词要求更高的置信度;长词本身信息量足,门槛可放宽。
|
|
388
388
|
*/
|
|
389
|
-
minBannedWordConfidence(keywordLength: any): 1 | 0.
|
|
389
|
+
minBannedWordConfidence(keywordLength: any): 1 | 0.55 | 0.6 | 0.65 | 0.45;
|
|
390
390
|
subsequenceMatch(text: any, keyword: any): {
|
|
391
391
|
start: any;
|
|
392
392
|
end: any;
|
package/lib/service.js
CHANGED
|
@@ -543,6 +543,13 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
543
543
|
clearTimeout(timer);
|
|
544
544
|
this._reminderTimers.clear();
|
|
545
545
|
this._idleTimers.clear();
|
|
546
|
+
try {
|
|
547
|
+
if (this.ai && typeof this.ai.dispose === 'function')
|
|
548
|
+
this.ai.dispose();
|
|
549
|
+
}
|
|
550
|
+
catch (error) {
|
|
551
|
+
this._logger.warn(`[dispose] AI 引擎清理失败: ${String(error)}`);
|
|
552
|
+
}
|
|
546
553
|
}
|
|
547
554
|
isPlatformAllowed(platform) {
|
|
548
555
|
if (!platform)
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nestim/koishi-plugin-qq-group-manager",
|
|
3
3
|
"description": "Koishi QQ群管理插件(OneBot/LLOneBot):群管命令、权限校验、图片菜单、状态卡片、复读、AI群聊回复、记忆库、识图与自动管控(禁言/踢人)。",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.1",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"typings": "lib/index.d.ts",
|
|
7
7
|
"files": [
|