@nestim/koishi-plugin-qq-group-manager 1.4.14 → 1.5.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 +37 -0
- package/lib/ai/engine.d.ts +18 -2
- package/lib/ai/engine.js +178 -13
- package/lib/ai/hooks.d.ts +18 -3
- package/lib/ai/hooks.js +2 -2
- package/lib/ai/sdk.d.ts +62 -0
- package/lib/ai/sdk.js +225 -0
- package/lib/service.d.ts +2 -0
- package/lib/service.js +23 -0
- package/package.json +1 -1
- package/readme.md +31 -24
- package/src/ai/engine.ts +181 -13
- package/src/ai/hooks.ts +19 -3
- package/src/ai/sdk.ts +215 -0
- package/src/service.js +23 -0
package/lib/ai/sdk.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.QqgmSdkFacade = exports.QqgmStorage = exports.NamespacedStorage = exports.QqgmEventBus = void 0;
|
|
27
|
+
exports.getSharedEventBus = getSharedEventBus;
|
|
28
|
+
exports.getSdkFacade = getSdkFacade;
|
|
29
|
+
/**
|
|
30
|
+
* qqgm SDK v1(方案 A:运行时在主插件里,包/类型可独立)。
|
|
31
|
+
*
|
|
32
|
+
* 目标:以后表情、监控、风格、私聊等附属插件只依赖这个稳定契约,
|
|
33
|
+
* 不再需要改主插件。旧扩展点(qqgmAiHooks / qqgmAiRuntime)全部保留。
|
|
34
|
+
*
|
|
35
|
+
* 对外:
|
|
36
|
+
* ctx.root.get('qqgmSdk')
|
|
37
|
+
* .hooks 提示词/过滤器/afterReply/人设/上下文挤出
|
|
38
|
+
* .events 强类型事件总线(进程级稳定)
|
|
39
|
+
* .storage 命名空间 KV(data/qqgm-sdk/<namespace>.json)
|
|
40
|
+
* .telemetry { emit(event, payload) }
|
|
41
|
+
* .config 主插件配置(只读)
|
|
42
|
+
* .logger
|
|
43
|
+
*/
|
|
44
|
+
const fs = __importStar(require("node:fs"));
|
|
45
|
+
const path = __importStar(require("node:path"));
|
|
46
|
+
const EVENT_BUS_KEY = Symbol.for('qqgm.sdk.events');
|
|
47
|
+
const SDK_KEY = Symbol.for('qqgm.sdk');
|
|
48
|
+
/** 进程级事件总线:主插件重载后监听器不丢。 */
|
|
49
|
+
class QqgmEventBus {
|
|
50
|
+
handlers = new Map();
|
|
51
|
+
logger;
|
|
52
|
+
setLogger(logger) {
|
|
53
|
+
if (logger)
|
|
54
|
+
this.logger = logger;
|
|
55
|
+
}
|
|
56
|
+
on(event, handler) {
|
|
57
|
+
if (!event || typeof handler !== 'function')
|
|
58
|
+
return () => { };
|
|
59
|
+
let set = this.handlers.get(event);
|
|
60
|
+
if (!set) {
|
|
61
|
+
set = new Set();
|
|
62
|
+
this.handlers.set(event, set);
|
|
63
|
+
}
|
|
64
|
+
set.add(handler);
|
|
65
|
+
return () => this.off(event, handler);
|
|
66
|
+
}
|
|
67
|
+
off(event, handler) {
|
|
68
|
+
const set = this.handlers.get(event);
|
|
69
|
+
if (!set)
|
|
70
|
+
return;
|
|
71
|
+
set.delete(handler);
|
|
72
|
+
if (!set.size)
|
|
73
|
+
this.handlers.delete(event);
|
|
74
|
+
}
|
|
75
|
+
emit(event, payload = {}) {
|
|
76
|
+
const set = this.handlers.get(event);
|
|
77
|
+
if (!set || !set.size)
|
|
78
|
+
return;
|
|
79
|
+
for (const handler of [...set]) {
|
|
80
|
+
try {
|
|
81
|
+
handler(payload);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
this.logger?.warn?.(`[sdk:events] ${event} 处理失败: ${String(error)}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
count(event) {
|
|
89
|
+
if (event)
|
|
90
|
+
return this.handlers.get(event)?.size || 0;
|
|
91
|
+
let total = 0;
|
|
92
|
+
for (const set of this.handlers.values())
|
|
93
|
+
total += set.size;
|
|
94
|
+
return total;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
exports.QqgmEventBus = QqgmEventBus;
|
|
98
|
+
function getSharedEventBus() {
|
|
99
|
+
const store = globalThis;
|
|
100
|
+
if (!store[EVENT_BUS_KEY])
|
|
101
|
+
store[EVENT_BUS_KEY] = new QqgmEventBus();
|
|
102
|
+
return store[EVENT_BUS_KEY];
|
|
103
|
+
}
|
|
104
|
+
function safeName(name) {
|
|
105
|
+
return String(name || '')
|
|
106
|
+
.split(/[\\/]+/)
|
|
107
|
+
.map((part) => part.replace(/[^\w.-]+/g, '_').replace(/^\.+/, ''))
|
|
108
|
+
.filter(Boolean)
|
|
109
|
+
.join('/');
|
|
110
|
+
}
|
|
111
|
+
/** 单个命名空间的 JSON KV;同步写,适合低频配置/状态。 */
|
|
112
|
+
class NamespacedStorage {
|
|
113
|
+
file;
|
|
114
|
+
data = null;
|
|
115
|
+
constructor(file) {
|
|
116
|
+
this.file = file;
|
|
117
|
+
}
|
|
118
|
+
load() {
|
|
119
|
+
if (this.data)
|
|
120
|
+
return this.data;
|
|
121
|
+
try {
|
|
122
|
+
this.data = JSON.parse(fs.readFileSync(this.file, 'utf8'));
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
this.data = {};
|
|
126
|
+
}
|
|
127
|
+
return this.data;
|
|
128
|
+
}
|
|
129
|
+
flush() {
|
|
130
|
+
try {
|
|
131
|
+
fs.mkdirSync(path.dirname(this.file), { recursive: true });
|
|
132
|
+
const tmp = `${this.file}.tmp`;
|
|
133
|
+
fs.writeFileSync(tmp, JSON.stringify(this.data || {}, null, 2), 'utf8');
|
|
134
|
+
fs.renameSync(tmp, this.file);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
/* 存储失败不能影响主流程 */
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
get(key, fallback) {
|
|
141
|
+
const data = this.load();
|
|
142
|
+
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : fallback;
|
|
143
|
+
}
|
|
144
|
+
set(key, value) {
|
|
145
|
+
const data = this.load();
|
|
146
|
+
data[key] = value;
|
|
147
|
+
this.flush();
|
|
148
|
+
}
|
|
149
|
+
delete(key) {
|
|
150
|
+
const data = this.load();
|
|
151
|
+
delete data[key];
|
|
152
|
+
this.flush();
|
|
153
|
+
}
|
|
154
|
+
all() {
|
|
155
|
+
return { ...this.load() };
|
|
156
|
+
}
|
|
157
|
+
clear() {
|
|
158
|
+
this.data = {};
|
|
159
|
+
this.flush();
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
exports.NamespacedStorage = NamespacedStorage;
|
|
163
|
+
class QqgmStorage {
|
|
164
|
+
baseDir;
|
|
165
|
+
cache = new Map();
|
|
166
|
+
constructor(baseDir) {
|
|
167
|
+
this.baseDir = baseDir;
|
|
168
|
+
}
|
|
169
|
+
namespace(name) {
|
|
170
|
+
const key = safeName(name) || 'default';
|
|
171
|
+
let item = this.cache.get(key);
|
|
172
|
+
if (!item) {
|
|
173
|
+
item = new NamespacedStorage(path.join(this.baseDir, 'data', 'qqgm-sdk', `${key}.json`));
|
|
174
|
+
this.cache.set(key, item);
|
|
175
|
+
}
|
|
176
|
+
return item;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
exports.QqgmStorage = QqgmStorage;
|
|
180
|
+
/**
|
|
181
|
+
* 进程级门面:外部插件拿到的始终是同一个对象,主插件重载只换 current。
|
|
182
|
+
*/
|
|
183
|
+
class QqgmSdkFacade {
|
|
184
|
+
version = '1.0.0';
|
|
185
|
+
events = getSharedEventBus();
|
|
186
|
+
current = null;
|
|
187
|
+
storageCache = null;
|
|
188
|
+
telemetry = {
|
|
189
|
+
emit: (event, payload = {}) => this.events.emit(event, payload),
|
|
190
|
+
};
|
|
191
|
+
bind(service) {
|
|
192
|
+
this.current = service;
|
|
193
|
+
this.events.setLogger(service?._logger);
|
|
194
|
+
}
|
|
195
|
+
unbind(service) {
|
|
196
|
+
if (this.current === service)
|
|
197
|
+
this.current = null;
|
|
198
|
+
}
|
|
199
|
+
get hooks() {
|
|
200
|
+
return this.current?.ai?.hooks || null;
|
|
201
|
+
}
|
|
202
|
+
get config() {
|
|
203
|
+
return this.current?.config || {};
|
|
204
|
+
}
|
|
205
|
+
get logger() {
|
|
206
|
+
return this.current?._logger || console;
|
|
207
|
+
}
|
|
208
|
+
get storage() {
|
|
209
|
+
const base = String(this.current?.ctx?.baseDir || process.cwd());
|
|
210
|
+
if (!this.storageCache || this.storageCache.base !== base) {
|
|
211
|
+
this.storageCache = { base, storage: new QqgmStorage(base) };
|
|
212
|
+
}
|
|
213
|
+
return this.storageCache.storage;
|
|
214
|
+
}
|
|
215
|
+
emit(event, payload = {}) {
|
|
216
|
+
this.events.emit(event, payload);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
exports.QqgmSdkFacade = QqgmSdkFacade;
|
|
220
|
+
function getSdkFacade() {
|
|
221
|
+
const store = globalThis;
|
|
222
|
+
if (!store[SDK_KEY])
|
|
223
|
+
store[SDK_KEY] = new QqgmSdkFacade();
|
|
224
|
+
return store[SDK_KEY];
|
|
225
|
+
}
|
package/lib/service.d.ts
CHANGED
|
@@ -116,6 +116,8 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
|
|
|
116
116
|
*/
|
|
117
117
|
handleMemberAdded(session: any): Promise<void>;
|
|
118
118
|
ai: AiEngine;
|
|
119
|
+
sdk: import("./ai/sdk").QqgmSdkFacade;
|
|
120
|
+
events: import("./ai/sdk").QqgmEventBus;
|
|
119
121
|
/** 外部插件扩展点:提示词风格段 + 输出过滤(接口版本见 AiHookRegistry.version) */
|
|
120
122
|
get aiHooks(): import("./ai/hooks").AiHookRegistry;
|
|
121
123
|
reminderFilePath(): any;
|
package/lib/service.js
CHANGED
|
@@ -10,6 +10,7 @@ const node_fs_1 = __importDefault(require("node:fs"));
|
|
|
10
10
|
const { AiEngine } = require("./ai/engine");
|
|
11
11
|
const { getSharedAiHooks } = require("./ai/hooks");
|
|
12
12
|
const { getAiRuntimeFacade } = require("./ai/runtime");
|
|
13
|
+
const { getSdkFacade } = require("./ai/sdk");
|
|
13
14
|
let PLUGIN_VERSION = 'unknown';
|
|
14
15
|
try {
|
|
15
16
|
PLUGIN_VERSION = require('../package.json').version || 'unknown';
|
|
@@ -297,10 +298,17 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
297
298
|
const hooks = sharedHooks;
|
|
298
299
|
const facade = getAiRuntimeFacade();
|
|
299
300
|
facade.bind(this);
|
|
301
|
+
const sdk = getSdkFacade();
|
|
302
|
+
this.sdk = sdk;
|
|
303
|
+
this.events = sdk.events;
|
|
304
|
+
sdk.bind(this);
|
|
300
305
|
ctx.root.set('qqgmAiHooks', hooks);
|
|
301
306
|
ctx.root.set('qqgmAiRuntime', facade);
|
|
307
|
+
ctx.root.set('qqgmSdk', sdk);
|
|
308
|
+
this._logger.info(`[sdk] v${sdk.version} 已挂载(events / storage / telemetry / hooks v${hooks.version})`);
|
|
302
309
|
ctx.on('dispose', () => {
|
|
303
310
|
try {
|
|
311
|
+
sdk.unbind(this);
|
|
304
312
|
facade.unbind(this);
|
|
305
313
|
// 只有当前没有新实例接管时才撤掉对外暴露:旧实例的 dispose
|
|
306
314
|
// 可能晚于新实例的 bind,此时不能把新指针清掉。
|
|
@@ -558,6 +566,10 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
558
566
|
if (!text)
|
|
559
567
|
return;
|
|
560
568
|
await this.sendGroupText(groupId, text);
|
|
569
|
+
try {
|
|
570
|
+
this.ai.recordSelfText(groupId, text);
|
|
571
|
+
}
|
|
572
|
+
catch { /* ignore */ }
|
|
561
573
|
this._lastIdleTopicAt.set(groupId, Date.now());
|
|
562
574
|
this._logger.info(`[idle] topic sent group=${groupId} chars=${text.length}`);
|
|
563
575
|
}
|
|
@@ -923,6 +935,17 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
923
935
|
kept.splice(insertAt, 0, block);
|
|
924
936
|
const next = kept.length ? `${kept.join('\n\n---\n\n')}\n` : `${block}\n`;
|
|
925
937
|
await this.writeMemoryFile(next, scope);
|
|
938
|
+
try {
|
|
939
|
+
this.events?.emit?.('memory.committed', {
|
|
940
|
+
scopeKind: scope && scope.kind,
|
|
941
|
+
scopeId: scope && scope.id,
|
|
942
|
+
category: category || '其他',
|
|
943
|
+
chars: add.length,
|
|
944
|
+
removed: remove.size,
|
|
945
|
+
at: Date.now(),
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
catch { /* ignore */ }
|
|
926
949
|
return block;
|
|
927
950
|
});
|
|
928
951
|
}
|
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.5.1",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"typings": "lib/index.d.ts",
|
|
7
7
|
"files": [
|
package/readme.md
CHANGED
|
@@ -228,39 +228,46 @@ npm i @nestim/koishi-plugin-qq-group-manager
|
|
|
228
228
|
- `aiIdleTopicWebSearch` 开启时(默认开),用最近一句做 query 搜一次;没有上下文就搜当天热点,
|
|
229
229
|
结果不相关会自动忽略,搜不到也不影响发话题。
|
|
230
230
|
|
|
231
|
-
##
|
|
231
|
+
## 外部插件接口:SDK v1(1.5.0+)
|
|
232
232
|
|
|
233
|
-
|
|
234
|
-
不需要修改主插件源码:
|
|
233
|
+
主插件从 1.5.0 起在 `ctx.root` 挂一个进程级稳定的 SDK 门面,附属插件不用再碰主插件内部:
|
|
235
234
|
|
|
236
235
|
```ts
|
|
237
|
-
|
|
236
|
+
const sdk = ctx.root.get('qqgmSdk')
|
|
237
|
+
if (!sdk) return
|
|
238
238
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
239
|
+
// 1) 旧钩子全部保留(v3 方法一个没删)
|
|
240
|
+
const off1 = sdk.hooks.registerPromptSection(() => '说话短一点,别用“首先/其次”这类词')
|
|
241
|
+
const off2 = sdk.hooks.registerOutputFilter((text) => text.replace(/首先/g, ''))
|
|
242
242
|
|
|
243
|
-
|
|
244
|
-
|
|
243
|
+
// 2) 新事件:成功/失败/重试都进统计
|
|
244
|
+
const off3 = sdk.events.on('ai.request.end', (call) => {
|
|
245
|
+
console.log(call.kind, call.modelMs, call.status, call.usage)
|
|
246
|
+
})
|
|
245
247
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
+
// 3) 命名空间存储(data/qqgm-sdk/<namespace>.json)
|
|
249
|
+
const store = sdk.storage.namespace('my-plugin')
|
|
250
|
+
store.set('last', Date.now())
|
|
248
251
|
|
|
249
|
-
|
|
250
|
-
const off3 = hooks.registerPersonaOverride((ctx) => (ctx.groupId === '123456' ? '你是本群专属的猫娘' : null))
|
|
251
|
-
|
|
252
|
-
ctx.on('dispose', () => {
|
|
253
|
-
off1()
|
|
254
|
-
off2()
|
|
255
|
-
off3()
|
|
256
|
-
})
|
|
257
|
-
}
|
|
252
|
+
ctx.on('dispose', () => { off1(); off2(); off3() })
|
|
258
253
|
```
|
|
259
254
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
255
|
+
可用事件:
|
|
256
|
+
|
|
257
|
+
| 事件 | 关键字段 |
|
|
258
|
+
| --- | --- |
|
|
259
|
+
| `message.received` | `traceId, groupId, userId, messageId, at` |
|
|
260
|
+
| `ai.request.start` | `traceId, kind, groupId, model, at` |
|
|
261
|
+
| `ai.request.end` | `traceId, kind, modelMs, usage, finishReason, status, errorKind, retries` |
|
|
262
|
+
| `ai.reply.rendered` | `traceId, chars, renderedMs` |
|
|
263
|
+
| `ai.reply.sent` | `traceId, ok, sendMs, e2eMs` |
|
|
264
|
+
| `memory.committed` | `scopeKind, scopeId, category, chars, removed` |
|
|
265
|
+
|
|
266
|
+
- `kind`:`reply` / `idle` / `private` / `memory`。
|
|
267
|
+
- 失败调用也会发 `ai.request.end`,`status=error`,`errorKind=auth|rate_limit|http_4xx|http_5xx|timeout|empty|exception`。
|
|
268
|
+
- `sdk.hooks.version` 为 `4`:`>=2` contextEvicted,`>=3` personaOverride,`>=4` 当前消息/最近上下文。
|
|
269
|
+
- 提示词 provider 会收到 `ctx.current`(当前消息)与 `ctx.recent`(最近 12 条),不用再解析 `session.content`。
|
|
270
|
+
- 旧写法 `ctx.root.get('qqgmAiHooks')` / `ctx.root.get('qqgmAiRuntime')` 继续有效;`@nestim/qqgm-sdk` 类型包是可选的,不装也能跑 JS 插件。
|
|
264
271
|
|
|
265
272
|
|
|
266
273
|
## 数据文件
|
package/src/ai/engine.ts
CHANGED
|
@@ -47,6 +47,10 @@ import {
|
|
|
47
47
|
export interface AiHost {
|
|
48
48
|
config: any;
|
|
49
49
|
logger: any;
|
|
50
|
+
/** SDK v1 门面(主插件注入;测试中可为空) */
|
|
51
|
+
sdk?: any;
|
|
52
|
+
/** 进程级事件总线(等价于 sdk.events) */
|
|
53
|
+
events?: any;
|
|
50
54
|
getOneBotApi(session: any): any;
|
|
51
55
|
toGroupId(session: any): number | null;
|
|
52
56
|
extractImages(session: any): RenderedImage[];
|
|
@@ -60,6 +64,7 @@ export interface AiHost {
|
|
|
60
64
|
add: string;
|
|
61
65
|
remove?: string[];
|
|
62
66
|
label?: string;
|
|
67
|
+
category?: string;
|
|
63
68
|
}): Promise<void>;
|
|
64
69
|
readMemoryFile(scope?: { kind: 'group' | 'private'; id: string } | null): Promise<string>;
|
|
65
70
|
}
|
|
@@ -154,6 +159,22 @@ function formatNowText(date: Date): string {
|
|
|
154
159
|
return `${formatted}(${seasonOfMonth(month)})`;
|
|
155
160
|
}
|
|
156
161
|
|
|
162
|
+
function newTraceId(): string {
|
|
163
|
+
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function classifyModelFailure(result: any): string {
|
|
167
|
+
const status = Number(result?.status || 0);
|
|
168
|
+
if (status === 401 || status === 403) return 'auth';
|
|
169
|
+
if (status === 429) return 'rate_limit';
|
|
170
|
+
if (status >= 500) return 'http_5xx';
|
|
171
|
+
if (status >= 400) return 'http_4xx';
|
|
172
|
+
const error = String(result?.error || '');
|
|
173
|
+
if (/timeout|timed out|abort/i.test(error)) return 'timeout';
|
|
174
|
+
if (/empty|空内容|no content/i.test(error)) return 'empty';
|
|
175
|
+
return 'error';
|
|
176
|
+
}
|
|
177
|
+
|
|
157
178
|
export class AiEngine {
|
|
158
179
|
readonly state: AiState;
|
|
159
180
|
/** 外部插件扩展点:提示词风格段 + 输出过滤 */
|
|
@@ -588,13 +609,13 @@ export class AiEngine {
|
|
|
588
609
|
}
|
|
589
610
|
|
|
590
611
|
/** 机器人自己发出的消息:写回上下文,解决"说完就忘" */
|
|
591
|
-
recordSelf(session: any, text: string): void {
|
|
612
|
+
recordSelf(session: any, text: string, id?: string): void {
|
|
592
613
|
const key = this.groupKey(session);
|
|
593
614
|
if (!key || !text?.trim()) return;
|
|
594
615
|
const state = this.state.get(key);
|
|
595
616
|
const evicted = state.push(
|
|
596
617
|
{
|
|
597
|
-
id: `self-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
618
|
+
id: id || `self-${this.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
598
619
|
userId: String(session.bot?.selfId ?? ''),
|
|
599
620
|
name: this.selfName,
|
|
600
621
|
role: 'unknown',
|
|
@@ -611,6 +632,25 @@ export class AiEngine {
|
|
|
611
632
|
this.schedulePersist();
|
|
612
633
|
}
|
|
613
634
|
|
|
635
|
+
/** 主动话题等非 handle 路径发消息后,补一条自身发言到上下文 */
|
|
636
|
+
recordSelfText(groupId: string, text: string): void {
|
|
637
|
+
const bot = this.findBot();
|
|
638
|
+
this.recordSelf({
|
|
639
|
+
guildId: String(groupId),
|
|
640
|
+
platform: 'onebot',
|
|
641
|
+
bot: { selfId: bot?.selfId },
|
|
642
|
+
}, text);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** 发送失败时撤回预先写入的自身发言,避免上下文出现没发出去的话 */
|
|
646
|
+
private removeSelfRecord(session: any, id: string): void {
|
|
647
|
+
const key = this.groupKey(session);
|
|
648
|
+
const state = key ? this.state.peek(key) : undefined;
|
|
649
|
+
if (!state) return;
|
|
650
|
+
state.records = state.records.filter((record) => record.id !== id);
|
|
651
|
+
this.schedulePersist();
|
|
652
|
+
}
|
|
653
|
+
|
|
614
654
|
/**
|
|
615
655
|
* 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
|
|
616
656
|
* 失败不影响主流程。
|
|
@@ -890,13 +930,13 @@ export class AiEngine {
|
|
|
890
930
|
const prompt = buildSummaryPrompt(records, { kind, selfName: this.selfName });
|
|
891
931
|
let raw = "";
|
|
892
932
|
try {
|
|
893
|
-
const result = await this.
|
|
933
|
+
const result = await this.callModel({
|
|
894
934
|
system: prompt.system,
|
|
895
935
|
user: prompt.user,
|
|
896
936
|
temperature: 0.3,
|
|
897
937
|
maxTokens: 800,
|
|
898
938
|
model: String(cfg.memoryLearnModel || "").trim() || undefined,
|
|
899
|
-
});
|
|
939
|
+
}, { kind: 'memory', groupId: String(scope.id), trigger: 'summarize' });
|
|
900
940
|
if (!result || !result.ok) {
|
|
901
941
|
this.host.logger?.warn?.(`[memory-learn] 归纳调用失败: ${result && result.error}`);
|
|
902
942
|
return null;
|
|
@@ -1096,13 +1136,13 @@ export class AiEngine {
|
|
|
1096
1136
|
const marker = `## · ${AUTO_MEMORY_LABEL}`;
|
|
1097
1137
|
const input = fresh ? [...blocks, `${marker}\n${fresh}`] : blocks;
|
|
1098
1138
|
const prompt = buildConsolidatePrompt(input, { maxChars, kind, category });
|
|
1099
|
-
const result = await this.
|
|
1139
|
+
const result = await this.callModel({
|
|
1100
1140
|
system: prompt.system,
|
|
1101
1141
|
user: prompt.user,
|
|
1102
1142
|
temperature: 0.2,
|
|
1103
1143
|
maxTokens: Math.max(200, Math.min(500, maxChars * 5)),
|
|
1104
1144
|
model: String(cfg.memoryLearnModel || "").trim() || undefined,
|
|
1105
|
-
});
|
|
1145
|
+
}, { kind: 'memory', groupId: '', trigger: 'consolidate' });
|
|
1106
1146
|
if (!result || !result.ok) {
|
|
1107
1147
|
this.host.logger?.warn?.(`[memory-learn] 压缩调用失败: ${result?.error || "unknown"}`);
|
|
1108
1148
|
return "";
|
|
@@ -1277,6 +1317,15 @@ export class AiEngine {
|
|
|
1277
1317
|
if (!record) record = (await this.record(session)) ?? undefined;
|
|
1278
1318
|
if (!record) return;
|
|
1279
1319
|
|
|
1320
|
+
const traceId = newTraceId();
|
|
1321
|
+
this.emit('message.received', {
|
|
1322
|
+
traceId,
|
|
1323
|
+
groupId: String(session.guildId),
|
|
1324
|
+
userId: String(session.userId),
|
|
1325
|
+
messageId,
|
|
1326
|
+
at: record.at,
|
|
1327
|
+
});
|
|
1328
|
+
|
|
1280
1329
|
const mention = this.isMention(session, record);
|
|
1281
1330
|
const followupState = mention ? null : this.getFollowup(state, record, session);
|
|
1282
1331
|
const followup = !!followupState && this.shouldContinueFollowup(record, followupState);
|
|
@@ -1332,6 +1381,8 @@ export class AiEngine {
|
|
|
1332
1381
|
session,
|
|
1333
1382
|
groupId: String(session.guildId),
|
|
1334
1383
|
mode: 'reply',
|
|
1384
|
+
current: record,
|
|
1385
|
+
recent: state.records.slice(-12),
|
|
1335
1386
|
};
|
|
1336
1387
|
const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
|
|
1337
1388
|
const personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
|
|
@@ -1358,12 +1409,17 @@ export class AiEngine {
|
|
|
1358
1409
|
}
|
|
1359
1410
|
|
|
1360
1411
|
const images = await this.collectImages(session, record, state);
|
|
1361
|
-
const result = await this.
|
|
1412
|
+
const result = await this.callModel({
|
|
1362
1413
|
system: prompt.system,
|
|
1363
1414
|
user: prompt.user,
|
|
1364
1415
|
images,
|
|
1365
1416
|
temperature: Number(this.config.aiTemperature ?? 0.8),
|
|
1366
1417
|
maxTokens: Number(this.config.aiMaxOutputTokens ?? 400),
|
|
1418
|
+
}, {
|
|
1419
|
+
kind: 'reply',
|
|
1420
|
+
traceId,
|
|
1421
|
+
groupId: String(session.guildId),
|
|
1422
|
+
trigger: decision.reason,
|
|
1367
1423
|
});
|
|
1368
1424
|
|
|
1369
1425
|
if (!result.ok) {
|
|
@@ -1401,12 +1457,17 @@ export class AiEngine {
|
|
|
1401
1457
|
if (revisedSearch) {
|
|
1402
1458
|
const revisedInput = { ...promptInput, webSearch: revisedSearch };
|
|
1403
1459
|
const revisedUser = `${buildUserPrompt(revisedInput)}\n\n你刚才的回答是:「${truncate(finalRaw, 120)}」。现在补上了联网搜索结果,请根据结果重写最终回复;不要提“刚才/搜索/系统”,直接给答案。`;
|
|
1404
|
-
const revised = await this.
|
|
1460
|
+
const revised = await this.callModel({
|
|
1405
1461
|
system: prompt.system,
|
|
1406
1462
|
user: revisedUser,
|
|
1407
1463
|
images,
|
|
1408
1464
|
temperature: Number(this.config.aiTemperature ?? 0.8),
|
|
1409
1465
|
maxTokens: Number(this.config.aiMaxOutputTokens ?? 400),
|
|
1466
|
+
}, {
|
|
1467
|
+
kind: 'reply',
|
|
1468
|
+
traceId,
|
|
1469
|
+
groupId: String(session.guildId),
|
|
1470
|
+
trigger: 'revise',
|
|
1410
1471
|
});
|
|
1411
1472
|
if (revised.ok && revised.text && !PASS_RE.test(revised.text.trim())) {
|
|
1412
1473
|
finalRaw = revised.text.trim();
|
|
@@ -1437,9 +1498,38 @@ export class AiEngine {
|
|
|
1437
1498
|
return;
|
|
1438
1499
|
}
|
|
1439
1500
|
|
|
1440
|
-
|
|
1501
|
+
const renderedAt = this.now();
|
|
1502
|
+
this.emit('ai.reply.rendered', {
|
|
1503
|
+
traceId,
|
|
1504
|
+
groupId: String(session.guildId),
|
|
1505
|
+
chars: finalText.length,
|
|
1506
|
+
at: renderedAt,
|
|
1507
|
+
renderedMs: renderedAt - startedAt,
|
|
1508
|
+
});
|
|
1509
|
+
const selfId = `self-${this.now()}-${Math.random().toString(36).slice(2, 6)}`;
|
|
1510
|
+
// 先写入上下文再发送:发送等待期间用户追问,也能看到这句;失败再撤回
|
|
1511
|
+
this.recordSelf(session, finalText, selfId);
|
|
1512
|
+
const sendStartedAt = this.now();
|
|
1513
|
+
let sendError: any = null;
|
|
1514
|
+
try {
|
|
1515
|
+
await this.host.sendReply(session, finalText);
|
|
1516
|
+
} catch (error: any) {
|
|
1517
|
+
sendError = error;
|
|
1518
|
+
this.removeSelfRecord(session, selfId);
|
|
1519
|
+
throw error;
|
|
1520
|
+
} finally {
|
|
1521
|
+
const sentAt = this.now();
|
|
1522
|
+
this.emit('ai.reply.sent', {
|
|
1523
|
+
traceId,
|
|
1524
|
+
groupId: String(session.guildId),
|
|
1525
|
+
ok: !sendError,
|
|
1526
|
+
sendMs: sentAt - sendStartedAt,
|
|
1527
|
+
e2eMs: sentAt - startedAt,
|
|
1528
|
+
error: sendError ? String(sendError.message || sendError) : undefined,
|
|
1529
|
+
at: sentAt,
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1441
1532
|
state.counter = 0;
|
|
1442
|
-
this.recordSelf(session, finalText);
|
|
1443
1533
|
|
|
1444
1534
|
if (mention) this.startFollowup(state, record);
|
|
1445
1535
|
else if (followup && state.followup) this.bumpFollowup(state, record);
|
|
@@ -1468,9 +1558,87 @@ export class AiEngine {
|
|
|
1468
1558
|
}
|
|
1469
1559
|
}
|
|
1470
1560
|
|
|
1561
|
+
/** 发事件到 SDK 总线;监听器异常不能影响回复。 */
|
|
1562
|
+
private emit(event: string, payload: any): void {
|
|
1563
|
+
try {
|
|
1564
|
+
(this.host as any).events?.emit?.(event, payload);
|
|
1565
|
+
} catch { /* ignore */ }
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
/**
|
|
1569
|
+
* 统一模型调用入口:测量 model_ms、归一化 usage/失败原因,并发 ai.request.start/end。
|
|
1570
|
+
* 所有 provider.chat 调用都应走这里,监控插件才能覆盖成功/失败/重试。
|
|
1571
|
+
*/
|
|
1572
|
+
private async callModel(request: any, meta: any = {}): Promise<any> {
|
|
1573
|
+
const startedAt = this.now();
|
|
1574
|
+
const traceId = String(meta.traceId || newTraceId());
|
|
1575
|
+
const callId = `${traceId}-${String(meta.kind || 'reply')}-${startedAt.toString(36)}-${Math.random().toString(36).slice(2, 5)}`;
|
|
1576
|
+
const kind = String(meta.kind || 'reply');
|
|
1577
|
+
const groupId = String(meta.groupId || '');
|
|
1578
|
+
const model = String(request?.model || this.config.aiModel || '');
|
|
1579
|
+
this.emit('ai.request.start', {
|
|
1580
|
+
traceId,
|
|
1581
|
+
callId,
|
|
1582
|
+
kind,
|
|
1583
|
+
groupId,
|
|
1584
|
+
trigger: meta.trigger,
|
|
1585
|
+
model,
|
|
1586
|
+
at: startedAt,
|
|
1587
|
+
});
|
|
1588
|
+
|
|
1589
|
+
let result: any;
|
|
1590
|
+
try {
|
|
1591
|
+
result = await this.provider.chat(request);
|
|
1592
|
+
} catch (error: any) {
|
|
1593
|
+
const endedAt = this.now();
|
|
1594
|
+
this.emit('ai.request.end', {
|
|
1595
|
+
traceId,
|
|
1596
|
+
callId,
|
|
1597
|
+
kind,
|
|
1598
|
+
groupId,
|
|
1599
|
+
trigger: meta.trigger,
|
|
1600
|
+
model,
|
|
1601
|
+
startedAt,
|
|
1602
|
+
endedAt,
|
|
1603
|
+
modelMs: endedAt - startedAt,
|
|
1604
|
+
status: 'error',
|
|
1605
|
+
errorKind: 'exception',
|
|
1606
|
+
error: String(error?.message || error),
|
|
1607
|
+
retries: 0,
|
|
1608
|
+
});
|
|
1609
|
+
throw error;
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
const endedAt = this.now();
|
|
1613
|
+
this.emit('ai.request.end', {
|
|
1614
|
+
traceId,
|
|
1615
|
+
callId,
|
|
1616
|
+
kind,
|
|
1617
|
+
groupId,
|
|
1618
|
+
trigger: meta.trigger,
|
|
1619
|
+
model: String(result?.model || model),
|
|
1620
|
+
startedAt,
|
|
1621
|
+
endedAt,
|
|
1622
|
+
modelMs: endedAt - startedAt,
|
|
1623
|
+
usage: result?.usage,
|
|
1624
|
+
finishReason: result?.finishReason,
|
|
1625
|
+
status: result?.ok ? 'ok' : 'error',
|
|
1626
|
+
errorKind: result?.ok ? undefined : classifyModelFailure(result),
|
|
1627
|
+
error: result?.ok ? undefined : result?.error,
|
|
1628
|
+
retries: result?.degradedToText ? 1 : 0,
|
|
1629
|
+
degradedToText: !!result?.degradedToText,
|
|
1630
|
+
});
|
|
1631
|
+
return result;
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1471
1634
|
/** 供外部插件(如私聊插件)复用同一个模型 provider。 */
|
|
1472
1635
|
chat(request: any) {
|
|
1473
|
-
return this.
|
|
1636
|
+
return this.callModel(request, {
|
|
1637
|
+
kind: 'private',
|
|
1638
|
+
groupId: String(request?.groupId || request?.scopeId || ''),
|
|
1639
|
+
traceId: request?.traceId,
|
|
1640
|
+
trigger: 'private',
|
|
1641
|
+
});
|
|
1474
1642
|
}
|
|
1475
1643
|
|
|
1476
1644
|
/** 群内长时间没人说话时,生成一条主动话题:带时间/季节、最近上下文、相关记忆和联网结果。 */
|
|
@@ -1552,12 +1720,12 @@ export class AiEngine {
|
|
|
1552
1720
|
'- 不要问“在吗”,不要提“很久没人说话”,不要自我介绍;',
|
|
1553
1721
|
...sections,
|
|
1554
1722
|
].filter(Boolean).join('\n');
|
|
1555
|
-
const result = await this.
|
|
1723
|
+
const result = await this.callModel({
|
|
1556
1724
|
system,
|
|
1557
1725
|
user: '现在发一条主动话题。',
|
|
1558
1726
|
temperature: Number(this.config.aiTemperature ?? 0.8),
|
|
1559
1727
|
maxTokens: Math.min(300, Number(this.config.aiMaxOutputTokens ?? 400)),
|
|
1560
|
-
});
|
|
1728
|
+
}, { kind: 'idle', groupId, trigger: 'idle' });
|
|
1561
1729
|
if (!result.ok || !result.text) return '';
|
|
1562
1730
|
const raw = String(result.text).trim();
|
|
1563
1731
|
if (!raw || PASS_RE.test(raw)) return '';
|