@yangyangyuyu/dsh-inventory-panel 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +78 -2
- package/client.js +894 -0
- package/cordis.patch.yml +3 -0
- package/docs/DETAIL.md +52 -0
- package/icon.svg +6 -0
- package/index.js +640 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +48 -3
package/index.js
ADDED
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
/** Host half of the inventory panel: live plugin/skill inventory plus local skill editing. */
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { inflateRawSync } from 'node:zlib';
|
|
6
|
+
|
|
7
|
+
export const name = 'dsh-inventory-panel';
|
|
8
|
+
export const inject = ['webServer', 'skills', 'sessions'];
|
|
9
|
+
|
|
10
|
+
const LIST_ROUTE = '/api/dsh-inventory/list';
|
|
11
|
+
const SKILL_ROUTE = '/api/dsh-inventory/skill';
|
|
12
|
+
const SAVE_ROUTE = '/api/dsh-inventory/skill/save';
|
|
13
|
+
const TOGGLE_ROUTE = '/api/dsh-inventory/skill/enable';
|
|
14
|
+
const DELETE_ROUTE = '/api/dsh-inventory/skill/delete';
|
|
15
|
+
const IMPORT_ROUTE = '/api/dsh-inventory/skill/import';
|
|
16
|
+
|
|
17
|
+
const NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
|
|
18
|
+
const BODY_LIMIT = 200 * 1024;
|
|
19
|
+
const DESCRIPTION_LIMIT = 1024;
|
|
20
|
+
|
|
21
|
+
function readJson(path) {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
24
|
+
} catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function dshHome() {
|
|
30
|
+
const fromEnv = process.env.DSH_HOME;
|
|
31
|
+
return typeof fromEnv === 'string' && fromEnv.trim() !== '' ? fromEnv : join(homedir(), '.dsh');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function agentsHome() {
|
|
35
|
+
const fromEnv = process.env.DSH_AGENTS_HOME;
|
|
36
|
+
return typeof fromEnv === 'string' && fromEnv.trim() !== '' ? fromEnv : join(homedir(), '.agents');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function profileInfo() {
|
|
40
|
+
const home = dshHome();
|
|
41
|
+
const profile = process.env.DSH_PROFILE || 'desktop';
|
|
42
|
+
const dir = process.env.DSH_PROFILE_DIR || join(home, 'profiles', profile);
|
|
43
|
+
return { home, profile, dir };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function packageRoots(profileDir, home) {
|
|
47
|
+
return [join(profileDir, 'node_modules'), join(home, 'profiles', 'node_modules')];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function findManifest(packageName, roots) {
|
|
51
|
+
for (const root of roots) {
|
|
52
|
+
const candidate = join(root, packageName, 'package.json');
|
|
53
|
+
if (existsSync(candidate)) return candidate;
|
|
54
|
+
}
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function repoUrl(pkg) {
|
|
59
|
+
const url = pkg?.repository?.url;
|
|
60
|
+
if (typeof url !== 'string') return undefined;
|
|
61
|
+
return url.replace(/^git\+/, '').replace(/^github:/, 'https://github.com/').replace(/\.git$/, '');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Plain first paragraph of a package README, for plugins with a thin description. */
|
|
65
|
+
function readSummary(dir) {
|
|
66
|
+
const candidates = ['README.zh.md', 'README.zh-CN.md', 'readme.zh.md', 'README.md', 'readme.md'];
|
|
67
|
+
for (const candidate of candidates) {
|
|
68
|
+
const path = join(dir, candidate);
|
|
69
|
+
if (!existsSync(path)) continue;
|
|
70
|
+
try {
|
|
71
|
+
const summary = firstParagraph(readFileSync(path, 'utf8'));
|
|
72
|
+
if (summary !== '') return summary;
|
|
73
|
+
} catch {}
|
|
74
|
+
}
|
|
75
|
+
return '';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function firstParagraph(markdown) {
|
|
79
|
+
const collected = [];
|
|
80
|
+
let inFence = false;
|
|
81
|
+
for (const raw of markdown.split(/\r?\n/)) {
|
|
82
|
+
const line = raw.trim();
|
|
83
|
+
if (line.startsWith('```')) {
|
|
84
|
+
inFence = !inFence;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (inFence) continue;
|
|
88
|
+
if (line === '') {
|
|
89
|
+
if (collected.length > 0) break;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (/^#{1,6}\s/.test(line)) continue;
|
|
93
|
+
if (/^[![<|]/.test(line)) continue;
|
|
94
|
+
if (/^[-*+>]\s/.test(line)) continue;
|
|
95
|
+
if (/^[A-Za-z0-9 ._-]+:\s*$/.test(line)) continue;
|
|
96
|
+
collected.push(line);
|
|
97
|
+
}
|
|
98
|
+
return collected.join(' ')
|
|
99
|
+
.replace(/!\[[^\]]*\]\([^)]*\)/g, '')
|
|
100
|
+
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
|
|
101
|
+
.replace(/[`*_]/g, '')
|
|
102
|
+
.replace(/\s+/g, ' ')
|
|
103
|
+
.trim()
|
|
104
|
+
.slice(0, 260);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function describePlugin(dep, spec, roots, enabledBundles) {
|
|
108
|
+
const manifestPath = findManifest(dep, roots);
|
|
109
|
+
const pkg = manifestPath === undefined ? undefined : readJson(manifestPath);
|
|
110
|
+
const version = typeof pkg?.version === 'string' ? pkg.version : String(spec).replace(/^[a-z]+:/i, '');
|
|
111
|
+
return {
|
|
112
|
+
name: dep,
|
|
113
|
+
version,
|
|
114
|
+
description: typeof pkg?.description === 'string' ? pkg.description : '',
|
|
115
|
+
summary: manifestPath === undefined ? '' : readSummary(dirname(manifestPath)),
|
|
116
|
+
homepage: pkg?.homepage || repoUrl(pkg) || '',
|
|
117
|
+
enabled: enabledBundles.includes(dep),
|
|
118
|
+
path: manifestPath === undefined ? join(roots[0], dep) : dirname(manifestPath)
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function collectPlugins() {
|
|
123
|
+
const { home, profile, dir } = profileInfo();
|
|
124
|
+
const manifest = readJson(join(dir, 'package.json')) || {};
|
|
125
|
+
const dependencies = manifest.dependencies && typeof manifest.dependencies === 'object' ? manifest.dependencies : {};
|
|
126
|
+
const bundles = Array.isArray(manifest?.dsh?.profile?.bundles) ? manifest.dsh.profile.bundles : [];
|
|
127
|
+
const roots = packageRoots(dir, home);
|
|
128
|
+
|
|
129
|
+
const plugins = [];
|
|
130
|
+
for (const [dep, spec] of Object.entries(dependencies)) {
|
|
131
|
+
try {
|
|
132
|
+
plugins.push(describePlugin(dep, spec, roots, bundles));
|
|
133
|
+
} catch {
|
|
134
|
+
plugins.push({ name: dep, version: String(spec), description: '', summary: '', homepage: '', enabled: bundles.includes(dep), path: '' });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
plugins.sort((left, right) => left.name.localeCompare(right.name));
|
|
138
|
+
|
|
139
|
+
const builtins = bundles
|
|
140
|
+
.filter((bundle) => typeof bundle === 'string' && dependencies[bundle] === undefined)
|
|
141
|
+
.map((bundle) => ({ name: bundle, version: '', enabled: true }));
|
|
142
|
+
|
|
143
|
+
return { home, profile, plugins, bundles: builtins };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function activeCwds(ctx) {
|
|
147
|
+
const cwds = new Set();
|
|
148
|
+
try {
|
|
149
|
+
if (typeof ctx.sessions?.list === 'function') {
|
|
150
|
+
for (const session of ctx.sessions.list()) {
|
|
151
|
+
const cwd = session?.header?.cwd;
|
|
152
|
+
if (typeof cwd === 'string' && cwd !== '') cwds.add(cwd);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
} catch {}
|
|
156
|
+
if (typeof process.cwd === 'function') cwds.add(process.cwd());
|
|
157
|
+
return [...cwds];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function skillRoots(ctx) {
|
|
161
|
+
const { home } = profileInfo();
|
|
162
|
+
const roots = [];
|
|
163
|
+
for (const cwd of activeCwds(ctx)) {
|
|
164
|
+
roots.push({ id: 'project-dsh', label: '项目 .dsh/skills', dir: join(cwd, '.dsh', 'skills'), rank: 1, writable: true });
|
|
165
|
+
roots.push({ id: 'project-agents', label: '项目 .agents/skills', dir: join(cwd, '.agents', 'skills'), rank: 1, writable: true });
|
|
166
|
+
}
|
|
167
|
+
roots.push({ id: 'user-agents', label: '用户 ~/.agents/skills', dir: join(agentsHome(), 'skills'), rank: 2, writable: true });
|
|
168
|
+
roots.push({ id: 'user-dsh', label: '用户 DSH_HOME/skills', dir: join(home, 'skills'), rank: 3, writable: true });
|
|
169
|
+
return roots;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function parseFrontmatter(text) {
|
|
173
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
|
|
174
|
+
if (match === null) return { data: {}, body: text };
|
|
175
|
+
const data = {};
|
|
176
|
+
for (const line of match[1].split(/\r?\n/)) {
|
|
177
|
+
const parsed = /^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(line);
|
|
178
|
+
if (parsed === null) continue;
|
|
179
|
+
let value = parsed[2].trim();
|
|
180
|
+
if (value.length > 1 && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))) {
|
|
181
|
+
value = value.slice(1, -1);
|
|
182
|
+
}
|
|
183
|
+
if (value === 'true') value = true;
|
|
184
|
+
else if (value === 'false') value = false;
|
|
185
|
+
data[parsed[1]] = value;
|
|
186
|
+
}
|
|
187
|
+
return { data, body: text.slice(match[0].length) };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function splitFrontmatter(text) {
|
|
191
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
|
|
192
|
+
if (match === null) return { lines: null, body: text };
|
|
193
|
+
return { lines: match[1].split(/\r?\n/), body: text.slice(match[0].length) };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Rewrite only the named frontmatter keys, keeping every other line (nested blocks included) intact. */
|
|
197
|
+
function applyFrontmatter(text, updates) {
|
|
198
|
+
const { lines, body } = splitFrontmatter(text);
|
|
199
|
+
const kept = lines === null ? [] : lines.slice();
|
|
200
|
+
for (const key of Object.keys(updates)) {
|
|
201
|
+
const value = updates[key];
|
|
202
|
+
const pattern = new RegExp('^' + key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ':');
|
|
203
|
+
const index = kept.findIndex((line) => pattern.test(line));
|
|
204
|
+
if (value === undefined || value === null || value === '') {
|
|
205
|
+
if (index !== -1) kept.splice(index, 1);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const rendered = typeof value === 'boolean' ? key + ': ' + value : key + ': ' + JSON.stringify(String(value));
|
|
209
|
+
if (index === -1) kept.push(rendered);
|
|
210
|
+
else kept[index] = rendered;
|
|
211
|
+
}
|
|
212
|
+
const head = kept.length === 0 ? '' : '---\n' + kept.join('\n') + '\n---\n';
|
|
213
|
+
return head + body;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Build a file from existing frontmatter (or none) plus replacement keys and a new body. */
|
|
217
|
+
function buildWithFrontmatter(existingText, updates, body) {
|
|
218
|
+
const { lines } = splitFrontmatter(existingText === undefined ? '' : existingText);
|
|
219
|
+
const kept = lines === null ? [] : lines.slice();
|
|
220
|
+
for (const key of Object.keys(updates)) {
|
|
221
|
+
const value = updates[key];
|
|
222
|
+
const pattern = new RegExp('^' + key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ':');
|
|
223
|
+
const index = kept.findIndex((line) => pattern.test(line));
|
|
224
|
+
if (value === undefined || value === null || value === '') {
|
|
225
|
+
if (index !== -1) kept.splice(index, 1);
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
const rendered = typeof value === 'boolean' ? key + ': ' + value : key + ': ' + JSON.stringify(String(value));
|
|
229
|
+
if (index === -1) kept.push(rendered);
|
|
230
|
+
else kept[index] = rendered;
|
|
231
|
+
}
|
|
232
|
+
const head = kept.length === 0 ? '' : '---\n' + kept.join('\n') + '\n---\n';
|
|
233
|
+
return head + (body.startsWith('\n') ? body : '\n' + body);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function collectSkillFiles(ctx) {
|
|
237
|
+
const byName = new Map();
|
|
238
|
+
const roots = skillRoots(ctx).sort((left, right) => left.rank - right.rank);
|
|
239
|
+
for (const root of roots) {
|
|
240
|
+
if (!existsSync(root.dir)) continue;
|
|
241
|
+
let entries = [];
|
|
242
|
+
try {
|
|
243
|
+
entries = readdirSync(root.dir, { withFileTypes: true });
|
|
244
|
+
} catch {
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
for (const entry of entries) {
|
|
248
|
+
if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
|
|
249
|
+
const dir = join(root.dir, entry.name);
|
|
250
|
+
const path = join(dir, 'SKILL.md');
|
|
251
|
+
if (!existsSync(path)) continue;
|
|
252
|
+
let text = '';
|
|
253
|
+
try {
|
|
254
|
+
text = readFileSync(path, 'utf8');
|
|
255
|
+
} catch {
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
const parsed = parseFrontmatter(text);
|
|
259
|
+
const skillName = typeof parsed.data.name === 'string' && parsed.data.name !== '' ? parsed.data.name : entry.name;
|
|
260
|
+
if (byName.has(skillName)) continue;
|
|
261
|
+
byName.set(skillName, {
|
|
262
|
+
name: skillName,
|
|
263
|
+
path,
|
|
264
|
+
dir,
|
|
265
|
+
rootId: root.id,
|
|
266
|
+
rootLabel: root.label,
|
|
267
|
+
rootDir: root.dir,
|
|
268
|
+
description: typeof parsed.data.description === 'string' ? parsed.data.description : '',
|
|
269
|
+
whenToUse: typeof parsed.data['when-to-use'] === 'string' ? parsed.data['when-to-use'] : '',
|
|
270
|
+
disable: parsed.data['disable-model-invocation'] === true
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return byName;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function serializeSkill(skill, file) {
|
|
278
|
+
const modelInvocable = file === undefined ? skill?.invocation?.modelInvocable !== false : !file.disable;
|
|
279
|
+
return {
|
|
280
|
+
name: typeof skill?.name === 'string' ? skill.name : (file === undefined ? '' : file.name),
|
|
281
|
+
description: (file !== undefined && file.description !== '' ? file.description : (typeof skill?.description === 'string' ? skill.description : '')),
|
|
282
|
+
source: typeof skill?.source === 'string' ? skill.source : (file === undefined ? '' : file.rootId),
|
|
283
|
+
whenToUse: (file !== undefined && file.whenToUse !== '' ? file.whenToUse : (typeof skill?.whenToUse === 'string' ? skill.whenToUse : '')),
|
|
284
|
+
provider: typeof skill?.provider === 'string' ? skill.provider : '',
|
|
285
|
+
modelInvocable,
|
|
286
|
+
userInvocable: skill?.invocation?.userInvocable === true,
|
|
287
|
+
path: file === undefined ? '' : file.path,
|
|
288
|
+
rootLabel: file === undefined ? '' : file.rootLabel,
|
|
289
|
+
writable: file !== undefined
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async function collectSkills(ctx) {
|
|
294
|
+
const files = collectSkillFiles(ctx);
|
|
295
|
+
const byName = new Map();
|
|
296
|
+
for (const cwd of activeCwds(ctx)) {
|
|
297
|
+
try {
|
|
298
|
+
const snapshot = await ctx.skills.snapshot({ cwd });
|
|
299
|
+
for (const skill of Array.isArray(snapshot?.skills) ? snapshot.skills : []) {
|
|
300
|
+
const name = typeof skill?.name === 'string' ? skill.name : '';
|
|
301
|
+
if (name === '' || byName.has(name)) continue;
|
|
302
|
+
byName.set(name, serializeSkill(skill, files.get(name)));
|
|
303
|
+
}
|
|
304
|
+
} catch {}
|
|
305
|
+
}
|
|
306
|
+
for (const [name, file] of files) {
|
|
307
|
+
if (byName.has(name)) continue;
|
|
308
|
+
byName.set(name, serializeSkill(undefined, file));
|
|
309
|
+
}
|
|
310
|
+
return [...byName.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function inside(root, target) {
|
|
314
|
+
const base = resolve(root);
|
|
315
|
+
const full = resolve(target);
|
|
316
|
+
return full === base || full.startsWith(base.endsWith(sep) ? base : base + sep);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function allowedSkillPath(ctx, path) {
|
|
320
|
+
if (typeof path !== 'string' || path.trim() === '') return undefined;
|
|
321
|
+
const files = collectSkillFiles(ctx);
|
|
322
|
+
for (const file of files.values()) {
|
|
323
|
+
if (file.path === resolve(path) || file.dir === resolve(path)) return file;
|
|
324
|
+
}
|
|
325
|
+
return undefined;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function readBody(req, limit) {
|
|
329
|
+
return new Promise((resolveBody, reject) => {
|
|
330
|
+
let size = 0;
|
|
331
|
+
const chunks = [];
|
|
332
|
+
req.on('data', (chunk) => {
|
|
333
|
+
size += chunk.length;
|
|
334
|
+
if (size > limit) {
|
|
335
|
+
reject(new Error('request body too large'));
|
|
336
|
+
req.destroy();
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
chunks.push(chunk);
|
|
340
|
+
});
|
|
341
|
+
req.on('end', () => resolveBody(Buffer.concat(chunks).toString('utf8')));
|
|
342
|
+
req.on('error', reject);
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function readJsonBody(req, limit = BODY_LIMIT + 8192) {
|
|
347
|
+
const text = await readBody(req, limit);
|
|
348
|
+
if (text.trim() === '') return {};
|
|
349
|
+
const value = JSON.parse(text);
|
|
350
|
+
return typeof value === 'object' && value !== null ? value : {};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function writeFileAtomic(path, text) {
|
|
354
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
355
|
+
const temporary = path + '.' + String(Date.now()) + '.tmp';
|
|
356
|
+
writeFileSync(temporary, text, 'utf8');
|
|
357
|
+
renameSync(temporary, path);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Locate SKILL.md files up to a bounded depth: a directory that has one is the skill itself. */
|
|
361
|
+
function findSkillFiles(dir, depth = 0, out = []) {
|
|
362
|
+
if (out.length >= 200 || depth > 4) return out;
|
|
363
|
+
let entries = [];
|
|
364
|
+
try {
|
|
365
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
366
|
+
} catch {
|
|
367
|
+
return out;
|
|
368
|
+
}
|
|
369
|
+
if (entries.some((entry) => entry.isFile() && entry.name === 'SKILL.md')) {
|
|
370
|
+
out.push(join(dir, 'SKILL.md'));
|
|
371
|
+
return out;
|
|
372
|
+
}
|
|
373
|
+
for (const entry of entries) {
|
|
374
|
+
if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
|
|
375
|
+
findSkillFiles(join(dir, entry.name), depth + 1, out);
|
|
376
|
+
}
|
|
377
|
+
return out;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function findZipEnd(buffer) {
|
|
381
|
+
const floor = Math.max(0, buffer.length - 65558);
|
|
382
|
+
for (let index = buffer.length - 22; index >= floor; index -= 1) {
|
|
383
|
+
if (buffer.readUInt32LE(index) === 0x06054b50) return index;
|
|
384
|
+
}
|
|
385
|
+
return -1;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function readZipEntry(buffer, offset, method, compressedSize) {
|
|
389
|
+
if (buffer.readUInt32LE(offset) !== 0x04034b50) throw new Error('zip 条目损坏');
|
|
390
|
+
const nameLength = buffer.readUInt16LE(offset + 26);
|
|
391
|
+
const extraLength = buffer.readUInt16LE(offset + 28);
|
|
392
|
+
const start = offset + 30 + nameLength + extraLength;
|
|
393
|
+
const data = buffer.subarray(start, start + compressedSize);
|
|
394
|
+
if (method === 0) return data.toString('utf8');
|
|
395
|
+
if (method === 8) return inflateRawSync(data).toString('utf8');
|
|
396
|
+
throw new Error('不支持的压缩方式:' + String(method));
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Minimal ZIP reader: only entries ending in SKILL.md, bounded by size and count. */
|
|
400
|
+
function readZipSkills(buffer) {
|
|
401
|
+
const end = findZipEnd(buffer);
|
|
402
|
+
if (end === -1) throw new Error('这不是有效的 zip 文件');
|
|
403
|
+
const count = buffer.readUInt16LE(end + 10);
|
|
404
|
+
const directoryOffset = buffer.readUInt32LE(end + 16);
|
|
405
|
+
if (count > 500) throw new Error('压缩包内文件过多(最多 500 个)');
|
|
406
|
+
let cursor = directoryOffset;
|
|
407
|
+
const files = [];
|
|
408
|
+
for (let index = 0; index < count; index += 1) {
|
|
409
|
+
if (buffer.readUInt32LE(cursor) !== 0x02014b50) throw new Error('zip 目录损坏');
|
|
410
|
+
const method = buffer.readUInt16LE(cursor + 10);
|
|
411
|
+
const compressedSize = buffer.readUInt32LE(cursor + 20);
|
|
412
|
+
const uncompressedSize = buffer.readUInt32LE(cursor + 24);
|
|
413
|
+
const nameLength = buffer.readUInt16LE(cursor + 28);
|
|
414
|
+
const extraLength = buffer.readUInt16LE(cursor + 30);
|
|
415
|
+
const commentLength = buffer.readUInt16LE(cursor + 32);
|
|
416
|
+
const localOffset = buffer.readUInt32LE(cursor + 42);
|
|
417
|
+
const entryName = buffer.toString('utf8', cursor + 46, cursor + 46 + nameLength);
|
|
418
|
+
cursor += 46 + nameLength + extraLength + commentLength;
|
|
419
|
+
if (!entryName.endsWith('/SKILL.md') && entryName !== 'SKILL.md') continue;
|
|
420
|
+
if (uncompressedSize > 1024 * 1024) continue;
|
|
421
|
+
files.push({ entryName, text: readZipEntry(buffer, localOffset, method, compressedSize) });
|
|
422
|
+
}
|
|
423
|
+
return files;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function importSkillName(file) {
|
|
427
|
+
const source = typeof file.path === 'string' ? file.path : file.entryName;
|
|
428
|
+
return basename(dirname(source));
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function writeJson(res, status, body) {
|
|
432
|
+
const text = JSON.stringify(body);
|
|
433
|
+
res.statusCode = status;
|
|
434
|
+
res.setHeader('content-type', 'application/json; charset=utf-8');
|
|
435
|
+
res.setHeader('cache-control', 'no-store');
|
|
436
|
+
res.setHeader('content-length', Buffer.byteLength(text));
|
|
437
|
+
res.end(text);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export function apply(ctx) {
|
|
441
|
+
ctx.effect(() => {
|
|
442
|
+
const routes = [
|
|
443
|
+
{
|
|
444
|
+
kind: 'exact',
|
|
445
|
+
path: LIST_ROUTE,
|
|
446
|
+
handler: async (req, res) => {
|
|
447
|
+
if ((req.method || 'GET').toUpperCase() !== 'GET') {
|
|
448
|
+
writeJson(res, 405, { error: 'method not allowed' });
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
try {
|
|
452
|
+
const inventory = collectPlugins();
|
|
453
|
+
const skills = await collectSkills(ctx);
|
|
454
|
+
writeJson(res, 200, {
|
|
455
|
+
generatedAt: new Date().toISOString(),
|
|
456
|
+
home: inventory.home,
|
|
457
|
+
profile: inventory.profile,
|
|
458
|
+
plugins: inventory.plugins,
|
|
459
|
+
bundles: inventory.bundles,
|
|
460
|
+
skills,
|
|
461
|
+
roots: skillRoots(ctx).map((root) => ({ id: root.id, label: root.label, dir: root.dir }))
|
|
462
|
+
});
|
|
463
|
+
} catch (error) {
|
|
464
|
+
writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
},
|
|
468
|
+
{
|
|
469
|
+
kind: 'exact',
|
|
470
|
+
path: SKILL_ROUTE,
|
|
471
|
+
handler: async (req, res) => {
|
|
472
|
+
try {
|
|
473
|
+
const url = new URL(req.url ?? '/', 'http://x');
|
|
474
|
+
const file = allowedSkillPath(ctx, url.searchParams.get('path'));
|
|
475
|
+
if (file === undefined) {
|
|
476
|
+
writeJson(res, 404, { error: 'skill file not found' });
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
const text = readFileSync(file.path, 'utf8');
|
|
480
|
+
const parsed = parseFrontmatter(text);
|
|
481
|
+
writeJson(res, 200, {
|
|
482
|
+
name: typeof parsed.data.name === 'string' ? parsed.data.name : file.name,
|
|
483
|
+
description: typeof parsed.data.description === 'string' ? parsed.data.description : '',
|
|
484
|
+
whenToUse: typeof parsed.data['when-to-use'] === 'string' ? parsed.data['when-to-use'] : '',
|
|
485
|
+
disable: parsed.data['disable-model-invocation'] === true,
|
|
486
|
+
body: parsed.body,
|
|
487
|
+
path: file.path,
|
|
488
|
+
rootLabel: file.rootLabel
|
|
489
|
+
});
|
|
490
|
+
} catch (error) {
|
|
491
|
+
writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
},
|
|
495
|
+
{
|
|
496
|
+
kind: 'exact',
|
|
497
|
+
path: SAVE_ROUTE,
|
|
498
|
+
handler: async (req, res) => {
|
|
499
|
+
if ((req.method || 'GET').toUpperCase() !== 'POST') {
|
|
500
|
+
writeJson(res, 405, { error: 'method not allowed' });
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
try {
|
|
504
|
+
const body = await readJsonBody(req);
|
|
505
|
+
const description = typeof body.description === 'string' ? body.description.slice(0, DESCRIPTION_LIMIT) : '';
|
|
506
|
+
const whenToUse = typeof body.whenToUse === 'string' ? body.whenToUse.slice(0, DESCRIPTION_LIMIT) : '';
|
|
507
|
+
const text = typeof body.body === 'string' ? body.body : '';
|
|
508
|
+
if (Buffer.byteLength(text) > BODY_LIMIT) throw new Error('正文超过 200 KB 上限');
|
|
509
|
+
|
|
510
|
+
if (typeof body.path === 'string' && body.path !== '') {
|
|
511
|
+
const file = allowedSkillPath(ctx, body.path);
|
|
512
|
+
if (file === undefined) throw new Error('只能编辑本机技能目录里已有的技能');
|
|
513
|
+
const existing = readFileSync(file.path, 'utf8');
|
|
514
|
+
writeFileAtomic(file.path, buildWithFrontmatter(existing, { description, 'when-to-use': whenToUse }, text));
|
|
515
|
+
writeJson(res, 200, { path: file.path });
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
|
520
|
+
if (!NAME_PATTERN.test(name)) throw new Error('技能名只能用小写字母、数字和连字符');
|
|
521
|
+
const roots = skillRoots(ctx);
|
|
522
|
+
const target = roots.find((root) => root.id === body.root);
|
|
523
|
+
if (target === undefined || !target.writable) throw new Error('请选择一个可写入的技能目录');
|
|
524
|
+
const dir = join(target.dir, name);
|
|
525
|
+
if (existsSync(dir)) throw new Error('同名技能已存在:' + name);
|
|
526
|
+
mkdirSync(dir, { recursive: true });
|
|
527
|
+
const path = join(dir, 'SKILL.md');
|
|
528
|
+
writeFileAtomic(path, buildWithFrontmatter('', { name, description, 'when-to-use': whenToUse }, text));
|
|
529
|
+
writeJson(res, 200, { path });
|
|
530
|
+
} catch (error) {
|
|
531
|
+
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
},
|
|
535
|
+
{
|
|
536
|
+
kind: 'exact',
|
|
537
|
+
path: TOGGLE_ROUTE,
|
|
538
|
+
handler: async (req, res) => {
|
|
539
|
+
if ((req.method || 'GET').toUpperCase() !== 'POST') {
|
|
540
|
+
writeJson(res, 405, { error: 'method not allowed' });
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
try {
|
|
544
|
+
const body = await readJsonBody(req, 8192);
|
|
545
|
+
const file = allowedSkillPath(ctx, body.path);
|
|
546
|
+
if (file === undefined) throw new Error('只能修改本机技能目录里已有的技能');
|
|
547
|
+
const enabled = body.enabled !== false;
|
|
548
|
+
const existing = readFileSync(file.path, 'utf8');
|
|
549
|
+
writeFileAtomic(file.path, applyFrontmatter(existing, { 'disable-model-invocation': enabled ? undefined : true }));
|
|
550
|
+
writeJson(res, 200, { enabled });
|
|
551
|
+
} catch (error) {
|
|
552
|
+
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
},
|
|
556
|
+
{
|
|
557
|
+
kind: 'exact',
|
|
558
|
+
path: DELETE_ROUTE,
|
|
559
|
+
handler: async (req, res) => {
|
|
560
|
+
if ((req.method || 'GET').toUpperCase() !== 'POST') {
|
|
561
|
+
writeJson(res, 405, { error: 'method not allowed' });
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
try {
|
|
565
|
+
const body = await readJsonBody(req, 8192);
|
|
566
|
+
const file = allowedSkillPath(ctx, body.path);
|
|
567
|
+
if (file === undefined) throw new Error('只能删除本机技能目录里已有的技能');
|
|
568
|
+
const trash = join(file.rootDir, '.trash');
|
|
569
|
+
mkdirSync(trash, { recursive: true });
|
|
570
|
+
const target = join(trash, file.name + '-' + String(Date.now()));
|
|
571
|
+
renameSync(file.dir, target);
|
|
572
|
+
writeJson(res, 200, { moved: target });
|
|
573
|
+
} catch (error) {
|
|
574
|
+
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
},
|
|
578
|
+
{
|
|
579
|
+
kind: 'exact',
|
|
580
|
+
path: IMPORT_ROUTE,
|
|
581
|
+
handler: async (req, res) => {
|
|
582
|
+
if ((req.method || 'GET').toUpperCase() !== 'POST') {
|
|
583
|
+
writeJson(res, 405, { error: 'method not allowed' });
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
try {
|
|
587
|
+
const body = await readJsonBody(req, 28 * 1024 * 1024);
|
|
588
|
+
const roots = skillRoots(ctx);
|
|
589
|
+
const target = roots.find((root) => root.id === body.root && root.writable) || roots.find((root) => root.writable);
|
|
590
|
+
if (target === undefined) throw new Error('没有可写入的技能目录');
|
|
591
|
+
let files = [];
|
|
592
|
+
if (body.kind === 'directory') {
|
|
593
|
+
const dir = typeof body.path === 'string' ? body.path.trim() : '';
|
|
594
|
+
if (dir === '') throw new Error('请填写本机目录路径');
|
|
595
|
+
if (!existsSync(dir)) throw new Error('目录不存在:' + dir);
|
|
596
|
+
files = findSkillFiles(dir).map((path) => ({ path, text: readFileSync(path, 'utf8') }));
|
|
597
|
+
} else if (body.kind === 'archive') {
|
|
598
|
+
const data = typeof body.data === 'string' ? body.data : '';
|
|
599
|
+
const buffer = Buffer.from(data, 'base64');
|
|
600
|
+
if (buffer.length === 0) throw new Error('压缩包为空');
|
|
601
|
+
if (buffer.length > 20 * 1024 * 1024) throw new Error('压缩包超过 20 MB 上限');
|
|
602
|
+
files = readZipSkills(buffer);
|
|
603
|
+
} else {
|
|
604
|
+
throw new Error('未知的导入来源');
|
|
605
|
+
}
|
|
606
|
+
if (files.length === 0) throw new Error('没有在来源里找到 SKILL.md');
|
|
607
|
+
const imported = [];
|
|
608
|
+
const skipped = [];
|
|
609
|
+
for (const file of files) {
|
|
610
|
+
const parsed = parseFrontmatter(file.text);
|
|
611
|
+
const declared = typeof parsed.data.name === 'string' && parsed.data.name.trim() !== '' ? parsed.data.name.trim() : '';
|
|
612
|
+
const name = declared !== '' ? declared : importSkillName(file);
|
|
613
|
+
if (!NAME_PATTERN.test(name)) {
|
|
614
|
+
skipped.push({ name: name || '?', reason: '技能名不合规' });
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
const dir = join(target.dir, name);
|
|
618
|
+
if (existsSync(dir)) {
|
|
619
|
+
skipped.push({ name, reason: '同名技能已存在' });
|
|
620
|
+
continue;
|
|
621
|
+
}
|
|
622
|
+
writeFileAtomic(join(dir, 'SKILL.md'), file.text);
|
|
623
|
+
imported.push(name);
|
|
624
|
+
}
|
|
625
|
+
writeJson(res, 200, { imported, skipped, root: target.dir });
|
|
626
|
+
} catch (error) {
|
|
627
|
+
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
];
|
|
632
|
+
|
|
633
|
+
const disposers = routes.map((route) => ctx.webServer.register(route));
|
|
634
|
+
return () => {
|
|
635
|
+
for (const dispose of disposers) {
|
|
636
|
+
if (typeof dispose === 'function') dispose();
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
}, 'dsh-inventory-panel: routes');
|
|
640
|
+
}
|
package/locale/en.json
ADDED