@nestim/koishi-plugin-qq-group-manager 1.1.4 → 1.2.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 +299 -0
- package/lib/ai/engine.d.ts +74 -0
- package/lib/ai/engine.js +525 -0
- package/lib/ai/memory.d.ts +30 -0
- package/lib/ai/memory.js +89 -0
- package/lib/ai/prompt.d.ts +36 -0
- package/lib/ai/prompt.js +125 -0
- package/lib/ai/provider.d.ts +48 -0
- package/lib/ai/provider.js +194 -0
- package/lib/ai/state.d.ts +53 -0
- package/lib/ai/state.js +62 -0
- package/lib/ai/trigger.d.ts +28 -0
- package/lib/ai/trigger.js +41 -0
- package/lib/ai/vision.d.ts +15 -0
- package/lib/ai/vision.js +64 -0
- package/lib/core/names.d.ts +48 -0
- package/lib/core/names.js +144 -0
- package/lib/core/text.d.ts +47 -0
- package/lib/core/text.js +284 -0
- package/lib/index.d.ts +263 -54
- package/lib/index.js +19 -13
- package/lib/service.d.ts +574 -153
- package/lib/service.js +56 -1221
- package/package.json +18 -6
- package/readme.md +27 -13
- package/src/ai/engine.ts +568 -0
- package/src/ai/memory.ts +104 -0
- package/src/ai/prompt.ts +142 -0
- package/src/ai/provider.ts +221 -0
- package/src/ai/state.ts +91 -0
- package/src/ai/trigger.ts +60 -0
- package/src/ai/vision.ts +81 -0
- package/src/core/names.ts +158 -0
- package/src/core/text.ts +332 -0
- package/src/index.ts +186 -0
- package/src/service.js +3327 -0
- package/tsconfig.json +24 -0
- package/lib/commands.d.ts +0 -4
- package/lib/commands.js +0 -18
- package/lib/types.d.ts +0 -23
- package/lib/types.js +0 -2
package/package.json
CHANGED
|
@@ -1,24 +1,32 @@
|
|
|
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.2.0",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"typings": "lib/index.d.ts",
|
|
7
7
|
"files": [
|
|
8
8
|
"lib",
|
|
9
|
-
"
|
|
9
|
+
"src",
|
|
10
|
+
"tsconfig.json",
|
|
11
|
+
"CHANGELOG.md"
|
|
10
12
|
],
|
|
11
13
|
"license": "MIT",
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=18"
|
|
16
|
+
},
|
|
12
17
|
"scripts": {
|
|
13
|
-
"build": "
|
|
14
|
-
"clean": "
|
|
15
|
-
"rebuild": "npm run
|
|
18
|
+
"build": "node scripts/build.mjs",
|
|
19
|
+
"clean": "node -e \"require('node:fs').rmSync('lib',{recursive:true,force:true})\"",
|
|
20
|
+
"rebuild": "npm run build",
|
|
21
|
+
"test": "node --test \"test/*.test.mjs\"",
|
|
22
|
+
"prepublishOnly": "npm run test && npm run build"
|
|
16
23
|
},
|
|
17
24
|
"keywords": [
|
|
18
25
|
"qq",
|
|
19
26
|
"group",
|
|
20
27
|
"onebot",
|
|
21
28
|
"llonebot",
|
|
29
|
+
"napcat",
|
|
22
30
|
"koishi",
|
|
23
31
|
"koishi-plugin",
|
|
24
32
|
"chatbot",
|
|
@@ -27,7 +35,11 @@
|
|
|
27
35
|
"vision",
|
|
28
36
|
"ai"
|
|
29
37
|
],
|
|
30
|
-
"devDependencies": {
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/node": "^22.20.5",
|
|
40
|
+
"koishi": "4.18.11",
|
|
41
|
+
"typescript": "5.6.3"
|
|
42
|
+
},
|
|
31
43
|
"peerDependencies": {
|
|
32
44
|
"koishi": "^4.18.7"
|
|
33
45
|
},
|
package/readme.md
CHANGED
|
@@ -29,7 +29,7 @@ Koishi 控制台「探索器 Explorer」里查看和手改。
|
|
|
29
29
|
| **黑名单** | 按群独立存储(`banMember_<群号>.md`);入群自动比对并踢出,可选踢人时自动记录 |
|
|
30
30
|
| **入群审核** | 新申请推送到群内,管理员用 `approve` / `reject` 放行或拒绝;待审单落盘,**重启不丢** |
|
|
31
31
|
| **记忆库** | `[memory]` 保存 / 列出 / 查询 / 删除,落盘 `Memory.md`;开启后 AI 回复会检索并引用相关记忆 |
|
|
32
|
-
| **AI 群聊回复** |
|
|
32
|
+
| **AI 群聊回复** | 三道闸门(阈值 / 概率 / 冷却)+ 模型自行 `<pass/>` 决定是否接话;群名片、引用、@ 目标、自己历史发言都进上下文;记忆按相关度注入;图片并发解析并限时。多人格、点名后话题跟随、温度与输出上限 |
|
|
33
33
|
| **AI 识图** | 图片下载转 data URL 后送入模型,兼容 CQ 码 / HTML `<img>` / 元素三种形态与表情包 |
|
|
34
34
|
| **复读** | 连续相同消息达阈值复读,支持图片引用回查;复读事件会进入 AI 上下文 |
|
|
35
35
|
| **娱乐** | 自我约束(口球)与违规禁言惩罚,可开关与调节参数 |
|
|
@@ -97,25 +97,39 @@ npm i @nestim/koishi-plugin-qq-group-manager
|
|
|
97
97
|
| `enableJoinRequestReview` | `true` | 是否发起入群审核 |
|
|
98
98
|
| `enableAiReply` | `false` | AI 回复总开关(建议配合 `aiReplyRequireGroupRule` 逐群开启) |
|
|
99
99
|
| `aiReplyRequireGroupRule` | `true` | 仅对已在 `groupRules` 中单独配置的群启用 AI 回复 |
|
|
100
|
+
| `aiContextWindow` | `30` | 进入提示词的消息条数(建议 20~40) |
|
|
101
|
+
| `aiReplyDecision` | `single` | `single` 一次调用(推荐)/ `two-stage` 两次调用 |
|
|
102
|
+
| `aiMaxReplyChars` | `120` | 单条回复最大字符数 |
|
|
103
|
+
| `aiImageBudgetMs` | `6000` | 图片解析总预算(毫秒),超时跳过 |
|
|
104
|
+
| `aiDebugPrompt` | `false` | 把最终提示词写入日志,排查"答非所问" |
|
|
100
105
|
| `dryRun` | `false` | 演练模式:只输出计划动作,不真正执行 |
|
|
101
106
|
|
|
102
107
|
## AI 回复与识图
|
|
103
108
|
|
|
104
109
|
- **接口**:`openai-compatible`(OpenAI 兼容 Chat Completions)与 `gemini`(原生 `generateContent`)两类。
|
|
105
|
-
-
|
|
106
|
-
1. `aiMessageThreshold` 消息阈值(`threshold` / `hybrid
|
|
110
|
+
- **触发**:先过三道闸门,任一不过都不产生模型调用:
|
|
111
|
+
1. `aiMessageThreshold` 消息阈值(`threshold` / `hybrid`)——累计未达阈值不触发;
|
|
107
112
|
2. `aiRandomReplyProbability` 随机概率(`random` / `hybrid`)——每条消息掷一次骰,未掷中直接跳过;
|
|
108
|
-
3. `
|
|
113
|
+
3. 冷却:同一群两次真正调用模型之间至少间隔 `aiMinReplyIntervalSeconds`。
|
|
109
114
|
|
|
110
115
|
`hybrid` 表示**两者都需满足**(先够消息数,再掷中概率)。消息中命中智能体自称或直接 `@bot` 时,
|
|
111
|
-
|
|
116
|
+
越过上述全部闸门直接触发。点名与点名后跟随不受冷却限制。
|
|
117
|
+
- **接话决策**:默认 `aiReplyDecision: single`——模型在回复时自行判断,不值得接话就只输出 `<pass/>`,
|
|
118
|
+
此时不会发消息并重置计数。这样「要不要回」和「回什么」是同一次判断,不会出现
|
|
119
|
+
「判定说该回、生成却回了另一条」的错位。设为 `two-stage` 则先判定再生成(多一次延迟)。
|
|
120
|
+
- **上下文**:`aiContextWindow` 条消息按**时间顺序**进入提示词,包含 @ 目标(渲染成群昵称)、
|
|
121
|
+
引用消息原文、图片/表情/卡片占位,以及**机器人自己的历史发言**——不会"说完就忘"。
|
|
122
|
+
只回应当前消息,引用与回答始终指向同一条。
|
|
123
|
+
- **群名片**:优先取群名片,为空时调用 `getGroupMemberInfo` 补齐并缓存,最后才退回 QQ 昵称/QQ 号。
|
|
124
|
+
- **记忆**:只有与当前消息(或最近三条)真正有词面交集的记忆才会注入,并且提示词明确允许忽略;
|
|
125
|
+
旧版「搜不到就注入最近 6 条」的行为已移除,不会再出现"聊什么都能扯回某条旧记忆"。
|
|
112
126
|
- **多人格**:`aiPersonas` 保存多套「自称 + 系统提示词」,用 `aiActivePersona` 切换。
|
|
113
|
-
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
-
|
|
118
|
-
|
|
127
|
+
- **识图**:开启 `aiEnableImageRecognition` 后,图片并发下载并转为 data URL 再送入模型;
|
|
128
|
+
总预算由 `aiImageBudgetMs` 控制(默认 6 秒),超时直接跳过,不再把回复拖到几十秒。
|
|
129
|
+
模型不支持图片时会自动降级为纯文本并记住该结论,后续不再重复尝试。
|
|
130
|
+
- **输出**:单条消息,`aiMaxReplyChars`(默认 120)限制长度;推荐 `aiTemperature` 0.7~0.9。
|
|
131
|
+
- **调试**:`aiDebugPrompt` 打开后会把最终提示词写进日志,便于排查"到底看到了什么"。
|
|
132
|
+
|
|
119
133
|
|
|
120
134
|
## 数据文件
|
|
121
135
|
|
|
@@ -168,8 +182,8 @@ as Markdown files that you can read and edit directly in the Koishi console (Exp
|
|
|
168
182
|
| **Blacklist** | Stored per group (`banMember_<groupId>.md`); join requests are matched automatically and rejected |
|
|
169
183
|
| **Join review** | New requests are pushed to the group; admins use `approve` / `reject`. Pending requests are persisted and **survive restarts** |
|
|
170
184
|
| **Memory store** | `[memory]` save / list / search / delete into `Memory.md`; when enabled, AI replies retrieve and cite relevant memories |
|
|
171
|
-
| **AI replies** | Three
|
|
172
|
-
| **AI vision** | Images are downloaded and converted to data URLs before being sent to the model; handles CQ codes, HTML `<img>` and message elements, including stickers |
|
|
185
|
+
| **AI replies** | Three gates (threshold / probability / cooldown) plus a model-decided `<pass/>` opt-out. Group cards, quoted text, @ targets and the bot's own history all enter the prompt; memories are injected only when relevant; images are resolved concurrently with a time budget. Multiple personas, follow-up window, temperature and output limits |
|
|
186
|
+
| **AI vision** | Images are downloaded concurrently and converted to data URLs before being sent to the model; handles CQ codes, HTML `<img>` and message elements, including stickers. Models without vision support degrade to text automatically |
|
|
173
187
|
| **Repeat (echo)** | Echoes a message once consecutive repeats reach a threshold; repeat events feed into the AI context |
|
|
174
188
|
|
|
175
189
|
### Install
|
package/src/ai/engine.ts
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI 回复引擎。
|
|
3
|
+
*
|
|
4
|
+
* 一次「收到消息」的完整流程:
|
|
5
|
+
* record() 记录到上下文(所有消息都记,包括被管控/指令之外的人话)
|
|
6
|
+
* handle() 判定是否接话 → 组装提示词 → (可选)解析图片 → 调模型
|
|
7
|
+
* → 输出正文 / <pass/> → 发送 → 把自己的回复写回上下文
|
|
8
|
+
*
|
|
9
|
+
* 关键取舍:
|
|
10
|
+
* - 决策与生成合并为一次模型调用,避免"兴趣判定答非所问、生成又挑另一条";
|
|
11
|
+
* - 只回应当前消息,引用与回答永远一致;
|
|
12
|
+
* - 允许模型用 <pass/> 主动放弃,放弃也重置计数,避免每条消息都空转调用。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { AiState, GroupState, ChatRecord, FollowupState } from './state';
|
|
16
|
+
import { decideTrigger } from './trigger';
|
|
17
|
+
import { buildJudgePrompt, buildReplyPrompt, PASS_TOKEN } from './prompt';
|
|
18
|
+
import { ChatProvider, ChatResult } from './provider';
|
|
19
|
+
import { pickImages, resolveImages } from './vision';
|
|
20
|
+
import { selectMemoryBlocks, splitMemoryBlocks, tokenizeForMatch } from './memory';
|
|
21
|
+
import { NameResolver, MemberIdentity } from '../core/names';
|
|
22
|
+
import { renderMessage, RenderedImage, truncate } from '../core/text';
|
|
23
|
+
|
|
24
|
+
export interface AiHost {
|
|
25
|
+
config: any;
|
|
26
|
+
logger: any;
|
|
27
|
+
getOneBotApi(session: any): any;
|
|
28
|
+
toGroupId(session: any): number | null;
|
|
29
|
+
extractImages(session: any): RenderedImage[];
|
|
30
|
+
resolveImage(ref: string, session: any): Promise<string>;
|
|
31
|
+
sendReply(session: any, text: string): Promise<void>;
|
|
32
|
+
readMemoryFile(): Promise<string>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface AiDeps {
|
|
36
|
+
provider?: ChatProvider;
|
|
37
|
+
state?: AiState;
|
|
38
|
+
rng?: () => number;
|
|
39
|
+
now?: () => number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const PASS_RE = /^\s*<(?:pass\s*\/?|不回复)>/i;
|
|
43
|
+
|
|
44
|
+
function cleanReply(text: string, selfName: string): string {
|
|
45
|
+
let out = String(text || '')
|
|
46
|
+
.replace(/^\s*```[a-zA-Z0-9_-]*\s*\n?/, '')
|
|
47
|
+
.replace(/\n?\s*```\s*$/, '')
|
|
48
|
+
// 防止模型输出被平台解析成图片/CQ 码(h.text 本身不解析,这里只是保持干净)
|
|
49
|
+
.replace(/\[CQ:[^\]]+\]/gi, '')
|
|
50
|
+
.replace(/<img\b[^>]*>/gi, '')
|
|
51
|
+
.trim();
|
|
52
|
+
// 去掉模型自作主张的「自称:」前缀
|
|
53
|
+
const prefix = new RegExp(`^\\s*${selfName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*[::]\\s*`, 'i');
|
|
54
|
+
out = out.replace(prefix, '');
|
|
55
|
+
// 整句被引号包住时脱掉
|
|
56
|
+
if (/^[“"「].*[”"」]$/.test(out)) out = out.slice(1, -1).trim();
|
|
57
|
+
return out.replace(/\s+/g, ' ').trim();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function clipReply(text: string, maxChars: number): string {
|
|
61
|
+
const max = Math.max(20, maxChars || 120);
|
|
62
|
+
if (text.length <= max) return text;
|
|
63
|
+
const slice = text.slice(0, max);
|
|
64
|
+
const boundary = Math.max(
|
|
65
|
+
slice.lastIndexOf('。'),
|
|
66
|
+
slice.lastIndexOf('!'),
|
|
67
|
+
slice.lastIndexOf('?'),
|
|
68
|
+
slice.lastIndexOf(','),
|
|
69
|
+
slice.lastIndexOf(';'),
|
|
70
|
+
slice.lastIndexOf(';'),
|
|
71
|
+
);
|
|
72
|
+
if (boundary >= max * 0.5) return slice.slice(0, boundary + 1);
|
|
73
|
+
return `${slice}…`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export class AiEngine {
|
|
77
|
+
readonly state: AiState;
|
|
78
|
+
private provider: ChatProvider;
|
|
79
|
+
private names: NameResolver;
|
|
80
|
+
private rng: () => number;
|
|
81
|
+
private now: () => number;
|
|
82
|
+
private host: AiHost;
|
|
83
|
+
private config: any;
|
|
84
|
+
|
|
85
|
+
constructor(host: AiHost, deps: AiDeps = {}) {
|
|
86
|
+
this.host = host;
|
|
87
|
+
this.config = host.config;
|
|
88
|
+
this.state = deps.state ?? new AiState();
|
|
89
|
+
this.provider = deps.provider ?? new ChatProvider(host.config, host.logger);
|
|
90
|
+
this.names = new NameResolver({
|
|
91
|
+
getOneBotApi: (session) => host.getOneBotApi(session),
|
|
92
|
+
toGroupId: (session) => host.toGroupId(session),
|
|
93
|
+
logger: host.logger,
|
|
94
|
+
});
|
|
95
|
+
this.rng = deps.rng ?? Math.random;
|
|
96
|
+
this.now = deps.now ?? Date.now;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ---------------------------------------------------------------- 配置
|
|
100
|
+
|
|
101
|
+
private groupKey(session: any): string {
|
|
102
|
+
if (!session?.guildId) return '';
|
|
103
|
+
return `${session.platform ?? 'unknown'}:${session.guildId}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private ruleFor(session: any): any {
|
|
107
|
+
const guildId = String(session?.guildId ?? '');
|
|
108
|
+
const rules: any[] = Array.isArray(this.config.groupRules) ? this.config.groupRules : [];
|
|
109
|
+
return rules.find((item) => String(item?.guildId ?? '').trim() === guildId);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
resolveEnabled(session: any): boolean {
|
|
113
|
+
const rule = this.ruleFor(session);
|
|
114
|
+
const requireRule = this.config.aiReplyRequireGroupRule !== false;
|
|
115
|
+
if (requireRule && !rule) return false;
|
|
116
|
+
if (rule && typeof rule.enableAiReply === 'boolean') return rule.enableAiReply;
|
|
117
|
+
return !!this.config.enableAiReply;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private get contextWindow(): number {
|
|
121
|
+
const value = Number(this.config.aiContextWindow ?? 24);
|
|
122
|
+
return Math.max(6, Math.min(100, Number.isFinite(value) ? value : 24));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private get selfName(): string {
|
|
126
|
+
const persona = this.activePersona();
|
|
127
|
+
return String(persona?.selfName || this.config.aiAgentName || 'MeowBot').trim() || 'MeowBot';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private activePersona(): any {
|
|
131
|
+
const id = String(this.config.aiActivePersona ?? '').trim();
|
|
132
|
+
if (!id) return null;
|
|
133
|
+
const list: any[] = Array.isArray(this.config.aiPersonas) ? this.config.aiPersonas : [];
|
|
134
|
+
return list.find((item) => String(item?.id ?? '').trim() === id) ?? null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private get personaPrompt(): string {
|
|
138
|
+
const persona = this.activePersona();
|
|
139
|
+
return String(persona?.prompt || this.config.aiSystemPrompt || '').trim();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
private get maxReplyChars(): number {
|
|
143
|
+
const value = Number(this.config.aiMaxReplyChars ?? 120);
|
|
144
|
+
return Math.max(20, Math.min(500, Number.isFinite(value) ? value : 120));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private get debugPrompt(): boolean {
|
|
148
|
+
return !!this.config.aiDebugPrompt;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ---------------------------------------------------------------- 记录
|
|
152
|
+
|
|
153
|
+
/** 是否像指令(这类消息不进上下文,避免污染) */
|
|
154
|
+
private isCommandLike(text: string): boolean {
|
|
155
|
+
const value = String(text || '').trim();
|
|
156
|
+
if (!value) return false;
|
|
157
|
+
if (/^[/.!!##]/.test(value)) return true;
|
|
158
|
+
if (/^\[[^\]\s]+\]/.test(value)) return true;
|
|
159
|
+
const prefixes = [this.config.command, this.config.menuCommand, 'help']
|
|
160
|
+
.map((item: any) => String(item ?? '').trim())
|
|
161
|
+
.filter(Boolean);
|
|
162
|
+
return prefixes.some((prefix: string) => value === prefix || value.startsWith(`${prefix} `));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 记录一条群消息;返回落库后的记录(指令类返回 null) */
|
|
166
|
+
async record(session: any): Promise<ChatRecord | null> {
|
|
167
|
+
const key = this.groupKey(session);
|
|
168
|
+
if (!key || !session?.userId) return null;
|
|
169
|
+
if (String(session.userId) === String(session.bot?.selfId ?? '')) return null;
|
|
170
|
+
|
|
171
|
+
const state = this.state.get(key);
|
|
172
|
+
const messageId = String(session.messageId ?? '');
|
|
173
|
+
if (messageId) {
|
|
174
|
+
const existing = state.records.find((item) => item.id === messageId);
|
|
175
|
+
if (existing) return existing;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const contextWindow = this.contextWindow;
|
|
179
|
+
|
|
180
|
+
// 先排除指令,避免为指令解析 @ / 查群名片
|
|
181
|
+
const rawText = String(session.content ?? '').trim();
|
|
182
|
+
if (this.isCommandLike(rawText.replace(/^\s*(<at\b[^>]*\/?>|\[CQ:at,[^\]]+\])\s*/i, ''))) {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const identity: MemberIdentity = await this.names.identify(session);
|
|
187
|
+
|
|
188
|
+
const rendered = await renderMessage(session, this.names.resolverFor(session), {
|
|
189
|
+
selfId: String(session.bot?.selfId ?? session.selfId ?? ''),
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
const record: ChatRecord = {
|
|
193
|
+
id: messageId || `local-${this.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
|
194
|
+
userId: String(session.userId),
|
|
195
|
+
name: identity.name || String(session.userId),
|
|
196
|
+
role: identity.role,
|
|
197
|
+
text: rendered.text,
|
|
198
|
+
images: rendered.images,
|
|
199
|
+
quote: rendered.quote,
|
|
200
|
+
mentions: rendered.mentions,
|
|
201
|
+
atBot: rendered.atBot,
|
|
202
|
+
self: false,
|
|
203
|
+
at: Number(session.timestamp) || this.now(),
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
state.push(record, contextWindow);
|
|
207
|
+
state.counter += 1;
|
|
208
|
+
return record;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** 追加一条系统注记(复读等),不进计数、不触发 */
|
|
212
|
+
note(text: string, groupKey?: string, session?: any): void {
|
|
213
|
+
const key = groupKey || (session ? this.groupKey(session) : '');
|
|
214
|
+
if (!key || !text?.trim()) return;
|
|
215
|
+
const state = this.state.get(key);
|
|
216
|
+
state.push(
|
|
217
|
+
{
|
|
218
|
+
id: `note-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
219
|
+
userId: 'system',
|
|
220
|
+
name: '系统',
|
|
221
|
+
role: 'unknown',
|
|
222
|
+
text: String(text).trim(),
|
|
223
|
+
images: [],
|
|
224
|
+
mentions: [],
|
|
225
|
+
atBot: false,
|
|
226
|
+
self: false,
|
|
227
|
+
at: this.now(),
|
|
228
|
+
command: true,
|
|
229
|
+
},
|
|
230
|
+
this.contextWindow,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
|
|
235
|
+
recordSelf(session: any, text: string): void {
|
|
236
|
+
const key = this.groupKey(session);
|
|
237
|
+
if (!key || !text?.trim()) return;
|
|
238
|
+
const state = this.state.get(key);
|
|
239
|
+
state.push(
|
|
240
|
+
{
|
|
241
|
+
id: `self-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
242
|
+
userId: String(session.bot?.selfId ?? ''),
|
|
243
|
+
name: this.selfName,
|
|
244
|
+
role: 'unknown',
|
|
245
|
+
text: String(text).trim(),
|
|
246
|
+
images: [],
|
|
247
|
+
mentions: [],
|
|
248
|
+
atBot: false,
|
|
249
|
+
self: true,
|
|
250
|
+
at: this.now(),
|
|
251
|
+
},
|
|
252
|
+
this.contextWindow,
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// ---------------------------------------------------------------- 点名 / 跟随
|
|
257
|
+
|
|
258
|
+
private isMention(session: any, record: ChatRecord): boolean {
|
|
259
|
+
// 渲染阶段已经确认 @ 了 bot,不依赖 session.content 的序列化格式
|
|
260
|
+
if (record.atBot) return true;
|
|
261
|
+
const selfId = String(session?.bot?.selfId ?? session?.selfId ?? '');
|
|
262
|
+
if (selfId) {
|
|
263
|
+
const content = String(session?.content ?? '');
|
|
264
|
+
if (content.includes(`<at id="${selfId}"`)) return true;
|
|
265
|
+
const escaped = selfId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
266
|
+
if (new RegExp(`\\[CQ:at,[^\\]]*(?:qq|id)=${escaped}(?:,|\\])`, 'i').test(content)) return true;
|
|
267
|
+
}
|
|
268
|
+
// 只叫名字(不带 @)是否算点名,交给 aiEnableDirectMentionTrigger 控制
|
|
269
|
+
if (this.config.aiEnableDirectMentionTrigger === false) return false;
|
|
270
|
+
const name = this.selfName.toLowerCase();
|
|
271
|
+
if (!name) return false;
|
|
272
|
+
return String(record.text || '').toLowerCase().includes(name);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private addressesOthers(record: ChatRecord, session: any): boolean {
|
|
276
|
+
const selfId = String(session?.bot?.selfId ?? '');
|
|
277
|
+
return record.mentions.length > 0 && !record.mentions.includes(selfId);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
private shouldContinueFollowup(record: ChatRecord, followup: FollowupState): boolean {
|
|
281
|
+
const text = String(record.text || '').trim();
|
|
282
|
+
if (!text) return false;
|
|
283
|
+
if (this.isCommandLike(text)) return false;
|
|
284
|
+
if (/^[/.!!##]/.test(text)) return false;
|
|
285
|
+
if (text.length <= 2) return false;
|
|
286
|
+
if (/^[\u{1F300}-\u{1FAFF}\s~~!!.。]+$/u.test(text)) return false;
|
|
287
|
+
if (/(换个话题|换个问题|另外|题外话|不聊这个|先不说这个|说点别的|再问个新的)/.test(text)) return false;
|
|
288
|
+
|
|
289
|
+
const current = tokenizeForMatch(text);
|
|
290
|
+
const overlap = [...current].filter((token) => followup.anchorTokens.includes(token)).length;
|
|
291
|
+
const ratio = overlap / Math.max(1, Math.min(current.size || 1, followup.anchorTokens.length || 1));
|
|
292
|
+
if (text.length >= 8 && overlap === 0 && !/[??]/.test(text)) return false;
|
|
293
|
+
if (text.length >= 8 && ratio <= 0.12 && /[??]/.test(text)) return false;
|
|
294
|
+
|
|
295
|
+
if (/[??]/.test(text)) return true;
|
|
296
|
+
if (/(继续|然后|那|所以|为什么|怎么|如何|帮我|还能|可以吗|行吗|对不对|是不是)/.test(text)) return true;
|
|
297
|
+
return text.length >= 6;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private startFollowup(state: GroupState, record: ChatRecord): void {
|
|
301
|
+
if (this.config.aiEnableFollowupAfterMention === false) return;
|
|
302
|
+
const seconds = Math.max(1, Number(this.config.aiFollowupWindowSeconds ?? 120));
|
|
303
|
+
state.followup = {
|
|
304
|
+
userId: record.userId,
|
|
305
|
+
expiresAt: this.now() + seconds * 1000,
|
|
306
|
+
turns: 0,
|
|
307
|
+
anchorTokens: [...tokenizeForMatch(record.text)],
|
|
308
|
+
lastText: record.text,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
private bumpFollowup(state: GroupState, record: ChatRecord): void {
|
|
313
|
+
const followup = state.followup;
|
|
314
|
+
if (!followup) return;
|
|
315
|
+
followup.turns += 1;
|
|
316
|
+
followup.lastText = record.text;
|
|
317
|
+
const seconds = Math.max(1, Number(this.config.aiFollowupWindowSeconds ?? 120));
|
|
318
|
+
followup.expiresAt = this.now() + seconds * 1000;
|
|
319
|
+
const maxTurns = Math.max(1, Number(this.config.aiFollowupMaxTurns ?? 3));
|
|
320
|
+
if (followup.turns >= maxTurns) state.followup = null;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
private getFollowup(state: GroupState, record: ChatRecord, session: any): FollowupState | null {
|
|
324
|
+
const followup = state.followup;
|
|
325
|
+
if (!followup) return null;
|
|
326
|
+
if (this.now() > followup.expiresAt) {
|
|
327
|
+
state.followup = null;
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
if (followup.userId !== record.userId) return null;
|
|
331
|
+
if (this.addressesOthers(record, session)) {
|
|
332
|
+
state.followup = null;
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
return followup;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// ---------------------------------------------------------------- 记忆
|
|
339
|
+
|
|
340
|
+
private async loadMemories(record: ChatRecord, state: GroupState): Promise<string[]> {
|
|
341
|
+
if (!this.config.enableMemory || this.config.memoryInAi === false) return [];
|
|
342
|
+
let content = '';
|
|
343
|
+
try {
|
|
344
|
+
content = await this.host.readMemoryFile();
|
|
345
|
+
} catch {
|
|
346
|
+
return [];
|
|
347
|
+
}
|
|
348
|
+
const blocks = splitMemoryBlocks(content);
|
|
349
|
+
if (!blocks.length) return [];
|
|
350
|
+
const recent = state.records.slice(-3).map((item) => item.text);
|
|
351
|
+
const selected = selectMemoryBlocks(blocks, [record.text, ...recent], {
|
|
352
|
+
limit: 3,
|
|
353
|
+
minScore: 0.12,
|
|
354
|
+
maxChars: 160,
|
|
355
|
+
});
|
|
356
|
+
return selected.map((item) => item.text);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// ---------------------------------------------------------------- 主流程
|
|
360
|
+
|
|
361
|
+
async handle(session: any): Promise<void> {
|
|
362
|
+
const key = this.groupKey(session);
|
|
363
|
+
if (!key) return;
|
|
364
|
+
if (!this.resolveEnabled(session)) return;
|
|
365
|
+
if (String(session.userId) === String(session.bot?.selfId ?? '')) return;
|
|
366
|
+
if (session.platform && !this.platformAllowed(session.platform)) return;
|
|
367
|
+
|
|
368
|
+
const state = this.state.get(key);
|
|
369
|
+
const messageId = String(session.messageId ?? '');
|
|
370
|
+
if (messageId && state.isDuplicate(`${session.platform}:${session.guildId}:${session.userId}:${messageId}`, this.now())) {
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
let record = messageId ? state.records.find((item) => item.id === messageId) : undefined;
|
|
375
|
+
if (!record) record = (await this.record(session)) ?? undefined;
|
|
376
|
+
if (!record) return;
|
|
377
|
+
|
|
378
|
+
const mention = this.isMention(session, record);
|
|
379
|
+
const followupState = mention ? null : this.getFollowup(state, record, session);
|
|
380
|
+
const followup = !!followupState && this.shouldContinueFollowup(record, followupState);
|
|
381
|
+
|
|
382
|
+
const threshold = Math.max(1, Number(this.config.aiMessageThreshold ?? 15));
|
|
383
|
+
const decision = decideTrigger({
|
|
384
|
+
mode: (this.config.aiReplyMode || 'hybrid') as any,
|
|
385
|
+
counter: state.counter,
|
|
386
|
+
threshold,
|
|
387
|
+
probability: Number(this.config.aiRandomReplyProbability ?? 0.08),
|
|
388
|
+
now: this.now(),
|
|
389
|
+
lastAttemptAt: state.lastAttemptAt,
|
|
390
|
+
minIntervalMs: Math.max(0, Number(this.config.aiMinReplyIntervalSeconds ?? 45)) * 1000,
|
|
391
|
+
inFlight: state.inFlight,
|
|
392
|
+
mention,
|
|
393
|
+
followup,
|
|
394
|
+
rng: this.rng,
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
this.log('ai-trigger', {
|
|
398
|
+
fire: decision.fire,
|
|
399
|
+
reason: decision.reason,
|
|
400
|
+
counter: state.counter,
|
|
401
|
+
threshold,
|
|
402
|
+
mention,
|
|
403
|
+
followup,
|
|
404
|
+
ctx: state.records.length,
|
|
405
|
+
}, session);
|
|
406
|
+
if (!decision.fire) return;
|
|
407
|
+
|
|
408
|
+
state.inFlight = true;
|
|
409
|
+
state.lastAttemptAt = this.now();
|
|
410
|
+
const startedAt = this.now();
|
|
411
|
+
|
|
412
|
+
try {
|
|
413
|
+
const allowPass = !mention && !followup;
|
|
414
|
+
const memories = await this.loadMemories(record, state);
|
|
415
|
+
const promptInput = {
|
|
416
|
+
selfName: this.selfName,
|
|
417
|
+
persona: this.personaPrompt,
|
|
418
|
+
groupId: String(session.guildId),
|
|
419
|
+
records: state.records,
|
|
420
|
+
current: record,
|
|
421
|
+
mention,
|
|
422
|
+
followup,
|
|
423
|
+
allowPass,
|
|
424
|
+
memories,
|
|
425
|
+
maxReplyChars: this.maxReplyChars,
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
if (allowPass && this.config.aiReplyDecision === 'two-stage') {
|
|
429
|
+
const judge = await this.judge(promptInput);
|
|
430
|
+
if (!judge) {
|
|
431
|
+
state.counter = 0;
|
|
432
|
+
this.log('ai-pass', { by: 'judge', latencyMs: this.now() - startedAt }, session);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const prompt = buildReplyPrompt(promptInput);
|
|
438
|
+
if (this.debugPrompt) {
|
|
439
|
+
this.host.logger.info(`[ai-debug] system=${prompt.system}\n[ai-debug] user=${prompt.user}`);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const images = await this.collectImages(session, record);
|
|
443
|
+
const result = await this.provider.chat({
|
|
444
|
+
system: prompt.system,
|
|
445
|
+
user: prompt.user,
|
|
446
|
+
images,
|
|
447
|
+
temperature: Number(this.config.aiTemperature ?? 0.8),
|
|
448
|
+
maxTokens: Number(this.config.aiMaxOutputTokens ?? 400),
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
if (!result.ok) {
|
|
452
|
+
this.log('ai-reply', {
|
|
453
|
+
ok: false,
|
|
454
|
+
error: result.error,
|
|
455
|
+
trigger: decision.reason,
|
|
456
|
+
latencyMs: this.now() - startedAt,
|
|
457
|
+
}, session);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const raw = String(result.text || '').trim();
|
|
462
|
+
if (!raw || PASS_RE.test(raw)) {
|
|
463
|
+
state.counter = 0;
|
|
464
|
+
this.log('ai-pass', {
|
|
465
|
+
by: 'model',
|
|
466
|
+
trigger: decision.reason,
|
|
467
|
+
latencyMs: this.now() - startedAt,
|
|
468
|
+
}, session);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const cleaned = clipReply(cleanReply(raw, this.selfName), this.maxReplyChars);
|
|
473
|
+
if (!cleaned) {
|
|
474
|
+
state.counter = 0;
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
await this.host.sendReply(session, cleaned);
|
|
479
|
+
state.lastReplyAt = this.now();
|
|
480
|
+
state.counter = 0;
|
|
481
|
+
this.recordSelf(session, cleaned);
|
|
482
|
+
|
|
483
|
+
if (mention) this.startFollowup(state, record);
|
|
484
|
+
else if (followup && state.followup) this.bumpFollowup(state, record);
|
|
485
|
+
|
|
486
|
+
this.log('ai-reply', {
|
|
487
|
+
ok: true,
|
|
488
|
+
trigger: decision.reason,
|
|
489
|
+
latencyMs: this.now() - startedAt,
|
|
490
|
+
images: images.length,
|
|
491
|
+
degradedToText: !!result.degradedToText,
|
|
492
|
+
chars: cleaned.length,
|
|
493
|
+
preview: cleaned.slice(0, 60),
|
|
494
|
+
}, session);
|
|
495
|
+
} catch (error: any) {
|
|
496
|
+
this.log('ai-reply', {
|
|
497
|
+
ok: false,
|
|
498
|
+
error: String(error?.message || error),
|
|
499
|
+
trigger: decision.reason,
|
|
500
|
+
}, session);
|
|
501
|
+
} finally {
|
|
502
|
+
state.inFlight = false;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
private async collectImages(session: any, record: ChatRecord): Promise<string[]> {
|
|
507
|
+
if (this.config.aiEnableImageRecognition === false) return [];
|
|
508
|
+
const maxCount = Math.max(0, Number(this.config.aiImageMaxCount ?? 2));
|
|
509
|
+
if (!maxCount) return [];
|
|
510
|
+
|
|
511
|
+
const own = record.images.length ? record.images : this.host.extractImages(session);
|
|
512
|
+
const quoted = record.quote ? this.host.extractImages(session?.quote) : [];
|
|
513
|
+
const items = pickImages(own, quoted, maxCount);
|
|
514
|
+
if (!items.length) return [];
|
|
515
|
+
|
|
516
|
+
return resolveImages(
|
|
517
|
+
items,
|
|
518
|
+
(ref) => this.host.resolveImage(ref, session),
|
|
519
|
+
{ maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) },
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
private async judge(input: any): Promise<boolean> {
|
|
524
|
+
const prompt = buildJudgePrompt(input);
|
|
525
|
+
const result: ChatResult = await this.provider.chat({
|
|
526
|
+
system: prompt.system,
|
|
527
|
+
user: prompt.user,
|
|
528
|
+
temperature: 0.1,
|
|
529
|
+
maxTokens: 256,
|
|
530
|
+
});
|
|
531
|
+
if (!result.ok || !result.text) return false;
|
|
532
|
+
const match = result.text.match(/\{[\s\S]*\}/);
|
|
533
|
+
if (!match) return false;
|
|
534
|
+
try {
|
|
535
|
+
const parsed = JSON.parse(match[0]);
|
|
536
|
+
const score = Number(parsed?.score) || 0;
|
|
537
|
+
const min = Number(this.config.aiInterestMinScore ?? 60);
|
|
538
|
+
return !!parsed?.reply && score >= min;
|
|
539
|
+
} catch {
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
private platformAllowed(platform: string): boolean {
|
|
545
|
+
const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
|
|
546
|
+
return list.includes(platform);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
private log(event: string, data: Record<string, any>, session: any): void {
|
|
550
|
+
const extra = Object.entries(data)
|
|
551
|
+
.filter(([, value]) => value !== undefined)
|
|
552
|
+
.map(([key, value]) => `${key}=${typeof value === 'string' ? JSON.stringify(value) : value}`)
|
|
553
|
+
.join(' ');
|
|
554
|
+
this.host.logger.info(
|
|
555
|
+
`[${event}] ${extra} | platform=${session?.platform ?? '?'} user=${session?.userId ?? '?'} guild=${session?.guildId ?? '?'}`,
|
|
556
|
+
);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** 供指令/调试使用 */
|
|
560
|
+
displayNameFor(session: any, qq: string): Promise<string> {
|
|
561
|
+
return this.names.display(session, qq);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
clear(): void {
|
|
565
|
+
this.state.clear();
|
|
566
|
+
this.names.clear();
|
|
567
|
+
}
|
|
568
|
+
}
|