@nestim/koishi-plugin-qq-group-manager 1.4.5 → 1.4.6

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,54 +2,86 @@
2
2
 
3
3
  本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
- ## 1.4.5
6
-
7
- ### 改进
8
-
9
- - **提示词里给每个发言人带上 QQ 号,用于区分身份**。
10
-
11
- 之前只渲染「昵称(角色)」,昵称重复或改动时模型分不清谁是谁,
12
- 会出现把另一个机器人当成自己、把两个同名群友记混的情况。
13
-
14
- 现在渲染成 `昵称(角色#QQ号)`:
15
-
16
- ```
17
- [15:15] 小明(成员#10001): 你好
18
- [15:15] MeowBot(你#9999): 我说过
19
- [15:15] 冬木(管理员#2): 在吗
20
- ```
21
-
22
- - **QQ 号只作为身份参考,明确要求模型不要写进回复**;
23
- - 自己的发言标 `(你#自己QQ号)`,别人的(包括其他机器人)都不会被标成自己;
24
- - 引用消息也带上被引用者的 QQ 号(`「回复 小明#333:……」`);
25
- - `unknown` 角色用「成员」兜底,避免出现 `小明(#10001)` 这种孤立井号。
26
-
27
- 规则里新增两条约束:判断「谁是谁」必须看 #号;标着(你)的才是自己。
28
-
29
- ### 测试
30
-
31
- - 新增 9 项身份测试:QQ 号是否出现、同名用户区分、自己/其他机器人区分、
32
- 引用带号、禁止输出 QQ 号、缺 userId 时不产生空 `#`。
33
- ## 1.4.4
34
-
35
- ### 改进
36
-
37
- - **`[memory] list` 改为分页显示**。
38
-
39
- 原先固定显示「最近 10 条」,记忆攒多之后一屏刷不完,也没法往前翻。
40
-
41
- 现在:
42
-
43
- - 默认显示**最新 5 条**(第 1 页就是刚记下的内容);
44
- - 每页 5 条,序号是全局序号;
45
- - `[memory] list 1` ~ `[memory] list 9` 翻页,页码越大越往前;
46
- - 末尾固定提示「记忆库共 N 条,第 X/Y 页」和翻页用法;
47
- - 页码越界自动夹到有效范围,非法输入回落到第 1 页。
48
-
49
- ### 测试
50
-
51
- - 新增 11 项分页测试:默认页、翻页、末页、越界夹取、非法输入、空库、
52
- 整页边界、全局序号、自定义页大小。
5
+ ## 1.4.6
6
+
7
+ ### 修复
8
+
9
+ - **主插件单独重载后,配套插件(表情包 / 聊天风格 / 私聊)全部失效**。
10
+
11
+ 之前每次加载主插件都会新建一个 `AiHookRegistry`,再用
12
+ `ctx.root.set('qqgmAiHooks', ...)` 覆盖旧对象;而 qqgm-meme、
13
+ qqgm-chat-style、qqgm-private 只在启动时解析一次扩展点并长期持有。
14
+ 在控制台单独重启主插件后,新引擎拿到的是空注册表,外部插件还挂在旧对象上:
15
+
16
+ - 表情包不再追加(提示词里也没有 `[表情: 情绪]` 说明);
17
+ - 聊天风格段从 system prompt 里消失;
18
+ - 私聊继续用旧配置、旧引擎,`chat()` 走已销毁的实例。
19
+
20
+ 只有把整个 Koishi 重启一遍才能恢复。
21
+
22
+ 现在改为:
23
+
24
+ - `qqgmAiHooks` 使用 `globalThis` + `Symbol.for` 做**进程级单例**,
25
+ 模块被重新 `require`(甚至从不同路径加载两份)也拿到同一个注册表,
26
+ 重载前后对象身份不变,外部插件注册的钩子继续有效;
27
+ - `qqgmAiRuntime` 改为**稳定的门面对象**,重载只把内部 `current` 指针换到新服务,
28
+ 外部插件读到的 `config` / `hooks` / `chat` 永远是最新的;
29
+ - 旧实例的 `dispose` 会先检查是否有新实例接管,不会误清新指针。
30
+
31
+ ### 测试
32
+
33
+ - 新增跨模块重载测试:清空 `require` 缓存后重新加载,注册表身份与已注册钩子保持不变。
34
+ - 新增运行时门面测试:新实例先接管、旧实例后 `dispose` 时,指针不会被清空。
35
+ - 新增主插件重载集成测试:连续构造两个 `QQGroupManagerService`,外部钩子在重载后仍然生效。
36
+
37
+ ## 1.4.5
38
+
39
+ ### 改进
40
+
41
+ - **提示词里给每个发言人带上 QQ 号,用于区分身份**。
42
+
43
+ 之前只渲染「昵称(角色)」,昵称重复或改动时模型分不清谁是谁,
44
+ 会出现把另一个机器人当成自己、把两个同名群友记混的情况。
45
+
46
+ 现在渲染成 `昵称(角色#QQ号)`:
47
+
48
+ ```
49
+ [15:15] 小明(成员#10001): 你好
50
+ [15:15] MeowBot(你#9999): 我说过
51
+ [15:15] 冬木(管理员#2): 在吗
52
+ ```
53
+
54
+ - **QQ 号只作为身份参考,明确要求模型不要写进回复**;
55
+ - 自己的发言标 `(你#自己QQ号)`,别人的(包括其他机器人)都不会被标成自己;
56
+ - 引用消息也带上被引用者的 QQ 号(`「回复 小明#333:……」`);
57
+ - `unknown` 角色用「成员」兜底,避免出现 `小明(#10001)` 这种孤立井号。
58
+
59
+ 规则里新增两条约束:判断「谁是谁」必须看 #号;标着(你)的才是自己。
60
+
61
+ ### 测试
62
+
63
+ - 新增 9 项身份测试:QQ 号是否出现、同名用户区分、自己/其他机器人区分、
64
+ 引用带号、禁止输出 QQ 号、缺 userId 时不产生空 `#`。
65
+ ## 1.4.4
66
+
67
+ ### 改进
68
+
69
+ - **`[memory] list` 改为分页显示**。
70
+
71
+ 原先固定显示「最近 10 条」,记忆攒多之后一屏刷不完,也没法往前翻。
72
+
73
+ 现在:
74
+
75
+ - 默认显示**最新 5 条**(第 1 页就是刚记下的内容);
76
+ - 每页 5 条,序号是全局序号;
77
+ - `[memory] list 1` ~ `[memory] list 9` 翻页,页码越大越往前;
78
+ - 末尾固定提示「记忆库共 N 条,第 X/Y 页」和翻页用法;
79
+ - 页码越界自动夹到有效范围,非法输入回落到第 1 页。
80
+
81
+ ### 测试
82
+
83
+ - 新增 11 项分页测试:默认页、翻页、末页、越界夹取、非法输入、空库、
84
+ 整页边界、全局序号、自定义页大小。
53
85
  ## 1.4.3
