dsh-klbq 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,175 +1,196 @@
1
- // dsh-klbq — 卡拉彼丘战绩查询插件。
2
- //
3
- // 只做一件事:把一个 `klbq_query` 工具挂进 DSH,让 agent(以及通过桥接接进来的 QQ)
4
- // 能按昵称查战绩,并把结果渲染成一张长图落到本地文件。
5
- //
6
- // 设计取舍:
7
- // - 不返回 base64 图片。工具结果是进模型上下文的,一张 500KB 的 PNG 变成 base64 会把
8
- // 上下文撑爆;改成「写文件 + 返回路径 + 关键数据摘要」,模型看摘要、人看图片。
9
- // - 不依赖 canvas/puppeteer:用系统自带 Edge 无头截图(见 render.js 的说明)。
10
-
11
- import fs from 'node:fs';
12
- import os from 'node:os';
13
- import path from 'node:path';
14
-
15
- import { searchPlayers, fetchSummoner, rankedLabel, rankedTierOf } from './dakanu.js';
16
- import { buildHtml, renderPng } from './render.js';
17
-
18
- export const name = 'dsh-klbq';
19
- export const inject = ['tools'];
20
-
21
- const DEFAULT_MAX_MATCHES = 10;
22
-
23
- /** 图片输出目录:系统临时目录下,避免污染用户工作区 */
24
- function cardDir() {
25
- const dir = path.join(os.tmpdir(), 'dsh-klbq-cards');
26
- fs.mkdirSync(dir, { recursive: true });
27
- return dir;
28
- }
29
-
30
- const pct = (v) => `${((Number(v) || 0) * 100).toFixed(1)}%`;
31
- const num = (v, d = 0) => (Number.isFinite(Number(v)) ? (d ? Number(v).toFixed(d) : String(Math.round(Number(v)))) : '-');
32
-
33
- function summaryText(value) {
34
- if (!value?.ok) return `查询失败:${value?.error ?? '未知错误'}`;
35
- const s = value.summary ?? {};
36
- const lines = [
37
- `${value.nickname}(Lv.${value.level ?? '-'})`,
38
- `当前段位:${value.currentRank} 历史最高:${value.topRank}`,
39
- `场次 ${num(s.rounds)} 胜率 ${pct(s.winRate)} KDA ${num(s.kda, 2)} 均伤 ${num(s.avgDamage)}`,
40
- `图片:${value.imagePath}`,
41
- ];
42
- if (value.recent?.length) {
43
- lines.push(`最近 ${value.recent.length} 场:` + value.recent.map((m) => `${m.result === 'win' ? '胜' : '负'} ${m.kda}`).join(' / '));
44
- }
45
- return lines.join('\n');
46
- }
47
-
48
- /**
49
- * 昵称 → 图片。抽成独立函数,方便测试/复用。
50
- * @param {string} nickname
51
- * @param {{maxMatches?: number, browserPath?: string, width?: number}} options
52
- */
53
- export async function queryPlayer(nickname, options = {}) {
54
- const q = String(nickname ?? '').trim();
55
- if (!q) throw new Error('nickname 不能为空');
56
-
57
- const candidates = await searchPlayers(q);
58
- if (!candidates.length) throw new Error(`没找到玩家「${q}」,检查游戏昵称是否正确`);
59
-
60
- // 精确匹配 > 前缀匹配 > 第一个候选
61
- const lower = q.toLowerCase();
62
- const pick = candidates.find((c) => c.nickname.toLowerCase() === lower)
63
- ?? candidates.find((c) => c.nickname.toLowerCase().startsWith(lower))
64
- ?? candidates[0];
65
-
66
- const profile = await fetchSummoner(pick.playerId, pick.nickname);
67
- const maxMatches = Math.max(0, Math.min(20, Number(options.maxMatches ?? DEFAULT_MAX_MATCHES) || DEFAULT_MAX_MATCHES));
68
- const width = Number(options.width ?? 900) || 900;
69
-
70
- const html = buildHtml(profile, { width, maxMatches });
71
- const buffer = await renderPng(html, { width, browserPath: options.browserPath });
72
-
73
- const safeName = String(profile.player?.nickname ?? pick.nickname).replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 40);
74
- const file = path.join(cardDir(), `${safeName}-${Date.now()}.png`);
75
- fs.writeFileSync(file, buffer);
76
-
77
- const s = profile.summary ?? {};
78
- const matches = Array.isArray(profile.matches) ? profile.matches.slice(0, maxMatches) : [];
79
- return {
80
- ok: true,
81
- nickname: profile.player?.nickname ?? pick.nickname,
82
- playerId: pick.playerId,
83
- level: profile.player?.level ?? null,
84
- currentRank: rankedLabel(profile.rank?.segment),
85
- topRank: rankedLabel(profile.rank?.historicalSegment),
86
- currentSegment: profile.rank?.segment ?? null,
87
- topSegment: profile.rank?.historicalSegment ?? null,
88
- summary: {
89
- rounds: s.rounds ?? null,
90
- wins: s.wins ?? null,
91
- losses: s.losses ?? null,
92
- winRate: s.winRate ?? null,
93
- kda: s.kda ?? null,
94
- kd: s.kd ?? null,
95
- avgDamage: s.avgDamage ?? null,
96
- avgKill: s.avgKill ?? null,
97
- mvpRate: s.mvpRate ?? null,
98
- headshotRate: s.headshotRate ?? null,
99
- },
100
- matches: matches.length,
101
- recent: matches.map((m) => ({
102
- result: m.result,
103
- mode: m.modeLabel ?? m.mode ?? null,
104
- kda: `${num(m.kills)}/${num(m.deaths)}/${num(m.assists)}`,
105
- score: `${num(m.myScore)}:${num(m.opponentScore)}`,
106
- })),
107
- imagePath: file,
108
- imageBytes: buffer.length,
109
- };
110
- }
111
-
112
- const OUTPUT_SCHEMA = {
113
- type: 'object',
114
- properties: {
115
- ok: { type: 'boolean' },
116
- error: { type: 'string' },
117
- nickname: { type: 'string' },
118
- playerId: { type: 'string' },
119
- level: { type: 'number' },
120
- currentRank: { type: 'string' },
121
- topRank: { type: 'string' },
122
- imagePath: { type: 'string' },
123
- imageBytes: { type: 'number' },
124
- },
125
- };
126
-
127
- const DEFINITION = {
128
- name: 'klbq_query',
129
- description:
130
- '查询卡拉彼丘(Strinova)玩家战绩。按游戏昵称在 dakanu.com 取数,'
131
- + '渲染一张包含排位段位(当前/历史最高)、总览、模式、角色、最近对局的长图,'
132
- + '图片写到本地并返回路径与关键数据摘要。',
133
- parameters: {
134
- type: 'object',
135
- properties: {
136
- nickname: { type: 'string', description: '游戏昵称或 UID,例如 ahiahdiawh' },
137
- maxMatches: { type: 'number', description: `最近对局条数,0~20,默认 ${DEFAULT_MAX_MATCHES}` },
138
- },
139
- required: ['nickname'],
140
- additionalProperties: false,
141
- },
142
- output: {
143
- schema: OUTPUT_SCHEMA,
144
- render: (_args, value) => [{ type: 'text', text: summaryText(value) }],
145
- },
146
- async resolve(args) {
147
- try {
148
- return await queryPlayer(args?.nickname, { maxMatches: args?.maxMatches });
149
- } catch (error) {
150
- return { ok: false, error: String(error?.message ?? error) };
151
- }
152
- },
153
- };
154
-
155
- export function apply(ctx) {
156
- // 加载自检:插件装好了但没被 loader 挂上时,光看「没报错」分辨不出来。
157
- // 每次 apply 往临时目录追加一行,够判断 DSH 到底有没有把它载入。
158
- const marker = path.join(os.tmpdir(), 'dsh-klbq-plugin.log');
159
- const note = (msg) => {
160
- try { fs.appendFileSync(marker, `[${new Date().toISOString()}] ${msg}\n`); } catch { /* 自检写不进去不影响主流程 */ }
161
- };
162
- note('apply() 已执行');
163
-
164
- try {
165
- const dispose = ctx.tools.register(DEFINITION);
166
- note('klbq_query 注册成功');
167
- ctx.effect(() => () => {
168
- try { dispose?.(); } catch { /* 卸载失败不该拖垮进程退出 */ }
169
- }, 'dsh-klbq: klbq_query tool');
170
- } catch (error) {
171
- // 不抛出:插件挂不上也不该让 DSH 启动失败,但必须留下原因。
172
- note(`klbq_query 注册失败:${error?.message ?? error}`);
173
- ctx.logger?.warn?.(`dsh-klbq: klbq_query 注册失败:${error?.message ?? error}`);
174
- }
175
- }
1
+ // dsh-klbq — 卡拉彼丘战绩查询插件。
2
+ //
3
+ // 只做一件事:把一个 `klbq_query` 工具挂进 DSH,让 agent(以及通过桥接接进来的 QQ)
4
+ // 能按昵称查战绩,并把结果渲染成一张长图落到本地文件。
5
+ //
6
+ // 设计取舍:
7
+ // - 不返回 base64 图片。工具结果是进模型上下文的,一张 500KB 的 PNG 变成 base64 会把
8
+ // 上下文撑爆;改成「写文件 + 返回路径 + 关键数据摘要」,模型看摘要、人看图片。
9
+ // - 不依赖 canvas/puppeteer:用系统自带 Edge 无头截图(见 render.js 的说明)。
10
+
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+
15
+ import { searchPlayers, fetchSummoner, rankedLabel, rankedTierOf } from './dakanu.js';
16
+ import { buildHtml, renderPng } from './render.js';
17
+ import { detectQQBot, installQQBotBridge } from './qqbot.js';
18
+
19
+ export const name = 'dsh-klbq';
20
+ export const inject = ['tools'];
21
+
22
+ const DEFAULT_MAX_MATCHES = 10;
23
+
24
+ /** 图片输出目录:系统临时目录下,避免污染用户工作区 */
25
+ function cardDir() {
26
+ const dir = path.join(os.tmpdir(), 'dsh-klbq-cards');
27
+ fs.mkdirSync(dir, { recursive: true });
28
+ return dir;
29
+ }
30
+
31
+ const pct = (v) => `${((Number(v) || 0) * 100).toFixed(1)}%`;
32
+ const num = (v, d = 0) => (Number.isFinite(Number(v)) ? (d ? Number(v).toFixed(d) : String(Math.round(Number(v)))) : '-');
33
+
34
+ function summaryText(value) {
35
+ if (!value?.ok) return `查询失败:${value?.error ?? '未知错误'}`;
36
+ const s = value.summary ?? {};
37
+ const lines = [
38
+ `${value.nickname}(Lv.${value.level ?? '-'})`,
39
+ `当前段位:${value.currentRank} 历史最高:${value.topRank}`,
40
+ `场次 ${num(s.rounds)} 胜率 ${pct(s.winRate)} KDA ${num(s.kda, 2)} 均伤 ${num(s.avgDamage)}`,
41
+ `图片:${value.imagePath}`,
42
+ ];
43
+ if (value.recent?.length) {
44
+ lines.push(`最近 ${value.recent.length} 场:` + value.recent.map((m) => `${m.result === 'win' ? '胜' : '负'} ${m.kda}`).join(' / '));
45
+ }
46
+ return lines.join('\n');
47
+ }
48
+
49
+ /**
50
+ * 昵称 → 图片。抽成独立函数,方便测试/复用。
51
+ * @param {string} nickname
52
+ * @param {{maxMatches?: number, browserPath?: string, width?: number}} options
53
+ */
54
+ export async function queryPlayer(nickname, options = {}) {
55
+ const q = String(nickname ?? '').trim();
56
+ if (!q) throw new Error('nickname 不能为空');
57
+
58
+ const candidates = await searchPlayers(q);
59
+ if (!candidates.length) throw new Error(`没找到玩家「${q}」,检查游戏昵称是否正确`);
60
+
61
+ // 精确匹配 > 前缀匹配 > 第一个候选
62
+ const lower = q.toLowerCase();
63
+ const pick = candidates.find((c) => c.nickname.toLowerCase() === lower)
64
+ ?? candidates.find((c) => c.nickname.toLowerCase().startsWith(lower))
65
+ ?? candidates[0];
66
+
67
+ const profile = await fetchSummoner(pick.playerId, pick.nickname);
68
+ const maxMatches = Math.max(0, Math.min(20, Number(options.maxMatches ?? DEFAULT_MAX_MATCHES) || DEFAULT_MAX_MATCHES));
69
+ const width = Number(options.width ?? 900) || 900;
70
+
71
+ const html = buildHtml(profile, { width, maxMatches });
72
+ const buffer = await renderPng(html, { width, browserPath: options.browserPath });
73
+
74
+ const safeName = String(profile.player?.nickname ?? pick.nickname).replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 40);
75
+ const file = path.join(cardDir(), `${safeName}-${Date.now()}.png`);
76
+ fs.writeFileSync(file, buffer);
77
+
78
+ const s = profile.summary ?? {};
79
+ const matches = Array.isArray(profile.matches) ? profile.matches.slice(0, maxMatches) : [];
80
+ return {
81
+ ok: true,
82
+ nickname: profile.player?.nickname ?? pick.nickname,
83
+ playerId: pick.playerId,
84
+ level: profile.player?.level ?? null,
85
+ currentRank: rankedLabel(profile.rank?.segment),
86
+ topRank: rankedLabel(profile.rank?.historicalSegment),
87
+ currentSegment: profile.rank?.segment ?? null,
88
+ topSegment: profile.rank?.historicalSegment ?? null,
89
+ summary: {
90
+ rounds: s.rounds ?? null,
91
+ wins: s.wins ?? null,
92
+ losses: s.losses ?? null,
93
+ winRate: s.winRate ?? null,
94
+ kda: s.kda ?? null,
95
+ kd: s.kd ?? null,
96
+ avgDamage: s.avgDamage ?? null,
97
+ avgKill: s.avgKill ?? null,
98
+ mvpRate: s.mvpRate ?? null,
99
+ headshotRate: s.headshotRate ?? null,
100
+ },
101
+ matches: matches.length,
102
+ recent: matches.map((m) => ({
103
+ result: m.result,
104
+ mode: m.modeLabel ?? m.mode ?? null,
105
+ kda: `${num(m.kills)}/${num(m.deaths)}/${num(m.assists)}`,
106
+ score: `${num(m.myScore)}:${num(m.opponentScore)}`,
107
+ })),
108
+ imagePath: file,
109
+ imageBytes: buffer.length,
110
+ };
111
+ }
112
+
113
+ const OUTPUT_SCHEMA = {
114
+ type: 'object',
115
+ properties: {
116
+ ok: { type: 'boolean' },
117
+ error: { type: 'string' },
118
+ nickname: { type: 'string' },
119
+ playerId: { type: 'string' },
120
+ level: { type: 'number' },
121
+ currentRank: { type: 'string' },
122
+ topRank: { type: 'string' },
123
+ imagePath: { type: 'string' },
124
+ imageBytes: { type: 'number' },
125
+ },
126
+ };
127
+
128
+ const DEFINITION = {
129
+ name: 'klbq_query',
130
+ description:
131
+ '查询卡拉彼丘(Strinova)玩家战绩。按游戏昵称在 dakanu.com 取数,'
132
+ + '渲染一张包含排位段位(当前/历史最高)、总览、模式、角色、最近对局的长图,'
133
+ + '图片写到本地并返回路径与关键数据摘要。'
134
+ + '在 QQ 机器人等即时通讯通道里,拿到 imagePath 后应调用 present 把它声明为交付物,'
135
+ + '图片会随本轮自动发送给用户。',
136
+ parameters: {
137
+ type: 'object',
138
+ properties: {
139
+ nickname: { type: 'string', description: '游戏昵称或 UID,例如 ahiahdiawh' },
140
+ maxMatches: { type: 'number', description: `最近对局条数,0~20,默认 ${DEFAULT_MAX_MATCHES}` },
141
+ },
142
+ required: ['nickname'],
143
+ additionalProperties: false,
144
+ },
145
+ output: {
146
+ schema: OUTPUT_SCHEMA,
147
+ render: (_args, value) => [{ type: 'text', text: summaryText(value) }],
148
+ },
149
+ async resolve(args) {
150
+ try {
151
+ return await queryPlayer(args?.nickname, { maxMatches: args?.maxMatches });
152
+ } catch (error) {
153
+ return { ok: false, error: String(error?.message ?? error) };
154
+ }
155
+ },
156
+ };
157
+
158
+ export function apply(ctx, config = {}) {
159
+ // 加载自检:插件装好了但没被 loader 挂上时,光看「没报错」分辨不出来。
160
+ // 每次 apply 往临时目录追加一行,够判断 DSH 到底有没有把它载入。
161
+ const marker = path.join(os.tmpdir(), 'dsh-klbq-plugin.log');
162
+ const note = (msg) => {
163
+ try { fs.appendFileSync(marker, `[${new Date().toISOString()}] ${msg}\n`); } catch { /* 自检写不进去不影响主流程 */ }
164
+ };
165
+ note('apply() 已执行');
166
+
167
+ try {
168
+ const dispose = ctx.tools.register(DEFINITION);
169
+ note('klbq_query 注册成功');
170
+ ctx.effect(() => () => {
171
+ try { dispose?.(); } catch { /* 卸载失败不该拖垮进程退出 */ }
172
+ }, 'dsh-klbq: klbq_query tool');
173
+ } catch (error) {
174
+ // 不抛出:插件挂不上也不该让 DSH 启动失败,但必须留下原因。
175
+ note(`klbq_query 注册失败:${error?.message ?? error}`);
176
+ ctx.logger?.warn?.(`dsh-klbq: klbq_query 注册失败:${error?.message ?? error}`);
177
+ }
178
+
179
+ // ── QQ 官方机器人通道适配 ──
180
+ // dsh-qqbot 的 /klbq 不会命中它自己的命令表,最终作为普通消息进 agent,
181
+ // 所以这里把「收到 /klbq 该怎么做」挂到 system prompt 上。
182
+ try {
183
+ const qqbotConfig = config?.integrations?.qqbot ?? {};
184
+ if (qqbotConfig.promptInjection === false) {
185
+ note('QQ 机器人适配:已按配置禁用');
186
+ } else if (detectQQBot()) {
187
+ const ok = installQQBotBridge(ctx, { logger: ctx.logger, prompt: qqbotConfig.prompt });
188
+ note(`QQ 机器人适配:${ok ? '已挂载' : '挂载失败'}`);
189
+ } else {
190
+ note('QQ 机器人适配:未检测到 @tencent-connect/dsh-qqbot,跳过');
191
+ }
192
+ } catch (error) {
193
+ note(`QQ 机器人适配异常:${error?.message ?? error}`);
194
+ ctx.logger?.warn?.(`dsh-klbq: QQ 机器人适配异常:${error?.message ?? error}`);
195
+ }
196
+ }
package/lib/qqbot.js ADDED
@@ -0,0 +1,143 @@
1
+ // 与 @tencent-connect/dsh-qqbot(QQ 官方机器人通道)的适配层。
2
+ //
3
+ // 为什么是「提示词注入」而不是注册斜杠命令:
4
+ // dsh-qqbot 的命令表是硬编码的(dist/commands/index.js 的 buildCommandList),
5
+ // 没有对外扩展点,第三方插件加不进 /klbq。但它的 slashCommand 中间件对
6
+ // **未注册**的命令是 `await next()` 放行的(qqbot-nodejs/dist/middleware/
7
+ // slash-command.js 第 124-128 行),所以 `/klbq 昵称` 不会被吞掉,会照常
8
+ // 进入 agent 回合。于是我们要做的只是教会 agent 收到这类消息该干什么。
9
+ //
10
+ // 代价:注入的段落会出现在每个回合的 system prompt 里(约 150 token)。
11
+ // 不需要的话可以在插件配置里关掉:integrations.qqbot.promptInjection = false。
12
+
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import { createRequire } from 'node:module';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ const QQ_BOT_PACKAGE = '@tencent-connect/dsh-qqbot';
20
+ const SECTION_NAME = 'dsh-klbq:qqbot-usage';
21
+ const PKG_ENTRY = QQ_BOT_PACKAGE + '/package.json';
22
+
23
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
24
+
25
+ let detected; // undefined = 未探测过
26
+
27
+ /**
28
+ * 在 node_modules 里按目录结构逐级向上找这个包。
29
+ *
30
+ * 插件常常以 `link:` 方式挂在 `~/.dsh/plugins/<name>`,而依赖装在
31
+ * `~/.dsh/profiles/<profile>/node_modules`——不是它的祖先目录,
32
+ * 单靠 require.resolve 会漏判。所以这里同时扫 profile 目录。
33
+ */
34
+ function existsAsPackage(dir) {
35
+ try {
36
+ return fs.existsSync(path.join(dir, QQ_BOT_PACKAGE, 'package.json'));
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ function probeFileSystem() {
43
+ // 1) 从插件自身目录逐级向上找 node_modules
44
+ let dir = HERE;
45
+ for (let i = 0; i < 6; i += 1) {
46
+ if (existsAsPackage(path.join(dir, 'node_modules'))) return true;
47
+ const parent = path.dirname(dir);
48
+ if (parent === dir) break;
49
+ dir = parent;
50
+ }
51
+
52
+ // 2) 扫 DSH profile 的 node_modules(link: 场景的常规位置)
53
+ try {
54
+ const dshHome = path.join(os.homedir(), '.dsh');
55
+ const profilesDir = path.join(dshHome, 'profiles');
56
+ for (const profile of fs.readdirSync(profilesDir).slice(0, 20)) {
57
+ if (existsAsPackage(path.join(profilesDir, profile, 'node_modules'))) return true;
58
+ }
59
+ } catch { /* 没有 .dsh 目录就用别的手段 */ }
60
+
61
+ return false;
62
+ }
63
+
64
+ /** 判断 DSH 里有没有装 QQ 机器人通道(装了就认为需要适配)。结果会缓存。 */
65
+ export function detectQQBot() {
66
+ if (detected !== undefined) return detected;
67
+
68
+ const require = createRequire(import.meta.url);
69
+ for (const spec of [PKG_ENTRY, QQ_BOT_PACKAGE]) {
70
+ try {
71
+ require.resolve(spec);
72
+ detected = true;
73
+ return detected;
74
+ } catch { /* 继续试下一种手段 */ }
75
+ }
76
+
77
+ detected = probeFileSystem();
78
+ return detected;
79
+ }
80
+
81
+ /** 测试用:清掉探测缓存 */
82
+ export function resetQQBotDetection() {
83
+ detected = undefined;
84
+ }
85
+
86
+ /** 注入给 agent 的使用说明(保持简短,它每轮都在上下文里) */
87
+ export const QQBOT_PROMPT = [
88
+ '## 卡拉彼丘战绩查询(dsh-klbq)',
89
+ '',
90
+ '当用户消息以 `/klbq` 或 `klbq` 开头,或直接要求查卡拉彼丘(Strinova)战绩时:',
91
+ '1. 昵称 = 命令后面的**全部**文字,可能含空格,不要去头去尾随意截断。',
92
+ '2. 调用 `klbq_query` 工具(参数 `nickname`,可选 `maxMatches` 0~20)。',
93
+ '3. 工具返回 `imagePath`(本地 PNG 绝对路径)。若当前通道支持发文件,',
94
+ ' 紧接着调用 `present` 把该路径声明为交付物,图片会自动发到聊天里;',
95
+ ' 同时用一两句话点出段位、场次、胜率这几个关键数字,不要复述整张图。',
96
+ '4. 返回 `ok:false` 时把 `error` 原样告诉用户,**不要**编造数据。',
97
+ ].join('\n');
98
+
99
+ /** 判断 DSH 里有没有装 QQ 机器人通道(装了就认为需要适配) */
100
+
101
+ /**
102
+ * 把 /klbq 的使用说明挂到 system prompt 上。
103
+ *
104
+ * 契约与 dsh-qqbot 自身一致(dist/session/session-manager.js 的
105
+ * registerScopePromptInjection):`(assembly, context, next)` 瀑布流,
106
+ * 先 await next() 拿到下游组装结果,再追加 section。
107
+ *
108
+ * @param {any} ctx cordis 上下文
109
+ * @param {{logger?: any, prompt?: string, enabled?: boolean}} [options]
110
+ * @returns {boolean} 是否成功挂载
111
+ */
112
+ export function installQQBotBridge(ctx, options = {}) {
113
+ if (typeof ctx?.on !== 'function') return false;
114
+
115
+ const text = options.prompt ?? QQBOT_PROMPT;
116
+ const logger = options.logger;
117
+
118
+ const handler = async (assembly, context, next) => {
119
+ const assembled = await next();
120
+ // 只在有 agent 的回合注入;非 agent 的组装(如摘要压缩)不动。
121
+ if (!context?.agent) return assembled;
122
+ const sections = Array.isArray(assembled?.sections) ? assembled.sections : [];
123
+ // 幂等:同一个组装里已经有我们的段落就不再叠加。
124
+ if (sections.some((s) => s?.name === SECTION_NAME)) return assembled;
125
+ return { ...assembled, sections: [...sections, { name: SECTION_NAME, order: 95, text }] };
126
+ };
127
+
128
+ try {
129
+ const dispose = ctx.on('system-prompt/assemble', handler);
130
+ logger?.info?.('dsh-klbq: 已注入 QQ 机器人(/klbq)使用说明');
131
+ if (typeof ctx.effect === 'function') {
132
+ ctx.effect(() => () => {
133
+ try { dispose?.(); } catch { /* 卸载失败不影响进程 */ }
134
+ }, 'dsh-klbq: qqbot system-prompt hook');
135
+ }
136
+ return true;
137
+ } catch (error) {
138
+ logger?.warn?.(`dsh-klbq: QQ 机器人适配挂载失败:${error?.message ?? error}`);
139
+ return false;
140
+ }
141
+ }
142
+
143
+ export { SECTION_NAME };