@nestim/koishi-plugin-qq-group-manager 1.4.10 → 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 CHANGED
@@ -2,6 +2,27 @@
2
2
 
3
3
  本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
+ ## 1.4.11
6
+
7
+ ### 修复
8
+
9
+ - **联网搜索命中缓存也会消耗每小时配额**。之前配额计数在缓存检查之前,
10
+ 同一个 query 在缓存有效期内重复出现,明明没有发请求也会扣次数,很快就撞上 `rate-limit`。
11
+ 现在先查缓存,命中直接返回、不占配额;换 query 仍受 `aiWebSearchMaxPerHour` 限制。
12
+ 被限流时日志会带上 `limit` 和 `resetIn`(还有多少秒恢复),方便区分“配额用完”和“接口故障”。
13
+
14
+ ### 新增
15
+
16
+ - **aiHooks v3:`registerPersonaOverride(provider)`**。外部插件可以按群覆盖主插件默认人设 /
17
+ 系统提示词(qqgm-chat-style 的分群提示词用的就是这个)。
18
+
19
+ - **`qqgmAiRuntime.images(session)`**。外部插件(qqgm-private)可以复用主插件的视觉链路,
20
+ 把消息里的图片转成 data URL 后一起发给模型。
21
+
22
+ ### 说明
23
+
24
+ - 不调用新接口的旧插件行为不变;`hooks.version` 升到 3。
25
+
5
26
  ## 1.4.10
6
27
 
7
28
  ### 新功能
