@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/src/ai/hooks.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* AI 扩展钩子:让外部插件给提示词追加“风格段”,并在发送前过滤输出。
|
|
3
3
|
*
|
|
4
4
|
* 设计目标:
|
|
5
|
-
* -
|
|
5
|
+
* - 只暴露最小能力,不把引擎内部结构漏出去;
|
|
6
6
|
* - 任何钩子抛错都不能影响正常回复(记录日志后继续);
|
|
7
7
|
* - 输出过滤器返回 null 表示“这条不要发”(按 pass 处理);
|
|
8
8
|
* - version 用于外部插件做兼容检查。
|
|
@@ -21,15 +21,46 @@ export interface AiAfterReplyContext extends AiHookContext {
|
|
|
21
21
|
/** 已经发送并写入上下文的最终文本 */
|
|
22
22
|
text: string;
|
|
23
23
|
}
|
|
24
|
+
|
|
24
25
|
export type AfterReplyHandler = (ctx: AiAfterReplyContext) => void | Promise<void>;
|
|
25
26
|
|
|
27
|
+
/** 一条被挤出上下文的消息。字段与 ChatRecord 对齐,但只挑外部需要的部分。 */
|
|
28
|
+
export interface EvictedRecord {
|
|
29
|
+
id: string;
|
|
30
|
+
userId: string;
|
|
31
|
+
name: string;
|
|
32
|
+
role?: string;
|
|
33
|
+
text: string;
|
|
34
|
+
self: boolean;
|
|
35
|
+
at: number;
|
|
36
|
+
command?: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 上下文挤出事件:一次可能挤掉多条。 */
|
|
40
|
+
export interface ContextEvictedContext {
|
|
41
|
+
/** 群号;私聊时为空字符串 */
|
|
42
|
+
groupId: string;
|
|
43
|
+
/** 会话类型 */
|
|
44
|
+
kind: 'group' | 'private';
|
|
45
|
+
/** 作用域 ID:群聊=群号,私聊=对方 QQ 号 */
|
|
46
|
+
scopeId: string;
|
|
47
|
+
session?: any;
|
|
48
|
+
/** 本次被挤出的消息,按时间先后排列 */
|
|
49
|
+
evicted: EvictedRecord[];
|
|
50
|
+
/** 当前上下文窗口大小 */
|
|
51
|
+
window: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export type ContextEvictedHandler = (ctx: ContextEvictedContext) => void | Promise<void>;
|
|
55
|
+
|
|
26
56
|
export class AiHookRegistry {
|
|
27
|
-
/** 钩子接口版本;外部插件应检查 >=
|
|
28
|
-
readonly version =
|
|
57
|
+
/** 钩子接口版本;外部插件应检查 >= 2 才能用 contextEvicted */
|
|
58
|
+
readonly version = 2;
|
|
29
59
|
|
|
30
60
|
private sections = new Set<PromptSectionProvider>();
|
|
31
61
|
private filters = new Set<OutputFilter>();
|
|
32
62
|
private afterReplyHandlers = new Set<AfterReplyHandler>();
|
|
63
|
+
private evictedHandlers = new Set<ContextEvictedHandler>();
|
|
33
64
|
|
|
34
65
|
constructor(private logger?: any) {}
|
|
35
66
|
|
|
@@ -49,6 +80,15 @@ export class AiHookRegistry {
|
|
|
49
80
|
return () => this.afterReplyHandlers.delete(handler);
|
|
50
81
|
}
|
|
51
82
|
|
|
83
|
+
/**
|
|
84
|
+
* 上下文挤出消息时触发(2.0+)。
|
|
85
|
+
* 用于把这些即将被丢弃的消息交给外部插件做归纳、归档等。
|
|
86
|
+
*/
|
|
87
|
+
registerContextEvicted(handler: ContextEvictedHandler): () => void {
|
|
88
|
+
this.evictedHandlers.add(handler);
|
|
89
|
+
return () => this.evictedHandlers.delete(handler);
|
|
90
|
+
}
|
|
91
|
+
|
|
52
92
|
/** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
|
|
53
93
|
async collectSections(ctx: AiHookContext): Promise<string[]> {
|
|
54
94
|
const out: string[] = [];
|
|
@@ -88,4 +128,16 @@ export class AiHookRegistry {
|
|
|
88
128
|
}
|
|
89
129
|
}
|
|
90
130
|
}
|
|
131
|
+
|
|
132
|
+
/** 上下文挤出后执行;单个 handler 失败只记日志,不影响其它。 */
|
|
133
|
+
async runContextEvicted(ctx: ContextEvictedContext): Promise<void> {
|
|
134
|
+
if (!this.evictedHandlers.size) return;
|
|
135
|
+
for (const handler of this.evictedHandlers) {
|
|
136
|
+
try {
|
|
137
|
+
await handler(ctx);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
this.logger?.warn?.(`[ai-hooks] context-evicted failed: ${String(error)}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
91
143
|
}
|
package/src/ai/learn.ts
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆自动归纳(纯函数 + 轻量状态)。
|
|
3
|
+
*
|
|
4
|
+
* 触发时机由 engine 在上下文挤出时调用:
|
|
5
|
+
* - 累计条数达到「上下文窗口 × 倍率」
|
|
6
|
+
* - 或距最后一条消息超过 idleHours 且期间有新消息(由 idle 定时器驱动)
|
|
7
|
+
*
|
|
8
|
+
* 归纳出来的内容是一次性的一长串,150 字以内,写入对应作用域的记忆文件。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { truncate } from '../core/text';
|
|
12
|
+
|
|
13
|
+
export const MAX_SUMMARY_CHARS = 150;
|
|
14
|
+
|
|
15
|
+
export interface EvictedLike {
|
|
16
|
+
id?: string;
|
|
17
|
+
userId?: string;
|
|
18
|
+
name?: string;
|
|
19
|
+
text?: string;
|
|
20
|
+
self?: boolean;
|
|
21
|
+
at?: number;
|
|
22
|
+
command?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 正在累计的一批消息 */
|
|
26
|
+
export class LearnBucket {
|
|
27
|
+
records: EvictedLike[] = [];
|
|
28
|
+
lastActivityAt = 0;
|
|
29
|
+
lastLearnedAt = 0;
|
|
30
|
+
|
|
31
|
+
push(records: EvictedLike[], threshold: number, now: number): boolean {
|
|
32
|
+
if (!records || !records.length) return false;
|
|
33
|
+
this.records.push(...records);
|
|
34
|
+
this.lastActivityAt = now;
|
|
35
|
+
return this.records.length >= Math.max(1, threshold);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 距最后一条消息超过 idleMs,且确实有内容 */
|
|
39
|
+
isIdle(now: number, idleMs: number): boolean {
|
|
40
|
+
if (!this.records.length) return false;
|
|
41
|
+
if (!this.lastActivityAt) return false;
|
|
42
|
+
return now - this.lastActivityAt >= idleMs;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
drain(): EvictedLike[] {
|
|
46
|
+
const out = this.records;
|
|
47
|
+
this.records = [];
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
get size(): number {
|
|
52
|
+
return this.records.length;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 按作用域保存累计桶 */
|
|
57
|
+
export class LearnStore {
|
|
58
|
+
private map = new Map<string, LearnBucket>();
|
|
59
|
+
|
|
60
|
+
private key(kind: string, scopeId: string): string {
|
|
61
|
+
return `${kind}:${scopeId}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
get(kind: string, scopeId: string): LearnBucket {
|
|
65
|
+
const k = this.key(kind, scopeId);
|
|
66
|
+
let bucket = this.map.get(k);
|
|
67
|
+
if (!bucket) {
|
|
68
|
+
bucket = new LearnBucket();
|
|
69
|
+
this.map.set(k, bucket);
|
|
70
|
+
}
|
|
71
|
+
return bucket;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
idleList(now: number, idleMs: number): Array<{ kind: string; scopeId: string; bucket: LearnBucket }> {
|
|
75
|
+
const out: Array<{ kind: string; scopeId: string; bucket: LearnBucket }> = [];
|
|
76
|
+
for (const [k, bucket] of this.map) {
|
|
77
|
+
if (!bucket.size) continue;
|
|
78
|
+
if (!bucket.isIdle(now, idleMs)) continue;
|
|
79
|
+
const idx = k.indexOf(':');
|
|
80
|
+
out.push({ kind: k.slice(0, idx), scopeId: k.slice(idx + 1), bucket });
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
clear(): void {
|
|
86
|
+
this.map.clear();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 把一批消息渲染成模型可读的文本 */
|
|
91
|
+
export function renderForSummary(records: EvictedLike[], selfName = 'bot'): string {
|
|
92
|
+
const lines: string[] = [];
|
|
93
|
+
for (const item of records) {
|
|
94
|
+
if (!item || item.command) continue;
|
|
95
|
+
const text = String(item.text || '').replace(/\s+/g, ' ').trim();
|
|
96
|
+
if (!text) continue;
|
|
97
|
+
const who = item.self ? selfName : String(item.name || item.userId || '某人');
|
|
98
|
+
lines.push(`${who}: ${truncate(text, 160)}`);
|
|
99
|
+
}
|
|
100
|
+
return lines.join('\n');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 归纳提示词 */
|
|
104
|
+
export function buildSummaryPrompt(
|
|
105
|
+
records: EvictedLike[],
|
|
106
|
+
options: { kind?: string; selfName?: string } = {},
|
|
107
|
+
): { system: string; user: string } {
|
|
108
|
+
const label = options.kind === 'private' ? '私聊' : '群聊';
|
|
109
|
+
const body = renderForSummary(records, options.selfName || 'bot');
|
|
110
|
+
const system = [
|
|
111
|
+
`你在整理一段${label}记录,从中提炼值得长期记住的信息。`,
|
|
112
|
+
'',
|
|
113
|
+
'只保留这几类:',
|
|
114
|
+
'1. 人物关系与称呼(谁是谁、怎么叫、什么身份)',
|
|
115
|
+
'2. 稳定的偏好、立场、习惯(不是一时的情绪)',
|
|
116
|
+
'3. 群内或两人之间约定俗成的说法、黑话',
|
|
117
|
+
'4. 反复出现、以后还会聊到的话题',
|
|
118
|
+
'',
|
|
119
|
+
'必须丢掉:寒暄、打招呼、一次性的抱怨或玩笑、已经结束的接梗、纯表情。',
|
|
120
|
+
'',
|
|
121
|
+
'输出要求:',
|
|
122
|
+
'- 只输出一条记忆,纯文本,不要标题、不要列表、不要编号、不要 Markdown;',
|
|
123
|
+
`- 不超过 ${MAX_SUMMARY_CHARS} 字;`,
|
|
124
|
+
'- 用陈述句写事实,不要写「他们聊到」「讨论了」这类过程描述;',
|
|
125
|
+
'- 如果没有任何值得长期记住的内容,只输出一个词:NONE',
|
|
126
|
+
].join('\n');
|
|
127
|
+
|
|
128
|
+
const user = ['【记录】', body || '(空)', '', '现在输出那一条记忆,或输出 NONE。'].join('\n');
|
|
129
|
+
return { system, user };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 清洗模型输出 */
|
|
133
|
+
export function cleanSummary(raw: string, maxChars = MAX_SUMMARY_CHARS): string {
|
|
134
|
+
let text = String(raw || '').trim();
|
|
135
|
+
if (!text) return '';
|
|
136
|
+
text = text
|
|
137
|
+
.replace(/^```[a-zA-Z0-9_-]*\s*\n?/, '')
|
|
138
|
+
.replace(/\n?\s*```\s*$/, '')
|
|
139
|
+
.replace(/^["'“”‘’「」]+|["'“”‘’「」]+$/g, '')
|
|
140
|
+
.trim();
|
|
141
|
+
|
|
142
|
+
text = text
|
|
143
|
+
.split(/\r?\n/)
|
|
144
|
+
.map((line) => line.replace(/^\s*(?:[-*+·]|\d+[.)、])\s*/, '').trim())
|
|
145
|
+
.filter(Boolean)
|
|
146
|
+
.join(' ')
|
|
147
|
+
.replace(/\s+/g, ' ')
|
|
148
|
+
.trim();
|
|
149
|
+
|
|
150
|
+
if (/^(?:none|无|没有|n\/a)$/i.test(text)) return '';
|
|
151
|
+
|
|
152
|
+
const limit = Math.max(20, maxChars);
|
|
153
|
+
if (text.length > limit) {
|
|
154
|
+
const slice = text.slice(0, limit);
|
|
155
|
+
let cut = -1;
|
|
156
|
+
for (const ch of ['。', '!', '?', ';']) {
|
|
157
|
+
cut = Math.max(cut, slice.lastIndexOf(ch));
|
|
158
|
+
}
|
|
159
|
+
text = cut >= Math.floor(limit * 0.5) ? slice.slice(0, cut + 1) : `${slice}…`;
|
|
160
|
+
}
|
|
161
|
+
return text.trim();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const CJK = /[\u4e00-\u9fa5]/;
|
|
165
|
+
|
|
166
|
+
function tokenize(text: string): Set<string> {
|
|
167
|
+
const tokens = new Set<string>();
|
|
168
|
+
const normalized = String(text || '')
|
|
169
|
+
.toLowerCase()
|
|
170
|
+
.replace(/[^\u4e00-\u9fa5a-z0-9]+/g, ' ')
|
|
171
|
+
.trim();
|
|
172
|
+
if (!normalized) return tokens;
|
|
173
|
+
for (const chunk of normalized.split(/\s+/)) {
|
|
174
|
+
if (!chunk) continue;
|
|
175
|
+
if (CJK.test(chunk)) {
|
|
176
|
+
const chars = [...chunk];
|
|
177
|
+
if (chars.length === 1) {
|
|
178
|
+
tokens.add(chunk);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
for (let i = 0; i < chars.length - 1; i += 1) tokens.add(chars[i] + chars[i + 1]);
|
|
182
|
+
} else if (chunk.length >= 2) {
|
|
183
|
+
tokens.add(chunk);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return tokens;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Jaccard 相似度,用于挡住重复记忆 */
|
|
190
|
+
export function similarityOf(a: string, b: string): number {
|
|
191
|
+
const ta = tokenize(a);
|
|
192
|
+
const tb = tokenize(b);
|
|
193
|
+
if (!ta.size || !tb.size) return 0;
|
|
194
|
+
let inter = 0;
|
|
195
|
+
for (const t of ta) if (tb.has(t)) inter += 1;
|
|
196
|
+
const union = ta.size + tb.size - inter;
|
|
197
|
+
return union ? inter / union : 0;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 判断是否与已有记忆重复 */
|
|
201
|
+
export function isDuplicate(candidate: string, existing: string[], threshold = 0.55): boolean {
|
|
202
|
+
const text = String(candidate || '').trim();
|
|
203
|
+
if (!text) return false;
|
|
204
|
+
for (const item of existing || []) {
|
|
205
|
+
if (similarityOf(text, String(item || '')) >= threshold) return true;
|
|
206
|
+
}
|
|
207
|
+
return false;
|
|
208
|
+
}
|
package/src/ai/state.ts
CHANGED
|
@@ -47,14 +47,17 @@ export class GroupState {
|
|
|
47
47
|
followup: FollowupState | null = null;
|
|
48
48
|
seen = new Map<string, number>();
|
|
49
49
|
|
|
50
|
-
|
|
50
|
+
/** 挤压上下文,返回被挤出的消息(按时间先后)。 */
|
|
51
|
+
trim(window: number): ChatRecord[] {
|
|
51
52
|
const max = Math.max(6, window || 24);
|
|
52
|
-
if (this.records.length
|
|
53
|
+
if (this.records.length <= max) return [];
|
|
54
|
+
return this.records.splice(0, this.records.length - max);
|
|
53
55
|
}
|
|
54
56
|
|
|
55
|
-
|
|
57
|
+
/** @returns 本次被挤出的消息,供外部做归纳 */
|
|
58
|
+
push(record: ChatRecord, window: number): ChatRecord[] {
|
|
56
59
|
this.records.push(record);
|
|
57
|
-
this.trim(window);
|
|
60
|
+
return this.trim(window);
|
|
58
61
|
}
|
|
59
62
|
|
|
60
63
|
/** 事件去重:同一 messageId 15 秒内只处理一次 */
|
package/src/index.ts
CHANGED
|
@@ -59,9 +59,18 @@ export const Config = Schema.intersect([
|
|
|
59
59
|
autoViolationWindowMinutes: Schema.natural().default(60).description('违规计数统计窗口(分钟):窗口内连续违规才累计,超时未违规则重新计数。'),
|
|
60
60
|
}).description('自动管控'),
|
|
61
61
|
Schema.object({
|
|
62
|
-
enableMemory: Schema.boolean().default(true).description('启用记忆库:群内发送 [memory] 内容
|
|
63
|
-
memoryFileName: Schema.string().default('Memory.md').description('
|
|
64
|
-
|
|
62
|
+
enableMemory: Schema.boolean().default(true).description('启用记忆库:群内发送 [memory] 内容 保存,[memory] search 关键词 查询、[memory] delete 关键词 删除,AI 回复可引用。'),
|
|
63
|
+
memoryFileName: Schema.string().default('Memory.md').description('记忆库基础文件名(保存在 Koishi 数据目录)。按作用域分文件时用它作为前缀,例如 Memory.md → Memory_123456_群聊.md。'),
|
|
64
|
+
memoryPerScope: Schema.boolean().default(true).description('按私聊/群聊分开存储:群聊写 Memory_<群号>_群聊.md,私聊写 Memory_<QQ号>_私聊.md。关闭则所有会话共用单文件(旧行为)。'),
|
|
65
|
+
memoryInAi: Schema.boolean().default(true).description('AI 回复/识图时是否参考记忆库内容(只读当前会话对应的文件)。'),
|
|
66
|
+
memoryAutoLearn: Schema.boolean().default(false).description('自动归纳:上下文挤满后,把被挤出的消息交给外部学习插件总结成记忆。这里只负责抛出事件,实际归纳由 qqgm-memory-learn 完成。'),
|
|
67
|
+
memoryAutoLearnGroups: Schema.array(String).role('table').default([]).description('自动归纳生效的群号/QQ号白名单;留空表示全部生效。'),
|
|
68
|
+
memoryLearnIdleHours: Schema.natural().min(1).max(72).default(8).description('空闲兜底:距最后一条消息超过这么多小时且期间有新消息,就归纳一次。一直没新消息则不触发。'),
|
|
69
|
+
memoryLearnThresholdScale: Schema.number().min(1).max(10).step(0.5).default(1).description('归纳阈值 = aiContextWindow × 该倍数。填 1 表示攒满一个上下文窗口就归纳。'),
|
|
70
|
+
memoryLearnMaxChars: Schema.natural().min(40).max(300).default(150).description('单条自动记忆的字数上限。'),
|
|
71
|
+
memoryLearnPushBack: Schema.boolean().default(true).description('归纳后把结果回推到原会话:私聊发私聊、群聊发对应群。'),
|
|
72
|
+
memoryLearnDuplicateThreshold: Schema.number().min(0.3).max(0.95).step(0.05).default(0.55).description('与已有记忆相似度超过该值就跳过,避免同一件事反复记。'),
|
|
73
|
+
memoryLearnDailyLimit: Schema.natural().min(1).max(200).default(30).description('每个作用域每天最多归纳几次,防止刷模型额度。'),
|
|
65
74
|
}).description('记忆库'),
|
|
66
75
|
Schema.object({
|
|
67
76
|
enableBlacklist: Schema.boolean().default(true).description('全局黑名单系统开关。单个群未单独设置时跟随此值;单个群设置后以该群为准(全局关着也能为某群单独开启)。'),
|