@nestim/koishi-plugin-qq-group-manager 1.4.0 → 1.4.2
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 +42 -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/ai/provider.js +23 -10
- package/lib/core/bmp.d.ts +24 -0
- package/lib/core/bmp.js +224 -0
- package/lib/index.d.ts +12 -0
- package/lib/index.js +6 -0
- package/lib/service.d.ts +6 -1
- package/lib/service.js +28 -3
- package/package.json +1 -1
- package/readme.md +37 -2
- package/src/ai/engine.ts +211 -44
- package/src/ai/learn.ts +208 -0
- package/src/ai/provider.ts +27 -9
- package/src/core/bmp.ts +225 -0
- package/src/index.ts +7 -1
- package/src/service.js +3774 -3749
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,47 @@
|
|
|
2
2
|
|
|
3
3
|
本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
|
|
4
4
|
|
|
5
|
+
## 1.4.2
|
|
6
|
+
|
|
7
|
+
### 新增
|
|
8
|
+
|
|
9
|
+
- **内置 BMP → PNG 转换**(零依赖,纯 JS 实现)。
|
|
10
|
+
|
|
11
|
+
QQ 有时会把图片存成 BMP 格式,而 DeepSeek 等视觉模型只接受 `webp / png / jpeg / gif`,
|
|
12
|
+
直接发送 BMP 会被 400 拒绝。现在识别到 BMP 后会在本地转成 PNG 再送给模型,
|
|
13
|
+
这张图就能正常被识别,不再被跳过。
|
|
14
|
+
|
|
15
|
+
支持 1 / 4 / 8 / 16 / 24 / 32 位 BMP、8 位调色板、`BI_RGB` 与 `BI_BITFIELDS`;
|
|
16
|
+
RLE 压缩、OS/2 v1 头、超过 8192×8192 或 2000 万像素的图会放弃转换并跳过该图。
|
|
17
|
+
|
|
18
|
+
### 修复
|
|
19
|
+
|
|
20
|
+
- **BMP 图片无法被识别**。此前 BMP 会被原样作为 `image/bmp` 发送,模型返回
|
|
21
|
+
`You have uploaded an unsupported image`(400)。
|
|
22
|
+
|
|
23
|
+
- **一次图片格式错误会导致后续所有图片都不再发送**。
|
|
24
|
+
|
|
25
|
+
原逻辑把任何 400 都判定为「模型不支持视觉」,并永久置位 `visionUnsupported`,
|
|
26
|
+
之后即便发的是正常 JPG/PNG 也会被跳过,必须重启才能恢复。
|
|
27
|
+
|
|
28
|
+
现在区分两种情况:
|
|
29
|
+
- 格式问题(`unsupported image` / `invalid image` / 尺寸超限等)→ **只跳过本次**,不影响后续;
|
|
30
|
+
- 确实是模型不支持视觉 → 才记住并跳过后续图片。
|
|
31
|
+
|
|
32
|
+
## 1.4.1
|
|
33
|
+
|
|
34
|
+
### 新增
|
|
35
|
+
|
|
36
|
+
- **AI 自动归纳记忆(内建,不需要额外插件)**:
|
|
37
|
+
上下文挤满、最老的消息即将被丢弃时,把它们累计起来;达到阈值(`aiContextWindow × memoryLearnThresholdScale`)
|
|
38
|
+
或空闲满 `memoryLearnIdleHours`(默认 8h,且期间有新消息)后,交给模型归纳成一条不超过
|
|
39
|
+
`memoryLearnMaxChars`(默认 150 字)的记忆,去重后写入对应作用域的记忆文件,并回推到原会话。
|
|
40
|
+
- 私聊发私聊、群聊发对应群,不会串台。
|
|
41
|
+
- 写入前去重(相似度阈值 `memoryLearnDuplicateThreshold`),避免同一件事反复记。
|
|
42
|
+
- 每作用域每天上限 `memoryLearnDailyLimit`(默认 30 次),防刷额度。
|
|
43
|
+
- 总开关 `memoryAutoLearn`(默认关),生效范围 `memoryAutoLearnGroups` 白名单。
|
|
44
|
+
- 系统备注(复读等)与指令消息不参与归纳。
|
|
45
|
+
|
|
5
46
|
## 1.4.0
|
|
6
47
|
|
|
7
48
|
### 新增
|
|
@@ -10,12 +51,7 @@
|
|
|
10
51
|
不再把不同群、私聊的记忆混在一个文件里。可用 `memoryPerScope` 关闭以恢复旧行为。
|
|
11
52
|
`[memory]` 指令与 AI 引用都只读写当前会话对应的文件。
|
|
12
53
|
- **`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 小时后交给模型归纳成一条记忆并写回,再回推到原会话。
|
|
54
|
+
交给外部插件处理(自动归纳已内建,此钩子仅用于第三方扩展)。
|
|
19
55
|
|
|
20
56
|
## 1.3.1
|
|
21
57
|
|
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/ai/provider.js
CHANGED
|
@@ -49,16 +49,29 @@ class ChatProvider {
|
|
|
49
49
|
: await this.callOpenAi(request, images);
|
|
50
50
|
if (result.ok)
|
|
51
51
|
return { ...result, text: stripFence(result.text || '') };
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
52
|
+
if (images.length) {
|
|
53
|
+
const errorText = String(result.error || '');
|
|
54
|
+
const rejected = result.status === 400
|
|
55
|
+
|| result.status === 422
|
|
56
|
+
|| /image|vision|multimodal/i.test(errorText);
|
|
57
|
+
if (rejected) {
|
|
58
|
+
// 「格式不对」和「模型不支持视觉」是两件事,必须分开处理。
|
|
59
|
+
// 前者只跳过这一次,后者才记进 visionUnsupported。
|
|
60
|
+
const formatProblem = /unsupported image|invalid image|image format|must be|one of the following formats|too large|dimension/i.test(errorText);
|
|
61
|
+
if (!formatProblem) {
|
|
62
|
+
this.visionUnsupported = true;
|
|
63
|
+
this.logger?.warn?.(`[ai] 模型不支持图片(${result.status ?? '?'}),后续自动跳过图片: ${errorText}`);
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
this.logger?.warn?.(`[ai] 本次图片格式不被接受(${result.status ?? '?'}),仅跳过本次,不影响后续: ${errorText}`);
|
|
67
|
+
}
|
|
68
|
+
const fallback = provider === 'gemini'
|
|
69
|
+
? await this.callGemini(request, [])
|
|
70
|
+
: await this.callOpenAi(request, []);
|
|
71
|
+
if (fallback.ok)
|
|
72
|
+
return { ...fallback, text: stripFence(fallback.text || ''), degradedToText: true };
|
|
73
|
+
return fallback;
|
|
74
|
+
}
|
|
62
75
|
}
|
|
63
76
|
return result;
|
|
64
77
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 内置 BMP → PNG 转码(纯 JS,零依赖)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要:
|
|
5
|
+
* QQ 有时会把图片存成 BMP。DeepSeek 等视觉模型只接受 webp/png/jpeg/gif,
|
|
6
|
+
* 直接发 BMP 会 400。与其跳过这张图,不如转成 PNG 再发。
|
|
7
|
+
*
|
|
8
|
+
* 支持:
|
|
9
|
+
* - 1/4/8/16/24/32 位 BMP
|
|
10
|
+
* - BI_RGB(未压缩)、BI_BITFIELDS
|
|
11
|
+
* - 8 位调色板(含 RLE8 不处理,直接按索引读,够用)
|
|
12
|
+
*
|
|
13
|
+
* 不支持(遇到就返回 null,调用方回退到"跳过这张图"):
|
|
14
|
+
* - RLE 压缩
|
|
15
|
+
* - OS/2 v1 头
|
|
16
|
+
* - 带 alpha 的复杂变体(按 32 位 BGRA 直读,够常见场景用)
|
|
17
|
+
*/
|
|
18
|
+
/** 判断是不是 BMP */
|
|
19
|
+
export declare function isBmp(buffer: any): boolean;
|
|
20
|
+
/**
|
|
21
|
+
* BMP → PNG buffer。
|
|
22
|
+
* @returns {Buffer|null} 成功返回 PNG,无法处理返回 null
|
|
23
|
+
*/
|
|
24
|
+
export declare function bmpToPng(buffer: any): Buffer;
|