@@ -179,6 +179,11 @@ export declare class AiEngine {
179
179
  private readForwards;
180
180
  private recentImageRecords;
181
181
  private collectImages;
182
+ /**
183
+ * 供外部插件(qqgm-private)复用:把一条私聊消息里的图片解析成 data URL。
184
+ * 不做上下文回看,只看当前消息本身。
185
+ */
186
+ resolveSessionImages(session: any): Promise<string[]>;
182
187
  private platformAllowed;
183
188
  private log;
184
189
  /** 供指令/调试使用 */
package/lib/ai/engine.js CHANGED
@@ -1048,10 +1048,11 @@ class AiEngine {
1048
1048
  mode: 'reply',
1049
1049
  };
1050
1050
  const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
1051
+ const personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
1051
1052
  const webSearch = await this.webSearch(record, session);
1052
1053
  const promptInput = {
1053
1054
  selfName: this.selfName,
1054
- persona: this.personaPrompt,
1055
+ persona: personaOverride || this.personaPrompt,
1055
1056
  groupId: String(session.guildId),
1056
1057
  records: this.clampContext(state.records),
1057
1058
  current: record,
@@ -1178,16 +1179,20 @@ class AiEngine {
1178
1179
  async idleTopic(groupId) {
1179
1180
  const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
1180
1181
  let sections = [];
1182
+ let personaOverride = null;
1181
1183
  try {
1182
- sections = this.clampStyle(await this.hooks.collectSections({ session, groupId, mode: 'reply' }));
1184
+ const hookCtx = { session, groupId, mode: 'reply' };
1185
+ sections = this.clampStyle(await this.hooks.collectSections(hookCtx));
1186
+ personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
1183
1187
  }
1184
1188
  catch { /* ignore */ }
1185
1189
  const system = [
1186
1190
  `你是 QQ 群 ${groupId} 里的一个普通成员。`,
1191
+ personaOverride || this.personaPrompt,
1187
1192
  '群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
1188
1193
  '不要问“在吗”,不要提“很久没人说话”,不要自我介绍。',
1189
1194
  ...sections,
1190
- ].join('\n');
1195
+ ].filter(Boolean).join('\n');
1191
1196
  const result = await this.provider.chat({
1192
1197
  system,
1193
1198
  user: '现在发一条主动话题。',
@@ -1220,23 +1225,31 @@ class AiEngine {
1220
1225
  if (this.searchUnsupportedUntil > now)
1221
1226
  return '';
1222
1227
  const groupId = String(session?.guildId || '');
1223
- const maxPerHour = Math.max(0, Number(this.config.aiWebSearchMaxPerHour ?? 10));
1228
+ // 先查缓存:命中缓存不消耗搜索配额
1229
+ const cacheMinutes = Math.max(0, Number(this.config.aiWebSearchCacheMinutes ?? 10));
1230
+ const cacheKey = `${String(this.config.aiBaseUrl || '')}|${query}`;
1231
+ if (cacheMinutes > 0) {
1232
+ const hit = this.searchCache.get(cacheKey);
1233
+ if (hit && now - hit.at < cacheMinutes * 60_000)
1234
+ return hit.section;
1235
+ }
1236
+ const maxPerHour = Math.max(0, Number(this.config.aiWebSearchMaxPerHour ?? 30));
1224
1237
  if (maxPerHour > 0) {
1225
1238
  const list = (this.searchRate.get(groupId) || []).filter((t) => now - t < 3600_000);
1226
1239
  if (list.length >= maxPerHour) {
1227
- this.log('web-search', { ok: false, reason: 'rate-limit', groupId }, session);
1240
+ const resetIn = Math.max(1, Math.ceil((list[0] + 3600_000 - now) / 1000));
1241
+ this.log('web-search', {
1242
+ ok: false,
1243
+ reason: 'rate-limit',
1244
+ limit: maxPerHour,
1245
+ resetIn,
1246
+ groupId,
1247
+ }, session);
1228
1248
  return '';
1229
1249
  }
1230
1250
  list.push(now);
1231
1251
  this.searchRate.set(groupId, list);
1232
1252
  }
1233
- const cacheMinutes = Math.max(0, Number(this.config.aiWebSearchCacheMinutes ?? 10));
1234
- const cacheKey = `${String(this.config.aiBaseUrl || '')}|${query}`;
1235
- if (cacheMinutes > 0) {
1236
- const hit = this.searchCache.get(cacheKey);
1237
- if (hit && now - hit.at < cacheMinutes * 60_000)
1238
- return hit.section;
1239
- }
1240
1253
  const startedAt = this.now();
1241
1254
  const outcome = await (0, websearch_1.fetchWebSearch)({
1242
1255
  query,
@@ -1360,6 +1373,27 @@ class AiEngine {
1360
1373
  return [];
1361
1374
  return (0, vision_1.resolveImages)(items, (ref) => this.host.resolveImage(ref, session), { maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) });
1362
1375
  }
1376
+ /**
1377
+ * 供外部插件(qqgm-private)复用:把一条私聊消息里的图片解析成 data URL。
1378
+ * 不做上下文回看,只看当前消息本身。
1379
+ */
1380
+ async resolveSessionImages(session) {
1381
+ if (this.config.aiEnableImageRecognition === false)
1382
+ return [];
1383
+ const maxCount = Math.max(0, Number(this.config.aiImageMaxCount ?? 2));
1384
+ if (!maxCount)
1385
+ return [];
1386
+ let own = [];
1387
+ try {
1388
+ own = this.host.extractImages(session) || [];
1389
+ }
1390
+ catch {
1391
+ own = [];
1392
+ }
1393
+ if (!own.length)
1394
+ return [];
1395
+ return (0, vision_1.resolveImages)(own, (ref) => this.host.resolveImage(ref, session), { maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) });
1396
+ }
1363
1397
  platformAllowed(platform) {
1364
1398
  const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
1365
1399
  return list.includes(platform);
package/lib/ai/hooks.d.ts CHANGED
@@ -14,6 +14,8 @@ export interface AiHookContext {
14
14
  }
15
15
  export type PromptSectionProvider = (ctx: AiHookContext) => string | Promise<string>;
16
16
  export type OutputFilter = (text: string, ctx: AiHookContext) => string | null | Promise<string | null>;
17
+ /** 覆盖主插件的默认人设/系统提示词;返回空表示不覆盖。 */
18
+ export type PersonaOverrideProvider = (ctx: AiHookContext) => string | null | Promise<string | null>;
17
19
  export interface AiAfterReplyContext extends AiHookContext {
18
20
  /** 已经发送并写入上下文的最终文本 */
19
21
  text: string;
@@ -47,12 +49,13 @@ export interface ContextEvictedContext {
47
49
  export type ContextEvictedHandler = (ctx: ContextEvictedContext) => void | Promise<void>;
48
50
  export declare class AiHookRegistry {
49
51
  private logger?;
50
- /** 钩子接口版本;外部插件应检查 >= 2 才能用 contextEvicted */
51
- readonly version = 2;
52
+ /** 钩子接口版本;>=2 支持 contextEvicted,>=3 支持 registerPersonaOverride */
53
+ readonly version = 3;
52
54
  private sections;
53
55
  private filters;
54
56
  private afterReplyHandlers;
55
57
  private evictedHandlers;
58
+ private personaOverrides;
56
59
  constructor(logger?: any);
57
60
  /** 主插件重载后把新实例的 logger 接到同一个注册表上。 */
58
61
  setLogger(logger?: any): void;
@@ -62,8 +65,11 @@ export declare class AiHookRegistry {
62
65
  filters: number;
63
66
  afterReply: number;
64
67
  evicted: number;
68
+ persona: number;
65
69
  };
66
70
  registerPromptSection(provider: PromptSectionProvider): () => void;
71
+ /** 覆盖主插件默认人设(按群);第一个返回非空文本的生效。 */
72
+ registerPersonaOverride(provider: PersonaOverrideProvider): () => void;
67
73
  registerOutputFilter(filter: OutputFilter): () => void;
68
74
  /** 文字回复已发送后触发;用于追加表情包等后续动作。 */
69
75
  registerAfterReply(handler: AfterReplyHandler): () => void;
@@ -72,6 +78,8 @@ export declare class AiHookRegistry {
72
78
  * 用于把这些即将被丢弃的消息交给外部插件做归纳、归档等。
73
79
  */
74
80
  registerContextEvicted(handler: ContextEvictedHandler): () => void;
81
+ /** 第一个非空的人设覆盖生效;失败只记日志。 */
82
+ collectPersonaOverride(ctx: AiHookContext): Promise<string | null>;
75
83
  /** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
76
84
  collectSections(ctx: AiHookContext): Promise<string[]>;
77
85
  /** 依次执行输出过滤器;返回 null 表示丢弃本条回复。 */
package/lib/ai/hooks.js CHANGED
@@ -13,12 +13,13 @@ exports.AiHookRegistry = void 0;
13
13
  exports.getSharedAiHooks = getSharedAiHooks;
14
14
  class AiHookRegistry {
15
15
  logger;
16
- /** 钩子接口版本;外部插件应检查 >= 2 才能用 contextEvicted */
17
- version = 2;
16
+ /** 钩子接口版本;>=2 支持 contextEvicted,>=3 支持 registerPersonaOverride */
17
+ version = 3;
18
18
  sections = new Set();
19
19
  filters = new Set();
20
20
  afterReplyHandlers = new Set();
21
21
  evictedHandlers = new Set();
22
+ personaOverrides = new Set();
22
23
  constructor(logger) {
23
24
  this.logger = logger;
24
25
  }
@@ -34,12 +35,18 @@ class AiHookRegistry {
34
35
  filters: this.filters.size,
35
36
  afterReply: this.afterReplyHandlers.size,
36
37
  evicted: this.evictedHandlers.size,
38
+ persona: this.personaOverrides.size,
37
39
  };
38
40
  }
39
41
  registerPromptSection(provider) {
40
42
  this.sections.add(provider);
41
43
  return () => this.sections.delete(provider);
42
44
  }
45
+ /** 覆盖主插件默认人设(按群);第一个返回非空文本的生效。 */
46
+ registerPersonaOverride(provider) {
47
+ this.personaOverrides.add(provider);
48
+ return () => this.personaOverrides.delete(provider);
49
+ }
43
50
  registerOutputFilter(filter) {
44
51
  this.filters.add(filter);
45
52
  return () => this.filters.delete(filter);
@@ -57,6 +64,20 @@ class AiHookRegistry {
57
64
  this.evictedHandlers.add(handler);
58
65
  return () => this.evictedHandlers.delete(handler);
59
66
  }
67
+ /** 第一个非空的人设覆盖生效;失败只记日志。 */
68
+ async collectPersonaOverride(ctx) {
69
+ for (const provider of this.personaOverrides) {
70
+ try {
71
+ const text = await provider(ctx);
72
+ if (text && String(text).trim())
73
+ return String(text).trim();
74
+ }
75
+ catch (error) {
76
+ this.logger?.warn?.(`[ai-hooks] persona override failed: ${String(error)}`);
77
+ }
78
+ }
79
+ return null;
80
+ }
60
81
  /** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
61
82
  async collectSections(ctx) {
62
83
  const out = [];
@@ -25,5 +25,7 @@ export declare class AiRuntimeFacade {
25
25
  get config(): any;
26
26
  get hooks(): AiHookRegistry;
27
27
  chat(request: AiRuntimeChatRequest): Promise<any>;
28
+ /** 把一条消息里的图片解析成 data URL(私聊插件复用主插件的视觉链路) */
29
+ images(session: any): Promise<string[]>;
28
30
  }
29
31
  export declare function getAiRuntimeFacade(): AiRuntimeFacade;
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/index.js CHANGED
@@ -179,7 +179,7 @@ exports.Config = koishi_1.Schema.intersect([
179
179
  ]).role('radio').default('auto').description('联网搜索触发方式。'),
180
180
  aiWebSearchMaxResults: koishi_1.Schema.natural().min(1).max(10).default(5).description('每次联网搜索取几条结果。'),
181
181
  aiWebSearchTimeoutMs: koishi_1.Schema.natural().min(500).max(15000).default(4000).description('搜索请求超时(毫秒)。'),
182
- 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=不限。命中缓存不占次数。'),
183
183
  aiWebSearchCacheMinutes: koishi_1.Schema.natural().min(0).max(1440).default(10).description('相同 query 的结果缓存分钟数;0=不缓存。'),
184
184
  aiRequestTimeoutSeconds: koishi_1.Schema.natural().min(5).max(120).default(20).description('单次模型请求超时(秒)。'),
185
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.10",
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
@@ -227,16 +227,21 @@ export function apply(ctx) {
227
227
  // 发送前过滤;返回 null 表示这条不发(按 pass 处理)
228
228
  const off2 = hooks.registerOutputFilter((text) => text.replace(/首先/g, ''))
229
229
 
230
+ // 按群覆盖主插件默认人设(v3+;返回空表示不覆盖)
231
+ const off3 = hooks.registerPersonaOverride((ctx) => (ctx.groupId === '123456' ? '你是本群专属的猫娘' : null))
232
+
230
233
  ctx.on('dispose', () => {
231
234
  off1()
232
235
  off2()
236
+ off3()
233
237
  })
234
238
  }
235
239
  ```
236
240
 
237
241
  - 风格段插在基础规则之后、`<pass/>` 规则之前,并声明“与系统规则冲突时以系统规则为准”。
238
242
  - 过滤器按注册顺序执行,异常会被隔离;过滤后的文本才会写回上下文。
239
- - `hooks.version` 目前为 `1`,外部插件应先检查版本。
243
+ - `hooks.version` 目前为 `3`:`>=2` 支持 `registerContextEvicted`,`>=3` 支持 `registerPersonaOverride`。
244
+ - 私聊类插件还可以用 `ctx.root.get('qqgmAiRuntime').images(session)` 复用主插件的图片解析链路。
240
245
 
241
246
 
242
247
  ## 数据文件
package/src/ai/engine.ts CHANGED
@@ -1106,10 +1106,11 @@ export class AiEngine {
1106
1106
  mode: 'reply',
1107
1107
  };
1108
1108
  const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
1109
+ const personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
1109
1110
  const webSearch = await this.webSearch(record, session);
1110
1111
  const promptInput = {
1111
1112
  selfName: this.selfName,
1112
- persona: this.personaPrompt,
1113
+ persona: personaOverride || this.personaPrompt,
1113
1114
  groupId: String(session.guildId),
1114
1115
  records: this.clampContext(state.records),
1115
1116
  current: record,
@@ -1248,15 +1249,19 @@ export class AiEngine {
1248
1249
  async idleTopic(groupId: string): Promise<string> {
1249
1250
  const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
1250
1251
  let sections: string[] = [];
1252
+ let personaOverride: string | null = null;
1251
1253
  try {
1252
- sections = this.clampStyle(await this.hooks.collectSections({ session, groupId, mode: 'reply' }));
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);
1253
1257
  } catch { /* ignore */ }
1254
1258
  const system = [
1255
1259
  `你是 QQ 群 ${groupId} 里的一个普通成员。`,
1260
+ personaOverride || this.personaPrompt,
1256
1261
  '群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
1257
1262
  '不要问“在吗”,不要提“很久没人说话”,不要自我介绍。',
1258
1263
  ...sections,
1259
- ].join('\n');
1264
+ ].filter(Boolean).join('\n');
1260
1265
  const result = await this.provider.chat({
1261
1266
  system,
1262
1267
  user: '现在发一条主动话题。',
@@ -1284,24 +1289,33 @@ export class AiEngine {
1284
1289
  const now = this.now();
1285
1290
  if (this.searchUnsupportedUntil > now) return '';
1286
1291
  const groupId = String(session?.guildId || '');
1287
- const maxPerHour = Math.max(0, Number(this.config.aiWebSearchMaxPerHour ?? 10));
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));
1288
1302
  if (maxPerHour > 0) {
1289
1303
  const list = (this.searchRate.get(groupId) || []).filter((t) => now - t < 3600_000);
1290
1304
  if (list.length >= maxPerHour) {
1291
- this.log('web-search', { ok: false, reason: 'rate-limit', groupId }, session);
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);
1292
1313
  return '';
1293
1314
  }
1294
1315
  list.push(now);
1295
1316
  this.searchRate.set(groupId, list);
1296
1317
  }
1297
1318
 
1298
- const cacheMinutes = Math.max(0, Number(this.config.aiWebSearchCacheMinutes ?? 10));
1299
- const cacheKey = `${String(this.config.aiBaseUrl || '')}|${query}`;
1300
- if (cacheMinutes > 0) {
1301
- const hit = this.searchCache.get(cacheKey);
1302
- if (hit && now - hit.at < cacheMinutes * 60_000) return hit.section;
1303
- }
1304
-
1305
1319
  const startedAt = this.now();
1306
1320
  const outcome = await fetchWebSearch({
1307
1321
  query,
@@ -1426,6 +1440,28 @@ export class AiEngine {
1426
1440
  );
1427
1441
  }
1428
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
+
1429
1465
  private platformAllowed(platform: string): boolean {
1430
1466
  const list = Array.isArray(this.config.platformFilter) ? this.config.platformFilter : ['onebot'];
1431
1467
  return list.includes(platform);
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
- /** 钩子接口版本;外部插件应检查 >= 2 才能用 contextEvicted */
58
- readonly version = 2;
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);
package/src/ai/runtime.ts CHANGED
@@ -50,6 +50,15 @@ export class AiRuntimeFacade {
50
50
  }
51
51
  return this.current.ai.chat(request);
52
52
  }
53
+
54
+ /** 把一条消息里的图片解析成 data URL(私聊插件复用主插件的视觉链路) */
55
+ images(session: any): Promise<string[]> {
56
+ if (!this.current || !this.current.ai
57
+ || typeof this.current.ai.resolveSessionImages !== 'function') {
58
+ return Promise.resolve([]);
59
+ }
60
+ return this.current.ai.resolveSessionImages(session);
61
+ }
53
62
  }
54
63
 
55
64
  export function getAiRuntimeFacade(): AiRuntimeFacade {
package/src/index.ts CHANGED
@@ -176,7 +176,7 @@ export const Config = Schema.intersect([
176
176
  ]).role('radio').default('auto').description('联网搜索触发方式。'),
177
177
  aiWebSearchMaxResults: Schema.natural().min(1).max(10).default(5).description('每次联网搜索取几条结果。'),
178
178
  aiWebSearchTimeoutMs: Schema.natural().min(500).max(15000).default(4000).description('搜索请求超时(毫秒)。'),
179
- aiWebSearchMaxPerHour: Schema.natural().min(0).max(100).default(10).description('每个群每小时最多搜索次数;0=不限。'),
179
+ aiWebSearchMaxPerHour: Schema.natural().min(0).max(100).default(10).description('每个群每小时最多搜索次数;0=不限。命中缓存不占次数。'),
180
180
  aiWebSearchCacheMinutes: Schema.natural().min(0).max(1440).default(10).description('相同 query 的结果缓存分钟数;0=不缓存。'),
181
181
  aiRequestTimeoutSeconds: Schema.natural().min(5).max(120).default(20).description('单次模型请求超时(秒)。'),
182
182
  aiDebugPrompt: Schema.boolean().default(false).description('调试:把最终系统提示词与用户提示词写入日志(排查"答非所问"时打开,平时关闭)。'),