dsh-klbq 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CSAHuan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # dsh-klbq
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 卡拉彼丘(Strinova)战绩查询的 DSH 插件:按游戏昵称从 [dakanu.com](https://dakanu.com) 取数,
4
+ 渲染成一张长图(排位段位 / 总览 / 模式 / 角色 / 最近对局),并把工具 `klbq_query` 暴露给 agent。
5
+
6
+ ## 提供的工具
7
+
8
+ ### `klbq_query`
9
+
10
+ | 参数 | 类型 | 说明 |
11
+ |---|---|---|
12
+ | `nickname` | string(必填) | 游戏昵称或 UID |
13
+ | `maxMatches` | number | 最近对局条数 0~20,默认 10 |
14
+
15
+ 返回:
16
+
17
+ ```jsonc
18
+ {
19
+ "ok": true,
20
+ "nickname": "ahiahdiawh",
21
+ "level": 62,
22
+ "currentRank": "束缚电子 II", // 排位当前段位
23
+ "topRank": "禁闭夸克 III", // 排位历史最高
24
+ "summary": { "rounds": 30, "winRate": 0.5, "kda": 2.86, "avgDamage": 3220, ... },
25
+ "recent": [ { "result": "win", "mode": "排位爆破", "kda": "8/6/15", "score": "9:4" } ],
26
+ "imagePath": "C:\\Users\\...\\Temp\\dsh-klbq-cards\\ahiahdiawh-1794051495410.png",
27
+ "imageBytes": 413696
28
+ }
29
+ ```
30
+
31
+ 图片写到系统临时目录的 `dsh-klbq-cards/` 下。**工具不返回 base64**——
32
+ 一张 500KB 的 PNG 进上下文会非常浪费,所以「模型看摘要、人看图片」。
33
+
34
+ ## 安装
35
+
36
+ 插件以本地 link 方式挂在 DSH profile 上:
37
+
38
+ ```json
39
+ // ~/.dsh/profiles/<profile>/package.json
40
+ "dependencies": { "dsh-klbq": "link:C:/Users/<you>/.dsh/plugins/dsh-klbq" },
41
+ "dsh": { "profile": { "bundles": [ ..., "dsh-klbq" ] } }
42
+ ```
43
+
44
+ 并把插件目录软链到 profile 的 `node_modules/dsh-klbq`。DSH 重启后生效。
45
+
46
+ ## 两个实现要点(改代码前务必先读)
47
+
48
+ 1. **SNI 阻断**:本机直连 `https://dakanu.com` 会在 TLS 握手阶段被 RST
49
+ (ClientHello 带这个域名就被重置;不带 SNI 直连 IP 能拿到 301/200)。
50
+ 因此请求统一「连 IP + `servername: ''` + `Host` 头」,并 `rejectUnauthorized: false`。
51
+ `servername` 必须是**空字符串**,写成 `undefined` 时 Node 会补成域名 → 必被重置。
52
+ 这条通道只取公开战绩、不传凭据;**不要**用它传输密钥或隐私数据。
53
+
54
+ 2. **两套段位体系**:排位是「至纯物质 / 升格分子 / 虚空原子 / 聚变质子 / 自由中子 /
55
+ 束缚电子 / 禁闭夸克 / 无限超弦 / 奇点」(按 `rank.segment` 号段);
56
+ 挑战赛是「青铜…传奇」(按 `gradeScore` 算)。卡片右上角用排位,别混用。
57
+
58
+ ## 渲染
59
+
60
+ 用系统自带的 Edge / Chrome 无头截图(两趟:先 `--dump-dom` 量内容高度,再按高度截图),
61
+ 不引入 canvas / puppeteer 之类的重依赖。找不到浏览器时可用环境变量 `KLBQ_BROWSER` 指定路径。
62
+
63
+ ## 更新日志
64
+
65
+ ### 0.1.1 — 取数提速
66
+
67
+ dakanu 站点有两个 A 记录,快慢差 **5 倍**(实测搜索接口 5.37s vs 0.93s)。
68
+ 旧版按 DNS 顺序依次尝试,会稳定命中慢的那个,用户感知就是「查一次要八九秒」。
69
+
70
+ - **双 IP 并行对冲**:两个 IP 同时发请求,谁先成功用谁,耗时取决于较快者
71
+ - **连接复用**:一次查询的「搜索 + 详情」共用同一条 TLS 连接,省掉第二次握手
72
+ - **结果缓存**:搜索映射缓存 10 分钟、详情缓存 90 秒,重复查询不再走网络
73
+
74
+ 实测:搜索 3565ms → ~700ms,详情 5555ms → ~1000ms,重复查询整链 ~2s(原 ~9s)。
75
+
76
+ ## 许可
77
+
78
+ MIT
Binary file
@@ -0,0 +1,9 @@
1
+ # 把 dsh-klbq 挂进 DSH 的插件链。
2
+ #
3
+ # entry 的 `id` 与 `name` 都写成 dsh-klbq:id 用于 loader 内定位,
4
+ # name 是包名(node_modules 里解析到的就是它)。
5
+ # 这个插件只注册工具,不注入 UI,所以不需要 Config 之外的额外接线。
6
+ - insert:
7
+ - id: dsh-klbq
8
+ name: dsh-klbq
9
+ config: {}
package/lib/dakanu.js ADDED
@@ -0,0 +1,192 @@
1
+ // dakanu.com 数据访问层。
2
+ //
3
+ // 两个必须保留的细节(都是实测结论,改动前先读):
4
+ //
5
+ // 1) **SNI 阻断**:本机直连 https://dakanu.com 会在 TLS 握手阶段被 RST
6
+ // (ClientHello 里带这个域名就被重置;不带 SNI 直连 IP 能正常拿到 301/200)。
7
+ // 因此统一「连 IP + servername:'' 不发 SNI + Host 头指明站点」,
8
+ // 并设置 rejectUnauthorized:false —— 证书是签给域名的,省略 SNI 后必然对不上。
9
+ // 这条通道只取公开战绩、不传任何凭据;不要用它传输密钥或隐私数据。
10
+ // 注意:servername 必须是**空字符串**,写 undefined 时 Node 会补成域名 → 必被重置。
11
+ //
12
+ // 2) **两套段位体系**:排位是「原子/质子/中子/电子/夸克/超弦…」(按 segment 号段),
13
+ // 挑战赛是「青铜…传奇」(按 gradeScore 算)。卡片右上角用排位,别混用。
14
+
15
+ import https from 'node:https';
16
+ import dns from 'node:dns';
17
+
18
+ const SITE_HOST = 'www.dakanu.com';
19
+ // 2026-11 实测的 A 记录;解析失败时兜底
20
+ const FALLBACK_IPS = ['43.169.14.133', '43.169.13.133'];
21
+ const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
22
+
23
+ let ipCache = { at: 0, ips: [] };
24
+
25
+ // 连接复用:一次查询要走「搜索 + 详情」两次请求,共用一条 TLS 连接能省掉
26
+ // 第二次 0.4~0.7 秒的握手开销。注意 servername 保持空字符串(见 httpsGetOnce 的说明)。
27
+ // 结果缓存:dakanu 后端不稳定(同一接口实测 0.6~25 秒都有),
28
+ // 同一个玩家短时间内重复查询没必要再走网络。搜索映射缓存 10 分钟(昵称极少变),
29
+ // 详情缓存 90 秒(战绩不会秒变)。
30
+ const resultCache = new Map();
31
+ const CACHE_TTL_SEARCH = 10 * 60 * 1000;
32
+ const CACHE_TTL_SUMMONER = 90 * 1000;
33
+ const CACHE_MAX_ENTRIES = 200;
34
+
35
+ function cached(key, ttlMs, loader) {
36
+ const hit = resultCache.get(key);
37
+ if (hit && Date.now() - hit.at < ttlMs) return Promise.resolve(hit.value);
38
+ return loader().then((value) => {
39
+ if (resultCache.size >= CACHE_MAX_ENTRIES) {
40
+ const oldest = resultCache.keys().next().value;
41
+ if (oldest !== undefined) resultCache.delete(oldest);
42
+ }
43
+ resultCache.set(key, { at: Date.now(), value });
44
+ return value;
45
+ });
46
+ }
47
+ const keepAliveAgent = new https.Agent({ keepAlive: true, maxSockets: 4, keepAliveMsecs: 30000 });
48
+
49
+ /** 解析站点 IP:系统 DNS 没被拦(只有 SNI 被拦),失败退回内置列表 */
50
+ async function resolveSiteIps() {
51
+ const now = Date.now();
52
+ if (ipCache.ips.length && now - ipCache.at < 10 * 60 * 1000) return ipCache.ips;
53
+ try {
54
+ const list = await dns.promises.resolve4(SITE_HOST);
55
+ if (list.length) {
56
+ ipCache = { at: now, ips: list };
57
+ return list;
58
+ }
59
+ } catch { /* 用兜底 IP */ }
60
+ return FALLBACK_IPS;
61
+ }
62
+
63
+ function httpsGetOnce(ip, pathname, { timeoutMs = 20000 } = {}) {
64
+ return new Promise((resolve, reject) => {
65
+ const req = https.request({
66
+ host: ip,
67
+ port: 443,
68
+ path: pathname,
69
+ method: 'GET',
70
+ servername: '', // 关键:空字符串,不能是 undefined
71
+ rejectUnauthorized: false, // 证书签给域名;这条通道只取公开数据
72
+ agent: keepAliveAgent, // 复用连接:省下每次 0.4~0.7 秒的 TLS 握手
73
+ headers: {
74
+ host: SITE_HOST,
75
+ 'user-agent': UA,
76
+ accept: 'application/json, text/plain, */*',
77
+ 'accept-language': 'zh-CN,zh;q=0.9',
78
+ 'accept-encoding': 'identity',
79
+ },
80
+ timeout: timeoutMs,
81
+ }, (res) => {
82
+ const chunks = [];
83
+ res.on('data', (c) => chunks.push(c));
84
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString('utf8') }));
85
+ });
86
+ req.on('timeout', () => req.destroy(new Error(`请求超时(${ip}${pathname})`)));
87
+ req.on('error', reject);
88
+ req.end();
89
+ });
90
+ }
91
+
92
+ /**
93
+ * 并行对冲取数。
94
+ *
95
+ * 为什么不能「按 DNS 顺序依次尝试」:站点两个 A 记录**快慢差 5 倍**
96
+ * (实测 43.169.13.133 搜索接口 5.4s,43.169.14.133 只要 0.9s)。
97
+ * 顺序尝试会稳定选中那个慢的,用户看到的就是「查一次要八九秒」。
98
+ * 改成两个 IP 同时发、谁先成功用谁,慢 IP 只做备份,总耗时取决于快的那个。
99
+ */
100
+ export async function dakanuGet(pathname, opts = {}) {
101
+ const ips = await resolveSiteIps();
102
+ if (ips.length === 1) return httpsGetOnce(ips[0], pathname, opts);
103
+
104
+ return new Promise((resolve, reject) => {
105
+ let settled = false;
106
+ let pending = ips.length;
107
+ let lastError = null;
108
+
109
+ const fail = (error) => {
110
+ lastError = error;
111
+ pending -= 1;
112
+ if (pending === 0 && !settled) reject(lastError ?? new Error('dakanu 请求失败'));
113
+ };
114
+
115
+ for (const ip of ips) {
116
+ httpsGetOnce(ip, pathname, opts).then((res) => {
117
+ if (settled) return;
118
+ if (res.status >= 500) { fail(new Error(`HTTP ${res.status}`)); return; }
119
+ settled = true;
120
+ resolve(res);
121
+ }).catch((error) => {
122
+ if (settled) return;
123
+ fail(error);
124
+ });
125
+ }
126
+ });
127
+ }
128
+
129
+ async function dakanuJson(pathname) {
130
+ // 缓存放在这一层最省事:搜索和详情都从这里出去,按 pathname 分档过期。
131
+ const ttl = pathname.startsWith('/api/search/players') ? CACHE_TTL_SEARCH
132
+ : pathname.startsWith('/api/summoner/') ? CACHE_TTL_SUMMONER
133
+ : 60 * 1000;
134
+ return cached(pathname, ttl, async () => {
135
+ const res = await dakanuGet(pathname);
136
+ let json = null;
137
+ try { json = JSON.parse(res.text); } catch { /* 下面统一报错 */ }
138
+ if (!json) throw new Error(`返回非 JSON(HTTP ${res.status})`);
139
+ return json;
140
+ });
141
+ }
142
+
143
+ /** 按昵称搜索玩家 */
144
+ export async function searchPlayers(query) {
145
+ const q = String(query ?? '').trim();
146
+ if (!q) throw new Error('昵称不能为空');
147
+ const json = await dakanuJson(`/api/search/players?q=${encodeURIComponent(q)}`);
148
+ const list = Array.isArray(json?.suggestions) ? json.suggestions : [];
149
+ return list
150
+ .map((s) => ({
151
+ playerId: String(s.playerId ?? ''),
152
+ nickname: String(s.nickname ?? ''),
153
+ exact: s.exact === true,
154
+ level: s.level ?? null,
155
+ }))
156
+ .filter((s) => s.playerId && s.nickname);
157
+ }
158
+
159
+ /** 拉取玩家详情(段位/总览/模式/角色/最近对局) */
160
+ export async function fetchSummoner(playerId, nickname) {
161
+ const qs = nickname ? `?nickname=${encodeURIComponent(nickname)}` : '';
162
+ const json = await dakanuJson(`/api/summoner/${encodeURIComponent(playerId)}${qs}`);
163
+ if (!json?.ok || !json.profile) throw new Error(json?.error || '查询失败:站点未返回战绩数据');
164
+ return json.profile;
165
+ }
166
+
167
+ /** 排位段位表(站点前端 es[]):按 segment 号段映射,段内分 IV~I */
168
+ export const RANKED_TIERS = [
169
+ { id: 'substance', name: '至纯物质', fromSeg: 1, toSeg: 3, divisions: ['III', 'II', 'I'], color: '#6c7178' },
170
+ { id: 'molecule', name: '升格分子', fromSeg: 4, toSeg: 6, divisions: ['III', 'II', 'I'], color: '#c07a52' },
171
+ { id: 'atom', name: '虚空原子', fromSeg: 7, toSeg: 10, divisions: ['IV', 'III', 'II', 'I'], color: '#9aa7b5' },
172
+ { id: 'proton', name: '聚变质子', fromSeg: 11, toSeg: 14, divisions: ['IV', 'III', 'II', 'I'], color: '#d0a63c' },
173
+ { id: 'neutron', name: '自由中子', fromSeg: 15, toSeg: 18, divisions: ['IV', 'III', 'II', 'I'], color: '#28b3a4' },
174
+ { id: 'electron', name: '束缚电子', fromSeg: 19, toSeg: 23, divisions: ['V', 'IV', 'III', 'II', 'I'], color: '#3f8fd6' },
175
+ { id: 'quark', name: '禁闭夸克', fromSeg: 24, toSeg: 28, divisions: ['V', 'IV', 'III', 'II', 'I'], color: '#9b5cd6' },
176
+ { id: 'superstring', name: '无限超弦', fromSeg: 29, toSeg: 29, divisions: [], color: '#d94a44' },
177
+ { id: 'singularity', name: '奇点', fromSeg: 30, toSeg: 30, divisions: [], color: '#d84a4a' },
178
+ ];
179
+
180
+ export function rankedTierOf(segment) {
181
+ const seg = Number(segment);
182
+ if (!Number.isFinite(seg) || seg < 1) return null;
183
+ const tier = RANKED_TIERS.find((t) => seg >= t.fromSeg && seg <= t.toSeg);
184
+ if (!tier) return null;
185
+ return { name: tier.name, division: tier.divisions[seg - tier.fromSeg] ?? '', color: tier.color, segment: seg };
186
+ }
187
+
188
+ export function rankedLabel(segment) {
189
+ const t = rankedTierOf(segment);
190
+ if (!t) return '未定级';
191
+ return t.division ? `${t.name} ${t.division}` : t.name;
192
+ }
package/lib/index.js ADDED
@@ -0,0 +1,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
+
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
+ }
package/lib/render.js ADDED
@@ -0,0 +1,253 @@
1
+ // 长图渲染:手写 HTML → Edge/Chrome 无头截图。
2
+ //
3
+ // 为什么不用 canvas/puppeteer:
4
+ // Electron 主进程里再装一套原生 canvas 很容易和 DSH 自身的 node 版本打架,
5
+ // 而 Edge 是 Windows 预装的,`--screenshot` 已经够用,零依赖。
6
+ //
7
+ // 两趟渲染:先 --dump-dom 量出内容高度,再按该高度截图,
8
+ // 否则固定 window-size 会在长图底部留一大块空白。
9
+
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { execFile } from 'node:child_process';
14
+ import { rankedTierOf } from './dakanu.js';
15
+
16
+ const BROWSERS = [
17
+ 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
18
+ 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
19
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
20
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
21
+ ];
22
+
23
+ export function findBrowser(override) {
24
+ if (override && fs.existsSync(override)) return override;
25
+ const fromEnv = process.env.KLBQ_BROWSER;
26
+ if (fromEnv && fs.existsSync(fromEnv)) return fromEnv;
27
+ for (const p of BROWSERS) if (fs.existsSync(p)) return p;
28
+ return null;
29
+ }
30
+
31
+ const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
32
+ const pct = (v) => `${((Number(v) || 0) * 100).toFixed(1)}%`;
33
+ const num = (v, digits = 0) => {
34
+ const n = Number(v);
35
+ if (!Number.isFinite(n)) return '-';
36
+ return digits ? n.toFixed(digits) : String(Math.round(n));
37
+ };
38
+ const fmtDuration = (s) => {
39
+ const sec = Number(s) || 0;
40
+ return `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
41
+ };
42
+ const fmtTime = (unix) => {
43
+ const t = Number(unix);
44
+ if (!Number.isFinite(t) || t <= 0) return '-';
45
+ const d = new Date(t * 1000);
46
+ const pad = (n) => String(n).padStart(2, '0');
47
+ return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
48
+ };
49
+
50
+ /** 生成整张长图的 HTML */
51
+ export function buildHtml(profile, { width = 900, maxMatches = 10 } = {}) {
52
+ const p = profile ?? {};
53
+ const player = p.player ?? {};
54
+ const presence = p.presence ?? {};
55
+ const summary = p.summary ?? {};
56
+ const modes = Array.isArray(p.modes) ? p.modes : [];
57
+ const roles = Array.isArray(p.roles) ? [...p.roles].sort((a, b) => (b.count ?? 0) - (a.count ?? 0)) : [];
58
+ const matches = Array.isArray(p.matches) ? p.matches.slice(0, maxMatches) : [];
59
+ const roleName = new Map(roles.map((r) => [String(r.roleId), r.name]));
60
+
61
+ // 排位:当前 / 历史最高
62
+ const curTier = rankedTierOf(p.rank?.segment);
63
+ const topTier = rankedTierOf(p.rank?.historicalSegment);
64
+ const curName = curTier ? (curTier.division ? `${curTier.name} ${curTier.division}` : curTier.name) : '未定级';
65
+ const topName = topTier ? (topTier.division ? `${topTier.name} ${topTier.division}` : topTier.name) : '未定级';
66
+ const curColor = curTier?.color ?? '#9aa7b5';
67
+ const topColor = topTier?.color ?? '#cdd8ee';
68
+ const online = presence.state === 'online' || presence.statusText === 'online';
69
+
70
+ const statCell = (label, value, sub = '') => `
71
+ <div class="cell">
72
+ <div class="cell-label">${esc(label)}</div>
73
+ <div class="cell-value">${esc(value)}</div>
74
+ ${sub ? `<div class="cell-sub">${esc(sub)}</div>` : ''}
75
+ </div>`;
76
+
77
+ const modeRows = modes.map((m) => `
78
+ <div class="mode-row">
79
+ <div class="mode-name">${esc(m.label ?? m.mode ?? '-')}</div>
80
+ <div class="mode-bar"><i style="width:${Math.min(100, (Number(m.winRate) || 0) * 100).toFixed(1)}%"></i></div>
81
+ <div class="mode-win">${pct(m.winRate)}</div>
82
+ <div class="mode-kda">KDA ${num(m.kda, 2)}</div>
83
+ <div class="mode-dmg">均伤 ${num(m.avgDamage)}</div>
84
+ <div class="mode-rounds">${num(m.rounds)} 场</div>
85
+ </div>`).join('');
86
+
87
+ const roleRows = roles.slice(0, 8).map((r) => `
88
+ <div class="role-row">
89
+ <div class="role-name">${esc(r.name ?? r.roleId)}</div>
90
+ <div class="role-bar"><i style="width:${Math.min(100, (Number(r.winRate) || 0) * 100).toFixed(1)}%"></i></div>
91
+ <div class="role-win">${pct(r.winRate)}</div>
92
+ <div class="role-kd">KD ${num(r.kd, 2)}</div>
93
+ <div class="role-dmg">均伤 ${num(r.avgDamage)}</div>
94
+ <div class="role-count">${num(r.count)} 场</div>
95
+ </div>`).join('');
96
+
97
+ const matchRows = matches.map((m) => {
98
+ const win = m.result === 'win';
99
+ const delta = Number(m.divisionScoreDelta);
100
+ const deltaTxt = Number.isFinite(delta) && delta !== 0 ? `${delta > 0 ? '+' : ''}${delta}` : '';
101
+ return `
102
+ <div class="match-row ${win ? 'win' : 'lose'}">
103
+ <div class="m-result">${win ? '胜' : '负'}</div>
104
+ <div class="m-mode">${esc(m.modeLabel ?? m.mode ?? '-')}</div>
105
+ <div class="m-role">${esc(roleName.get(String(m.roleId)) ?? '-')}</div>
106
+ <div class="m-kda">${num(m.kills)}/${num(m.deaths)}/${num(m.assists)}</div>
107
+ <div class="m-score">${num(m.myScore)}:${num(m.opponentScore)}</div>
108
+ <div class="m-dur">${fmtDuration(m.durationSeconds)}</div>
109
+ <div class="m-delta">${esc(deltaTxt)}</div>
110
+ <div class="m-time">${fmtTime(m.playedAt)}</div>
111
+ </div>`;
112
+ }).join('');
113
+
114
+ return `<!doctype html>
115
+ <html lang="zh-CN"><head><meta charset="utf-8">
116
+ <style>
117
+ * { box-sizing: border-box; }
118
+ body { margin: 0; width: ${width}px; background: #0d1220; color: #e8eefc;
119
+ font-family: "Microsoft YaHei UI", "Microsoft YaHei", "PingFang SC", sans-serif; }
120
+ .wrap { padding: 28px 32px 34px; }
121
+ .head { display: flex; align-items: flex-start; justify-content: space-between; }
122
+ .nick { font-size: 40px; font-weight: 700; letter-spacing: .5px; line-height: 1.1; }
123
+ .sub { margin-top: 10px; font-size: 16px; color: #8fa0bf; }
124
+ .dot { display: inline-block; width: 9px; height: 9px; border-radius: 50%; margin-right: 6px;
125
+ background: ${online ? '#3ddc84' : '#6b7280'}; }
126
+ .badge { padding: 12px 18px; border-radius: 12px; text-align: right; min-width: 240px;
127
+ border: 1px solid ${curColor}55; background: ${curColor}14; }
128
+ .badge-row { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; }
129
+ .badge-row + .badge-row { margin-top: 6px; }
130
+ .badge-label { font-size: 13px; color: #8fa0bf; letter-spacing: .5px; }
131
+ .badge-top { font-size: 20px; font-weight: 600; }
132
+ .badge-cur { font-size: 28px; font-weight: 700; }
133
+ .badge .sc { margin-top: 8px; font-size: 13px; color: #8fa0bf; text-align: right; }
134
+ .card { margin-top: 22px; background: #141c2f; border: 1px solid #1f2a44; border-radius: 16px; padding: 18px 20px; }
135
+ .card h3 { margin: 0 0 14px; font-size: 17px; font-weight: 600; color: #9fb0cc; letter-spacing: 1px; }
136
+ .grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }
137
+ .cell { background: #101728; border-radius: 12px; padding: 14px 16px; }
138
+ .cell-label { font-size: 13px; color: #7f8fad; }
139
+ .cell-value { margin-top: 6px; font-size: 28px; font-weight: 700; color: #ffffff; }
140
+ .cell-sub { margin-top: 2px; font-size: 12px; color: #6f80a0; }
141
+ .mode-row, .role-row { display: grid; grid-template-columns: 96px 1fr 72px 96px 108px 64px;
142
+ align-items: center; gap: 10px; padding: 9px 0; border-top: 1px solid #1b2437; font-size: 14px; }
143
+ .mode-row:first-child, .role-row:first-child { border-top: none; }
144
+ .mode-name, .role-name { color: #dfe8ff; font-weight: 600; }
145
+ .mode-bar, .role-bar { height: 8px; background: #1d2740; border-radius: 6px; overflow: hidden; }
146
+ .mode-bar i, .role-bar i { display: block; height: 100%; border-radius: 6px;
147
+ background: linear-gradient(90deg, #3a8dff, #43e0c8); }
148
+ .mode-win, .role-win { color: #43e0c8; font-weight: 600; text-align: right; }
149
+ .mode-kda, .mode-dmg, .mode-rounds, .role-kd, .role-dmg, .role-count { color: #93a4c4; text-align: right; }
150
+ .match-row { display: grid; grid-template-columns: 44px 92px 76px 92px 62px 54px 52px 1fr;
151
+ align-items: center; gap: 8px; padding: 8px 0; border-top: 1px solid #1b2437; font-size: 14px; }
152
+ .match-row:first-child { border-top: none; }
153
+ .m-result { width: 32px; text-align: center; border-radius: 6px; font-weight: 700; font-size: 13px; padding: 3px 0; }
154
+ .match-row.win .m-result { background: #1d4f3a; color: #43e0c8; }
155
+ .match-row.lose .m-result { background: #4a2130; color: #ff7a94; }
156
+ .m-mode { color: #cfdaf2; }
157
+ .m-role { color: #93a4c4; }
158
+ .m-kda { color: #dfe8ff; font-weight: 600; }
159
+ .m-score, .m-dur { color: #8b9cbb; }
160
+ .m-delta { color: #7fd6a8; text-align: right; }
161
+ .match-row.lose .m-delta { color: #ff92a6; }
162
+ .m-time { color: #6f80a0; text-align: right; }
163
+ .foot { margin-top: 20px; font-size: 12px; color: #5d6a83; display: flex; justify-content: space-between; }
164
+ </style></head>
165
+ <body><div class="wrap">
166
+ <div class="head">
167
+ <div>
168
+ <div class="nick">${esc(player.nickname ?? '-')}</div>
169
+ <div class="sub">
170
+ <span class="dot"></span>${online ? '在线' : '离线'}
171
+ ${presence.regionLabel ? ` · ${esc(presence.regionLabel)}` : ''}
172
+ · Lv.${num(player.level)}
173
+ </div>
174
+ </div>
175
+ <div class="badge">
176
+ <div class="badge-row">
177
+ <span class="badge-label">历史最高</span>
178
+ <span class="badge-top" style="color:${topColor}">${esc(topName)}</span>
179
+ </div>
180
+ <div class="badge-row">
181
+ <span class="badge-label">当前段位</span>
182
+ <span class="badge-cur" style="color:${curColor}">${esc(curName)}</span>
183
+ </div>
184
+ ${p.rank?.divisionScore ? `<div class="sc">段位分 ${num(p.rank.divisionScore)}</div>` : ''}
185
+ </div>
186
+ </div>
187
+
188
+ <div class="card">
189
+ <h3>总览</h3>
190
+ <div class="grid">
191
+ ${statCell('场次', num(summary.rounds), `${num(summary.wins)} 胜 ${num(summary.losses)} 负`)}
192
+ ${statCell('胜率', pct(summary.winRate), '')}
193
+ ${statCell('KDA', num(summary.kda, 2), `KD ${num(summary.kd, 2)}`)}
194
+ ${statCell('场均伤害', num(summary.avgDamage), `总伤害 ${num(summary.damage)}`)}
195
+ ${statCell('场均击杀', num(summary.avgKill, 1), `助攻 ${num(summary.avgAssist, 1)}`)}
196
+ ${statCell('MVP 率', pct(summary.mvpRate), `爆头率 ${pct(summary.headshotRate)}`)}
197
+ </div>
198
+ </div>
199
+
200
+ ${modeRows ? `<div class="card"><h3>模式表现</h3>${modeRows}</div>` : ''}
201
+ ${roleRows ? `<div class="card"><h3>角色表现(按场次)</h3>${roleRows}</div>` : ''}
202
+ ${matchRows ? `<div class="card"><h3>最近对局</h3>${matchRows}</div>` : ''}
203
+
204
+ <div class="foot">
205
+ <span>数据来源 dakanu.com · 仅供娱乐参考</span>
206
+ <span>${fmtTime(Math.floor((player.queriedAt ?? Date.now()) / 1000))}</span>
207
+ </div>
208
+ <div id="__h" style="display:none"></div>
209
+ <script>document.getElementById('__h').textContent = String(Math.ceil(document.body.getBoundingClientRect().height));</script>
210
+ </div></body></html>`;
211
+ }
212
+
213
+ function runBrowser(bin, args, { timeoutMs = 60000 } = {}) {
214
+ return new Promise((resolve, reject) => {
215
+ execFile(bin, args, { timeout: timeoutMs, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => {
216
+ if (error && !stdout) {
217
+ return reject(new Error(`${path.basename(bin)} 执行失败:${error.message}${stderr ? ` / ${String(stderr).slice(0, 200)}` : ''}`));
218
+ }
219
+ resolve({ stdout: String(stdout ?? ''), stderr: String(stderr ?? '') });
220
+ });
221
+ });
222
+ }
223
+
224
+ /** HTML → PNG(两趟:先量高度,再按高度截图) */
225
+ export async function renderPng(html, { width = 900, timeoutMs = 90000, browserPath } = {}) {
226
+ const bin = findBrowser(browserPath);
227
+ if (!bin) throw new Error('没找到 Edge/Chrome,无法渲染图片(可用环境变量 KLBQ_BROWSER 指定)');
228
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-klbq-'));
229
+ const htmlFile = path.join(dir, 'card.html');
230
+ const pngFile = path.join(dir, 'card.png');
231
+ const profileDir = path.join(dir, 'profile');
232
+ fs.writeFileSync(htmlFile, html, 'utf8');
233
+ const url = 'file:///' + htmlFile.replace(/\\/g, '/');
234
+ const base = ['--headless=new', '--disable-gpu', '--no-sandbox', '--no-first-run', '--disable-extensions',
235
+ '--hide-scrollbars', '--force-device-scale-factor=2', `--user-data-dir=${profileDir}`];
236
+
237
+ let height = 1600;
238
+ try {
239
+ const { stdout } = await runBrowser(bin, [...base, '--dump-dom', url], { timeoutMs });
240
+ const m = /id="__h"[^>]*>\s*(\d+)\s*</.exec(stdout);
241
+ if (m) height = Math.max(400, Math.min(20000, Number(m[1])));
242
+ } catch { /* 量高度失败就退回默认值 */ }
243
+
244
+ await runBrowser(bin, [...base, `--screenshot=${pngFile}`, `--window-size=${width},${height}`, url], { timeoutMs });
245
+ for (let i = 0; i < 20; i += 1) {
246
+ if (fs.existsSync(pngFile) && fs.statSync(pngFile).size > 1000) break;
247
+ await new Promise((r) => setTimeout(r, 150));
248
+ }
249
+ const buf = fs.readFileSync(pngFile);
250
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* 清理失败无妨 */ }
251
+ if (!buf.length) throw new Error('截图结果为空');
252
+ return buf;
253
+ }
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "dsh-klbq",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "卡拉彼丘(Strinova)战绩查询:按昵称从 dakanu.com 取数并渲染长图(排位段位/总览/模式/角色/最近对局),作为 DSH 工具 klbq_query 暴露给 agent",
5
+ "type": "module",
6
+ "main": "./lib/index.js",
7
+ "icon": "./assets/icon.png",
8
+ "author": "CSAHuan",
9
+ "license": "MIT",
10
+ "homepage": "https://github.com/CSAHuan/dsh-klbq#readme",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/CSAHuan/dsh-klbq.git"
14
+ },
15
+ "bugs": {
16
+ "url": "https://github.com/CSAHuan/dsh-klbq/issues"
17
+ },
18
+ "keywords": [
19
+ "dsh",
20
+ "dsh-plugin",
21
+ "deepseek-harness",
22
+ "klbq",
23
+ "strinova",
24
+ "dakanu",
25
+ "game-stats"
26
+ ],
27
+ "engines": {
28
+ "node": ">=22.12.0"
29
+ },
30
+ "files": [
31
+ "lib",
32
+ "cordis.patch.yml",
33
+ "assets/icon.png",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "dsh": {
38
+ "bundle": {
39
+ "patch": "./cordis.patch.yml"
40
+ },
41
+ "compatibility": {
42
+ "dshReleases": {
43
+ "0.2.0-rc.2": "compatible",
44
+ "0.2.1-rc.2": "compatible"
45
+ }
46
+ }
47
+ },
48
+ "peerDependencies": {
49
+ "@deepseek-ai/cordis": "^4.0.4",
50
+ "@deepseek-ai/dsh": "^0.2.0-rc.2"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "@deepseek-ai/cordis": {
54
+ "optional": true
55
+ },
56
+ "@deepseek-ai/dsh": {
57
+ "optional": true
58
+ }
59
+ }
60
+ }