@nestim/koishi-plugin-qq-group-manager 1.2.3 → 1.2.5

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,25 @@
2
2
 
3
3
  本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
+ ## 1.2.5
6
+
7
+ ### 新增
8
+
9
+ - **`aiHooks.registerAfterReply`**:文字回复发送并写入上下文后触发,参数带最终文本。
10
+ 用于追加表情包等“文字之后”的动作,保证先文字、后图片。
11
+ - **root 暴露 `qqgmAiRuntime`**:`{ config, hooks, chat }`。私聊等外部插件可以复用
12
+ 同一个模型 provider 与同一套 style/meme 扩展点,不必重复配置 API Key。
13
+
14
+ ## 1.2.4
15
+
16
+ ### 修复
17
+
18
+ - **识图:先发图、再单独 @ 机器人时图片丢失**。`collectImages` 原本只看当前消息和引用消息,
19
+ 当前消息只有文字时 `images=0`,机器人会回“图没刷出来”。
20
+ 现在当前消息没有图时,会回看最近 2 分钟内**同一用户**最近 1–2 条消息里的图
21
+ (仍受 `aiImageMaxCount` 限制);不回看其他用户的图,也不回看超过 2 分钟的图。
22
+ - 删除 1.2.3 诊断期临时加的 `[ai-image]` 日志。
23
+
5
24
  ## 1.2.3
6
25
 
7
26
  ### 修复
@@ -12,7 +12,7 @@
12
12
  * - 允许模型用 <pass/> 主动放弃,放弃也重置计数,避免每条消息都空转调用。
13
13
  */
14
14
  import { AiState, ChatRecord } from './state';
15
- import { ChatProvider } from './provider';
15
+ import { ChatProvider, ChatResult } from './provider';
16
16
  import { RenderedImage } from '../core/text';
17
17
  import { AiHookRegistry } from './hooks';