54
86
 
55
87
  ### 修复
@@ -35,6 +35,11 @@ export interface AiDeps {
35
35
  rng?: () => number;
36
36
  now?: () => number;
37
37
  fetchImpl?: typeof fetch;
38
+ /**
39
+ * 钩子注册表。主插件会传入进程级共享实例;不传则每次新建,
40
+ * 保证测试/多实例之间互不串钩子。
41
+ */
42
+ hooks?: AiHookRegistry;
38
43
  }
39
44
  export declare class AiEngine {
40
45
  readonly state: AiState;
package/lib/ai/engine.js CHANGED
@@ -76,7 +76,9 @@ class AiEngine {
76
76
  this.host = host;
77
77
  this.config = host.config;
78
78
  this.state = deps.state ?? new state_1.AiState();
79
- this.hooks = new hooks_1.AiHookRegistry(host.logger);
79
+ // 默认独立注册表;主插件通过 deps.hooks 注入进程级单例,
80
+ // 这样主插件重载后外部插件注册的钩子不会丢。
81
+ this.hooks = deps.hooks ?? new hooks_1.AiHookRegistry(host.logger);
80
82
  this.provider = deps.provider ?? new provider_1.ChatProvider(host.config, host.logger);
81
83
  this.names = new names_1.NameResolver({
82
84
  getOneBotApi: (session) => host.getOneBotApi(session),
package/lib/ai/hooks.d.ts CHANGED
@@ -54,6 +54,15 @@ export declare class AiHookRegistry {
54
54
  private afterReplyHandlers;
55
55
  private evictedHandlers;
56
56
  constructor(logger?: any);
57
+ /** 主插件重载后把新实例的 logger 接到同一个注册表上。 */
58
+ setLogger(logger?: any): void;
59
+ /** 诊断用:当前已注册的钩子数量。 */
60
+ stats(): {
61
+ sections: number;
62
+ filters: number;
63
+ afterReply: number;
64
+ evicted: number;
65
+ };
57
66
  registerPromptSection(provider: PromptSectionProvider): () => void;
58
67
  registerOutputFilter(filter: OutputFilter): () => void;
59
68
  /** 文字回复已发送后触发;用于追加表情包等后续动作。 */
@@ -72,3 +81,4 @@ export declare class AiHookRegistry {
72
81
  /** 上下文挤出后执行;单个 handler 失败只记日志,不影响其它。 */
73
82
  runContextEvicted(ctx: ContextEvictedContext): Promise<void>;
74
83
  }
84
+ export declare function getSharedAiHooks(logger?: any): AiHookRegistry;
package/lib/ai/hooks.js CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.AiHookRegistry = void 0;
13
+ exports.getSharedAiHooks = getSharedAiHooks;
13
14
  class AiHookRegistry {
14
15
  logger;
15
16
  /** 钩子接口版本;外部插件应检查 >= 2 才能用 contextEvicted */
@@ -21,6 +22,20 @@ class AiHookRegistry {
21
22
  constructor(logger) {
22
23
  this.logger = logger;
23
24
  }
25
+ /** 主插件重载后把新实例的 logger 接到同一个注册表上。 */
26
+ setLogger(logger) {
27
+ if (logger)
28
+ this.logger = logger;
29
+ }
30
+ /** 诊断用:当前已注册的钩子数量。 */
31
+ stats() {
32
+ return {
33
+ sections: this.sections.size,
34
+ filters: this.filters.size,
35
+ afterReply: this.afterReplyHandlers.size,
36
+ evicted: this.evictedHandlers.size,
37
+ };
38
+ }
24
39
  registerPromptSection(provider) {
25
40
  this.sections.add(provider);
26
41
  return () => this.sections.delete(provider);
@@ -99,3 +114,30 @@ class AiHookRegistry {
99
114
  }
100
115
  }
101
116
  exports.AiHookRegistry = AiHookRegistry;
117
+ /**
118
+ * 进程级共享的钩子注册表。
119
+ *
120
+ * 背景:meme / chat-style / private 等外部插件只在启动时解析一次
121
+ * `qqgmAiHooks`,之后一直持有这个对象。如果主插件每次重载都 `new` 一个
122
+ * 新注册表,新引擎看到的是空注册表,而外部插件还挂在旧对象上——表现就是
123
+ * 主插件单独重启后表情包不发、聊天风格段消失、私聊用旧配置。
124
+ *
125
+ * 用 globalThis + Symbol.for 做单例:即使插件模块被重新 require、甚至从
126
+ * 不同路径加载了两份,拿到的也是同一个注册表,重载前后对象身份不变。
127
+ */
128
+ const SHARED_HOOKS = Symbol.for('qqgm.ai-hooks-registry');
129
+ function getSharedAiHooks(logger) {
130
+ const store = globalThis;
131
+ let registry = store[SHARED_HOOKS];
132
+ if (!registry) {
133
+ registry = new AiHookRegistry(logger);
134
+ store[SHARED_HOOKS] = registry;
135
+ logger?.info?.(`[ai-hooks] v${registry.version} 注册表已创建(进程级单例)`);
136
+ }
137
+ else if (logger) {
138
+ registry.setLogger(logger);
139
+ const stats = registry.stats();
140
+ logger.info?.(`[ai-hooks] 复用进程级注册表:风格段 ${stats.sections} / 过滤器 ${stats.filters} / 后处理 ${stats.afterReply}`);
141
+ }
142
+ return registry;
143
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * 主插件对外暴露的运行时门面(进程级单例)。
3
+ *
4
+ * 为什么需要它:
5
+ * - 外部插件(qqgm-private 等)会 `ctx.root.get('qqgmAiRuntime')` 之后长期持有该对象;
6
+ * - 如果每次主插件重载都 `set` 一个全新的 `{ config, hooks, chat }` 快照,
7
+ * 外部插件手里的旧快照就永远指向已经销毁的引擎:配置不更新、钩子对不上、
8
+ * chat() 走旧实例;
9
+ * - 这里改成稳定的门面对象,重载只是把 `current` 指针换到新服务,
10
+ * 外部插件持有的引用不变,读到的 config / hooks / chat 永远是最新的。
11
+ */
12
+ import { AiHookRegistry } from './hooks';
13
+ export interface AiRuntimeChatRequest {
14
+ system: string;
15
+ user: string;
16
+ temperature?: number;
17
+ maxTokens?: number;
18
+ [key: string]: any;
19
+ }
20
+ export declare class AiRuntimeFacade {
21
+ /** 当前存活的主插件服务;主插件卸载后为 null。 */
22
+ current: any;
23
+ bind(service: any): void;
24
+ unbind(service: any): void;
25
+ get config(): any;
26
+ get hooks(): AiHookRegistry;
27
+ chat(request: AiRuntimeChatRequest): Promise<any>;
28
+ }
29
+ export declare function getAiRuntimeFacade(): AiRuntimeFacade;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ /**
3
+ * 主插件对外暴露的运行时门面(进程级单例)。
4
+ *
5
+ * 为什么需要它:
6
+ * - 外部插件(qqgm-private 等)会 `ctx.root.get('qqgmAiRuntime')` 之后长期持有该对象;
7
+ * - 如果每次主插件重载都 `set` 一个全新的 `{ config, hooks, chat }` 快照,
8
+ * 外部插件手里的旧快照就永远指向已经销毁的引擎:配置不更新、钩子对不上、
9
+ * chat() 走旧实例;
10
+ * - 这里改成稳定的门面对象,重载只是把 `current` 指针换到新服务,
11
+ * 外部插件持有的引用不变,读到的 config / hooks / chat 永远是最新的。
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.AiRuntimeFacade = void 0;
15
+ exports.getAiRuntimeFacade = getAiRuntimeFacade;
16
+ const hooks_1 = require("./hooks");
17
+ const SHARED_RUNTIME = Symbol.for('qqgm.ai-runtime-facade');
18
+ class AiRuntimeFacade {
19
+ /** 当前存活的主插件服务;主插件卸载后为 null。 */
20
+ current = null;
21
+ bind(service) {
22
+ this.current = service;
23
+ }
24
+ unbind(service) {
25
+ if (this.current === service)
26
+ this.current = null;
27
+ }
28
+ get config() {
29
+ return this.current ? this.current.config : {};
30
+ }
31
+ get hooks() {
32
+ const live = this.current && this.current.ai && this.current.ai.hooks;
33
+ // 服务不在时也返回共享注册表,避免外部插件拿到 null 后直接崩掉。
34
+ return live || (0, hooks_1.getSharedAiHooks)();
35
+ }
36
+ chat(request) {
37
+ if (!this.current || !this.current.ai) {
38
+ return Promise.resolve({ ok: false, text: '', error: 'qqgm service not loaded' });
39
+ }
40
+ return this.current.ai.chat(request);
41
+ }
42
+ }
43
+ exports.AiRuntimeFacade = AiRuntimeFacade;
44
+ function getAiRuntimeFacade() {
45
+ const store = globalThis;
46
+ let facade = store[SHARED_RUNTIME];
47
+ if (!facade) {
48
+ facade = new AiRuntimeFacade();
49
+ store[SHARED_RUNTIME] = facade;
50
+ }
51
+ return facade;
52
+ }
package/lib/service.js CHANGED
@@ -8,6 +8,8 @@ const koishi_1 = require("koishi");
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const node_fs_1 = __importDefault(require("node:fs"));
10
10
  const { AiEngine } = require("./ai/engine");
11
+ const { getSharedAiHooks } = require("./ai/hooks");
12
+ const { getAiRuntimeFacade } = require("./ai/runtime");
11
13
  let PLUGIN_VERSION = 'unknown';
12
14
  try {
13
15
  PLUGIN_VERSION = require('../package.json').version || 'unknown';
@@ -281,22 +283,32 @@ class QQGroupManagerService extends koishi_1.Service {
281
283
  this.ctx = ctx;
282
284
  this.config = config;
283
285
  this._logger = ctx.logger('nestim-qq-group-manager');
284
- this.ai = new AiEngine(this);
286
+ // 进程级共享钩子:主插件重载后仍是同一个对象,外部插件注册的钩子不会丢。
287
+ const sharedHooks = getSharedAiHooks(this._logger);
288
+ this.ai = new AiEngine(this, { hooks: sharedHooks });
285
289
  // Koishi 的 Service 注册在插件 fork 作用域,兄弟插件的 inject 拿不到;
286
- // 额外把扩展点挂到 root,外部插件 inject 'qqgmAiHooks' 即可。
290
+ // 额外把扩展点挂到 root,外部插件运行时探测即可。
291
+ //
292
+ // 关键:hooks 与 runtime 都必须是「进程级稳定对象」。主插件单独重载
293
+ // 时不能换成新对象,否则 meme / chat-style / private 手里的旧引用会
294
+ // 指向已销毁的实例:新引擎看不到它们的钩子(表情包不发、风格段丢失),
295
+ // 私聊还会继续用旧配置和旧引擎。
287
296
  try {
288
- ctx.root.set('qqgmAiHooks', this.ai.hooks);
289
- const runtime = {
290
- config: this.config,
291
- hooks: this.ai.hooks,
292
- chat: (request) => this.ai.chat(request),
293
- };
294
- ctx.root.set('qqgmAiRuntime', runtime);
297
+ const hooks = sharedHooks;
298
+ const facade = getAiRuntimeFacade();
299
+ facade.bind(this);
300
+ ctx.root.set('qqgmAiHooks', hooks);
301
+ ctx.root.set('qqgmAiRuntime', facade);
295
302
  ctx.on('dispose', () => {
296
303
  try {
297
- if (ctx.root.get('qqgmAiHooks') === this.ai.hooks)
304
+ facade.unbind(this);
305
+ // 只有当前没有新实例接管时才撤掉对外暴露:旧实例的 dispose
306
+ // 可能晚于新实例的 bind,此时不能把新指针清掉。
307
+ if (facade.current)
308
+ return;
309
+ if (ctx.root.get('qqgmAiHooks') === hooks)
298
310
  ctx.root.set('qqgmAiHooks', undefined);
299
- if (ctx.root.get('qqgmAiRuntime')?.hooks === this.ai.hooks)
311
+ if (ctx.root.get('qqgmAiRuntime') === facade)
300
312
  ctx.root.set('qqgmAiRuntime', undefined);
301
313
  }
302
314
  catch { /* ignore */ }
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.5",
4
+ "version": "1.4.6",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
package/src/ai/engine.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
 
15
15
  import { AiState, GroupState, ChatRecord, FollowupState } from './state';
16
- import { LearnBucket, LearnStore, buildSummaryPrompt, cleanSummary, isDuplicate } from './learn';
16
+ import { LearnBucket, LearnStore, buildSummaryPrompt, cleanSummary, isDuplicate } from './learn';
17
17
  import { decideTrigger } from './trigger';
18
18
  import { buildJudgePrompt, buildReplyPrompt, buildUserPrompt, PASS_TOKEN } from './prompt';
19
19
  import { ChatProvider, ChatResult } from './provider';
@@ -47,6 +47,11 @@ export interface AiDeps {
47
47
  rng?: () => number;
48
48
  now?: () => number;
49
49
  fetchImpl?: typeof fetch;
50
+ /**
51
+ * 钩子注册表。主插件会传入进程级共享实例;不传则每次新建,
52
+ * 保证测试/多实例之间互不串钩子。
53
+ */
54
+ hooks?: AiHookRegistry;
50
55
  }
51
56
 
52
57
  const PASS_RE = /^\s*<(?:pass\s*\/?|不回复)>/i;
@@ -97,18 +102,20 @@ export class AiEngine {
97
102
  private searchCache = new Map<string, { at: number; section: string }>();
98
103
  private searchRate = new Map<string, number[]>();
99
104
  private searchUnsupportedUntil = 0;
100
- /** 自动归纳:按作用域累计被挤出的消息 */
101
- private learnStore = new LearnStore();
102
- /** 自动归纳:每个作用域每天的次数,防刷额度 */
103
- private learnDaily = new Map<string, number>();
104
- /** 自动归纳:空闲兜底定时器 */
105
- private learnTimer: any = null;
105
+ /** 自动归纳:按作用域累计被挤出的消息 */
106
+ private learnStore = new LearnStore();
107
+ /** 自动归纳:每个作用域每天的次数,防刷额度 */
108
+ private learnDaily = new Map<string, number>();
109
+ /** 自动归纳:空闲兜底定时器 */
110
+ private learnTimer: any = null;
106
111
 
107
112
  constructor(host: AiHost, deps: AiDeps = {}) {
108
113
  this.host = host;
109
114
  this.config = host.config;
110
115
  this.state = deps.state ?? new AiState();
111
- this.hooks = new AiHookRegistry(host.logger);
116
+ // 默认独立注册表;主插件通过 deps.hooks 注入进程级单例,
117
+ // 这样主插件重载后外部插件注册的钩子不会丢。
118
+ this.hooks = deps.hooks ?? new AiHookRegistry(host.logger);
112
119
  this.provider = deps.provider ?? new ChatProvider(host.config, host.logger);
113
120
  this.names = new NameResolver({
114
121
  getOneBotApi: (session) => host.getOneBotApi(session),
@@ -118,9 +125,9 @@ export class AiEngine {
118
125
  this.rng = deps.rng ?? Math.random;
119
126
  this.now = deps.now ?? Date.now;
120
127
  this.fetchImpl = deps.fetchImpl ?? globalThis.fetch;
121
-
122
- // 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
123
- this.startLearnTimer();
128
+
129
+ // 空闲兜底:消息量迟迟不满阈值时,超时后归纳一次
130
+ this.startLearnTimer();
124
131
  }
125
132
 
126
133
  // ---------------------------------------------------------------- 配置
@@ -288,207 +295,207 @@ export class AiEngine {
288
295
  * 把本次被挤出上下文的消息交给外部插件(用于自动归纳沉淀)。
289
296
  * 失败不影响主流程。
290
297
  */
291
- /**
292
- * 上下文挤出后的两件事:
293
- * 1. 交给外部插件(registerContextEvicted,可选)
294
- * 2. 内建自动归纳:累计到阈值或空闲后总结成一条记忆写回
295
- * 任何一步失败都不影响正常聊天。
296
- */
297
- private emitEvicted(evicted: ChatRecord[], groupKey?: string, session?: any): void {
298
- if (!evicted || !evicted.length) return;
299
-
300
- const isDirect = session?.isDirect === true || !session?.guildId;
301
- const guildId = String(session?.guildId || "");
302
- const userId = String(session?.userId || "");
303
- const kind: "group" | "private" = isDirect ? "private" : "group";
304
- const scopeId = isDirect ? userId : guildId;
305
- if (!scopeId) return;
306
-
307
- const cfg: any = this.config || {};
308
-
309
- // ---------- 1) 分发给外部插件 ----------
310
- if (this.hooks && typeof (this.hooks as any).runContextEvicted === "function") {
311
- const payload = evicted.map((item) => ({
312
- id: item.id,
313
- userId: item.userId,
314
- name: item.name,
315
- role: item.role,
316
- text: item.text,
317
- self: item.self,
318
- at: item.at,
319
- command: item.command,
320
- }));
321
- void this.hooks
322
- .runContextEvicted({
323
- groupId: guildId,
324
- kind,
325
- scopeId,
326
- session,
327
- evicted: payload,
328
- window: this.contextWindow,
329
- })
330
- .catch((error: any) => {
331
- this.host.logger?.warn?.(`[ai-evicted] 分发失败: ${String(error)}`);
332
- });
333
- }
334
-
335
- // ---------- 2) 内建自动归纳 ----------
336
- if (!cfg.memoryAutoLearn) return;
337
- if (!cfg.enableMemory || cfg.memoryAutoLearn === false) return;
338
- if (!this.resolveEnabled(session)) return;
339
- const allow: string[] = Array.isArray(cfg.memoryAutoLearnGroups) ? cfg.memoryAutoLearnGroups.map(String) : [];
340
- if (allow.length && !allow.includes(guildId) && !allow.includes(userId)) return;
341
-
342
- const bucket = this.learnStore.get(kind, scopeId);
343
- const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
344
- const fire = bucket.push(evicted, threshold, this.now());
345
- if (fire) {
346
- void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
347
- }
348
- }
349
-
350
- /** 归纳并(可选)回推到原会话 */
351
- /** 启动空闲兜底定时器;每 5 分钟检查一次 */
352
- private startLearnTimer(): void {
353
- if (this.learnTimer) return;
354
- const cfg: any = this.config || {};
355
- if (!cfg.memoryAutoLearn) return;
356
- const idleHours = Math.max(1, Number(cfg.memoryLearnIdleHours) || 8);
357
- const idleMs = idleHours * 60 * 60 * 1000;
358
- this.learnTimer = setInterval(() => {
359
- try {
360
- const pending = this.learnStore.idleList(this.now(), idleMs);
361
- for (const item of pending) {
362
- void this.learnAndReport(item.kind as any, item.scopeId, item.bucket, "idle");
363
- }
364
- } catch (error: any) {
365
- this.host.logger?.warn?.(`[memory-learn] 空闲检查失败: ${String(error)}`);
366
- }
367
- }, 5 * 60 * 1000);
368
- if (this.learnTimer.unref) this.learnTimer.unref();
369
- }
370
-
371
- /** 资源清理:停止定时器、清空缓存 */
372
- dispose(): void {
373
- if (this.learnTimer) {
374
- clearInterval(this.learnTimer);
375
- this.learnTimer = null;
376
- }
377
- this.learnStore.clear();
378
- this.learnDaily.clear();
379
- this.searchCache.clear();
380
- this.searchRate.clear();
381
- }
382
-
383
- private async learnAndReport(
384
- kind: "group" | "private",
385
- scopeId: string,
386
- bucket: LearnBucket,
387
- reason: string,
388
- session?: any,
389
- ): Promise<void> {
390
- const cfg: any = this.config || {};
391
- const records = bucket.drain();
392
- if (!records.length) return;
393
-
394
- const scope = { kind, id: scopeId } as any;
395
- const summary = await this.summarizeRecords(records, kind, scope, reason);
396
- if (!summary) return;
397
-
398
- if (cfg.memoryLearnPushBack === false) return;
399
-
400
- const text = `刚记住了:${summary}`;
401
- try {
402
- if (kind === "private") {
403
- const bot = (kind === "private" && session?.bot) || null;
404
- const targetBot = bot || this.findBot();
405
- if (targetBot) await targetBot.sendMessage(scopeId, text, { userId: scopeId });
406
- } else {
407
- const targetBot = session?.bot || this.findBot();
408
- if (targetBot) await targetBot.sendMessage(scopeId, text, { guildId: scopeId, channelId: scopeId });
409
- }
410
- } catch (error: any) {
411
- this.host.logger?.warn?.(`[memory-learn] 回推失败 ${kind}:${scopeId}: ${String(error)}`);
412
- }
413
- }
414
-
415
- /** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
416
- private async summarizeRecords(
417
- records: any[],
418
- kind: "group" | "private",
419
- scope: any,
420
- reason: string,
421
- ): Promise<string> {
422
- const cfg: any = this.config || {};
423
-
424
- // 每日上限
425
- const day = new Date();
426
- const dayStamp = `${day.getFullYear()}-${day.getMonth() + 1}-${day.getDate()}`;
427
- const dailyKey = `${kind}:${scope.id}:${dayStamp}`;
428
- const limit = Math.max(1, Number(cfg.memoryLearnDailyLimit) || 30);
429
- const used = this.learnDaily.get(dailyKey) || 0;
430
- if (used >= limit) {
431
- this.host.logger?.info?.(`[memory-learn] 已达每日上限 ${limit}(${kind}:${scope.id})`);
432
- return "";
433
- }
434
-
435
- const prompt = buildSummaryPrompt(records, { kind, selfName: this.selfName });
436
- let raw = "";
437
- try {
438
- const result = await this.provider.chat({
439
- system: prompt.system,
440
- user: prompt.user,
441
- temperature: 0.3,
442
- maxTokens: 400,
443
- });
444
- if (!result || !result.ok) {
445
- this.host.logger?.warn?.(`[memory-learn] 归纳调用失败: ${result && result.error}`);
446
- return "";
447
- }
448
- raw = String(result.text || "");
449
- } catch (error: any) {
450
- this.host.logger?.warn?.(`[memory-learn] 归纳异常: ${String(error)}`);
451
- return "";
452
- }
453
-
454
- const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
455
- let text = cleanSummary(raw, maxChars);
456
- if (!text) return "";
457
-
458
- // 去重
459
- let existing: string[] = [];
460
- try {
461
- const content = await (this.host as any).readMemoryFile(scope);
462
- existing = String(content || "")
463
- .split(/\r?\n---\r?\n/)
464
- .map((b: string) => b.trim())
465
- .filter(Boolean)
466
- .map((b: string) => b.split("\n").slice(1).join("\n").trim() || b);
467
- } catch {
468
- existing = [];
469
- }
470
- const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
471
- if (isDuplicate(text, existing, threshold)) {
472
- this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
473
- return "";
474
- }
475
-
476
- try {
477
- await (this.host as any).saveMemoryToFile("", text, scope, "自动归纳");
478
- this.learnDaily.set(dailyKey, used + 1);
479
- } catch (error: any) {
480
- this.host.logger?.warn?.(`[memory-learn] 写入失败: ${String(error)}`);
481
- return "";
482
- }
483
-
484
- this.host.logger?.info?.(`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${text.length}字`);
485
- return text;
486
- }
487
-
488
- private findBot(): any {
489
- const bots = (this.host as any)?.ctx?.bots || (this.host as any)?.bots || [];
490
- return (bots || []).find((item: any) => item.platform === "onebot") || null;
491
- }
298
+ /**
299
+ * 上下文挤出后的两件事:
300
+ * 1. 交给外部插件(registerContextEvicted,可选)
301
+ * 2. 内建自动归纳:累计到阈值或空闲后总结成一条记忆写回
302
+ * 任何一步失败都不影响正常聊天。
303
+ */
304
+ private emitEvicted(evicted: ChatRecord[], groupKey?: string, session?: any): void {
305
+ if (!evicted || !evicted.length) return;
306
+
307
+ const isDirect = session?.isDirect === true || !session?.guildId;
308
+ const guildId = String(session?.guildId || "");
309
+ const userId = String(session?.userId || "");
310
+ const kind: "group" | "private" = isDirect ? "private" : "group";
311
+ const scopeId = isDirect ? userId : guildId;
312
+ if (!scopeId) return;
313
+
314
+ const cfg: any = this.config || {};
315
+
316
+ // ---------- 1) 分发给外部插件 ----------
317
+ if (this.hooks && typeof (this.hooks as any).runContextEvicted === "function") {
318
+ const payload = evicted.map((item) => ({
319
+ id: item.id,
320
+ userId: item.userId,
321
+ name: item.name,
322
+ role: item.role,
323
+ text: item.text,
324
+ self: item.self,
325
+ at: item.at,
326
+ command: item.command,
327
+ }));
328
+ void this.hooks
329
+ .runContextEvicted({
330
+ groupId: guildId,
331
+ kind,
332
+ scopeId,
333
+ session,
334
+ evicted: payload,
335
+ window: this.contextWindow,
336
+ })
337
+ .catch((error: any) => {
338
+ this.host.logger?.warn?.(`[ai-evicted] 分发失败: ${String(error)}`);
339
+ });
340
+ }
341
+
342
+ // ---------- 2) 内建自动归纳 ----------
343
+ if (!cfg.memoryAutoLearn) return;
344
+ if (!cfg.enableMemory || cfg.memoryAutoLearn === false) return;
345
+ if (!this.resolveEnabled(session)) return;
346
+ const allow: string[] = Array.isArray(cfg.memoryAutoLearnGroups) ? cfg.memoryAutoLearnGroups.map(String) : [];
347
+ if (allow.length && !allow.includes(guildId) && !allow.includes(userId)) return;
348
+
349
+ const bucket = this.learnStore.get(kind, scopeId);
350
+ const threshold = Math.max(1, Math.round(this.contextWindow * (Number(cfg.memoryLearnThresholdScale) || 1)));
351
+ const fire = bucket.push(evicted, threshold, this.now());
352
+ if (fire) {
353
+ void this.learnAndReport(kind, scopeId, bucket, "threshold", session);
354
+ }
355
+ }
356
+
357
+ /** 归纳并(可选)回推到原会话 */
358
+ /** 启动空闲兜底定时器;每 5 分钟检查一次 */
359
+ private startLearnTimer(): void {
360
+ if (this.learnTimer) return;
361
+ const cfg: any = this.config || {};
362
+ if (!cfg.memoryAutoLearn) return;
363
+ const idleHours = Math.max(1, Number(cfg.memoryLearnIdleHours) || 8);
364
+ const idleMs = idleHours * 60 * 60 * 1000;
365
+ this.learnTimer = setInterval(() => {
366
+ try {
367
+ const pending = this.learnStore.idleList(this.now(), idleMs);
368
+ for (const item of pending) {
369
+ void this.learnAndReport(item.kind as any, item.scopeId, item.bucket, "idle");
370
+ }
371
+ } catch (error: any) {
372
+ this.host.logger?.warn?.(`[memory-learn] 空闲检查失败: ${String(error)}`);
373
+ }
374
+ }, 5 * 60 * 1000);
375
+ if (this.learnTimer.unref) this.learnTimer.unref();
376
+ }
377
+
378
+ /** 资源清理:停止定时器、清空缓存 */
379
+ dispose(): void {
380
+ if (this.learnTimer) {
381
+ clearInterval(this.learnTimer);
382
+ this.learnTimer = null;
383
+ }
384
+ this.learnStore.clear();
385
+ this.learnDaily.clear();
386
+ this.searchCache.clear();
387
+ this.searchRate.clear();
388
+ }
389
+
390
+ private async learnAndReport(
391
+ kind: "group" | "private",
392
+ scopeId: string,
393
+ bucket: LearnBucket,
394
+ reason: string,
395
+ session?: any,
396
+ ): Promise<void> {
397
+ const cfg: any = this.config || {};
398
+ const records = bucket.drain();
399
+ if (!records.length) return;
400
+
401
+ const scope = { kind, id: scopeId } as any;
402
+ const summary = await this.summarizeRecords(records, kind, scope, reason);
403
+ if (!summary) return;
404
+
405
+ if (cfg.memoryLearnPushBack === false) return;
406
+
407
+ const text = `刚记住了:${summary}`;
408
+ try {
409
+ if (kind === "private") {
410
+ const bot = (kind === "private" && session?.bot) || null;
411
+ const targetBot = bot || this.findBot();
412
+ if (targetBot) await targetBot.sendMessage(scopeId, text, { userId: scopeId });
413
+ } else {
414
+ const targetBot = session?.bot || this.findBot();
415
+ if (targetBot) await targetBot.sendMessage(scopeId, text, { guildId: scopeId, channelId: scopeId });
416
+ }
417
+ } catch (error: any) {
418
+ this.host.logger?.warn?.(`[memory-learn] 回推失败 ${kind}:${scopeId}: ${String(error)}`);
419
+ }
420
+ }
421
+
422
+ /** 把一批消息归纳成一条记忆并写入对应作用域;返回归纳文本或空 */
423
+ private async summarizeRecords(
424
+ records: any[],
425
+ kind: "group" | "private",
426
+ scope: any,
427
+ reason: string,
428
+ ): Promise<string> {
429
+ const cfg: any = this.config || {};
430
+
431
+ // 每日上限
432
+ const day = new Date();
433
+ const dayStamp = `${day.getFullYear()}-${day.getMonth() + 1}-${day.getDate()}`;
434
+ const dailyKey = `${kind}:${scope.id}:${dayStamp}`;
435
+ const limit = Math.max(1, Number(cfg.memoryLearnDailyLimit) || 30);
436
+ const used = this.learnDaily.get(dailyKey) || 0;
437
+ if (used >= limit) {
438
+ this.host.logger?.info?.(`[memory-learn] 已达每日上限 ${limit}(${kind}:${scope.id})`);
439
+ return "";
440
+ }
441
+
442
+ const prompt = buildSummaryPrompt(records, { kind, selfName: this.selfName });
443
+ let raw = "";
444
+ try {
445
+ const result = await this.provider.chat({
446
+ system: prompt.system,
447
+ user: prompt.user,
448
+ temperature: 0.3,
449
+ maxTokens: 400,
450
+ });
451
+ if (!result || !result.ok) {
452
+ this.host.logger?.warn?.(`[memory-learn] 归纳调用失败: ${result && result.error}`);
453
+ return "";
454
+ }
455
+ raw = String(result.text || "");
456
+ } catch (error: any) {
457
+ this.host.logger?.warn?.(`[memory-learn] 归纳异常: ${String(error)}`);
458
+ return "";
459
+ }
460
+
461
+ const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
462
+ let text = cleanSummary(raw, maxChars);
463
+ if (!text) return "";
464
+
465
+ // 去重
466
+ let existing: string[] = [];
467
+ try {
468
+ const content = await (this.host as any).readMemoryFile(scope);
469
+ existing = String(content || "")
470
+ .split(/\r?\n---\r?\n/)
471
+ .map((b: string) => b.trim())
472
+ .filter(Boolean)
473
+ .map((b: string) => b.split("\n").slice(1).join("\n").trim() || b);
474
+ } catch {
475
+ existing = [];
476
+ }
477
+ const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
478
+ if (isDuplicate(text, existing, threshold)) {
479
+ this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
480
+ return "";
481
+ }
482
+
483
+ try {
484
+ await (this.host as any).saveMemoryToFile("", text, scope, "自动归纳");
485
+ this.learnDaily.set(dailyKey, used + 1);
486
+ } catch (error: any) {
487
+ this.host.logger?.warn?.(`[memory-learn] 写入失败: ${String(error)}`);
488
+ return "";
489
+ }
490
+
491
+ this.host.logger?.info?.(`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${text.length}字`);
492
+ return text;
493
+ }
494
+
495
+ private findBot(): any {
496
+ const bots = (this.host as any)?.ctx?.bots || (this.host as any)?.bots || [];
497
+ return (bots || []).find((item: any) => item.platform === "onebot") || null;
498
+ }
492
499
 
493
500
  // ---------------------------------------------------------------- 点名 / 跟随
494
501
 
package/src/ai/hooks.ts CHANGED
@@ -64,6 +64,21 @@ export class AiHookRegistry {
64
64
 
65
65
  constructor(private logger?: any) {}
66
66
 
67
+ /** 主插件重载后把新实例的 logger 接到同一个注册表上。 */
68
+ setLogger(logger?: any): void {
69
+ if (logger) this.logger = logger;
70
+ }
71
+
72
+ /** 诊断用:当前已注册的钩子数量。 */
73
+ stats(): { sections: number; filters: number; afterReply: number; evicted: number } {
74
+ return {
75
+ sections: this.sections.size,
76
+ filters: this.filters.size,
77
+ afterReply: this.afterReplyHandlers.size,
78
+ evicted: this.evictedHandlers.size,
79
+ };
80
+ }
81
+
67
82
  registerPromptSection(provider: PromptSectionProvider): () => void {
68
83
  this.sections.add(provider);
69
84
  return () => this.sections.delete(provider);
@@ -141,3 +156,33 @@ export class AiHookRegistry {
141
156
  }
142
157
  }
143
158
  }
159
+
160
+ /**
161
+ * 进程级共享的钩子注册表。
162
+ *
163
+ * 背景:meme / chat-style / private 等外部插件只在启动时解析一次
164
+ * `qqgmAiHooks`,之后一直持有这个对象。如果主插件每次重载都 `new` 一个
165
+ * 新注册表,新引擎看到的是空注册表,而外部插件还挂在旧对象上——表现就是
166
+ * 主插件单独重启后表情包不发、聊天风格段消失、私聊用旧配置。
167
+ *
168
+ * 用 globalThis + Symbol.for 做单例:即使插件模块被重新 require、甚至从
169
+ * 不同路径加载了两份,拿到的也是同一个注册表,重载前后对象身份不变。
170
+ */
171
+ const SHARED_HOOKS = Symbol.for('qqgm.ai-hooks-registry');
172
+
173
+ export function getSharedAiHooks(logger?: any): AiHookRegistry {
174
+ const store = globalThis as any;
175
+ let registry: AiHookRegistry = store[SHARED_HOOKS];
176
+ if (!registry) {
177
+ registry = new AiHookRegistry(logger);
178
+ store[SHARED_HOOKS] = registry;
179
+ logger?.info?.(`[ai-hooks] v${registry.version} 注册表已创建(进程级单例)`);
180
+ } else if (logger) {
181
+ registry.setLogger(logger);
182
+ const stats = registry.stats();
183
+ logger.info?.(
184
+ `[ai-hooks] 复用进程级注册表:风格段 ${stats.sections} / 过滤器 ${stats.filters} / 后处理 ${stats.afterReply}`,
185
+ );
186
+ }
187
+ return registry;
188
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * 主插件对外暴露的运行时门面(进程级单例)。
3
+ *
4
+ * 为什么需要它:
5
+ * - 外部插件(qqgm-private 等)会 `ctx.root.get('qqgmAiRuntime')` 之后长期持有该对象;
6
+ * - 如果每次主插件重载都 `set` 一个全新的 `{ config, hooks, chat }` 快照,
7
+ * 外部插件手里的旧快照就永远指向已经销毁的引擎:配置不更新、钩子对不上、
8
+ * chat() 走旧实例;
9
+ * - 这里改成稳定的门面对象,重载只是把 `current` 指针换到新服务,
10
+ * 外部插件持有的引用不变,读到的 config / hooks / chat 永远是最新的。
11
+ */
12
+
13
+ import { AiHookRegistry, getSharedAiHooks } from './hooks';
14
+
15
+ const SHARED_RUNTIME = Symbol.for('qqgm.ai-runtime-facade');
16
+
17
+ export interface AiRuntimeChatRequest {
18
+ system: string;
19
+ user: string;
20
+ temperature?: number;
21
+ maxTokens?: number;
22
+ [key: string]: any;
23
+ }
24
+
25
+ export class AiRuntimeFacade {
26
+ /** 当前存活的主插件服务;主插件卸载后为 null。 */
27
+ current: any = null;
28
+
29
+ bind(service: any): void {
30
+ this.current = service;
31
+ }
32
+
33
+ unbind(service: any): void {
34
+ if (this.current === service) this.current = null;
35
+ }
36
+
37
+ get config(): any {
38
+ return this.current ? this.current.config : {};
39
+ }
40
+
41
+ get hooks(): AiHookRegistry {
42
+ const live = this.current && this.current.ai && this.current.ai.hooks;
43
+ // 服务不在时也返回共享注册表,避免外部插件拿到 null 后直接崩掉。
44
+ return live || getSharedAiHooks();
45
+ }
46
+
47
+ chat(request: AiRuntimeChatRequest): Promise<any> {
48
+ if (!this.current || !this.current.ai) {
49
+ return Promise.resolve({ ok: false, text: '', error: 'qqgm service not loaded' });
50
+ }
51
+ return this.current.ai.chat(request);
52
+ }
53
+ }
54
+
55
+ export function getAiRuntimeFacade(): AiRuntimeFacade {
56
+ const store = globalThis as any;
57
+ let facade: AiRuntimeFacade = store[SHARED_RUNTIME];
58
+ if (!facade) {
59
+ facade = new AiRuntimeFacade();
60
+ store[SHARED_RUNTIME] = facade;
61
+ }
62
+ return facade;
63
+ }
package/src/service.js CHANGED
@@ -8,6 +8,8 @@ const koishi_1 = require("koishi");
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const node_fs_1 = __importDefault(require("node:fs"));
10
10
  const { AiEngine } = require("./ai/engine");
11
+ const { getSharedAiHooks } = require("./ai/hooks");
12
+ const { getAiRuntimeFacade } = require("./ai/runtime");
11
13
  let PLUGIN_VERSION = 'unknown';
12
14
  try {
13
15
  PLUGIN_VERSION = require('../package.json').version || 'unknown';
@@ -284,22 +286,32 @@ class QQGroupManagerService extends koishi_1.Service {
284
286
  this.ctx = ctx;
285
287
  this.config = config;
286
288
  this._logger = ctx.logger('nestim-qq-group-manager');
287
- this.ai = new AiEngine(this);
289
+ // 进程级共享钩子:主插件重载后仍是同一个对象,外部插件注册的钩子不会丢。
290
+ const sharedHooks = getSharedAiHooks(this._logger);
291
+ this.ai = new AiEngine(this, { hooks: sharedHooks });
288
292
  // Koishi 的 Service 注册在插件 fork 作用域,兄弟插件的 inject 拿不到;
289
- // 额外把扩展点挂到 root,外部插件 inject 'qqgmAiHooks' 即可。
293
+ // 额外把扩展点挂到 root,外部插件运行时探测即可。
294
+ //
295
+ // 关键:hooks 与 runtime 都必须是「进程级稳定对象」。主插件单独重载
296
+ // 时不能换成新对象,否则 meme / chat-style / private 手里的旧引用会
297
+ // 指向已销毁的实例:新引擎看不到它们的钩子(表情包不发、风格段丢失),
298
+ // 私聊还会继续用旧配置和旧引擎。
290
299
  try {
291
- ctx.root.set('qqgmAiHooks', this.ai.hooks);
292
- const runtime = {
293
- config: this.config,
294
- hooks: this.ai.hooks,
295
- chat: (request) => this.ai.chat(request),
296
- };
297
- ctx.root.set('qqgmAiRuntime', runtime);
300
+ const hooks = sharedHooks;
301
+ const facade = getAiRuntimeFacade();
302
+ facade.bind(this);
303
+ ctx.root.set('qqgmAiHooks', hooks);
304
+ ctx.root.set('qqgmAiRuntime', facade);
298
305
  ctx.on('dispose', () => {
299
306
  try {
300
- if (ctx.root.get('qqgmAiHooks') === this.ai.hooks)
307
+ facade.unbind(this);
308
+ // 只有当前没有新实例接管时才撤掉对外暴露:旧实例的 dispose
309
+ // 可能晚于新实例的 bind,此时不能把新指针清掉。
310
+ if (facade.current)
311
+ return;
312
+ if (ctx.root.get('qqgmAiHooks') === hooks)
301
313
  ctx.root.set('qqgmAiHooks', undefined);
302
- if (ctx.root.get('qqgmAiRuntime')?.hooks === this.ai.hooks)
314
+ if (ctx.root.get('qqgmAiRuntime') === facade)
303
315
  ctx.root.set('qqgmAiRuntime', undefined);
304
316
  }
305
317
  catch { /* ignore */ }