@nestim/koishi-plugin-qq-group-manager 1.4.9 → 1.4.11
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 +47 -0
- package/lib/ai/engine.d.ts +27 -1
- package/lib/ai/engine.js +285 -13
- package/lib/ai/hooks.d.ts +10 -2
- package/lib/ai/hooks.js +23 -2
- package/lib/ai/learn.d.ts +8 -0
- package/lib/ai/learn.js +15 -0
- package/lib/ai/runtime.d.ts +2 -0
- package/lib/ai/runtime.js +8 -0
- package/lib/ai/state.d.ts +4 -0
- package/lib/ai/state.js +8 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +2 -1
- package/package.json +1 -1
- package/readme.md +26 -12
- package/src/ai/engine.ts +267 -13
- package/src/ai/hooks.ts +28 -5
- package/src/ai/learn.ts +16 -0
- package/src/ai/runtime.ts +9 -0
- package/src/ai/state.ts +10 -0
- package/src/index.ts +2 -1
package/lib/ai/runtime.js
CHANGED
|
@@ -39,6 +39,14 @@ class AiRuntimeFacade {
|
|
|
39
39
|
}
|
|
40
40
|
return this.current.ai.chat(request);
|
|
41
41
|
}
|
|
42
|
+
/** 把一条消息里的图片解析成 data URL(私聊插件复用主插件的视觉链路) */
|
|
43
|
+
images(session) {
|
|
44
|
+
if (!this.current || !this.current.ai
|
|
45
|
+
|| typeof this.current.ai.resolveSessionImages !== 'function') {
|
|
46
|
+
return Promise.resolve([]);
|
|
47
|
+
}
|
|
48
|
+
return this.current.ai.resolveSessionImages(session);
|
|
49
|
+
}
|
|
42
50
|
}
|
|
43
51
|
exports.AiRuntimeFacade = AiRuntimeFacade;
|
|
44
52
|
function getAiRuntimeFacade() {
|
package/lib/ai/state.d.ts
CHANGED
|
@@ -56,5 +56,9 @@ export declare class AiState {
|
|
|
56
56
|
private groups;
|
|
57
57
|
get(key: string): GroupState;
|
|
58
58
|
peek(key: string): GroupState | undefined;
|
|
59
|
+
/** 持久化用:遍历所有会话状态 */
|
|
60
|
+
entries(): Array<[string, GroupState]>;
|
|
61
|
+
/** 持久化用:恢复一个会话状态 */
|
|
62
|
+
set(key: string, state: GroupState): void;
|
|
59
63
|
clear(): void;
|
|
60
64
|
}
|
package/lib/ai/state.js
CHANGED
|
@@ -61,6 +61,14 @@ class AiState {
|
|
|
61
61
|
peek(key) {
|
|
62
62
|
return this.groups.get(key);
|
|
63
63
|
}
|
|
64
|
+
/** 持久化用:遍历所有会话状态 */
|
|
65
|
+
entries() {
|
|
66
|
+
return [...this.groups.entries()];
|
|
67
|
+
}
|
|
68
|
+
/** 持久化用:恢复一个会话状态 */
|
|
69
|
+
set(key, state) {
|
|
70
|
+
this.groups.set(key, state);
|
|
71
|
+
}
|
|
64
72
|
clear() {
|
|
65
73
|
this.groups.clear();
|
|
66
74
|
}
|
package/lib/index.d.ts
CHANGED
|
@@ -171,6 +171,7 @@ export declare const Config: Schema<Schemastery.ObjectS<{
|
|
|
171
171
|
aiPseudoRandomStep: Schema<number, number>;
|
|
172
172
|
aiMinReplyIntervalSeconds: Schema<number, number>;
|
|
173
173
|
aiContextWindow: Schema<number, number>;
|
|
174
|
+
persistAiState: Schema<boolean, boolean>;
|
|
174
175
|
aiContextMaxChars: Schema<number, number>;
|
|
175
176
|
aiStyleMaxChars: Schema<number, number>;
|
|
176
177
|
aiTemperature: Schema<number, number>;
|
|
@@ -337,6 +338,7 @@ export declare const Config: Schema<Schemastery.ObjectS<{
|
|
|
337
338
|
aiPseudoRandomStep: number;
|
|
338
339
|
aiMinReplyIntervalSeconds: number;
|
|
339
340
|
aiContextWindow: number;
|
|
341
|
+
persistAiState: boolean;
|
|
340
342
|
aiContextMaxChars: number;
|
|
341
343
|
aiStyleMaxChars: number;
|
|
342
344
|
aiTemperature: number;
|
package/lib/index.js
CHANGED
|
@@ -154,6 +154,7 @@ exports.Config = koishi_1.Schema.intersect([
|
|
|
154
154
|
aiPseudoRandomStep: koishi_1.Schema.number().min(0).max(1).step(0.001).default(0.01).description('伪随机每次未命中增加的概率(默认 0.01 = 1%)。只在真正掷骰且未命中时累加,冷却/阈值跳过不算。'),
|
|
155
155
|
aiMinReplyIntervalSeconds: koishi_1.Schema.natural().default(45).description('同一群两次真正调用模型的最短间隔(秒)。'),
|
|
156
156
|
aiContextWindow: koishi_1.Schema.natural().default(30).description('参与推理的最近消息条数(建议 20~40;太小会导致模型看不到前文)。'),
|
|
157
|
+
persistAiState: koishi_1.Schema.boolean().default(true).description('重启插件后恢复最近上下文、未归纳的消息桶、计数与冷却(保存到 data/qqgm-ai-state.json,只存文本、不存图片)。关闭则每次重启都从头开始。'),
|
|
157
158
|
aiContextMaxChars: koishi_1.Schema.natural().min(0).max(20000).default(0).description('历史上下文的字数上限:超过后从最旧的消息开始丢(至少保留最近 4 条)。0 = 不限。想省 token 可设 2500~3500。'),
|
|
158
159
|
aiStyleMaxChars: koishi_1.Schema.natural().min(0).max(20000).default(0).description('外部插件注入的「说话风格」段每条最多保留多少字。0 = 不限。风格 skill 很长时可设 1200~1800 显著省 token。'),
|
|
159
160
|
aiTemperature: koishi_1.Schema.number().min(0).max(2).step(0.1).default(0.8).description('生成温度(0~2)。群聊接话建议 0.7~0.9,过高会跑题、复述、发散。'),
|
|
@@ -178,7 +179,7 @@ exports.Config = koishi_1.Schema.intersect([
|
|
|
178
179
|
]).role('radio').default('auto').description('联网搜索触发方式。'),
|
|
179
180
|
aiWebSearchMaxResults: koishi_1.Schema.natural().min(1).max(10).default(5).description('每次联网搜索取几条结果。'),
|
|
180
181
|
aiWebSearchTimeoutMs: koishi_1.Schema.natural().min(500).max(15000).default(4000).description('搜索请求超时(毫秒)。'),
|
|
181
|
-
aiWebSearchMaxPerHour: koishi_1.Schema.natural().min(0).max(100).default(10).description('每个群每小时最多搜索次数;0
|
|
182
|
+
aiWebSearchMaxPerHour: koishi_1.Schema.natural().min(0).max(100).default(10).description('每个群每小时最多搜索次数;0=不限。命中缓存不占次数。'),
|
|
182
183
|
aiWebSearchCacheMinutes: koishi_1.Schema.natural().min(0).max(1440).default(10).description('相同 query 的结果缓存分钟数;0=不缓存。'),
|
|
183
184
|
aiRequestTimeoutSeconds: koishi_1.Schema.natural().min(5).max(120).default(20).description('单次模型请求超时(秒)。'),
|
|
184
185
|
aiDebugPrompt: koishi_1.Schema.boolean().default(false).description('调试:把最终系统提示词与用户提示词写入日志(排查"答非所问"时打开,平时关闭)。'),
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nestim/koishi-plugin-qq-group-manager",
|
|
3
3
|
"description": "Koishi QQ群管理插件(OneBot/LLOneBot):群管命令、权限校验、图片菜单、状态卡片、复读、AI群聊回复、记忆库、识图与自动管控(禁言/踢人)。",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.11",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"typings": "lib/index.d.ts",
|
|
7
7
|
"files": [
|
package/readme.md
CHANGED
|
@@ -92,22 +92,30 @@ npm i @nestim/koishi-plugin-qq-group-manager
|
|
|
92
92
|
| `bannedWordScoreThreshold` | `70` | 违禁词评分触发阈值(强关键词共用) |
|
|
93
93
|
| `strongKeywords` | `[]` | 强关键词;命中即触发且**无视白名单豁免**,支持 `关键词\|分值` |
|
|
94
94
|
| `groupRules` | `[]` | 按群覆盖策略(违禁词、强关键词、白名单关键词、AI 开关、自动处罚阈值等) |
|
|
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` | 相似度超此值跳过,避免重复记 |
|
|
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
103
|
| `memoryLearnDailyLimit` | `30` | 每作用域每天最多归纳次数 |
|
|
104
|
+
| `memoryLearnConsolidate` | `true` | 自动记忆压缩:每 N 条合并成 1 条 |
|
|
105
|
+
| `memoryLearnConsolidateEvery` | `5` | 每多少条自动记忆压缩一次 |
|
|
106
|
+
| `memoryLearnMaxEntries` | `15` | 自动记忆条数上限(不含手动 `[memory]`) |
|
|
107
|
+
| `memoryLearnConsolidateMaxChars` | `90` | 压缩后单条记忆字数上限 |
|
|
108
|
+
| `memoryLearnModel` | 空 | 归纳/压缩专用模型,留空沿用 `aiModel` |
|
|
104
109
|
| `blacklistFileName` | `banMember.md` | 黑名单文件名模板,实际为 `banMember_<群号>.md` |
|
|
105
110
|
| `pendingJoinFileName` | `JoinRequests.md` | 待审入群申请落盘文件名 |
|
|
106
111
|
| `enableJoinRequestReview` | `true` | 是否发起入群审核 |
|
|
107
112
|
| `enableAiReply` | `false` | AI 回复总开关(建议配合 `aiReplyRequireGroupRule` 逐群开启) |
|
|
108
113
|
| `aiReplyRequireGroupRule` | `true` | 仅对已在 `groupRules` 中单独配置的群启用 AI 回复 |
|
|
109
114
|
| `aiContextWindow` | `30` | 进入提示词的消息条数(建议 20~40) |
|
|
110
|
-
| `
|
|
115
|
+
| `persistAiState` | `true` | 重启后恢复最近上下文、未归纳消息、计数与冷却(保存到 `data/qqgm-ai-state.json`,只存文本) |
|
|
116
|
+
| `aiMaxOutputTokens` | `1500` | 思考 + 回答的总 token 上限(`max_tokens`),不是只限制正文 |
|
|
117
|
+
| `aiPseudoRandom` | `true` | 随机未命中时逐步提高概率,到 1 必定回复 |
|
|
118
|
+
| `aiPseudoRandomStep` | `0.01` | 每次未命中增加的概率 |
|
|
111
119
|
| `aiMaxReplyChars` | `120` | 单条回复最大字符数 |
|
|
112
120
|
| `aiQuoteReplyMode` | `random` | 回复是否引用触发消息:`random` / `always` / `never` |
|
|
113
121
|
| `aiQuoteReplyProbability` | `0.5` | `random` 模式下的引用概率 |
|
|
@@ -167,7 +175,7 @@ npm i @nestim/koishi-plugin-qq-group-manager
|
|
|
167
175
|
| 插件 | 作用 | 地址 |
|
|
168
176
|
| --- | --- | --- |
|
|
169
177
|
| `@nestim/koishi-plugin-qqgm-chat-style` | 聊天风格:一个主风格 + 多个按概率随机叠加的追加风格 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-chat-style) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-chat-style) |
|
|
170
|
-
| `@nestim/koishi-plugin-qqgm-meme` | 表情包:AI 用 `[表情: 情绪]` 抽图,按概率补在文字后面 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-meme) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-meme) |
|
|
178
|
+
| `@nestim/koishi-plugin-qqgm-meme` | 表情包:AI 用 `[表情: 情绪]` 抽图,按概率补在文字后面 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-meme) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-meme) |
|
|
171
179
|
| `@nestim/koishi-plugin-qqgm-private` | 私聊:AI 自动回复 + 定时主动私发 | [npm](https://www.npmjs.com/package/@nestim/koishi-plugin-qqgm-private) · [GitHub](https://github.com/Miseat/koishi-plugin-qqgm-private) |
|
|
172
180
|
|
|
173
181
|
定时提醒(`[提醒] 明天 8 点 开会`)**内建在本插件里**,不需要额外安装。
|
|
@@ -219,16 +227,21 @@ export function apply(ctx) {
|
|
|
219
227
|
// 发送前过滤;返回 null 表示这条不发(按 pass 处理)
|
|
220
228
|
const off2 = hooks.registerOutputFilter((text) => text.replace(/首先/g, ''))
|
|
221
229
|
|
|
230
|
+
// 按群覆盖主插件默认人设(v3+;返回空表示不覆盖)
|
|
231
|
+
const off3 = hooks.registerPersonaOverride((ctx) => (ctx.groupId === '123456' ? '你是本群专属的猫娘' : null))
|
|
232
|
+
|
|
222
233
|
ctx.on('dispose', () => {
|
|
223
234
|
off1()
|
|
224
235
|
off2()
|
|
236
|
+
off3()
|
|
225
237
|
})
|
|
226
238
|
}
|
|
227
239
|
```
|
|
228
240
|
|
|
229
241
|
- 风格段插在基础规则之后、`<pass/>` 规则之前,并声明“与系统规则冲突时以系统规则为准”。
|
|
230
242
|
- 过滤器按注册顺序执行,异常会被隔离;过滤后的文本才会写回上下文。
|
|
231
|
-
- `hooks.version` 目前为 `
|
|
243
|
+
- `hooks.version` 目前为 `3`:`>=2` 支持 `registerContextEvicted`,`>=3` 支持 `registerPersonaOverride`。
|
|
244
|
+
- 私聊类插件还可以用 `ctx.root.get('qqgmAiRuntime').images(session)` 复用主插件的图片解析链路。
|
|
232
245
|
|
|
233
246
|
|
|
234
247
|
## 数据文件
|
|
@@ -237,10 +250,11 @@ export function apply(ctx) {
|
|
|
237
250
|
|
|
238
251
|
| 文件 | 内容 |
|
|
239
252
|
| --- | --- |
|
|
240
|
-
| `Memory_<群号>_群聊.md` | 该群的记忆,条目之间以 `---` 分隔 |
|
|
253
|
+
| `Memory_<群号>_群聊.md` | 该群的记忆,条目之间以 `---` 分隔 |
|
|
241
254
|
| `Memory_<QQ号>_私聊.md` | 与该用户的私聊记忆 |
|
|
242
255
|
| `banMember_<群号>.md` | 各群黑名单,`## QQ号 · 备注` + 加入时间 |
|
|
243
256
|
| `JoinRequests.md` | 待审入群申请(人类可读表格 + 机器可读区段),重启自动恢复、过期自动清理 |
|
|
257
|
+
| `qqgm-ai-state.json` | AI 上下文与未归纳消息的持久化快照(`persistAiState`,只存文本、不存图片) |
|
|
244
258
|
|
|
245
259
|
## 权限模型
|
|
246
260
|
|
package/src/ai/engine.ts
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { AiState, GroupState, ChatRecord, FollowupState } from './state';
|
|
16
|
+
import * as fs from 'node:fs';
|
|
17
|
+
import * as path from 'node:path';
|
|
16
18
|
import {
|
|
17
19
|
LearnBucket,
|
|
18
20
|
LearnStore,
|
|
@@ -142,6 +144,9 @@ export class AiEngine {
|
|
|
142
144
|
private learnDaily = new Map<string, number>();
|
|
143
145
|
/** 自动归纳:空闲兜底定时器 */
|
|
144
146
|
private learnTimer: any = null;
|
|
147
|
+
/** 状态持久化:退出/定时把上下文与待归纳桶写到 data/qqgm-ai-state.json */
|
|
148
|
+
private persistEnabled = true;
|
|
149
|
+
private persistTimer: any = null;
|
|
145
150
|
|
|
146
151
|
constructor(host: AiHost, deps: AiDeps = {}) {
|
|
147
152
|
this.host = host;
|
|
@@ -160,10 +165,215 @@ export class AiEngine {
|
|
|
160
165
|
this.now = deps.now ?? Date.now;
|
|
161
166
|
this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
|
|
162
167
|
|
|
168
|
+
// 只有配置明确为 true 才持久化。生产环境 Schema 默认就是 true;
|
|
169
|
+
// 测试里用裸对象构造引擎时不会误写/误读仓库目录下的状态文件。
|
|
170
|
+
this.persistEnabled = host.config?.persistAiState === true;
|
|
171
|
+
this.restorePersistedState();
|
|
172
|
+
|
|
163
173
|
// 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
|
|
164
174
|
this.startLearnTimer();
|
|
165
175
|
}
|
|
166
176
|
|
|
177
|
+
// ---------------------------------------------------------------- 持久化
|
|
178
|
+
|
|
179
|
+
/** 持久化文件路径(Koishi 数据目录下) */
|
|
180
|
+
private stateFilePath(): string {
|
|
181
|
+
const base = (this.host as any)?.ctx?.baseDir || process.cwd();
|
|
182
|
+
return path.join(base, 'data', 'qqgm-ai-state.json');
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** 精简一条记录用于落盘:去掉图片(Data URL 太大),文本做上限 */
|
|
186
|
+
private slimRecord(record: ChatRecord): any {
|
|
187
|
+
return {
|
|
188
|
+
id: String(record.id || ''),
|
|
189
|
+
userId: String(record.userId || ''),
|
|
190
|
+
name: String(record.name || ''),
|
|
191
|
+
role: record.role || 'unknown',
|
|
192
|
+
text: String(record.text || '').slice(0, 600),
|
|
193
|
+
quote: record.quote
|
|
194
|
+
? {
|
|
195
|
+
name: String((record.quote as any).name || ''),
|
|
196
|
+
userId: String((record.quote as any).userId || ''),
|
|
197
|
+
text: String((record.quote as any).text || '').slice(0, 200),
|
|
198
|
+
id: String((record.quote as any).id || ''),
|
|
199
|
+
}
|
|
200
|
+
: undefined,
|
|
201
|
+
forwardText: record.forwardText ? String(record.forwardText).slice(0, 1200) : undefined,
|
|
202
|
+
mentions: Array.isArray(record.mentions) ? record.mentions.map(String).slice(0, 20) : [],
|
|
203
|
+
atBot: !!record.atBot,
|
|
204
|
+
self: !!record.self,
|
|
205
|
+
at: Number(record.at) || 0,
|
|
206
|
+
command: record.command ? true : undefined,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private reviveRecord(raw: any): ChatRecord | null {
|
|
211
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
212
|
+
const text = String(raw.text || '').trim();
|
|
213
|
+
if (!text && !raw.command) return null;
|
|
214
|
+
return {
|
|
215
|
+
id: String(raw.id || `restored-${Math.random().toString(36).slice(2, 8)}`),
|
|
216
|
+
userId: String(raw.userId || ''),
|
|
217
|
+
name: String(raw.name || raw.userId || ''),
|
|
218
|
+
role: raw.role || 'unknown',
|
|
219
|
+
text,
|
|
220
|
+
images: [],
|
|
221
|
+
quote: raw.quote?.text
|
|
222
|
+
? {
|
|
223
|
+
name: String(raw.quote.name || ''),
|
|
224
|
+
userId: String(raw.quote.userId || ''),
|
|
225
|
+
text: String(raw.quote.text || ''),
|
|
226
|
+
id: String(raw.quote.id || ''),
|
|
227
|
+
images: [],
|
|
228
|
+
}
|
|
229
|
+
: undefined,
|
|
230
|
+
forwardText: raw.forwardText ? String(raw.forwardText) : undefined,
|
|
231
|
+
mentions: Array.isArray(raw.mentions) ? raw.mentions.map(String) : [],
|
|
232
|
+
atBot: !!raw.atBot,
|
|
233
|
+
self: !!raw.self,
|
|
234
|
+
at: Number(raw.at) || 0,
|
|
235
|
+
command: !!raw.command,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* 恢复上次退出时的状态。
|
|
241
|
+
*
|
|
242
|
+
* - 最近上下文:只恢复 6 小时以内的,避免重启后把很久以前的消息当成“最近”;
|
|
243
|
+
* - 未归纳消息桶:全部恢复(它们还没变成记忆,丢了就真丢了);
|
|
244
|
+
* - 计数、模型调用冷却、伪随机加成、点名跟随:一并恢复。
|
|
245
|
+
*/
|
|
246
|
+
private restorePersistedState(): void {
|
|
247
|
+
if (!this.persistEnabled) return;
|
|
248
|
+
const file = this.stateFilePath();
|
|
249
|
+
let data: any;
|
|
250
|
+
try {
|
|
251
|
+
data = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
252
|
+
} catch {
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (!data || data.version !== 1) return;
|
|
256
|
+
|
|
257
|
+
const now = this.now();
|
|
258
|
+
const ttl = 6 * 60 * 60 * 1000;
|
|
259
|
+
let groups = 0;
|
|
260
|
+
let learns = 0;
|
|
261
|
+
|
|
262
|
+
for (const [key, raw] of Object.entries(data.groups || {})) {
|
|
263
|
+
const item: any = raw;
|
|
264
|
+
if (!item || typeof item !== 'object') continue;
|
|
265
|
+
const st = new GroupState();
|
|
266
|
+
st.counter = Math.max(0, Number(item.counter) || 0);
|
|
267
|
+
st.lastAttemptAt = Math.max(0, Number(item.lastAttemptAt) || 0);
|
|
268
|
+
st.lastCooldownNoticeAt = Math.max(0, Number(item.lastCooldownNoticeAt) || 0);
|
|
269
|
+
st.randomBoost = Math.min(1, Math.max(0, Number(item.randomBoost) || 0));
|
|
270
|
+
const followup = item.followup;
|
|
271
|
+
if (followup && Number(followup.expiresAt) > now && typeof followup.userId === 'string') {
|
|
272
|
+
st.followup = followup as FollowupState;
|
|
273
|
+
}
|
|
274
|
+
st.records = (Array.isArray(item.records) ? item.records : [])
|
|
275
|
+
.map((record: any) => this.reviveRecord(record))
|
|
276
|
+
.filter((record: ChatRecord | null): record is ChatRecord => !!record)
|
|
277
|
+
.filter((record: ChatRecord) => now - record.at <= ttl);
|
|
278
|
+
if (st.records.length > this.contextWindow) {
|
|
279
|
+
st.records = st.records.slice(-this.contextWindow);
|
|
280
|
+
}
|
|
281
|
+
if (!st.records.length) {
|
|
282
|
+
st.counter = 0;
|
|
283
|
+
st.followup = null;
|
|
284
|
+
// 上下文过期就不恢复这个会话,避免凭空出现一个空状态
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
this.state.set(key, st);
|
|
288
|
+
groups += 1;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
for (const [key, raw] of Object.entries(data.learn || {})) {
|
|
292
|
+
const item: any = raw;
|
|
293
|
+
const idx = key.indexOf(':');
|
|
294
|
+
if (idx < 0 || !item || typeof item !== 'object') continue;
|
|
295
|
+
const bucket = new LearnBucket();
|
|
296
|
+
bucket.records = (Array.isArray(item.records) ? item.records : [])
|
|
297
|
+
.map((record: any) => this.reviveRecord(record))
|
|
298
|
+
.filter((record: ChatRecord | null): record is ChatRecord => !!record);
|
|
299
|
+
bucket.lastActivityAt = Number(item.lastActivityAt) || 0;
|
|
300
|
+
bucket.lastLearnedAt = Number(item.lastLearnedAt) || 0;
|
|
301
|
+
if (!bucket.records.length) continue;
|
|
302
|
+
this.learnStore.set(key.slice(0, idx), key.slice(idx + 1), bucket);
|
|
303
|
+
learns += 1;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
for (const pair of Array.isArray(data.learnDaily) ? data.learnDaily : []) {
|
|
307
|
+
if (Array.isArray(pair) && pair.length === 2) {
|
|
308
|
+
this.learnDaily.set(String(pair[0]), Math.max(0, Number(pair[1]) || 0));
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (groups || learns) {
|
|
313
|
+
this.host.logger?.info?.(`[ai-state] 已恢复 ${groups} 个会话、${learns} 个待归纳桶`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** 落盘当前状态(同步、原子替换,dispose 时调用) */
|
|
318
|
+
private flushPersistedState(): void {
|
|
319
|
+
if (!this.persistEnabled) return;
|
|
320
|
+
if (this.persistTimer) {
|
|
321
|
+
clearTimeout(this.persistTimer);
|
|
322
|
+
this.persistTimer = null;
|
|
323
|
+
}
|
|
324
|
+
try {
|
|
325
|
+
const file = this.stateFilePath();
|
|
326
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
327
|
+
const tmp = `${file}.tmp`;
|
|
328
|
+
fs.writeFileSync(tmp, JSON.stringify(this.snapshotState()), 'utf8');
|
|
329
|
+
fs.renameSync(tmp, file);
|
|
330
|
+
} catch (error: any) {
|
|
331
|
+
this.host.logger?.warn?.(`[ai-state] 保存失败: ${String(error)}`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private snapshotState(): any {
|
|
336
|
+
const groups: Record<string, any> = {};
|
|
337
|
+
for (const [key, st] of this.state.entries()) {
|
|
338
|
+
if (!st.records.length && !st.counter && !st.randomBoost) continue;
|
|
339
|
+
groups[key] = {
|
|
340
|
+
counter: st.counter,
|
|
341
|
+
lastAttemptAt: st.lastAttemptAt,
|
|
342
|
+
lastCooldownNoticeAt: st.lastCooldownNoticeAt,
|
|
343
|
+
randomBoost: st.randomBoost,
|
|
344
|
+
followup: st.followup,
|
|
345
|
+
records: st.records.map((record) => this.slimRecord(record)),
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const learn: Record<string, any> = {};
|
|
350
|
+
for (const item of this.learnStore.entries()) {
|
|
351
|
+
learn[`${item.kind}:${item.scopeId}`] = {
|
|
352
|
+
lastActivityAt: item.bucket.lastActivityAt,
|
|
353
|
+
lastLearnedAt: item.bucket.lastLearnedAt,
|
|
354
|
+
records: item.bucket.records.map((record) => this.slimRecord(record as ChatRecord)),
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
return {
|
|
359
|
+
version: 1,
|
|
360
|
+
savedAt: this.now(),
|
|
361
|
+
groups,
|
|
362
|
+
learn,
|
|
363
|
+
learnDaily: [...this.learnDaily.entries()],
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** 防抖落盘:状态变化频繁,最多 3 秒写一次 */
|
|
368
|
+
private schedulePersist(): void {
|
|
369
|
+
if (!this.persistEnabled || this.persistTimer) return;
|
|
370
|
+
this.persistTimer = setTimeout(() => {
|
|
371
|
+
this.persistTimer = null;
|
|
372
|
+
this.flushPersistedState();
|
|
373
|
+
}, 3000);
|
|
374
|
+
if (this.persistTimer.unref) this.persistTimer.unref();
|
|
375
|
+
}
|
|
376
|
+
|
|
167
377
|
// ---------------------------------------------------------------- 配置
|
|
168
378
|
|
|
169
379
|
private groupKey(session: any): string {
|
|
@@ -318,6 +528,7 @@ export class AiEngine {
|
|
|
318
528
|
const evicted = state.push(record, contextWindow);
|
|
319
529
|
this.emitEvicted(evicted, key, session);
|
|
320
530
|
state.counter += 1;
|
|
531
|
+
this.schedulePersist();
|
|
321
532
|
return record;
|
|
322
533
|
}
|
|
323
534
|
|
|
@@ -343,6 +554,7 @@ export class AiEngine {
|
|
|
343
554
|
this.contextWindow,
|
|
344
555
|
);
|
|
345
556
|
this.emitEvicted(evicted, groupKey, session);
|
|
557
|
+
this.schedulePersist();
|
|
346
558
|
}
|
|
347
559
|
|
|
348
560
|
/** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
|
|
@@ -366,6 +578,7 @@ export class AiEngine {
|
|
|
366
578
|
this.contextWindow,
|
|
367
579
|
);
|
|
368
580
|
this.emitEvicted(evicted, key, session);
|
|
581
|
+
this.schedulePersist();
|
|
369
582
|
}
|
|
370
583
|
|
|
371
584
|
/**
|
|
@@ -426,6 +639,7 @@ export class AiEngine {
|
|
|
426
639
|
const bucket = this.learnStore.get(kind, scopeId);
|
|
427
640
|
const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
|
|
428
641
|
const fire = bucket.push(evicted, threshold, this.now());
|
|
642
|
+
this.schedulePersist();
|
|
429
643
|
if (fire) {
|
|
430
644
|
void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
|
|
431
645
|
}
|
|
@@ -452,8 +666,9 @@ export class AiEngine {
|
|
|
452
666
|
if (this.learnTimer.unref) this.learnTimer.unref();
|
|
453
667
|
}
|
|
454
668
|
|
|
455
|
-
/**
|
|
669
|
+
/** 资源清理:落盘状态、停止定时器、清空缓存 */
|
|
456
670
|
dispose(): void {
|
|
671
|
+
this.flushPersistedState();
|
|
457
672
|
if (this.learnTimer) {
|
|
458
673
|
clearInterval(this.learnTimer);
|
|
459
674
|
this.learnTimer = null;
|
|
@@ -474,6 +689,7 @@ export class AiEngine {
|
|
|
474
689
|
const cfg: any = this.config || {};
|
|
475
690
|
const records = bucket.drain();
|
|
476
691
|
if (!records.length) return;
|
|
692
|
+
this.schedulePersist();
|
|
477
693
|
|
|
478
694
|
const scope = { kind, id: scopeId } as any;
|
|
479
695
|
const saved = await this.summarizeRecords(records, kind, scope, reason);
|
|
@@ -890,10 +1106,11 @@ export class AiEngine {
|
|
|
890
1106
|
mode: 'reply',
|
|
891
1107
|
};
|
|
892
1108
|
const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
|
|
1109
|
+
const personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
|
|
893
1110
|
const webSearch = await this.webSearch(record, session);
|
|
894
1111
|
const promptInput = {
|
|
895
1112
|
selfName: this.selfName,
|
|
896
|
-
persona: this.personaPrompt,
|
|
1113
|
+
persona: personaOverride || this.personaPrompt,
|
|
897
1114
|
groupId: String(session.guildId),
|
|
898
1115
|
records: this.clampContext(state.records),
|
|
899
1116
|
current: record,
|
|
@@ -1019,6 +1236,7 @@ export class AiEngine {
|
|
|
1019
1236
|
}, session);
|
|
1020
1237
|
} finally {
|
|
1021
1238
|
state.inFlight = false;
|
|
1239
|
+
this.schedulePersist();
|
|
1022
1240
|
}
|
|
1023
1241
|
}
|
|
1024
1242
|
|
|
@@ -1031,15 +1249,19 @@ export class AiEngine {
|
|
|
1031
1249
|
async idleTopic(groupId: string): Promise<string> {
|
|
1032
1250
|
const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
|
|
1033
1251
|
let sections: string[] = [];
|
|
1252
|
+
let personaOverride: string | null = null;
|
|
1034
1253
|
try {
|
|
1035
|
-
|
|
1254
|
+
const hookCtx = { session, groupId, mode: 'reply' as const };
|
|
1255
|
+
sections = this.clampStyle(await this.hooks.collectSections(hookCtx));
|
|
1256
|
+
personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
|
|
1036
1257
|
} catch { /* ignore */ }
|
|
1037
1258
|
const system = [
|
|
1038
1259
|
`你是 QQ 群 ${groupId} 里的一个普通成员。`,
|
|
1260
|
+
personaOverride || this.personaPrompt,
|
|
1039
1261
|
'群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
|
|
1040
1262
|
'不要问“在吗”,不要提“很久没人说话”,不要自我介绍。',
|
|
1041
1263
|
...sections,
|
|
1042
|
-
].join('\n');
|
|
1264
|
+
].filter(Boolean).join('\n');
|
|
1043
1265
|
const result = await this.provider.chat({
|
|
1044
1266
|
system,
|
|
1045
1267
|
user: '现在发一条主动话题。',
|
|
@@ -1067,24 +1289,33 @@ export class AiEngine {
|
|
|
1067
1289
|
const now = this.now();
|
|
1068
1290
|
if (this.searchUnsupportedUntil > now) return '';
|
|
1069
1291
|
const groupId = String(session?.guildId || '');
|
|
1070
|
-
|
|
1292
|
+
|
|
1293
|
+
// 先查缓存:命中缓存不消耗搜索配额
|
|
1294
|
+
const cacheMinutes = Math.max(0, Number(this.config.aiWebSearchCacheMinutes ?? 10));
|
|
1295
|
+
const cacheKey = `${String(this.config.aiBaseUrl || '')}|${query}`;
|
|
1296
|
+
if (cacheMinutes > 0) {
|
|
1297
|
+
const hit = this.searchCache.get(cacheKey);
|
|
1298
|
+
if (hit && now - hit.at < cacheMinutes * 60_000) return hit.section;
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
const maxPerHour = Math.max(0, Number(this.config.aiWebSearchMaxPerHour ?? 30));
|
|
1071
1302
|
if (maxPerHour > 0) {
|
|
1072
1303
|
const list = (this.searchRate.get(groupId) || []).filter((t) => now - t < 3600_000);
|
|
1073
1304
|
if (list.length >= maxPerHour) {
|
|
1074
|
-
|
|
1305
|
+
const resetIn = Math.max(1, Math.ceil((list[0] + 3600_000 - now) / 1000));
|
|
1306
|
+
this.log('web-search', {
|
|
1307
|
+
ok: false,
|
|
1308
|
+
reason: 'rate-limit',
|
|
1309
|
+
limit: maxPerHour,
|
|
1310
|
+
resetIn,
|
|
1311
|
+
groupId,
|
|
1312
|
+
}, session);
|
|
1075
1313
|
return '';
|
|
1076
1314
|
}
|
|
1077
1315
|
list.push(now);
|
|
1078
1316
|
this.searchRate.set(groupId, list);
|
|
1079
1317
|
}
|
|
1080
1318
|
|
|
1081
|
-
const cacheMinutes = Math.max(0, Number(this.config.aiWebSearchCacheMinutes ?? 10));
|
|
1082
|
-
const cacheKey = `${String(this.config.aiBaseUrl || '')}|${query}`;
|
|
1083
|
-
if (cacheMinutes > 0) {
|
|
1084
|
-
const hit = this.searchCache.get(cacheKey);
|
|
1085
|
-
if (hit && now - hit.at < cacheMinutes * 60_000) return hit.section;
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
1319
|
const startedAt = this.now();
|
|
1089
1320
|
const outcome = await fetchWebSearch({
|
|
1090
1321
|
query,
|
|
@@ -1209,6 +1440,28 @@ export class AiEngine {
|
|
|
1209
1440
|
);
|
|
1210
1441
|
}
|
|
1211
1442
|
|
|
1443
|
+
/**
|
|
1444
|
+
* 供外部插件(qqgm-private)复用:把一条私聊消息里的图片解析成 data URL。
|
|
1445
|
+
* 不做上下文回看,只看当前消息本身。
|
|
1446
|
+
*/
|
|
1447
|
+
async resolveSessionImages(session: any): Promise<string[]> {
|
|
1448
|
+
if (this.config.aiEnableImageRecognition === false) return [];
|
|
1449
|
+
const maxCount = Math.max(0, Number(this.config.aiImageMaxCount ?? 2));
|
|
1450
|
+
if (!maxCount) return [];
|
|
1451
|
+
let own: RenderedImage[] = [];
|
|
1452
|
+
try {
|
|
1453
|
+
own = this.host.extractImages(session) || [];
|
|
1454
|
+
} catch {
|
|
1455
|
+
own = [];
|
|
1456
|
+
}
|
|
1457
|
+
if (!own.length) return [];
|
|
1458
|
+
return resolveImages(
|
|
1459
|
+
own,
|
|
1460
|
+
(ref) => this.host.resolveImage(ref, session),
|
|
1461
|
+
{ maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) },
|
|
1462
|
+
);
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1212
1465
|
private platformAllowed(platform: string): boolean {
|
|
1213
1466
|
const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
|
|
1214
1467
|
return list.includes(platform);
|
|
@@ -1232,5 +1485,6 @@ export class AiEngine {
|
|
|
1232
1485
|
clear(): void {
|
|
1233
1486
|
this.state.clear();
|
|
1234
1487
|
this.names.clear();
|
|
1488
|
+
this.flushPersistedState();
|
|
1235
1489
|
}
|
|
1236
1490
|
}
|
package/src/ai/hooks.ts
CHANGED
|
@@ -17,6 +17,9 @@ export interface AiHookContext {
|
|
|
17
17
|
export type PromptSectionProvider = (ctx: AiHookContext) => string | Promise<string>;
|
|
18
18
|
export type OutputFilter = (text: string, ctx: AiHookContext) => string | null | Promise<string | null>;
|
|
19
19
|
|
|
20
|
+
/** 覆盖主插件的默认人设/系统提示词;返回空表示不覆盖。 */
|
|
21
|
+
export type PersonaOverrideProvider = (ctx: AiHookContext) => string | null | Promise<string | null>;
|
|
22
|
+
|
|
20
23
|
export interface AiAfterReplyContext extends AiHookContext {
|
|
21
24
|
/** 已经发送并写入上下文的最终文本 */
|
|
22
25
|
text: string;
|
|
@@ -54,13 +57,14 @@ export interface ContextEvictedContext {
|
|
|
54
57
|
export type ContextEvictedHandler = (ctx: ContextEvictedContext) => void | Promise<void>;
|
|
55
58
|
|
|
56
59
|
export class AiHookRegistry {
|
|
57
|
-
/**
|
|
58
|
-
readonly version =
|
|
60
|
+
/** 钩子接口版本;>=2 支持 contextEvicted,>=3 支持 registerPersonaOverride */
|
|
61
|
+
readonly version = 3;
|
|
59
62
|
|
|
60
63
|
private sections = new Set<PromptSectionProvider>();
|
|
61
64
|
private filters = new Set<OutputFilter>();
|
|
62
65
|
private afterReplyHandlers = new Set<AfterReplyHandler>();
|
|
63
66
|
private evictedHandlers = new Set<ContextEvictedHandler>();
|
|
67
|
+
private personaOverrides = new Set<PersonaOverrideProvider>();
|
|
64
68
|
|
|
65
69
|
constructor(private logger?: any) {}
|
|
66
70
|
|
|
@@ -70,12 +74,13 @@ export class AiHookRegistry {
|
|
|
70
74
|
}
|
|
71
75
|
|
|
72
76
|
/** 诊断用:当前已注册的钩子数量。 */
|
|
73
|
-
stats(): { sections: number; filters: number; afterReply: number; evicted: number } {
|
|
77
|
+
stats(): { sections: number; filters: number; afterReply: number; evicted: number; persona: number } {
|
|
74
78
|
return {
|
|
75
79
|
sections: this.sections.size,
|
|
76
80
|
filters: this.filters.size,
|
|
77
81
|
afterReply: this.afterReplyHandlers.size,
|
|
78
82
|
evicted: this.evictedHandlers.size,
|
|
83
|
+
persona: this.personaOverrides.size,
|
|
79
84
|
};
|
|
80
85
|
}
|
|
81
86
|
|
|
@@ -84,6 +89,12 @@ export class AiHookRegistry {
|
|
|
84
89
|
return () => this.sections.delete(provider);
|
|
85
90
|
}
|
|
86
91
|
|
|
92
|
+
/** 覆盖主插件默认人设(按群);第一个返回非空文本的生效。 */
|
|
93
|
+
registerPersonaOverride(provider: PersonaOverrideProvider): () => void {
|
|
94
|
+
this.personaOverrides.add(provider);
|
|
95
|
+
return () => this.personaOverrides.delete(provider);
|
|
96
|
+
}
|
|
97
|
+
|
|
87
98
|
registerOutputFilter(filter: OutputFilter): () => void {
|
|
88
99
|
this.filters.add(filter);
|
|
89
100
|
return () => this.filters.delete(filter);
|
|
@@ -104,9 +115,21 @@ export class AiHookRegistry {
|
|
|
104
115
|
return () => this.evictedHandlers.delete(handler);
|
|
105
116
|
}
|
|
106
117
|
|
|
118
|
+
/** 第一个非空的人设覆盖生效;失败只记日志。 */
|
|
119
|
+
async collectPersonaOverride(ctx: AiHookContext): Promise<string | null> {
|
|
120
|
+
for (const provider of this.personaOverrides) {
|
|
121
|
+
try {
|
|
122
|
+
const text = await provider(ctx);
|
|
123
|
+
if (text && String(text).trim()) return String(text).trim();
|
|
124
|
+
} catch (error) {
|
|
125
|
+
this.logger?.warn?.(`[ai-hooks] persona override failed: ${String(error)}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
|
|
107
131
|
/** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
|
|
108
|
-
async collectSections(ctx: AiHookContext): Promise<string[]> {
|
|
109
|
-
const out: string[] = [];
|
|
132
|
+
async collectSections(ctx: AiHookContext): Promise<string[]> { const out: string[] = [];
|
|
110
133
|
for (const provider of this.sections) {
|
|
111
134
|
try {
|
|
112
135
|
const text = await provider(ctx);
|