@nestim/koishi-plugin-qq-group-manager 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/lib/ai/engine.d.ts +9 -1
- package/lib/ai/engine.js +63 -6
- package/lib/ai/hooks.d.ts +37 -3
- package/lib/ai/hooks.js +25 -3
- package/lib/ai/state.d.ts +4 -2
- package/lib/ai/state.js +6 -3
- package/lib/index.d.ts +6 -0
- package/lib/index.js +6 -3
- package/lib/service.d.ts +32 -6
- package/lib/service.js +64 -21
- package/package.json +1 -1
- package/readme.md +33 -4
- package/src/ai/engine.ts +866 -810
- package/src/ai/engine.ts.bak.manual +814 -0
- package/src/ai/hooks.ts +55 -3
- package/src/ai/state.ts +7 -4
- package/src/index.ts +6 -3
- package/src/service.js +64 -22
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
|
|
4
4
|
|
|
5
|
+
## 1.4.0
|
|
6
|
+
|
|
7
|
+
### 新增
|
|
8
|
+
|
|
9
|
+
- **记忆按作用域分文件**:群聊写 `Memory_<群号>_群聊.md`,私聊写 `Memory_<QQ号>_私聊.md`。
|
|
10
|
+
不再把不同群、私聊的记忆混在一个文件里。可用 `memoryPerScope` 关闭以恢复旧行为。
|
|
11
|
+
`[memory]` 指令与 AI 引用都只读写当前会话对应的文件。
|
|
12
|
+
- **`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 小时后交给模型归纳成一条记忆并写回,再回推到原会话。
|
|
19
|
+
|
|
20
|
+
## 1.3.1
|
|
21
|
+
|
|
22
|
+
### 文档
|
|
23
|
+
|
|
24
|
+
- README 增加配套插件跳转:`@nestim/koishi-plugin-qqgm-chat-style`(聊天风格)与
|
|
25
|
+
`@nestim/koishi-plugin-qqgm-meme`(表情包),以及两个可直接使用的聊天风格 skill
|
|
26
|
+
(`northern-netizen-chat`、`naruto-mobile-chat`)。
|
|
27
|
+
- 明确标注**定时提醒内建在本插件**,无需额外安装。
|
|
28
|
+
|
|
5
29
|
## 1.3.0
|
|
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;
|
|
@@ -65,6 +68,11 @@ export declare class AiEngine {
|
|
|
65
68
|
note(text: string, groupKey?: string, session?: any): void;
|
|
66
69
|
/** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
|
|
67
70
|
recordSelf(session: any, text: string): void;
|
|
71
|
+
/**
|
|
72
|
+
* 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
|
|
73
|
+
* 失败不影响主流程。
|
|
74
|
+
*/
|
|
75
|
+
private emitEvicted;
|
|
68
76
|
private isMention;
|
|
69
77
|
private addressesOthers;
|
|
70
78
|
private shouldContinueFollowup;
|
package/lib/ai/engine.js
CHANGED
|
@@ -179,7 +179,8 @@ class AiEngine {
|
|
|
179
179
|
self: false,
|
|
180
180
|
at: Number(session.timestamp) || this.now(),
|
|
181
181
|
};
|
|
182
|
-
state.push(record, contextWindow);
|
|
182
|
+
const evicted = state.push(record, contextWindow);
|
|
183
|
+
this.emitEvicted(evicted, key, session);
|
|
183
184
|
state.counter += 1;
|
|
184
185
|
return record;
|
|
185
186
|
}
|
|
@@ -189,7 +190,7 @@ class AiEngine {
|
|
|
189
190
|
if (!key || !text?.trim())
|
|
190
191
|
return;
|
|
191
192
|
const state = this.state.get(key);
|
|
192
|
-
state.push({
|
|
193
|
+
const evicted = state.push({
|
|
193
194
|
id: `note-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
194
195
|
userId: 'system',
|
|
195
196
|
name: '系统',
|
|
@@ -202,6 +203,7 @@ class AiEngine {
|
|
|
202
203
|
at: this.now(),
|
|
203
204
|
command: true,
|
|
204
205
|
}, this.contextWindow);
|
|
206
|
+
this.emitEvicted(evicted, groupKey, session);
|
|
205
207
|
}
|
|
206
208
|
/** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
|
|
207
209
|
recordSelf(session, text) {
|
|
@@ -209,7 +211,7 @@ class AiEngine {
|
|
|
209
211
|
if (!key || !text?.trim())
|
|
210
212
|
return;
|
|
211
213
|
const state = this.state.get(key);
|
|
212
|
-
state.push({
|
|
214
|
+
const evicted = state.push({
|
|
213
215
|
id: `self-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
214
216
|
userId: String(session.bot?.selfId ?? ''),
|
|
215
217
|
name: this.selfName,
|
|
@@ -221,6 +223,57 @@ class AiEngine {
|
|
|
221
223
|
self: true,
|
|
222
224
|
at: this.now(),
|
|
223
225
|
}, this.contextWindow);
|
|
226
|
+
this.emitEvicted(evicted, key, session);
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
|
|
230
|
+
* 失败不影响主流程。
|
|
231
|
+
*/
|
|
232
|
+
emitEvicted(evicted, groupKey, session) {
|
|
233
|
+
if (!evicted || !evicted.length)
|
|
234
|
+
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
|
+
const isDirect = session?.isDirect === true || !session?.guildId;
|
|
249
|
+
const guildId = String(session?.guildId || "");
|
|
250
|
+
const userId = String(session?.userId || "");
|
|
251
|
+
const kind = isDirect ? "private" : "group";
|
|
252
|
+
const scopeId = isDirect ? userId : guildId;
|
|
253
|
+
if (!scopeId)
|
|
254
|
+
return;
|
|
255
|
+
const payload = evicted.map((item) => ({
|
|
256
|
+
id: item.id,
|
|
257
|
+
userId: item.userId,
|
|
258
|
+
name: item.name,
|
|
259
|
+
role: item.role,
|
|
260
|
+
text: item.text,
|
|
261
|
+
self: item.self,
|
|
262
|
+
at: item.at,
|
|
263
|
+
command: item.command,
|
|
264
|
+
}));
|
|
265
|
+
void this.hooks
|
|
266
|
+
.runContextEvicted({
|
|
267
|
+
groupId: guildId,
|
|
268
|
+
kind,
|
|
269
|
+
scopeId,
|
|
270
|
+
session,
|
|
271
|
+
evicted: payload,
|
|
272
|
+
window: this.contextWindow,
|
|
273
|
+
})
|
|
274
|
+
.catch((error) => {
|
|
275
|
+
this.host.logger?.warn?.(`[ai-evicted] 分发失败: ${String(error)}`);
|
|
276
|
+
});
|
|
224
277
|
}
|
|
225
278
|
// ---------------------------------------------------------------- 点名 / 跟随
|
|
226
279
|
isMention(session, record) {
|
|
@@ -319,12 +372,16 @@ class AiEngine {
|
|
|
319
372
|
return followup;
|
|
320
373
|
}
|
|
321
374
|
// ---------------------------------------------------------------- 记忆
|
|
322
|
-
async loadMemories(record, state) {
|
|
375
|
+
async loadMemories(record, state, session) {
|
|
323
376
|
if (!this.config.enableMemory || this.config.memoryInAi === false)
|
|
324
377
|
return [];
|
|
325
378
|
let content = '';
|
|
326
379
|
try {
|
|
327
|
-
|
|
380
|
+
// 按作用域读对应文件:群聊读该群,私聊读该用户
|
|
381
|
+
const scope = typeof this.host.memoryScopeOf === 'function'
|
|
382
|
+
? this.host.memoryScopeOf(session)
|
|
383
|
+
: null;
|
|
384
|
+
content = await this.host.readMemoryFile(scope);
|
|
328
385
|
}
|
|
329
386
|
catch {
|
|
330
387
|
return [];
|
|
@@ -399,7 +456,7 @@ class AiEngine {
|
|
|
399
456
|
const startedAt = this.now();
|
|
400
457
|
try {
|
|
401
458
|
const allowPass = !mention && !followup;
|
|
402
|
-
const memories = await this.loadMemories(record, state);
|
|
459
|
+
const memories = await this.loadMemories(record, state, session);
|
|
403
460
|
const hookCtx = {
|
|
404
461
|
session,
|
|
405
462
|
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;
|
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,10 @@ 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[]>;
|
|
75
78
|
}> | Schemastery.ObjectS<{
|
|
76
79
|
enableBlacklist: Schema<boolean, boolean>;
|
|
77
80
|
blacklistFileName: Schema<string, string>;
|
|
@@ -235,7 +238,10 @@ export declare const Config: Schema<Schemastery.ObjectS<{
|
|
|
235
238
|
} & {
|
|
236
239
|
enableMemory: boolean;
|
|
237
240
|
memoryFileName: string;
|
|
241
|
+
memoryPerScope: boolean;
|
|
238
242
|
memoryInAi: boolean;
|
|
243
|
+
memoryAutoLearn: boolean;
|
|
244
|
+
memoryAutoLearnGroups: string[];
|
|
239
245
|
} & {
|
|
240
246
|
enableBlacklist: boolean;
|
|
241
247
|
blacklistFileName: string;
|
package/lib/index.js
CHANGED
|
@@ -62,9 +62,12 @@ 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号白名单;留空表示全部生效。'),
|
|
68
71
|
}).description('记忆库'),
|
|
69
72
|
koishi_1.Schema.object({
|
|
70
73
|
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>;
|
package/lib/service.js
CHANGED
|
@@ -761,13 +761,44 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
761
761
|
}
|
|
762
762
|
}
|
|
763
763
|
// ============ 记忆库 ============
|
|
764
|
-
|
|
764
|
+
/**
|
|
765
|
+
* 记忆按作用域分文件:
|
|
766
|
+
* 群聊 → Memory_<群号>_群聊.md
|
|
767
|
+
* 私聊 → Memory_<QQ号>_私聊.md
|
|
768
|
+
*
|
|
769
|
+
* scope 为空时回落到旧的单文件(memoryFileName),保持兼容。
|
|
770
|
+
* @param {{kind:'group'|'private', id:string}|null} scope
|
|
771
|
+
*/
|
|
772
|
+
getMemoryFilePath(scope) {
|
|
765
773
|
const base = (this.ctx && this.ctx.baseDir) || process.cwd();
|
|
766
|
-
const
|
|
767
|
-
|
|
774
|
+
const legacy = (this.config.memoryFileName || 'Memory.md').trim();
|
|
775
|
+
const kind = scope && scope.kind;
|
|
776
|
+
const id = scope && String(scope.id || '').replace(/[^\w.-]/g, '');
|
|
777
|
+
if (!kind || !id) {
|
|
778
|
+
return node_path_1.default.resolve(base, legacy);
|
|
779
|
+
}
|
|
780
|
+
if (this.config.memoryPerScope === false) {
|
|
781
|
+
return node_path_1.default.resolve(base, legacy);
|
|
782
|
+
}
|
|
783
|
+
const label = kind === 'private' ? '私聊' : '群聊';
|
|
784
|
+
// 从旧文件名里取基础名,例如 Memory.md → Memory
|
|
785
|
+
const stem = legacy.replace(/\.md$/i, '') || 'Memory';
|
|
786
|
+
return node_path_1.default.resolve(base, `${stem}_${id}_${label}.md`);
|
|
787
|
+
}
|
|
788
|
+
/** 把 session 归一成作用域;群聊取群号,私聊取对方 QQ 号。 */
|
|
789
|
+
memoryScopeOf(session) {
|
|
790
|
+
if (!session)
|
|
791
|
+
return null;
|
|
792
|
+
const isDirect = session.isDirect === true || !session.guildId;
|
|
793
|
+
if (isDirect) {
|
|
794
|
+
const uid = String(session.userId || '').trim();
|
|
795
|
+
return uid ? { kind: 'private', id: uid } : null;
|
|
796
|
+
}
|
|
797
|
+
const gid = String(session.guildId || '').trim();
|
|
798
|
+
return gid ? { kind: 'group', id: gid } : null;
|
|
768
799
|
}
|
|
769
|
-
async readMemoryFile() {
|
|
770
|
-
const p = this.getMemoryFilePath();
|
|
800
|
+
async readMemoryFile(scope) {
|
|
801
|
+
const p = this.getMemoryFilePath(scope);
|
|
771
802
|
try {
|
|
772
803
|
return await node_fs_1.default.promises.readFile(p, 'utf8');
|
|
773
804
|
}
|
|
@@ -775,8 +806,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
775
806
|
return '';
|
|
776
807
|
}
|
|
777
808
|
}
|
|
778
|
-
async writeMemoryFile(content) {
|
|
779
|
-
const p = this.getMemoryFilePath();
|
|
809
|
+
async writeMemoryFile(content, scope) {
|
|
810
|
+
const p = this.getMemoryFilePath(scope);
|
|
780
811
|
await node_fs_1.default.promises.writeFile(p, String(content), 'utf8');
|
|
781
812
|
}
|
|
782
813
|
extractMemoryBlocks(content) {
|
|
@@ -796,32 +827,40 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
796
827
|
this._memoryWriteLock = run.then(() => undefined, () => undefined);
|
|
797
828
|
return run;
|
|
798
829
|
}
|
|
799
|
-
|
|
830
|
+
/**
|
|
831
|
+
* 追加一条记忆。
|
|
832
|
+
* @param {string} userId 写入者(旧字段,保留用于标记)
|
|
833
|
+
* @param {string} content 记忆正文
|
|
834
|
+
* @param {{kind:'group'|'private', id:string}|null} scope 作用域;为空则写旧单文件
|
|
835
|
+
* @param {string} [label] 自定义来源标记,例如「自动归纳」
|
|
836
|
+
*/
|
|
837
|
+
async saveMemoryToFile(userId, content, scope, label) {
|
|
800
838
|
return this.runMemoryWriteLocked(async () => {
|
|
801
839
|
const now = new Date();
|
|
802
840
|
const stamp = now.toLocaleString('zh-CN', { hour12: false });
|
|
803
|
-
const
|
|
804
|
-
const
|
|
841
|
+
const who = label || `用户 ${userId || 'unknown'}`;
|
|
842
|
+
const block = `## ${stamp} · ${who}\n${String(content).trim()}`;
|
|
843
|
+
const existing = (await this.readMemoryFile(scope)).trim();
|
|
805
844
|
const next = existing ? `${existing}\n\n---\n\n${block}\n` : `${block}\n`;
|
|
806
|
-
await this.writeMemoryFile(next);
|
|
845
|
+
await this.writeMemoryFile(next, scope);
|
|
807
846
|
return block;
|
|
808
847
|
});
|
|
809
848
|
}
|
|
810
|
-
async searchMemory(keyword, limit = 8) {
|
|
811
|
-
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
849
|
+
async searchMemory(keyword, limit = 8, scope) {
|
|
850
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile(scope));
|
|
812
851
|
const kw = String(keyword || '').trim();
|
|
813
852
|
if (!kw)
|
|
814
853
|
return blocks.slice(-limit);
|
|
815
854
|
return blocks.filter((b) => b.includes(kw)).slice(-limit);
|
|
816
855
|
}
|
|
817
856
|
/** 按关键词删除记忆条目(含该关键词的整条记忆块)。返回 { ok, removed, message } */
|
|
818
|
-
async deleteMemoryByKeyword(keyword) {
|
|
857
|
+
async deleteMemoryByKeyword(keyword, scope) {
|
|
819
858
|
const kw = String(keyword ?? '').trim();
|
|
820
859
|
if (!kw)
|
|
821
860
|
return { ok: false, removed: 0, message: '关键词为空。' };
|
|
822
861
|
// 同样走写锁:删除与保存并发时不会互相覆盖
|
|
823
862
|
return this.runMemoryWriteLocked(async () => {
|
|
824
|
-
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
863
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile(scope));
|
|
825
864
|
if (!blocks.length)
|
|
826
865
|
return { ok: false, removed: 0, message: '记忆库为空。' };
|
|
827
866
|
const kept = blocks.filter((b) => !b.includes(kw));
|
|
@@ -829,7 +868,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
829
868
|
if (!removed)
|
|
830
869
|
return { ok: false, removed: 0, message: `未找到包含「${kw}」的记忆` };
|
|
831
870
|
const content = kept.length ? kept.join('\n\n---\n\n') + '\n' : '';
|
|
832
|
-
await this.writeMemoryFile(content);
|
|
871
|
+
await this.writeMemoryFile(content, scope);
|
|
833
872
|
return { ok: true, removed, message: `已删除 ${removed} 条` };
|
|
834
873
|
});
|
|
835
874
|
}
|
|
@@ -2850,17 +2889,19 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2850
2889
|
await session.send(this.styleText('请给出要删除的关键词。'));
|
|
2851
2890
|
return true;
|
|
2852
2891
|
}
|
|
2853
|
-
const
|
|
2892
|
+
const mscope = this.memoryScopeOf(session);
|
|
2893
|
+
const results = await this.searchMemory(keyword, 8, mscope);
|
|
2854
2894
|
if (!results.length) {
|
|
2855
2895
|
await session.send(this.styleText(`删除失败,未找到包含「${keyword}」的记忆。`));
|
|
2856
2896
|
return true;
|
|
2857
2897
|
}
|
|
2858
|
-
const r = await this.deleteMemoryByKeyword(keyword);
|
|
2898
|
+
const r = await this.deleteMemoryByKeyword(keyword, mscope);
|
|
2859
2899
|
await session.send(this.styleText(r.ok ? `已删除 ${r.removed} 条记忆。` : `删除失败:${r.message}`));
|
|
2860
2900
|
return true;
|
|
2861
2901
|
}
|
|
2862
2902
|
if (/^(?:list|all)$/i.test(sub)) {
|
|
2863
|
-
const
|
|
2903
|
+
const mscope = this.memoryScopeOf(session);
|
|
2904
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile(mscope));
|
|
2864
2905
|
if (!blocks.length) {
|
|
2865
2906
|
await session.send(this.styleText('记忆库为空。'));
|
|
2866
2907
|
return true;
|
|
@@ -2873,7 +2914,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2873
2914
|
const queryMatch = sub.match(/^(?:search|query|find)\s*[::]?\s*([\s\S]*)$/i);
|
|
2874
2915
|
if (queryMatch) {
|
|
2875
2916
|
const keyword = queryMatch[1].trim();
|
|
2876
|
-
const
|
|
2917
|
+
const mscope = this.memoryScopeOf(session);
|
|
2918
|
+
const results = await this.searchMemory(keyword, 8, mscope);
|
|
2877
2919
|
if (!results.length) {
|
|
2878
2920
|
await session.send(this.styleText(keyword ? `没有找到包含「${keyword}」的记忆。` : '记忆库为空或没有可显示的记录。'));
|
|
2879
2921
|
return true;
|
|
@@ -2885,7 +2927,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2885
2927
|
}
|
|
2886
2928
|
// 保存
|
|
2887
2929
|
try {
|
|
2888
|
-
|
|
2930
|
+
const mscope = this.memoryScopeOf(session);
|
|
2931
|
+
await this.saveMemoryToFile(session.userId, sub, mscope);
|
|
2889
2932
|
await session.send(this.styleText('已记住。'));
|
|
2890
2933
|
this.logCommandResult('memory-save', { ok: true, message: 'memory saved' }, session, { content: sub });
|
|
2891
2934
|
}
|
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.0",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"typings": "lib/index.d.ts",
|
|
7
7
|
"files": [
|