@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/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/state.d.ts
CHANGED
|
@@ -42,8 +42,10 @@ export declare class GroupState {
|
|
|
42
42
|
inFlight: boolean;
|
|
43
43
|
followup: FollowupState | null;
|
|
44
44
|
seen: Map<string, number>;
|
|
45
|
-
|
|
46
|
-
|
|
45
|
+
/** 挤压上下文,返回被挤出的消息(按时间先后)。 */
|
|
46
|
+
trim(window: number): ChatRecord[];
|
|
47
|
+
/** @returns 本次被挤出的消息,供外部做归纳 */
|
|
48
|
+
push(record: ChatRecord, window: number): ChatRecord[];
|
|
47
49
|
/** 事件去重:同一 messageId 15 秒内只处理一次 */
|
|
48
50
|
isDuplicate(key: string, now: number): boolean;
|
|
49
51
|
}
|
package/lib/ai/state.js
CHANGED
|
@@ -18,14 +18,17 @@ class GroupState {
|
|
|
18
18
|
inFlight = false;
|
|
19
19
|
followup = null;
|
|
20
20
|
seen = new Map();
|
|
21
|
+
/** 挤压上下文,返回被挤出的消息(按时间先后)。 */
|
|
21
22
|
trim(window) {
|
|
22
23
|
const max = Math.max(6, window || 24);
|
|
23
|
-
if (this.records.length
|
|
24
|
-
|
|
24
|
+
if (this.records.length <= max)
|
|
25
|
+
return [];
|
|
26
|
+
return this.records.splice(0, this.records.length - max);
|
|
25
27
|
}
|
|
28
|
+
/** @returns 本次被挤出的消息,供外部做归纳 */
|
|
26
29
|
push(record, window) {
|
|
27
30
|
this.records.push(record);
|
|
28
|
-
this.trim(window);
|
|
31
|
+
return this.trim(window);
|
|
29
32
|
}
|
|
30
33
|
/** 事件去重:同一 messageId 15 秒内只处理一次 */
|
|
31
34
|
isDuplicate(key, now) {
|
package/lib/index.d.ts
CHANGED
|
@@ -71,7 +71,16 @@ export declare const Config: Schema<Schemastery.ObjectS<{
|
|
|
71
71
|
}> | Schemastery.ObjectS<{
|
|
72
72
|
enableMemory: Schema<boolean, boolean>;
|
|
73
73
|
memoryFileName: Schema<string, string>;
|
|
74
|
+
memoryPerScope: Schema<boolean, boolean>;
|
|
74
75
|
memoryInAi: Schema<boolean, boolean>;
|
|
76
|
+
memoryAutoLearn: Schema<boolean, boolean>;
|
|
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>;
|
|
75
84
|
}> | Schemastery.ObjectS<{
|
|
76
85
|
enableBlacklist: Schema<boolean, boolean>;
|
|
77
86
|
blacklistFileName: Schema<string, string>;
|
|
@@ -235,7 +244,16 @@ export declare const Config: Schema<Schemastery.ObjectS<{
|
|
|
235
244
|
} & {
|
|
236
245
|
enableMemory: boolean;
|
|
237
246
|
memoryFileName: string;
|
|
247
|
+
memoryPerScope: boolean;
|
|
238
248
|
memoryInAi: boolean;
|
|
249
|
+
memoryAutoLearn: boolean;
|
|
250
|
+
memoryAutoLearnGroups: string[];
|
|
251
|
+
memoryLearnIdleHours: number;
|
|
252
|
+
memoryLearnThresholdScale: number;
|
|
253
|
+
memoryLearnMaxChars: number;
|
|
254
|
+
memoryLearnPushBack: boolean;
|
|
255
|
+
memoryLearnDuplicateThreshold: number;
|
|
256
|
+
memoryLearnDailyLimit: number;
|
|
239
257
|
} & {
|
|
240
258
|
enableBlacklist: boolean;
|
|
241
259
|
blacklistFileName: string;
|
package/lib/index.js
CHANGED
|
@@ -62,9 +62,18 @@ exports.Config = koishi_1.Schema.intersect([
|
|
|
62
62
|
autoViolationWindowMinutes: koishi_1.Schema.natural().default(60).description('违规计数统计窗口(分钟):窗口内连续违规才累计,超时未违规则重新计数。'),
|
|
63
63
|
}).description('自动管控'),
|
|
64
64
|
koishi_1.Schema.object({
|
|
65
|
-
enableMemory: koishi_1.Schema.boolean().default(true).description('启用记忆库:群内发送 [memory] 内容
|
|
66
|
-
memoryFileName: koishi_1.Schema.string().default('Memory.md').description('
|
|
67
|
-
|
|
65
|
+
enableMemory: koishi_1.Schema.boolean().default(true).description('启用记忆库:群内发送 [memory] 内容 保存,[memory] search 关键词 查询、[memory] delete 关键词 删除,AI 回复可引用。'),
|
|
66
|
+
memoryFileName: koishi_1.Schema.string().default('Memory.md').description('记忆库基础文件名(保存在 Koishi 数据目录)。按作用域分文件时用它作为前缀,例如 Memory.md → Memory_123456_群聊.md。'),
|
|
67
|
+
memoryPerScope: koishi_1.Schema.boolean().default(true).description('按私聊/群聊分开存储:群聊写 Memory_<群号>_群聊.md,私聊写 Memory_<QQ号>_私聊.md。关闭则所有会话共用单文件(旧行为)。'),
|
|
68
|
+
memoryInAi: koishi_1.Schema.boolean().default(true).description('AI 回复/识图时是否参考记忆库内容(只读当前会话对应的文件)。'),
|
|
69
|
+
memoryAutoLearn: koishi_1.Schema.boolean().default(false).description('自动归纳:上下文挤满后,把被挤出的消息交给外部学习插件总结成记忆。这里只负责抛出事件,实际归纳由 qqgm-memory-learn 完成。'),
|
|
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('每个作用域每天最多归纳几次,防止刷模型额度。'),
|
|
68
77
|
}).description('记忆库'),
|
|
69
78
|
koishi_1.Schema.object({
|
|
70
79
|
enableBlacklist: koishi_1.Schema.boolean().default(true).description('全局黑名单系统开关。单个群未单独设置时跟随此值;单个群设置后以该群为准(全局关着也能为某群单独开启)。'),
|
package/lib/service.d.ts
CHANGED
|
@@ -189,9 +189,25 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
|
|
|
189
189
|
qq: string;
|
|
190
190
|
name: string;
|
|
191
191
|
}>;
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
192
|
+
/**
|
|
193
|
+
* 记忆按作用域分文件:
|
|
194
|
+
* 群聊 → Memory_<群号>_群聊.md
|
|
195
|
+
* 私聊 → Memory_<QQ号>_私聊.md
|
|
196
|
+
*
|
|
197
|
+
* scope 为空时回落到旧的单文件(memoryFileName),保持兼容。
|
|
198
|
+
* @param {{kind:'group'|'private', id:string}|null} scope
|
|
199
|
+
*/
|
|
200
|
+
getMemoryFilePath(scope: {
|
|
201
|
+
kind: "group" | "private";
|
|
202
|
+
id: string;
|
|
203
|
+
} | null): any;
|
|
204
|
+
/** 把 session 归一成作用域;群聊取群号,私聊取对方 QQ 号。 */
|
|
205
|
+
memoryScopeOf(session: any): {
|
|
206
|
+
kind: string;
|
|
207
|
+
id: string;
|
|
208
|
+
};
|
|
209
|
+
readMemoryFile(scope: any): Promise<any>;
|
|
210
|
+
writeMemoryFile(content: any, scope: any): Promise<void>;
|
|
195
211
|
extractMemoryBlocks(content: any): string[];
|
|
196
212
|
/**
|
|
197
213
|
* 记忆库写互斥:把「读整档 → 改 → 整写」串行化。
|
|
@@ -199,10 +215,20 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
|
|
|
199
215
|
* 记忆属于低频写,一把 promise 队列足够,无需文件锁。
|
|
200
216
|
*/
|
|
201
217
|
runMemoryWriteLocked(task: any): Promise<any>;
|
|
202
|
-
|
|
203
|
-
|
|
218
|
+
/**
|
|
219
|
+
* 追加一条记忆。
|
|
220
|
+
* @param {string} userId 写入者(旧字段,保留用于标记)
|
|
221
|
+
* @param {string} content 记忆正文
|
|
222
|
+
* @param {{kind:'group'|'private', id:string}|null} scope 作用域;为空则写旧单文件
|
|
223
|
+
* @param {string} [label] 自定义来源标记,例如「自动归纳」
|
|
224
|
+
*/
|
|
225
|
+
saveMemoryToFile(userId: string, content: string, scope: {
|
|
226
|
+
kind: "group" | "private";
|
|
227
|
+
id: string;
|
|
228
|
+
} | null, label?: string): Promise<any>;
|
|
229
|
+
searchMemory(keyword: any, limit: number, scope: any): Promise<string[]>;
|
|
204
230
|
/** 按关键词删除记忆条目(含该关键词的整条记忆块)。返回 { ok, removed, message } */
|
|
205
|
-
deleteMemoryByKeyword(keyword: any): Promise<any>;
|
|
231
|
+
deleteMemoryByKeyword(keyword: any, scope: any): Promise<any>;
|
|
206
232
|
getDisplayName(session: any): any;
|
|
207
233
|
splitAiReplyParts(text: any): any;
|
|
208
234
|
waitHumanLikeDelay(minMs?: number, maxMs?: number): Promise<void>;
|
|
@@ -360,7 +386,7 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
|
|
|
360
386
|
* 短关键词(2~4 字)极易被无关文本凑齐(如「领导说…红色包装袋」凑出「领红包」),
|
|
361
387
|
* 因此对短词要求更高的置信度;长词本身信息量足,门槛可放宽。
|
|
362
388
|
*/
|
|
363
|
-
minBannedWordConfidence(keywordLength: any): 1 | 0.
|
|
389
|
+
minBannedWordConfidence(keywordLength: any): 1 | 0.55 | 0.6 | 0.65 | 0.45;
|
|
364
390
|
subsequenceMatch(text: any, keyword: any): {
|
|
365
391
|
start: any;
|
|
366
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)
|
|
@@ -761,13 +768,44 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
761
768
|
}
|
|
762
769
|
}
|
|
763
770
|
// ============ 记忆库 ============
|
|
764
|
-
|
|
771
|
+
/**
|
|
772
|
+
* 记忆按作用域分文件:
|
|
773
|
+
* 群聊 → Memory_<群号>_群聊.md
|
|
774
|
+
* 私聊 → Memory_<QQ号>_私聊.md
|
|
775
|
+
*
|
|
776
|
+
* scope 为空时回落到旧的单文件(memoryFileName),保持兼容。
|
|
777
|
+
* @param {{kind:'group'|'private', id:string}|null} scope
|
|
778
|
+
*/
|
|
779
|
+
getMemoryFilePath(scope) {
|
|
765
780
|
const base = (this.ctx && this.ctx.baseDir) || process.cwd();
|
|
766
|
-
const
|
|
767
|
-
|
|
781
|
+
const legacy = (this.config.memoryFileName || 'Memory.md').trim();
|
|
782
|
+
const kind = scope && scope.kind;
|
|
783
|
+
const id = scope && String(scope.id || '').replace(/[^\w.-]/g, '');
|
|
784
|
+
if (!kind || !id) {
|
|
785
|
+
return node_path_1.default.resolve(base, legacy);
|
|
786
|
+
}
|
|
787
|
+
if (this.config.memoryPerScope === false) {
|
|
788
|
+
return node_path_1.default.resolve(base, legacy);
|
|
789
|
+
}
|
|
790
|
+
const label = kind === 'private' ? '私聊' : '群聊';
|
|
791
|
+
// 从旧文件名里取基础名,例如 Memory.md → Memory
|
|
792
|
+
const stem = legacy.replace(/\.md$/i, '') || 'Memory';
|
|
793
|
+
return node_path_1.default.resolve(base, `${stem}_${id}_${label}.md`);
|
|
794
|
+
}
|
|
795
|
+
/** 把 session 归一成作用域;群聊取群号,私聊取对方 QQ 号。 */
|
|
796
|
+
memoryScopeOf(session) {
|
|
797
|
+
if (!session)
|
|
798
|
+
return null;
|
|
799
|
+
const isDirect = session.isDirect === true || !session.guildId;
|
|
800
|
+
if (isDirect) {
|
|
801
|
+
const uid = String(session.userId || '').trim();
|
|
802
|
+
return uid ? { kind: 'private', id: uid } : null;
|
|
803
|
+
}
|
|
804
|
+
const gid = String(session.guildId || '').trim();
|
|
805
|
+
return gid ? { kind: 'group', id: gid } : null;
|
|
768
806
|
}
|
|
769
|
-
async readMemoryFile() {
|
|
770
|
-
const p = this.getMemoryFilePath();
|
|
807
|
+
async readMemoryFile(scope) {
|
|
808
|
+
const p = this.getMemoryFilePath(scope);
|
|
771
809
|
try {
|
|
772
810
|
return await node_fs_1.default.promises.readFile(p, 'utf8');
|
|
773
811
|
}
|
|
@@ -775,8 +813,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
775
813
|
return '';
|
|
776
814
|
}
|
|
777
815
|
}
|
|
778
|
-
async writeMemoryFile(content) {
|
|
779
|
-
const p = this.getMemoryFilePath();
|
|
816
|
+
async writeMemoryFile(content, scope) {
|
|
817
|
+
const p = this.getMemoryFilePath(scope);
|
|
780
818
|
await node_fs_1.default.promises.writeFile(p, String(content), 'utf8');
|
|
781
819
|
}
|
|
782
820
|
extractMemoryBlocks(content) {
|
|
@@ -796,32 +834,40 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
796
834
|
this._memoryWriteLock = run.then(() => undefined, () => undefined);
|
|
797
835
|
return run;
|
|
798
836
|
}
|
|
799
|
-
|
|
837
|
+
/**
|
|
838
|
+
* 追加一条记忆。
|
|
839
|
+
* @param {string} userId 写入者(旧字段,保留用于标记)
|
|
840
|
+
* @param {string} content 记忆正文
|
|
841
|
+
* @param {{kind:'group'|'private', id:string}|null} scope 作用域;为空则写旧单文件
|
|
842
|
+
* @param {string} [label] 自定义来源标记,例如「自动归纳」
|
|
843
|
+
*/
|
|
844
|
+
async saveMemoryToFile(userId, content, scope, label) {
|
|
800
845
|
return this.runMemoryWriteLocked(async () => {
|
|
801
846
|
const now = new Date();
|
|
802
847
|
const stamp = now.toLocaleString('zh-CN', { hour12: false });
|
|
803
|
-
const
|
|
804
|
-
const
|
|
848
|
+
const who = label || `用户 ${userId || 'unknown'}`;
|
|
849
|
+
const block = `## ${stamp} · ${who}\n${String(content).trim()}`;
|
|
850
|
+
const existing = (await this.readMemoryFile(scope)).trim();
|
|
805
851
|
const next = existing ? `${existing}\n\n---\n\n${block}\n` : `${block}\n`;
|
|
806
|
-
await this.writeMemoryFile(next);
|
|
852
|
+
await this.writeMemoryFile(next, scope);
|
|
807
853
|
return block;
|
|
808
854
|
});
|
|
809
855
|
}
|
|
810
|
-
async searchMemory(keyword, limit = 8) {
|
|
811
|
-
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
856
|
+
async searchMemory(keyword, limit = 8, scope) {
|
|
857
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile(scope));
|
|
812
858
|
const kw = String(keyword || '').trim();
|
|
813
859
|
if (!kw)
|
|
814
860
|
return blocks.slice(-limit);
|
|
815
861
|
return blocks.filter((b) => b.includes(kw)).slice(-limit);
|
|
816
862
|
}
|
|
817
863
|
/** 按关键词删除记忆条目(含该关键词的整条记忆块)。返回 { ok, removed, message } */
|
|
818
|
-
async deleteMemoryByKeyword(keyword) {
|
|
864
|
+
async deleteMemoryByKeyword(keyword, scope) {
|
|
819
865
|
const kw = String(keyword ?? '').trim();
|
|
820
866
|
if (!kw)
|
|
821
867
|
return { ok: false, removed: 0, message: '关键词为空。' };
|
|
822
868
|
// 同样走写锁:删除与保存并发时不会互相覆盖
|
|
823
869
|
return this.runMemoryWriteLocked(async () => {
|
|
824
|
-
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
870
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile(scope));
|
|
825
871
|
if (!blocks.length)
|
|
826
872
|
return { ok: false, removed: 0, message: '记忆库为空。' };
|
|
827
873
|
const kept = blocks.filter((b) => !b.includes(kw));
|
|
@@ -829,7 +875,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
829
875
|
if (!removed)
|
|
830
876
|
return { ok: false, removed: 0, message: `未找到包含「${kw}」的记忆` };
|
|
831
877
|
const content = kept.length ? kept.join('\n\n---\n\n') + '\n' : '';
|
|
832
|
-
await this.writeMemoryFile(content);
|
|
878
|
+
await this.writeMemoryFile(content, scope);
|
|
833
879
|
return { ok: true, removed, message: `已删除 ${removed} 条` };
|
|
834
880
|
});
|
|
835
881
|
}
|
|
@@ -2850,17 +2896,19 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2850
2896
|
await session.send(this.styleText('请给出要删除的关键词。'));
|
|
2851
2897
|
return true;
|
|
2852
2898
|
}
|
|
2853
|
-
const
|
|
2899
|
+
const mscope = this.memoryScopeOf(session);
|
|
2900
|
+
const results = await this.searchMemory(keyword, 8, mscope);
|
|
2854
2901
|
if (!results.length) {
|
|
2855
2902
|
await session.send(this.styleText(`删除失败,未找到包含「${keyword}」的记忆。`));
|
|
2856
2903
|
return true;
|
|
2857
2904
|
}
|
|
2858
|
-
const r = await this.deleteMemoryByKeyword(keyword);
|
|
2905
|
+
const r = await this.deleteMemoryByKeyword(keyword, mscope);
|
|
2859
2906
|
await session.send(this.styleText(r.ok ? `已删除 ${r.removed} 条记忆。` : `删除失败:${r.message}`));
|
|
2860
2907
|
return true;
|
|
2861
2908
|
}
|
|
2862
2909
|
if (/^(?:list|all)$/i.test(sub)) {
|
|
2863
|
-
const
|
|
2910
|
+
const mscope = this.memoryScopeOf(session);
|
|
2911
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile(mscope));
|
|
2864
2912
|
if (!blocks.length) {
|
|
2865
2913
|
await session.send(this.styleText('记忆库为空。'));
|
|
2866
2914
|
return true;
|
|
@@ -2873,7 +2921,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2873
2921
|
const queryMatch = sub.match(/^(?:search|query|find)\s*[::]?\s*([\s\S]*)$/i);
|
|
2874
2922
|
if (queryMatch) {
|
|
2875
2923
|
const keyword = queryMatch[1].trim();
|
|
2876
|
-
const
|
|
2924
|
+
const mscope = this.memoryScopeOf(session);
|
|
2925
|
+
const results = await this.searchMemory(keyword, 8, mscope);
|
|
2877
2926
|
if (!results.length) {
|
|
2878
2927
|
await session.send(this.styleText(keyword ? `没有找到包含「${keyword}」的记忆。` : '记忆库为空或没有可显示的记录。'));
|
|
2879
2928
|
return true;
|
|
@@ -2885,7 +2934,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2885
2934
|
}
|
|
2886
2935
|
// 保存
|
|
2887
2936
|
try {
|
|
2888
|
-
|
|
2937
|
+
const mscope = this.memoryScopeOf(session);
|
|
2938
|
+
await this.saveMemoryToFile(session.userId, sub, mscope);
|
|
2889
2939
|
await session.send(this.styleText('已记住。'));
|
|
2890
2940
|
this.logCommandResult('memory-save', { ok: true, message: 'memory saved' }, session, { content: sub });
|
|
2891
2941
|
}
|
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
|
+
"version": "1.4.1",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"typings": "lib/index.d.ts",
|
|
7
7
|
"files": [
|
package/readme.md
CHANGED
|
@@ -28,7 +28,7 @@ Koishi 控制台「探索器 Explorer」里查看和手改。
|
|
|
28
28
|
| **自动处罚** | 统计窗口内累计违规达到阈值后自动禁言 / 自动踢人,阈值、时长、窗口均可配 |
|
|
29
29
|
| **黑名单** | 按群独立存储(`banMember_<群号>.md`);入群自动比对并踢出,可选踢人时自动记录 |
|
|
30
30
|
| **入群审核** | 新申请推送到群内,管理员用 `approve` / `reject` 放行或拒绝;待审单落盘,**重启不丢** |
|
|
31
|
-
| **记忆库** | `[memory]` 保存 / 列出 / 查询 /
|
|
31
|
+
| **记忆库** | `[memory]` 保存 / 列出 / 查询 / 删除,**按私聊/群聊分文件**落盘;开启后 AI 回复会检索并引用当前会话的记忆 |
|
|
32
32
|
| **AI 群聊回复** | 三道闸门(阈值 / 概率 / 冷却)+ 模型自行 `<pass/>` 决定是否接话;群名片、引用、@ 目标、自己历史发言都进上下文;记忆按相关度注入;图片并发解析并限时。多人格、点名后话题跟随、温度与输出上限 |
|
|
33
33
|
| **AI 识图** | 图片下载转 data URL 后送入模型,兼容 CQ 码 / HTML `<img>` / 元素三种形态与表情包 |
|
|
34
34
|
| **AI 联网搜索** | 按问题自动判断是否联网,调用 DeepSeek 原生 Search API(复用现有 API Key),结果注入提示词;API 不支持 / 超时 / 无结果时自动回退普通回复 |
|
|
@@ -92,7 +92,15 @@ npm i @nestim/koishi-plugin-qq-group-manager
|
|
|
92
92
|
| `bannedWordScoreThreshold` | `70` | 违禁词评分触发阈值(强关键词共用) |
|
|
93
93
|
| `strongKeywords` | `[]` | 强关键词;命中即触发且**无视白名单豁免**,支持 `关键词\|分值` |
|
|
94
94
|
| `groupRules` | `[]` | 按群覆盖策略(违禁词、强关键词、白名单关键词、AI 开关、自动处罚阈值等) |
|
|
95
|
-
| `memoryFileName` | `Memory.md` |
|
|
95
|
+
| `memoryFileName` | `Memory.md` | 记忆库基础文件名;分作用域时作为前缀 |
|
|
96
|
+
| `memoryPerScope` | `true` | 按私聊/群聊分开存:`Memory_<群号>_群聊.md` / `Memory_<QQ号>_私聊.md` |
|
|
97
|
+
| `memoryAutoLearn` | `false` | **AI 自动归纳记忆**(内建):上下文挤满后把消息总结成记忆并回推 |
|
|
98
|
+
| `memoryLearnIdleHours` | `8` | 空闲兜底小时数;期间没有新消息则不触发 |
|
|
99
|
+
| `memoryLearnThresholdScale` | `1` | 归纳阈值 = `aiContextWindow × 该值` |
|
|
100
|
+
| `memoryLearnMaxChars` | `150` | 单条自动记忆字数上限 |
|
|
101
|
+
| `memoryLearnPushBack` | `true` | 归纳后回推原会话(私聊发私聊、群聊发对应群) |
|
|
102
|
+
| `memoryLearnDuplicateThreshold` | `0.55` | 相似度超此值跳过,避免重复记 |
|
|
103
|
+
| `memoryLearnDailyLimit` | `30` | 每作用域每天最多归纳次数 |
|
|
96
104
|
| `blacklistFileName` | `banMember.md` | 黑名单文件名模板,实际为 `banMember_<群号>.md` |
|
|
97
105
|
| `pendingJoinFileName` | `JoinRequests.md` | 待审入群申请落盘文件名 |
|
|
98
106
|
| `enableJoinRequestReview` | `true` | 是否发起入群审核 |
|
|
@@ -163,6 +171,35 @@ npm i @nestim/koishi-plugin-qq-group-manager
|
|
|
163
171
|
|
|
164
172
|
定时提醒(`[提醒] 明天 8 点 开会`)**内建在本插件里**,不需要额外安装。
|
|
165
173
|
|
|
174
|
+
## 记忆自动归纳(1.4.1+,内建)
|
|
175
|
+
|
|
176
|
+
不需要额外插件。开启 `memoryAutoLearn` 后:
|
|
177
|
+
|
|
178
|
+
```
|
|
179
|
+
上下文挤满(aiContextWindow 条)
|
|
180
|
+
↓ 最老的消息被挤出
|
|
181
|
+
累计到阈值(aiContextWindow × memoryLearnThresholdScale)
|
|
182
|
+
或空闲满 memoryLearnIdleHours(且期间有新消息)
|
|
183
|
+
↓
|
|
184
|
+
模型归纳成一条 ≤ memoryLearnMaxChars 的记忆
|
|
185
|
+
↓ 与已有记忆去重
|
|
186
|
+
写入 Memory_<群号>_群聊.md / Memory_<QQ号>_私聊.md
|
|
187
|
+
↓ 回推原会话
|
|
188
|
+
「刚记住了:……」
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
要点:
|
|
192
|
+
|
|
193
|
+
- **不会空转**:8 小时里一条新消息都没有,就不归纳。
|
|
194
|
+
- **不会串台**:私聊发私聊,群聊发对应群。
|
|
195
|
+
- **不会记废话**:提示词只允许人物关系、稳定偏好、群内黑话、反复出现的话题;
|
|
196
|
+
寒暄、一次性情绪、已结束的接梗、纯表情全部丢弃。
|
|
197
|
+
- **不会重复记**:写入前做相似度比对,超过 `memoryLearnDuplicateThreshold` 就跳过。
|
|
198
|
+
- **不会刷爆额度**:每作用域每天最多 `memoryLearnDailyLimit` 次。
|
|
199
|
+
- **系统备注与指令消息不参与归纳**(复读、命令结果等)。
|
|
200
|
+
|
|
201
|
+
自动写入了什么,可以直接在 Koishi 控制台「探索器」打开对应的 `Memory_*.md` 查看。
|
|
202
|
+
条目带的时间戳与来源标记能让你区分手动 `[memory]` 与 AI 自动归纳。
|
|
166
203
|
## 外部插件接口(1.2.2+)
|
|
167
204
|
|
|
168
205
|
主插件暴露一个很小的扩展点,第三方插件可以给 AI 追加“说话风格”,或在发送前过滤输出,
|
|
@@ -199,7 +236,8 @@ export function apply(ctx) {
|
|
|
199
236
|
|
|
200
237
|
| 文件 | 内容 |
|
|
201
238
|
| --- | --- |
|
|
202
|
-
| `
|
|
239
|
+
| `Memory_<群号>_群聊.md` | 该群的记忆,条目之间以 `---` 分隔 |
|
|
240
|
+
| `Memory_<QQ号>_私聊.md` | 与该用户的私聊记忆 |
|
|
203
241
|
| `banMember_<群号>.md` | 各群黑名单,`## QQ号 · 备注` + 加入时间 |
|
|
204
242
|
| `JoinRequests.md` | 待审入群申请(人类可读表格 + 机器可读区段),重启自动恢复、过期自动清理 |
|
|
205
243
|
|