dsh-mobile-plugin 0.5.30 → 0.5.32

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.
@@ -1,138 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * CLI 品牌图标:注册表里每条都带一枚官方 SVG(`icon` 字段),这里是它的本地缓存。
5
- *
6
- * 为什么放插件侧而不写进 App:清单里有二十来家、还在增加,每一家一枚 SVG 写进 App 就是
7
- * 每来一家都要发一次版。插件本来就在读那份注册表,顺手把图标存下来,App 只按 id 取。
8
- *
9
- * 缓存规则与注册表同一套:内存 → 盘上(`$DSH_HOME/storages/mobile-plugin/acp-icons.json`)
10
- * → 联网拉。拉不到就空着,App 退回首字母 / 方块 —— 不为此报错。
11
- *
12
- * **原样留着那份 SVG,只摘掉尺寸与命名空间**:注册表里的图标有的靠 `fill`(Claude、OpenCode),
13
- * 有的靠 `stroke`(Agoragentic 那一枚就是圆 + 三条线)。在插件这一层按「只留 path」筛一遍,
14
- * 描边那几家会整枚消失;颜色也不在这里定 —— App 侧统一把 `currentColor` 换成主题色(见
15
- * `components/CliLogo`),与 `ModelVendorBadge` 同一个规矩。
16
- */
17
-
18
- const fs = require('node:fs');
19
- const path = require('node:path');
20
-
21
- const paths = require('../../shared/paths');
22
-
23
- /** 一次拉取最多等这么久:图标是锦上添花,不该把「列清单」拖住。 */
24
- const FETCH_TIMEOUT_MS = 6000;
25
-
26
- /** 一枚图标在缓存里最多留这么久;注册表按小时更新,图标跟着换。 */
27
- const TTL_MS = 7 * 24 * 60 * 60 * 1000;
28
-
29
- let memory = null;
30
-
31
- function cacheFile() {
32
- return path.join(paths.dshHome(), 'storages', 'mobile-plugin', 'acp-icons.json');
33
- }
34
-
35
- /**
36
- * 官方 SVG → App 画得出来的那一份。
37
- *
38
- * 去掉 `width` / `height` 与 `xmlns`(尺寸由调用方给),`viewBox` 留着 —— 各家的画布不一样
39
- * (Claude 是 1200×1200),丢了它图标会被裁掉大半。解析不出 `viewBox` 的按 24×24 处理,
40
- * 这是 Simple Icons 的通用画布,也是我们内置那四家的。
41
- */
42
- function normalizeSvg(svg) {
43
- if (typeof svg !== 'string' || !svg.trim()) return '';
44
- const open = svg.match(/<svg\b[^>]*>/i);
45
- if (!open) return '';
46
- const viewBox = (open[0].match(/viewBox="([^"]+)"/i) || [])[1] || '0 0 24 24';
47
- const inner = svg
48
- .slice(open.index + open[0].length)
49
- .replace(/<\/svg>\s*$/i, '')
50
- .replace(/<(defs|style|title|desc)\b[\s\S]*?<\/\1>/gi, '')
51
- .trim();
52
- if (!inner) return '';
53
- return `<svg viewBox="${viewBox}" xmlns="http://www.w3.org/2000/svg">${inner}</svg>`;
54
- }
55
-
56
- function readCache() {
57
- try {
58
- const raw = JSON.parse(fs.readFileSync(cacheFile(), 'utf8'));
59
- const icons = raw && raw.icons && typeof raw.icons === 'object' ? raw.icons : null;
60
- if (!icons) return null;
61
- return { fetchedAt: Number(raw.fetchedAt) || 0, icons };
62
- } catch {
63
- return null;
64
- }
65
- }
66
-
67
- function writeCache(icons) {
68
- try {
69
- fs.mkdirSync(path.dirname(cacheFile()), { recursive: true });
70
- fs.writeFileSync(cacheFile(), JSON.stringify({ fetchedAt: Date.now(), icons }), 'utf8');
71
- } catch {
72
- // 写不进去只是下次再拉一遍。
73
- }
74
- }
75
-
76
- /**
77
- * id → SVG 串。
78
- *
79
- * `entries` 是注册表条目(`{ id, icon }`),`want` 是要哪几个 id(空 = 全都要)。
80
- * 只拉还没缓存过的那些,并发拉完;任何一条失败就当它没有图标。
81
- */
82
- async function loadIcons(entries, want) {
83
- const targets = (Array.isArray(entries) ? entries : [])
84
- .filter((entry) => entry && typeof entry.id === 'string' && typeof entry.icon === 'string' && entry.icon);
85
- const naming = new Set(Array.isArray(want) ? want : []);
86
- const picked = (list) => {
87
- const out = {};
88
- for (const id of naming.size ? naming : Object.keys(list)) {
89
- if (list[id]) out[id] = list[id];
90
- }
91
- return out;
92
- };
93
- if (targets.length === 0) return {};
94
-
95
- const now = Date.now();
96
- if (!memory || now - memory.at >= TTL_MS) {
97
- const cached = readCache();
98
- memory = cached && now - cached.fetchedAt < TTL_MS
99
- ? { at: cached.fetchedAt, icons: cached.icons }
100
- : { at: 0, icons: (cached && cached.icons) || {} };
101
- }
102
- const icons = { ...memory.icons };
103
- const todo = targets.filter((entry) => (naming.size === 0 || naming.has(entry.id)) && !icons[entry.id]);
104
- if (todo.length > 0) {
105
- const fetched = await Promise.all(todo.map(async (entry) => {
106
- try {
107
- const res = await fetch(entry.icon, {
108
- // 这台 CDN 不认裸 Node 的默认 UA(会回 403)。
109
- headers: { accept: 'image/svg+xml', 'user-agent': 'dsh-mobile' },
110
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
111
- });
112
- if (!res.ok) return null;
113
- const svg = normalizeSvg(await res.text());
114
- return svg ? [entry.id, svg] : null;
115
- } catch {
116
- return null;
117
- }
118
- }));
119
- let changed = false;
120
- for (const pair of fetched) {
121
- if (!pair) continue;
122
- icons[pair[0]] = pair[1];
123
- changed = true;
124
- }
125
- if (changed) {
126
- memory = { at: now, icons };
127
- writeCache(icons);
128
- }
129
- }
130
- return picked(icons);
131
- }
132
-
133
- /** 测试用:清掉内存那一份。 */
134
- function resetIconMemory() {
135
- memory = null;
136
- }
137
-
138
- module.exports = { loadIcons, normalizeSvg, resetIconMemory, cacheFile };
@@ -1,132 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * CLI 会话里的图片:发出去的那几张,以及手机上回头按 id 来取字节。
5
- *
6
- * 为什么不能沿用宿主那套附件:宿主的 `attachments/v1` 是会话日志的东西,CLI 会话根本没有
7
- * 那份日志。所以图片在插件这边自己存一份 —— 手机发上来时字节已经在盘上(分片上传落在收件箱),
8
- * 这里按**内容哈希**把它认下来(同一张图发两次只有一份),历史和实时帧里只下发一个
9
- * `attachmentId`,字节等手机真的要看时再取。
10
- *
11
- * 两条形状与宿主那套逐字对齐(App 的 `useAttachmentUri` / 原生通道只认这两种):
12
- *
13
- * - `{ type:'image', attachment:{ attachmentId, mediaType, name?, width?, height? } }`
14
- * —— 历史和实时帧里的引用;
15
- * - `/session/attachment` 上的三种回法:默认整份 base64、`raw:true` 走分块信封、
16
- * `dims:true` 只要宽高。
17
- *
18
- * 宽高在存的时候就量好(`imageSizeOf` 读文件头):不带它的话 App 只能先按 240 方盒占位、
19
- * 等解码完再变高,贴底的列表里那一跳就是「内容先停对了又被顶回去」。
20
- */
21
-
22
- const crypto = require('node:crypto');
23
- const fs = require('node:fs');
24
- const fsp = require('node:fs/promises');
25
- const path = require('node:path');
26
-
27
- const paths = require('../../shared/paths');
28
- const { imageSizeOf } = require('../local-images.js');
29
-
30
- /** 单张上限:与宿主那侧的附件限制同一个量级(10MB),超了就在发送时回绝。 */
31
- const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
32
-
33
- /** 只认这四种:App 的图片块本来就只有这几种,别的一律当不支持。 */
34
- const MEDIA_EXT = {
35
- 'image/png': 'png',
36
- 'image/jpeg': 'jpg',
37
- 'image/webp': 'webp',
38
- 'image/gif': 'gif',
39
- };
40
-
41
- function imageRoot() {
42
- return path.join(paths.dshHome(), 'storages', 'mobile-plugin', 'cli-images');
43
- }
44
-
45
- /** 内容哈希当 id(与宿主那套同一个口径:64 位小写十六进制)。 */
46
- function idOf(bytes) {
47
- return crypto.createHash('sha256').update(bytes).digest('hex');
48
- }
49
-
50
- function objectPath(attachmentId) {
51
- if (typeof attachmentId !== 'string' || !/^[0-9a-f]{64}$/.test(attachmentId)) return null;
52
- return path.join(imageRoot(), attachmentId);
53
- }
54
-
55
- /** 存一份字节 + 一份元数据(媒体类型与名字),回引用块用的那几格。 */
56
- async function saveImage({ bytes, mediaType, name }) {
57
- const type = typeof mediaType === 'string' && MEDIA_EXT[mediaType] ? mediaType : 'image/png';
58
- if (!Buffer.isBuffer(bytes) || bytes.length === 0) return null;
59
- if (bytes.length > MAX_IMAGE_BYTES) return null;
60
- const attachmentId = idOf(bytes);
61
- const target = objectPath(attachmentId);
62
- const root = imageRoot();
63
- await fsp.mkdir(root, { recursive: true });
64
- // 同一张图第二次发过来:文件已经在,元数据也够用,别再写一遍。
65
- if (!fs.existsSync(target)) await fsp.writeFile(target, bytes);
66
- const size = imageSizeOf(bytes);
67
- const meta = { mediaType: type, ...(typeof name === 'string' && name ? { name } : {}), ...(size || {}) };
68
- try {
69
- await fsp.writeFile(`${target}.json`, JSON.stringify(meta), 'utf8');
70
- } catch {
71
- // 元数据写不进去也不该让这一发失败:媒体类型还能从文件头猜。
72
- }
73
- return { attachmentId, ...meta };
74
- }
75
-
76
- /** 按 id 取回元数据(不认识 / 不在了回 null)。 */
77
- function metaOf(attachmentId) {
78
- const target = objectPath(attachmentId);
79
- if (!target) return null;
80
- try {
81
- const raw = JSON.parse(fs.readFileSync(`${target}.json`, 'utf8'));
82
- if (!raw || typeof raw !== 'object') return null;
83
- return {
84
- attachmentId,
85
- mediaType: typeof raw.mediaType === 'string' && MEDIA_EXT[raw.mediaType] ? raw.mediaType : 'image/png',
86
- ...(typeof raw.name === 'string' && raw.name ? { name: raw.name } : {}),
87
- ...(Number.isFinite(raw.width) && Number.isFinite(raw.height) ? { width: raw.width, height: raw.height } : {}),
88
- };
89
- } catch {
90
- return null;
91
- }
92
- }
93
-
94
- /** 按 id 打开字节(返回 `{ path, size }`;不在了回 null)。 */
95
- function openImage(attachmentId) {
96
- const target = objectPath(attachmentId);
97
- if (!target) return null;
98
- try {
99
- const stat = fs.statSync(target);
100
- if (!stat.isFile() || stat.size <= 0) return null;
101
- return { path: target, size: stat.size, ...(metaOf(attachmentId) || {}) };
102
- } catch {
103
- return null;
104
- }
105
- }
106
-
107
- /** 历史 / 实时帧里的引用块(App 的 `extractImages` 认这一种)。 */
108
- function imageBlockOf(meta) {
109
- if (!meta || typeof meta.attachmentId !== 'string') return null;
110
- return {
111
- type: 'image',
112
- attachment: {
113
- attachmentId: meta.attachmentId,
114
- mediaType: meta.mediaType,
115
- ...(meta.name ? { name: meta.name } : {}),
116
- ...(meta.width && meta.height ? { width: meta.width, height: meta.height } : {}),
117
- },
118
- mediaType: meta.mediaType,
119
- ...(meta.name ? { name: meta.name } : {}),
120
- ...(meta.width && meta.height ? { width: meta.width, height: meta.height } : {}),
121
- };
122
- }
123
-
124
- module.exports = {
125
- MAX_IMAGE_BYTES,
126
- MEDIA_EXT,
127
- imageRoot,
128
- saveImage,
129
- metaOf,
130
- openImage,
131
- imageBlockOf,
132
- };