18
18
  export interface AiHost {
@@ -67,6 +67,9 @@ export declare class AiEngine {
67
67
  private getFollowup;
68
68
  private loadMemories;
69
69
  handle(session: any): Promise<void>;
70
+ /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
71
+ chat(request: any): Promise<ChatResult>;
72
+ private recentImageRecords;
70
73
  private collectImages;
71
74
  private judge;
72
75
  private platformAllowed;
package/lib/ai/engine.js CHANGED
@@ -422,7 +422,7 @@ class AiEngine {
422
422
  if (this.debugPrompt) {
423
423
  this.host.logger.info(`[ai-debug] system=${prompt.system}\n[ai-debug] user=${prompt.user}`);
424
424
  }
425
- const images = await this.collectImages(session, record);
425
+ const images = await this.collectImages(session, record, state);
426
426
  const result = await this.provider.chat({
427
427
  system: prompt.system,
428
428
  user: prompt.user,
@@ -486,6 +486,7 @@ class AiEngine {
486
486
  chars: finalText.length,
487
487
  preview: finalText.slice(0, 60),
488
488
  }, session);
489
+ await this.hooks.runAfterReply({ ...hookCtx, text: finalText });
489
490
  }
490
491
  catch (error) {
491
492
  this.log('ai-reply', {
@@ -498,15 +499,38 @@ class AiEngine {
498
499
  state.inFlight = false;
499
500
  }
500
501
  }
501
- async collectImages(session, record) {
502
+ /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
503
+ chat(request) {
504
+ return this.provider.chat(request);
505
+ }
506
+ recentImageRecords(state, record, maxAgeMs = 120000) {
507
+ const cutoff = Number(record.at) - maxAgeMs;
508
+ const candidates = state.records
509
+ .filter((item) => (!item.self
510
+ && item.id !== record.id
511
+ && item.userId === record.userId
512
+ && item.images.length > 0
513
+ && Number(item.at) >= cutoff))
514
+ .slice(-4)
515
+ .reverse();
516
+ const out = [];
517
+ for (const item of candidates) {
518
+ for (const image of item.images)
519
+ out.push(image);
520
+ }
521
+ return out;
522
+ }
523
+ async collectImages(session, record, state) {
502
524
  if (this.config.aiEnableImageRecognition === false)
503
525
  return [];
504
526
  const maxCount = Math.max(0, Number(this.config.aiImageMaxCount ?? 2));
505
527
  if (!maxCount)
506
528
  return [];
507
529
  const own = record.images.length ? record.images : this.host.extractImages(session);
530
+ // 用户常见的“先发图,再单独 @ 一句”:当前消息没有图,回看同一用户最近 2 分钟内的图
531
+ const fallback = own.length ? [] : this.recentImageRecords(state, record);
508
532
  const quoted = record.quote ? this.host.extractImages(session?.quote) : [];
509
- const items = (0, vision_1.pickImages)(own, quoted, maxCount);
533
+ const items = (0, vision_1.pickImages)([...own, ...fallback], quoted, maxCount);
510
534
  if (!items.length)
511
535
  return [];
512
536
  return (0, vision_1.resolveImages)(items, (ref) => this.host.resolveImage(ref, session), { maxCount, budgetMs: Number(this.config.aiImageBudgetMs ?? 6000) });
package/lib/ai/hooks.d.ts CHANGED
@@ -14,17 +14,27 @@ 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
+ export interface AiAfterReplyContext extends AiHookContext {
18
+ /** 已经发送并写入上下文的最终文本 */
19
+ text: string;
20
+ }
21
+ export type AfterReplyHandler = (ctx: AiAfterReplyContext) => void | Promise<void>;
17
22
  export declare class AiHookRegistry {
18
23
  private logger?;
19
24
  /** 钩子接口版本;外部插件应检查 >= 1 */
20
25
  readonly version = 1;
21
26
  private sections;
22
27
  private filters;
28
+ private afterReplyHandlers;
23
29
  constructor(logger?: any);
24
30
  registerPromptSection(provider: PromptSectionProvider): () => void;
25
31
  registerOutputFilter(filter: OutputFilter): () => void;
32
+ /** 文字回复已发送后触发;用于追加表情包等后续动作。 */
33
+ registerAfterReply(handler: AfterReplyHandler): () => void;
26
34
  /** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
27
35
  collectSections(ctx: AiHookContext): Promise<string[]>;
28
36
  /** 依次执行输出过滤器;返回 null 表示丢弃本条回复。 */
29
37
  applyFilters(text: string, ctx: AiHookContext): Promise<string | null>;
38
+ /** 文字回复发送后执行;单个 handler 失败只记日志,不影响其它。 */
39
+ runAfterReply(ctx: AiAfterReplyContext): Promise<void>;
30
40
  }
package/lib/ai/hooks.js CHANGED
@@ -16,6 +16,7 @@ class AiHookRegistry {
16
16
  version = 1;
17
17
  sections = new Set();
18
18
  filters = new Set();
19
+ afterReplyHandlers = new Set();
19
20
  constructor(logger) {
20
21
  this.logger = logger;
21
22
  }
@@ -27,6 +28,11 @@ class AiHookRegistry {
27
28
  this.filters.add(filter);
28
29
  return () => this.filters.delete(filter);
29
30
  }
31
+ /** 文字回复已发送后触发;用于追加表情包等后续动作。 */
32
+ registerAfterReply(handler) {
33
+ this.afterReplyHandlers.add(handler);
34
+ return () => this.afterReplyHandlers.delete(handler);
35
+ }
30
36
  /** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
31
37
  async collectSections(ctx) {
32
38
  const out = [];
@@ -58,5 +64,16 @@ class AiHookRegistry {
58
64
  }
59
65
  return current;
60
66
  }
67
+ /** 文字回复发送后执行;单个 handler 失败只记日志,不影响其它。 */
68
+ async runAfterReply(ctx) {
69
+ for (const handler of this.afterReplyHandlers) {
70
+ try {
71
+ await handler(ctx);
72
+ }
73
+ catch (error) {
74
+ this.logger?.warn?.(`[ai-hooks] after-reply failed: ${String(error)}`);
75
+ }
76
+ }
77
+ }
61
78
  }
62
79
  exports.AiHookRegistry = AiHookRegistry;
package/lib/service.js CHANGED
@@ -189,10 +189,18 @@ class QQGroupManagerService extends koishi_1.Service {
189
189
  // 额外把扩展点挂到 root,外部插件 inject 'qqgmAiHooks' 即可。
190
190
  try {
191
191
  ctx.root.set('qqgmAiHooks', this.ai.hooks);
192
+ const runtime = {
193
+ config: this.config,
194
+ hooks: this.ai.hooks,
195
+ chat: (request) => this.ai.chat(request),
196
+ };
197
+ ctx.root.set('qqgmAiRuntime', runtime);
192
198
  ctx.on('dispose', () => {
193
199
  try {
194
200
  if (ctx.root.get('qqgmAiHooks') === this.ai.hooks)
195
201
  ctx.root.set('qqgmAiHooks', undefined);
202
+ if (ctx.root.get('qqgmAiRuntime')?.hooks === this.ai.hooks)
203
+ ctx.root.set('qqgmAiRuntime', undefined);
196
204
  }
197
205
  catch { /* ignore */ }
198
206
  });
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.2.3",
4
+ "version": "1.2.5",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
package/src/ai/engine.ts CHANGED
@@ -454,7 +454,7 @@ export class AiEngine {
454
454
  this.host.logger.info(`[ai-debug] system=${prompt.system}\n[ai-debug] user=${prompt.user}`);
455
455
  }
456
456
 
457
- const images = await this.collectImages(session, record);
457
+ const images = await this.collectImages(session, record, state);
458
458
  const result = await this.provider.chat({
459
459
  system: prompt.system,
460
460
  user: prompt.user,
@@ -524,6 +524,8 @@ export class AiEngine {
524
524
  chars: finalText.length,
525
525
  preview: finalText.slice(0, 60),
526
526
  }, session);
527
+
528
+ await this.hooks.runAfterReply({ ...hookCtx, text: finalText });
527
529
  } catch (error: any) {
528
530
  this.log('ai-reply', {
529
531
  ok: false,
@@ -535,14 +537,40 @@ export class AiEngine {
535
537
  }
536
538
  }
537
539
 
538
- private async collectImages(session: any, record: ChatRecord): Promise<string[]> {
540
+ /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
541
+ chat(request: any) {
542
+ return this.provider.chat(request);
543
+ }
544
+
545
+ private recentImageRecords(state: GroupState, record: ChatRecord, maxAgeMs = 120000): RenderedImage[] {
546
+ const cutoff = Number(record.at) - maxAgeMs;
547
+ const candidates = state.records
548
+ .filter((item) => (
549
+ !item.self
550
+ && item.id !== record.id
551
+ && item.userId === record.userId
552
+ && item.images.length > 0
553
+ && Number(item.at) >= cutoff
554
+ ))
555
+ .slice(-4)
556
+ .reverse();
557
+ const out: RenderedImage[] = [];
558
+ for (const item of candidates) {
559
+ for (const image of item.images) out.push(image);
560
+ }
561
+ return out;
562
+ }
563
+
564
+ private async collectImages(session: any, record: ChatRecord, state: GroupState): Promise<string[]> {
539
565
  if (this.config.aiEnableImageRecognition === false) return [];
540
566
  const maxCount = Math.max(0, Number(this.config.aiImageMaxCount ?? 2));
541
567
  if (!maxCount) return [];
542
568
 
543
569
  const own = record.images.length ? record.images : this.host.extractImages(session);
570
+ // 用户常见的“先发图,再单独 @ 一句”:当前消息没有图,回看同一用户最近 2 分钟内的图
571
+ const fallback = own.length ? [] : this.recentImageRecords(state, record);
544
572
  const quoted = record.quote ? this.host.extractImages(session?.quote) : [];
545
- const items = pickImages(own, quoted, maxCount);
573
+ const items = pickImages([...own, ...fallback], quoted, maxCount);
546
574
  if (!items.length) return [];
547
575
 
548
576
  return resolveImages(
package/src/ai/hooks.ts CHANGED
@@ -17,12 +17,19 @@ 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
+ export interface AiAfterReplyContext extends AiHookContext {
21
+ /** 已经发送并写入上下文的最终文本 */
22
+ text: string;
23
+ }
24
+ export type AfterReplyHandler = (ctx: AiAfterReplyContext) => void | Promise<void>;
25
+
20
26
  export class AiHookRegistry {
21
27
  /** 钩子接口版本;外部插件应检查 >= 1 */
22
28
  readonly version = 1;
23
29
 
24
30
  private sections = new Set<PromptSectionProvider>();
25
31
  private filters = new Set<OutputFilter>();
32
+ private afterReplyHandlers = new Set<AfterReplyHandler>();
26
33
 
27
34
  constructor(private logger?: any) {}
28
35
 
@@ -36,6 +43,12 @@ export class AiHookRegistry {
36
43
  return () => this.filters.delete(filter);
37
44
  }
38
45
 
46
+ /** 文字回复已发送后触发;用于追加表情包等后续动作。 */
47
+ registerAfterReply(handler: AfterReplyHandler): () => void {
48
+ this.afterReplyHandlers.add(handler);
49
+ return () => this.afterReplyHandlers.delete(handler);
50
+ }
51
+
39
52
  /** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
40
53
  async collectSections(ctx: AiHookContext): Promise<string[]> {
41
54
  const out: string[] = [];
@@ -64,4 +77,15 @@ export class AiHookRegistry {
64
77
  }
65
78
  return current;
66
79
  }
80
+
81
+ /** 文字回复发送后执行;单个 handler 失败只记日志,不影响其它。 */
82
+ async runAfterReply(ctx: AiAfterReplyContext): Promise<void> {
83
+ for (const handler of this.afterReplyHandlers) {
84
+ try {
85
+ await handler(ctx);
86
+ } catch (error) {
87
+ this.logger?.warn?.(`[ai-hooks] after-reply failed: ${String(error)}`);
88
+ }
89
+ }
90
+ }
67
91
  }
package/src/service.js CHANGED
@@ -190,10 +190,18 @@ class QQGroupManagerService extends koishi_1.Service {
190
190
  // 额外把扩展点挂到 root,外部插件 inject 'qqgmAiHooks' 即可。
191
191
  try {
192
192
  ctx.root.set('qqgmAiHooks', this.ai.hooks);
193
+ const runtime = {
194
+ config: this.config,
195
+ hooks: this.ai.hooks,
196
+ chat: (request) => this.ai.chat(request),
197
+ };
198
+ ctx.root.set('qqgmAiRuntime', runtime);
193
199
  ctx.on('dispose', () => {
194
200
  try {
195
201
  if (ctx.root.get('qqgmAiHooks') === this.ai.hooks)
196
202
  ctx.root.set('qqgmAiHooks', undefined);
203
+ if (ctx.root.get('qqgmAiRuntime')?.hooks === this.ai.hooks)
204
+ ctx.root.set('qqgmAiRuntime', undefined);
197
205
  }
198
206
  catch { /* ignore */ }
199
207
  });