dsh-skill-bazaar 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/index.js ADDED
@@ -0,0 +1,1546 @@
1
+ /**
2
+ * 技能市场 · Host 半
3
+ *
4
+ * 在 DSH 的 Web 服务器上注册 /api/skill-bazaar/* 路由:
5
+ * - 聚合 CherryIN(skills.cherryin.ai)与 skills.sh(www.skills.sh)两个默认源,
6
+ * 支持在面板里增删/启停自定义源(CherryIN 兼容、skills.sh 兼容、GitHub 仓库、自定义 JSON)。
7
+ * - 非中文名称与简介自动翻译成中文(微软 Edge 免密钥翻译,失败回退 MyMemory),结果落盘缓存。
8
+ * - 一键安装:CherryIN 技能下载 zip 解压;skills.sh / GitHub 技能 git clone 后定位
9
+ * SKILL.md 目录;统一复制到 ~/.agents/skills/<技能名>。
10
+ */
11
+ import { mkdirSync, readFileSync, writeFileSync, renameSync, existsSync, readdirSync, rmSync, cpSync, mkdtempSync, statSync } from 'node:fs';
12
+ import { join, dirname, basename, resolve, sep } from 'node:path';
13
+ import { homedir, tmpdir } from 'node:os';
14
+ import { spawn } from 'node:child_process';
15
+ import { inflateRawSync, gunzipSync } from 'node:zlib';
16
+ import { createHash, randomBytes } from 'node:crypto';
17
+
18
+ const name = 'dsh-skill-bazaar';
19
+ const inject = ['webServer'];
20
+
21
+ const HOST_ORIGIN = 'http://skill-bazaar.local';
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // 基础工具
25
+ // ---------------------------------------------------------------------------
26
+
27
+ function loadJsonFile(file, fallback) {
28
+ try {
29
+ return JSON.parse(readFileSync(file, 'utf8'));
30
+ } catch {
31
+ return fallback;
32
+ }
33
+ }
34
+
35
+ function writeJsonAtomic(file, data) {
36
+ const tmp = file + '.tmp-' + process.pid;
37
+ writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');
38
+ renameSync(tmp, file);
39
+ }
40
+
41
+ function writeJson(res, code, data) {
42
+ const body = JSON.stringify(data);
43
+ res.writeHead(code, {
44
+ 'Content-Type': 'application/json; charset=utf-8',
45
+ 'Cache-Control': 'no-store'
46
+ });
47
+ res.end(body);
48
+ }
49
+
50
+ function readBody(req, limit = 1024 * 1024) {
51
+ return new Promise((resolvePromise, reject) => {
52
+ let size = 0;
53
+ const chunks = [];
54
+ req.on('data', (chunk) => {
55
+ size += chunk.length;
56
+ if (size > limit) {
57
+ reject(new Error('请求体过大'));
58
+ req.destroy();
59
+ return;
60
+ }
61
+ chunks.push(chunk);
62
+ });
63
+ req.on('end', () => {
64
+ const text = Buffer.concat(chunks).toString('utf8');
65
+ if (!text) return resolvePromise({});
66
+ try {
67
+ resolvePromise(JSON.parse(text));
68
+ } catch {
69
+ reject(new Error('请求体不是有效 JSON'));
70
+ }
71
+ });
72
+ req.on('error', reject);
73
+ });
74
+ }
75
+
76
+ async function fetchWithTimeout(url, options = {}, timeout = 15000) {
77
+ const controller = new AbortController();
78
+ const timer = setTimeout(() => controller.abort(), timeout);
79
+ try {
80
+ return await fetch(url, { ...options, signal: controller.signal });
81
+ } finally {
82
+ clearTimeout(timer);
83
+ }
84
+ }
85
+
86
+ async function fetchText(url, options = {}, timeout = 15000) {
87
+ const res = await fetchWithTimeout(url, options, timeout);
88
+ if (!res.ok) throw new Error('HTTP ' + res.status + ' ' + url);
89
+ return await res.text();
90
+ }
91
+
92
+ async function fetchJson(url, options = {}, timeout = 15000) {
93
+ const res = await fetchWithTimeout(url, options, timeout);
94
+ if (!res.ok) throw new Error('HTTP ' + res.status + ' ' + url);
95
+ return await res.json();
96
+ }
97
+
98
+ async function fetchBuffer(url, options = {}, timeout = 30000) {
99
+ const res = await fetchWithTimeout(url, options, timeout);
100
+ if (!res.ok) throw new Error('HTTP ' + res.status + ' ' + url);
101
+ return Buffer.from(await res.arrayBuffer());
102
+ }
103
+
104
+ async function mapLimit(items, limit, fn) {
105
+ const results = new Array(items.length);
106
+ let index = 0;
107
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
108
+ while (index < items.length) {
109
+ const current = index++;
110
+ results[current] = await fn(items[current], current);
111
+ }
112
+ });
113
+ await Promise.all(workers);
114
+ return results;
115
+ }
116
+
117
+ function hasCJK(text) {
118
+ return /[\u3400-\u9fff]/.test(text || '');
119
+ }
120
+
121
+ function decodeEntities(text) {
122
+ return String(text || '')
123
+ .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
124
+ .replace(/&#(\d+);/g, (_, num) => String.fromCodePoint(Number(num)))
125
+ .replace(/&nbsp;/g, ' ')
126
+ .replace(/&amp;/g, '&')
127
+ .replace(/&lt;/g, '<')
128
+ .replace(/&gt;/g, '>')
129
+ .replace(/&quot;/g, '"')
130
+ .replace(/&#39;/g, "'");
131
+ }
132
+
133
+ function stripTags(text) {
134
+ return decodeEntities(String(text || '').replace(/<[^>]*>/g, ' ')).replace(/\s+/g, ' ').trim();
135
+ }
136
+
137
+ function hashKey(text) {
138
+ return createHash('sha1').update(text).digest('hex');
139
+ }
140
+
141
+ function sanitizeDirName(value) {
142
+ const cleaned = String(value || '')
143
+ .replace(/[<>:"/\\|?*\u0000-\u001f]/g, '-')
144
+ .replace(/\s+/g, '-')
145
+ .replace(/-+/g, '-')
146
+ .replace(/^[-.]+|[-.]+$/g, '')
147
+ .trim();
148
+ return cleaned.slice(0, 64) || 'skill-' + Date.now();
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // 插件主入口
153
+ // ---------------------------------------------------------------------------
154
+
155
+ export function apply(ctx, config = {}) {
156
+ const dshHome = config.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh');
157
+ const dataDir = join(dshHome, 'skill-bazaar');
158
+ const skillsDir = join(
159
+ config.agentsHome || process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'),
160
+ 'skills'
161
+ );
162
+ mkdirSync(dataDir, { recursive: true });
163
+ mkdirSync(skillsDir, { recursive: true });
164
+
165
+ const sourcesFile = join(dataDir, 'sources.json');
166
+ const translationFile = join(dataDir, 'translations.json');
167
+ const skillsShDetailFile = join(dataDir, 'skills-sh-details.json');
168
+
169
+ if (!existsSync(sourcesFile)) {
170
+ writeJsonAtomic(sourcesFile, {
171
+ sources: [
172
+ {
173
+ id: 'cherryin',
174
+ name: 'CherryIN 技能市场',
175
+ type: 'cherryin',
176
+ baseUrl: 'https://skills.cherryin.ai',
177
+ enabled: true,
178
+ builtin: true
179
+ },
180
+ {
181
+ id: 'skills-sh',
182
+ name: 'skills.sh',
183
+ type: 'skills-sh',
184
+ baseUrl: 'https://www.skills.sh',
185
+ enabled: true,
186
+ builtin: true
187
+ }
188
+ ]
189
+ });
190
+ }
191
+
192
+ // 安装目录:用户选择一个文件夹,Host 在其下识别 skills 目录,没有就创建
193
+ const recentTargetsFile = join(dataDir, 'targets.json');
194
+
195
+ function getWorkspaceDir() {
196
+ try {
197
+ const sessions = ctx.get?.('sessions', false);
198
+ if (sessions && typeof sessions.list === 'function') {
199
+ const list = sessions.list();
200
+ const active = list.find((s) => s && s.active) || list[0];
201
+ const cwd = active && active.header && active.header.cwd;
202
+ if (typeof cwd === 'string' && cwd.trim() !== '') return cwd;
203
+ }
204
+ } catch {}
205
+ return process.cwd();
206
+ }
207
+
208
+ /**
209
+ * 根据用户选择的文件夹,决定技能真正落盘的 skills 目录。
210
+ *
211
+ * 优先遵循已有的目录约定,都不存在时按 Agent Skills 规范创建 `<folder>/.agents/skills`:
212
+ * 1. 选中的文件夹本身就是技能目录(含 SKILL.md)→ 直接用它;
213
+ * 2. 选中的文件夹名就叫 skills → 直接用它(不套娃);
214
+ * 3. 选中的文件夹名是 .agents → 用它下面的 skills;
215
+ * 4. 它下面已有 skills 目录 → 用 `<folder>/skills`;
216
+ * 5. 它下面已有 .agents 目录 → 用 `<folder>/.agents/skills`;
217
+ * 6. 否则 → 创建 `<folder>/.agents/skills`(工作区/项目根目录的默认约定)。
218
+ */
219
+ function resolveSkillsDir(folder) {
220
+ const root = resolve(String(folder || '').trim());
221
+ if (existsSync(join(root, 'SKILL.md'))) return root;
222
+ if (basename(root).toLowerCase() === 'skills') return root;
223
+ if (basename(root).toLowerCase() === '.agents') return join(root, 'skills');
224
+ if (existsSync(join(root, 'skills'))) return join(root, 'skills');
225
+ if (existsSync(join(root, '.agents'))) return join(root, '.agents', 'skills');
226
+ return join(root, '.agents', 'skills');
227
+ }
228
+
229
+ function loadRecentTargets() {
230
+ const data = loadJsonFile(recentTargetsFile, { targets: [] });
231
+ return Array.isArray(data.targets) ? data.targets : [];
232
+ }
233
+
234
+ function rememberTarget(folder, skillsDir) {
235
+ const list = loadRecentTargets().filter((t) => t.folder !== folder);
236
+ list.unshift({ folder, skillsDir, at: Date.now() });
237
+ try {
238
+ writeJsonAtomic(recentTargetsFile, { targets: list.slice(0, 12) });
239
+ } catch {}
240
+ }
241
+
242
+ function findGitRoot(folder) {
243
+ let current = resolve(String(folder || '').trim());
244
+ while (true) {
245
+ if (existsSync(join(current, '.git'))) return current;
246
+ const parent = dirname(current);
247
+ if (parent === current) return '';
248
+ current = parent;
249
+ }
250
+ }
251
+
252
+ function listTargetOptions() {
253
+ const defaultFolder = join(homedir(), '.agents');
254
+ const workspace = getWorkspaceDir();
255
+ return {
256
+ userFolder: defaultFolder,
257
+ userSkillsDir: resolveSkillsDir(defaultFolder),
258
+ workspace,
259
+ workspaceSkillsDir: resolveSkillsDir(workspace),
260
+ workspaceGitRoot: findGitRoot(workspace),
261
+ recent: loadRecentTargets()
262
+ };
263
+ }
264
+
265
+ function scanDirs() {
266
+ const dirs = new Set([join(homedir(), '.agents', 'skills')]);
267
+ for (const target of loadRecentTargets()) {
268
+ if (target.skillsDir) dirs.add(target.skillsDir);
269
+ }
270
+ return dirs;
271
+ }
272
+
273
+ const translationCache = loadJsonFile(translationFile, {});
274
+ const skillsShDetailCache = loadJsonFile(skillsShDetailFile, {});
275
+ const cherryinCache = new Map();
276
+ const skillsShListCache = new Map();
277
+ const githubCache = new Map();
278
+ const jsonSourceCache = new Map();
279
+
280
+ let translationSaveTimer = null;
281
+ let detailSaveTimer = null;
282
+
283
+ function scheduleSaveTranslation() {
284
+ if (translationSaveTimer) return;
285
+ translationSaveTimer = setTimeout(() => {
286
+ translationSaveTimer = null;
287
+ try {
288
+ writeJsonAtomic(translationFile, translationCache);
289
+ } catch (err) {
290
+ ctx.logger?.warn?.('[skill-bazaar] 翻译缓存写入失败: ' + err.message);
291
+ }
292
+ }, 1500);
293
+ }
294
+
295
+ function scheduleSaveDetail() {
296
+ if (detailSaveTimer) return;
297
+ detailSaveTimer = setTimeout(() => {
298
+ detailSaveTimer = null;
299
+ try {
300
+ writeJsonAtomic(skillsShDetailFile, skillsShDetailCache);
301
+ } catch (err) {
302
+ ctx.logger?.warn?.('[skill-bazaar] 详情缓存写入失败: ' + err.message);
303
+ }
304
+ }, 2000);
305
+ }
306
+
307
+ // -------------------------------------------------------------------------
308
+ // 翻译:微软 Edge 批量翻译(免密钥、国内可直连)→ MyMemory → 原文
309
+ // -------------------------------------------------------------------------
310
+
311
+ async function microsoftTranslate(texts) {
312
+ const res = await fetchWithTimeout(
313
+ 'https://edge.microsoft.com/translate/translatetext?from=en&to=zh-Hans',
314
+ {
315
+ method: 'POST',
316
+ headers: { 'Content-Type': 'application/json' },
317
+ body: JSON.stringify(texts)
318
+ },
319
+ 20000
320
+ );
321
+ if (!res.ok) throw new Error('微软翻译 HTTP ' + res.status);
322
+ const data = await res.json();
323
+ if (!Array.isArray(data)) throw new Error('微软翻译返回格式异常');
324
+ return data.map(
325
+ (item) => (item && item.translations && item.translations[0] && item.translations[0].text) || ''
326
+ );
327
+ }
328
+
329
+ async function myMemoryTranslate(text) {
330
+ const data = await fetchJson(
331
+ 'https://api.mymemory.translated.net/get?q=' + encodeURIComponent(text) + '&langpair=en|zh-CN',
332
+ {},
333
+ 15000
334
+ );
335
+ const out = data && data.responseData && data.responseData.translatedText;
336
+ if (!out || /MYMEMORY WARNING/i.test(out)) throw new Error('MyMemory 无结果');
337
+ return out;
338
+ }
339
+
340
+ async function translateTexts(texts) {
341
+ const result = {};
342
+ const pending = [];
343
+ const seen = new Set();
344
+ for (const raw of texts) {
345
+ const text = String(raw || '').trim();
346
+ if (!text || seen.has(text)) continue;
347
+ seen.add(text);
348
+ if (hasCJK(text)) {
349
+ result[text] = text;
350
+ continue;
351
+ }
352
+ const key = hashKey(text);
353
+ if (translationCache[key]) {
354
+ result[text] = translationCache[key];
355
+ continue;
356
+ }
357
+ pending.push(text);
358
+ }
359
+ if (pending.length === 0) return result;
360
+
361
+ const batches = [];
362
+ let current = [];
363
+ let chars = 0;
364
+ for (const text of pending) {
365
+ if (current.length >= 16 || chars + text.length > 4000) {
366
+ batches.push(current);
367
+ current = [];
368
+ chars = 0;
369
+ }
370
+ current.push(text);
371
+ chars += text.length;
372
+ }
373
+ if (current.length) batches.push(current);
374
+
375
+ await mapLimit(batches, 4, async (batch) => {
376
+ let translated = null;
377
+ try {
378
+ translated = await microsoftTranslate(batch);
379
+ } catch (err) {
380
+ ctx.logger?.warn?.('[skill-bazaar] 微软翻译失败,尝试 MyMemory: ' + err.message);
381
+ }
382
+ for (let i = 0; i < batch.length; i += 1) {
383
+ const text = batch[i];
384
+ let out = translated && translated[i] ? translated[i] : '';
385
+ if (!out) {
386
+ try {
387
+ out = await myMemoryTranslate(text);
388
+ } catch {
389
+ out = '';
390
+ }
391
+ }
392
+ if (out) {
393
+ result[text] = out;
394
+ translationCache[hashKey(text)] = out;
395
+ } else {
396
+ result[text] = text;
397
+ }
398
+ }
399
+ });
400
+ scheduleSaveTranslation();
401
+ return result;
402
+ }
403
+
404
+ // -------------------------------------------------------------------------
405
+ // 源配置
406
+ // -------------------------------------------------------------------------
407
+
408
+ function loadSourcesConfig() {
409
+ const data = loadJsonFile(sourcesFile, { sources: [] });
410
+ if (!Array.isArray(data.sources)) data.sources = [];
411
+ return data;
412
+ }
413
+
414
+ function saveSourcesConfig(data) {
415
+ writeJsonAtomic(sourcesFile, data);
416
+ }
417
+
418
+ function getSource(sourceId) {
419
+ return loadSourcesConfig().sources.find((s) => s.id === sourceId) || null;
420
+ }
421
+
422
+ function publicSource(source) {
423
+ return {
424
+ id: source.id,
425
+ name: source.name,
426
+ type: source.type,
427
+ baseUrl: source.baseUrl || '',
428
+ repo: source.repo || '',
429
+ enabled: source.enabled !== false,
430
+ builtin: Boolean(source.builtin)
431
+ };
432
+ }
433
+
434
+ // -------------------------------------------------------------------------
435
+ // CherryIN
436
+ // -------------------------------------------------------------------------
437
+
438
+ async function fetchCherryinAll(source, force = false) {
439
+ const cached = cherryinCache.get(source.id);
440
+ if (!force && cached && Date.now() - cached.at < 10 * 60 * 1000) return cached.items;
441
+ const items = [];
442
+ for (let offset = 0; offset < 2000; offset += 100) {
443
+ const url = source.baseUrl.replace(/\/$/, '') + '/api/skills?limit=100&offset=' + offset;
444
+ const data = await fetchJson(url, {}, 20000);
445
+ const batch = Array.isArray(data.items) ? data.items : [];
446
+ items.push(...batch);
447
+ if (!data.pagination || !data.pagination.hasMore || batch.length === 0) break;
448
+ }
449
+ cherryinCache.set(source.id, { at: Date.now(), items });
450
+ return items;
451
+ }
452
+
453
+ function mapCherryin(source, raw) {
454
+ const nameEn = (raw.name && raw.name.en) || '';
455
+ const nameZh = (raw.name && raw.name.zh) || '';
456
+ const descEn = (raw.description && raw.description.en) || '';
457
+ const descZh = (raw.description && raw.description.zh) || '';
458
+ return {
459
+ source: source.id,
460
+ id: raw.id,
461
+ name: nameEn || nameZh,
462
+ nameZh: hasCJK(nameZh) ? nameZh : '',
463
+ description: descEn || descZh,
464
+ descriptionZh: hasCJK(descZh) ? descZh : '',
465
+ url: raw.sourceUrl || raw.githubRepoUrl || source.baseUrl,
466
+ tags: Array.isArray(raw.tags) ? raw.tags.slice(0, 6) : [],
467
+ installs: Number(raw.downloads) || 0,
468
+ author: raw.author || '',
469
+ domain: raw.domain || '',
470
+ version: raw.version || '',
471
+ downloadUrl: raw.downloadUrl || '',
472
+ repo: '',
473
+ skillId: raw.id
474
+ };
475
+ }
476
+
477
+ async function listCherryin(source, q, limit, force) {
478
+ const raws = await fetchCherryinAll(source, force);
479
+ let items = raws.map((raw) => mapCherryin(source, raw));
480
+ if (q) {
481
+ const needle = q.toLowerCase();
482
+ items = items.filter((item) =>
483
+ [item.name, item.nameZh, item.description, item.descriptionZh, item.author, item.domain, ...item.tags]
484
+ .join(' ')
485
+ .toLowerCase()
486
+ .includes(needle)
487
+ );
488
+ }
489
+ items.sort((a, b) => b.installs - a.installs);
490
+ return items.slice(0, limit);
491
+ }
492
+
493
+ // -------------------------------------------------------------------------
494
+ // skills.sh
495
+ // -------------------------------------------------------------------------
496
+
497
+ function parseSkillsShIndex(html) {
498
+ const items = [];
499
+ const chunks = String(html).split('<a class="group grid');
500
+ for (const chunk of chunks.slice(1)) {
501
+ const hrefMatch = chunk.match(/href="\/([^"/]+\/[^"/]+\/[^"/]+)"/);
502
+ if (!hrefMatch) continue;
503
+ const id = hrefMatch[1];
504
+ const parts = id.split('/');
505
+ if (parts.length !== 3) continue;
506
+ const nameMatch = chunk.match(/<h3[^>]*>([^<]+)<\/h3>/);
507
+ if (!nameMatch) continue;
508
+ const installsMatch = chunk.match(/aria-label="Weekly installs: ([\d,]+)/);
509
+ items.push({
510
+ id,
511
+ owner: parts[0],
512
+ repo: parts[1],
513
+ skillId: parts[2],
514
+ name: decodeEntities(nameMatch[1]).trim(),
515
+ installs: installsMatch ? Number(installsMatch[1].replace(/,/g, '')) : 0
516
+ });
517
+ }
518
+ const seen = new Set();
519
+ return items.filter((item) => {
520
+ if (seen.has(item.id)) return false;
521
+ seen.add(item.id);
522
+ return true;
523
+ });
524
+ }
525
+
526
+ function parseSkillsShDetail(html) {
527
+ const text = String(html);
528
+ let desc = '';
529
+ const meta = text.match(/<meta name="description" content="([^"]*)"/);
530
+ if (meta) desc = decodeEntities(meta[1]).replace(/\u2026\s*$/, '').trim();
531
+ const prose = text.match(/class="prose[^"]*"[^>]*>\s*<p>(?:<strong>)?([\s\S]{15,700}?)(?:<\/strong>)?<\/p>/);
532
+ if (prose) {
533
+ const candidate = stripTags(prose[1]);
534
+ if (candidate.length > desc.length) desc = candidate;
535
+ }
536
+ return desc;
537
+ }
538
+
539
+ async function fetchSkillsShList(source, force = false) {
540
+ const cached = skillsShListCache.get(source.id);
541
+ if (!force && cached && Date.now() - cached.at < 10 * 60 * 1000) return cached.items;
542
+ const html = await fetchText(source.baseUrl.replace(/\/$/, '') + '/', {}, 25000);
543
+ const items = parseSkillsShIndex(html);
544
+ if (items.length === 0) throw new Error('skills.sh 首页没有解析到技能');
545
+ skillsShListCache.set(source.id, { at: Date.now(), items });
546
+ return items;
547
+ }
548
+
549
+ async function fetchSkillsShDetail(source, item) {
550
+ const cacheKey = source.id + ':' + item.id;
551
+ const cached = skillsShDetailCache[cacheKey];
552
+ if (cached && Date.now() - cached.at < 7 * 24 * 60 * 60 * 1000) return cached.description;
553
+ const html = await fetchText(source.baseUrl.replace(/\/$/, '') + '/' + item.id, {}, 20000);
554
+ const description = parseSkillsShDetail(html);
555
+ skillsShDetailCache[cacheKey] = { at: Date.now(), description };
556
+ scheduleSaveDetail();
557
+ return description;
558
+ }
559
+
560
+ async function listSkillsSh(source, q, limit, force) {
561
+ let base;
562
+ if (q) {
563
+ const url =
564
+ source.baseUrl.replace(/\/$/, '') +
565
+ '/api/search?q=' +
566
+ encodeURIComponent(q) +
567
+ '&limit=' +
568
+ Math.min(limit * 2, 40);
569
+ const data = await fetchJson(url, {}, 20000);
570
+ base = (Array.isArray(data.skills) ? data.skills : []).map((raw) => ({
571
+ id: raw.id,
572
+ owner: (raw.source || '').split('/')[0],
573
+ repo: (raw.source || '').split('/')[1] || '',
574
+ skillId: raw.skillId || raw.name,
575
+ name: raw.name || raw.skillId,
576
+ installs: Number(raw.installs) || 0
577
+ }));
578
+ } else {
579
+ base = (await fetchSkillsShList(source, force)).slice(0, Math.min(Math.max(limit, 24), 80));
580
+ }
581
+ base = base.slice(0, Math.min(Math.max(limit, 12), 80));
582
+
583
+ const withDesc = await mapLimit(base, 6, async (item) => {
584
+ let description = '';
585
+ try {
586
+ description = await fetchSkillsShDetail(source, item);
587
+ } catch {
588
+ description = '';
589
+ }
590
+ return { ...item, description };
591
+ });
592
+
593
+ return withDesc.map((item) => ({
594
+ source: source.id,
595
+ id: item.id,
596
+ name: item.name,
597
+ nameZh: '',
598
+ description: item.description || '',
599
+ descriptionZh: '',
600
+ url: source.baseUrl.replace(/\/$/, '') + '/' + item.id,
601
+ tags: [],
602
+ installs: item.installs,
603
+ author: item.owner,
604
+ domain: '',
605
+ version: '',
606
+ downloadUrl: '',
607
+ repo: item.owner + '/' + item.repo,
608
+ skillId: item.skillId
609
+ }));
610
+ }
611
+
612
+ // -------------------------------------------------------------------------
613
+ // GitHub 源
614
+ // -------------------------------------------------------------------------
615
+
616
+ function parseFrontmatter(text) {
617
+ const result = {};
618
+ const match = String(text).match(/^---\s*\r?\n([\s\S]*?)\r?\n---/);
619
+ if (!match) return result;
620
+ const lines = match[1].split(/\r?\n/);
621
+ for (let i = 0; i < lines.length; i += 1) {
622
+ const kv = lines[i].match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
623
+ if (!kv) continue;
624
+ const key = kv[1];
625
+ let value = kv[2].trim();
626
+ if (value === '|' || value === '>') {
627
+ const block = [];
628
+ while (i + 1 < lines.length && /^\s{2,}\S/.test(lines[i + 1])) {
629
+ block.push(lines[i + 1].trim());
630
+ i += 1;
631
+ }
632
+ value = block.join(value === '|' ? '\n' : ' ');
633
+ } else if (/^['"].*['"]$/.test(value)) {
634
+ value = value.slice(1, -1);
635
+ }
636
+ result[key] = value;
637
+ }
638
+ return result;
639
+ }
640
+
641
+ async function fetchGithubList(source, force = false) {
642
+ const cached = githubCache.get(source.id);
643
+ if (!force && cached && Date.now() - cached.at < 30 * 60 * 1000) return cached.items;
644
+ const repo = source.repo;
645
+ const subPath = (source.path || 'skills').replace(/^\/+|\/+$/g, '');
646
+ const data = await fetchJson(
647
+ 'https://api.github.com/repos/' + repo + '/contents/' + subPath,
648
+ { headers: { 'User-Agent': 'dsh-skill-bazaar' } },
649
+ 20000
650
+ );
651
+ if (!Array.isArray(data)) throw new Error('GitHub 目录结构异常');
652
+ const dirs = data.filter((entry) => entry.type === 'dir');
653
+
654
+ const items = await mapLimit(dirs, 4, async (dir) => {
655
+ try {
656
+ const md = await fetchJson(
657
+ 'https://api.github.com/repos/' + repo + '/contents/' + subPath + '/' + dir.name + '/SKILL.md',
658
+ { headers: { 'User-Agent': 'dsh-skill-bazaar' } },
659
+ 20000
660
+ );
661
+ const content = Buffer.from(md.content || '', 'base64').toString('utf8');
662
+ const fm = parseFrontmatter(content);
663
+ return { name: fm.name || dir.name, description: fm.description || '', dirName: dir.name };
664
+ } catch {
665
+ return null;
666
+ }
667
+ });
668
+
669
+ const list = items.filter(Boolean);
670
+ const mapped = list.map((item) => ({
671
+ source: source.id,
672
+ id: subPath + '/' + item.dirName,
673
+ name: item.name,
674
+ nameZh: '',
675
+ description: item.description,
676
+ descriptionZh: '',
677
+ url: 'https://github.com/' + repo + '/tree/HEAD/' + subPath + '/' + item.dirName,
678
+ tags: [],
679
+ installs: 0,
680
+ author: repo.split('/')[0],
681
+ domain: '',
682
+ version: '',
683
+ downloadUrl: '',
684
+ repo,
685
+ skillId: item.dirName,
686
+ githubDir: subPath + '/' + item.dirName
687
+ }));
688
+ githubCache.set(source.id, { at: Date.now(), items: mapped });
689
+ return mapped;
690
+ }
691
+
692
+ async function listGithub(source, q, limit, force) {
693
+ let items = await fetchGithubList(source, force);
694
+ if (q) {
695
+ const needle = q.toLowerCase();
696
+ items = items.filter((item) =>
697
+ [item.name, item.description, item.author].join(' ').toLowerCase().includes(needle)
698
+ );
699
+ }
700
+ return items.slice(0, limit);
701
+ }
702
+
703
+ // -------------------------------------------------------------------------
704
+ // 自定义 JSON 源
705
+ // -------------------------------------------------------------------------
706
+
707
+ async function fetchJsonSourceList(source, force = false) {
708
+ const cached = jsonSourceCache.get(source.id);
709
+ if (!force && cached && Date.now() - cached.at < 10 * 60 * 1000) return cached.items;
710
+ const url = source.listUrl || source.baseUrl;
711
+ if (!url) throw new Error('自定义源缺少 listUrl');
712
+ const data = await fetchJson(url, {}, 20000);
713
+ const arr = Array.isArray(data) ? data : data.items || data.skills || [];
714
+ if (!Array.isArray(arr)) throw new Error('自定义源返回的不是数组');
715
+ const fields = source.fields || {};
716
+ const pick = (obj, key, fallback) => {
717
+ const field = fields[key] || fallback;
718
+ return field && obj[field] !== undefined ? obj[field] : '';
719
+ };
720
+ const items = arr.map((raw, index) => {
721
+ const itemName = String(pick(raw, 'name', 'name'));
722
+ return {
723
+ source: source.id,
724
+ id: String(pick(raw, 'id', 'id') || itemName || index),
725
+ name: itemName,
726
+ nameZh: '',
727
+ description: String(pick(raw, 'description', 'description')),
728
+ descriptionZh: '',
729
+ url: String(pick(raw, 'url', 'url') || ''),
730
+ tags: Array.isArray(pick(raw, 'tags', 'tags')) ? pick(raw, 'tags', 'tags').slice(0, 6) : [],
731
+ installs: Number(pick(raw, 'installs', 'installs')) || 0,
732
+ author: String(pick(raw, 'author', 'author') || ''),
733
+ domain: '',
734
+ version: '',
735
+ downloadUrl: String(pick(raw, 'downloadUrl', 'downloadUrl') || ''),
736
+ repo: String(pick(raw, 'repo', 'repo') || ''),
737
+ skillId: String(pick(raw, 'skillId', 'skillId') || itemName),
738
+ raw
739
+ };
740
+ });
741
+ jsonSourceCache.set(source.id, { at: Date.now(), items });
742
+ return items;
743
+ }
744
+
745
+ async function listJsonSource(source, q, limit, force) {
746
+ let items = await fetchJsonSourceList(source, force);
747
+ if (q) {
748
+ const needle = q.toLowerCase();
749
+ items = items.filter((item) =>
750
+ [item.name, item.description, item.author, ...item.tags].join(' ').toLowerCase().includes(needle)
751
+ );
752
+ }
753
+ return items.slice(0, limit);
754
+ }
755
+
756
+ // -------------------------------------------------------------------------
757
+ // 聚合 + 翻译
758
+ // -------------------------------------------------------------------------
759
+
760
+ async function listSource(source, q, limit, force) {
761
+ switch (source.type) {
762
+ case 'cherryin':
763
+ return await listCherryin(source, q, limit, force);
764
+ case 'skills-sh':
765
+ return await listSkillsSh(source, q, limit, force);
766
+ case 'github':
767
+ return await listGithub(source, q, limit, force);
768
+ case 'json':
769
+ return await listJsonSource(source, q, limit, force);
770
+ default:
771
+ throw new Error('未知的源类型: ' + source.type);
772
+ }
773
+ }
774
+
775
+ async function loadSkills({ sourceId = 'all', q = '', limit = 30, force = false, onlyPackage = false } = {}) {
776
+ const configData = loadSourcesConfig();
777
+ const sources = configData.sources.filter((s) => s.enabled !== false);
778
+ const selected = sourceId === 'all' ? sources : sources.filter((s) => s.id === sourceId);
779
+ const errors = [];
780
+ const groups = await mapLimit(selected, 4, async (source) => {
781
+ try {
782
+ return await listSource(source, q, limit, force);
783
+ } catch (err) {
784
+ errors.push({ source: source.id, name: source.name, message: err.message });
785
+ return [];
786
+ }
787
+ });
788
+ let items = groups.flat().slice(0, limit * Math.max(1, selected.length));
789
+
790
+ const texts = [];
791
+ for (const item of items) {
792
+ if (item.nameZh) texts.push(item.nameZh);
793
+ else if (item.name) texts.push(item.name);
794
+ if (item.descriptionZh) texts.push(item.descriptionZh);
795
+ else if (item.description) texts.push(item.description);
796
+ }
797
+ let translated = {};
798
+ try {
799
+ translated = await translateTexts(texts);
800
+ } catch (err) {
801
+ ctx.logger?.warn?.('[skill-bazaar] 批量翻译失败: ' + err.message);
802
+ }
803
+ for (const item of items) {
804
+ if (!item.nameZh && item.name) item.nameZh = translated[item.name] || '';
805
+ if (!item.descriptionZh && item.description) item.descriptionZh = translated[item.description] || '';
806
+ }
807
+
808
+ if (onlyPackage) items = items.filter((item) => isPackageItem(item));
809
+
810
+ const installed = scanInstalled();
811
+ const installedNames = new Set(installed.map((s) => s.name.toLowerCase()));
812
+ const installedDirs = new Set(installed.map((s) => s.dir.toLowerCase()));
813
+ for (const item of items) {
814
+ item.installed =
815
+ installedDirs.has(sanitizeDirName(item.skillId || item.name).toLowerCase()) ||
816
+ installedNames.has(String(item.skillId || item.name).toLowerCase());
817
+ item.installable = Boolean(item.downloadUrl || item.repo);
818
+ }
819
+ return { items, errors, sources: sources.map(publicSource) };
820
+ }
821
+
822
+ /** 技能包判定:描述带“包含 N 个”或标签含 collection。 */
823
+ function isPackageItem(item) {
824
+ const text = String(item.descriptionZh || item.description || '');
825
+ return /包含\s*\d+\s*个/.test(text) || (item.tags || []).includes('collection');
826
+ }
827
+
828
+ // -------------------------------------------------------------------------
829
+ // 安装
830
+ // -------------------------------------------------------------------------
831
+
832
+ function unzipBuffer(buffer, destDir) {
833
+ const buf = buffer;
834
+ let eocd = -1;
835
+ const min = Math.max(0, buf.length - 22 - 65536);
836
+ for (let i = buf.length - 22; i >= min; i -= 1) {
837
+ if (buf.readUInt32LE(i) === 0x06054b50) {
838
+ eocd = i;
839
+ break;
840
+ }
841
+ }
842
+ if (eocd < 0) throw new Error('不是有效的 zip 文件');
843
+ const count = buf.readUInt16LE(eocd + 10);
844
+ let offset = buf.readUInt32LE(eocd + 16);
845
+ const destRoot = resolve(destDir) + sep;
846
+ for (let n = 0; n < count; n += 1) {
847
+ if (buf.readUInt32LE(offset) !== 0x02014b50) break;
848
+ const method = buf.readUInt16LE(offset + 10);
849
+ const compSize = buf.readUInt32LE(offset + 20);
850
+ const nameLen = buf.readUInt16LE(offset + 28);
851
+ const extraLen = buf.readUInt16LE(offset + 30);
852
+ const commentLen = buf.readUInt16LE(offset + 32);
853
+ const localOffset = buf.readUInt32LE(offset + 42);
854
+ const entryName = buf.toString('utf8', offset + 46, offset + 46 + nameLen);
855
+ offset += 46 + nameLen + extraLen + commentLen;
856
+ if (!entryName || entryName.endsWith('/')) continue;
857
+ const localNameLen = buf.readUInt16LE(localOffset + 26);
858
+ const localExtraLen = buf.readUInt16LE(localOffset + 28);
859
+ const dataStart = localOffset + 30 + localNameLen + localExtraLen;
860
+ const compressed = buf.subarray(dataStart, dataStart + compSize);
861
+ let data;
862
+ if (method === 0) data = compressed;
863
+ else if (method === 8) data = inflateRawSync(compressed);
864
+ else continue;
865
+ const outPath = resolve(destDir, entryName);
866
+ if (!outPath.startsWith(destRoot)) continue;
867
+ mkdirSync(dirname(outPath), { recursive: true });
868
+ writeFileSync(outPath, data);
869
+ }
870
+ }
871
+
872
+ function findSkillRoots(rootDir) {
873
+ const found = [];
874
+ const walk = (dir, depth) => {
875
+ if (depth > 6) return;
876
+ let entries;
877
+ try {
878
+ entries = readdirSync(dir, { withFileTypes: true });
879
+ } catch {
880
+ return;
881
+ }
882
+ if (entries.some((e) => e.isFile() && e.name.toLowerCase() === 'skill.md')) {
883
+ found.push({ dir, depth });
884
+ }
885
+ for (const entry of entries) {
886
+ if (entry.isDirectory() && entry.name !== 'node_modules' && entry.name !== '.git') {
887
+ walk(join(dir, entry.name), depth + 1);
888
+ }
889
+ }
890
+ };
891
+ walk(rootDir, 0);
892
+ if (found.length === 0) return [];
893
+ found.sort((a, b) => a.depth - b.depth);
894
+ const roots = [];
895
+ for (const item of found) {
896
+ const resolved = resolve(item.dir);
897
+ if (!roots.some((parent) => resolved.startsWith(resolve(parent) + sep))) {
898
+ roots.push(item.dir);
899
+ }
900
+ }
901
+ return roots;
902
+ }
903
+
904
+ function findSkillRoot(rootDir) {
905
+ return findSkillRoots(rootDir)[0] || null;
906
+ }
907
+
908
+ function sleep(ms) {
909
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
910
+ }
911
+
912
+ /** 解压 GitHub codeload 的 tar.gz(不需要 git,国内可直连)。 */
913
+ function untarGz(buffer, destDir) {
914
+ const tar = gunzipSync(buffer);
915
+ const root = resolve(destDir) + sep;
916
+ let offset = 0;
917
+ while (offset + 512 <= tar.length) {
918
+ const header = tar.subarray(offset, offset + 512);
919
+ if (header.every((byte) => byte === 0)) break;
920
+ const readStr = (start, length) => {
921
+ let end = start;
922
+ while (end < start + length && tar[end] !== 0) end += 1;
923
+ return tar.toString('utf8', start, end);
924
+ };
925
+ const name = readStr(offset, 100);
926
+ const prefix = readStr(offset + 345, 155);
927
+ const fullName = prefix ? prefix + '/' + name : name;
928
+ const size = parseInt(readStr(offset + 124, 12).trim(), 8) || 0;
929
+ const type = String.fromCharCode(header[156] || 0);
930
+ const dataStart = offset + 512;
931
+ offset = dataStart + Math.ceil(size / 512) * 512;
932
+ if (!fullName || fullName.endsWith('/')) continue;
933
+ if (type === '1' || type === '2' || type === '5') continue;
934
+ const outPath = resolve(destDir, fullName);
935
+ if (!outPath.startsWith(root)) continue;
936
+ mkdirSync(dirname(outPath), { recursive: true });
937
+ writeFileSync(outPath, tar.subarray(dataStart, dataStart + size));
938
+ }
939
+ }
940
+
941
+ /**
942
+ * 获取 GitHub 仓库内容:优先 codeload tarball(国内直连更稳),失败回退 git clone。
943
+ */
944
+ async function fetchRepoTree(repo, destDir) {
945
+ try {
946
+ const tar = await fetchBuffer(
947
+ 'https://codeload.github.com/' + repo + '/tar.gz/HEAD',
948
+ {},
949
+ 180000
950
+ );
951
+ untarGz(tar, destDir);
952
+ return;
953
+ } catch (err) {
954
+ ctx.logger?.warn?.('[skill-bazaar] codeload 失败,回退 git clone: ' + err.message);
955
+ rmSync(destDir, { recursive: true, force: true });
956
+ mkdirSync(destDir, { recursive: true });
957
+ await runCommand(
958
+ 'git',
959
+ ['clone', '--depth', '1', '--quiet', 'https://github.com/' + repo + '.git', destDir],
960
+ 240000
961
+ );
962
+ }
963
+ }
964
+
965
+ /**
966
+ * 安装技能包:一个压缩包/仓库里有多个技能目录(每个含 SKILL.md)时,
967
+ * 把每个技能分别复制到目标目录,而不是只取第一个。
968
+ */
969
+ async function installSkillPackage(roots, force, targetDir) {
970
+ const base = targetDir || skillsDir;
971
+ mkdirSync(base, { recursive: true });
972
+ const plans = [];
973
+ const seen = new Set();
974
+ for (const root of roots) {
975
+ const fm = readSkillFrontmatter(root);
976
+ let name = sanitizeDirName(fm.name || basename(root));
977
+ let index = 2;
978
+ while (seen.has(name)) {
979
+ name = sanitizeDirName((fm.name || basename(root)) + '-' + index);
980
+ index += 1;
981
+ }
982
+ seen.add(name);
983
+ plans.push({ root, name });
984
+ }
985
+
986
+ const conflicts = [];
987
+ for (const plan of plans) {
988
+ const target = join(base, plan.name);
989
+ if (!existsSync(target)) continue;
990
+ let isEmpty = false;
991
+ try {
992
+ isEmpty = readdirSync(target).length === 0;
993
+ } catch {
994
+ isEmpty = false;
995
+ }
996
+ if (!isEmpty) conflicts.push(target);
997
+ }
998
+ if (conflicts.length > 0 && !force) {
999
+ return { conflict: true, paths: conflicts, path: base };
1000
+ }
1001
+
1002
+ const installed = [];
1003
+ for (const plan of plans) {
1004
+ const target = join(base, plan.name);
1005
+ let lastError = null;
1006
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
1007
+ try {
1008
+ if (existsSync(target)) rmSync(target, { recursive: true, force: true });
1009
+ cpSync(plan.root, target, { recursive: true });
1010
+ lastError = null;
1011
+ break;
1012
+ } catch (err) {
1013
+ lastError = err;
1014
+ try {
1015
+ rmSync(target, { recursive: true, force: true });
1016
+ } catch {}
1017
+ if (attempt < 3) await sleep(250 * attempt);
1018
+ }
1019
+ }
1020
+ if (lastError) throw lastError;
1021
+ installed.push({ name: plan.name, path: target });
1022
+ }
1023
+ return {
1024
+ conflict: false,
1025
+ path: base,
1026
+ package: plans.length > 1,
1027
+ skillCount: plans.length,
1028
+ installed
1029
+ };
1030
+ }
1031
+
1032
+ function readSkillFrontmatter(dir) {
1033
+ try {
1034
+ return parseFrontmatter(readFileSync(join(dir, 'SKILL.md'), 'utf8'));
1035
+ } catch {
1036
+ return {};
1037
+ }
1038
+ }
1039
+
1040
+ function scanInstalled() {
1041
+ const out = [];
1042
+ const seen = new Set();
1043
+ const bases = scanDirs();
1044
+ for (const base of bases) {
1045
+ if (!existsSync(base)) continue;
1046
+ let entries;
1047
+ try {
1048
+ entries = readdirSync(base, { withFileTypes: true });
1049
+ } catch {
1050
+ continue;
1051
+ }
1052
+ for (const entry of entries) {
1053
+ if (!entry.isDirectory()) continue;
1054
+ const key = base + '::' + entry.name;
1055
+ if (seen.has(key)) continue;
1056
+ seen.add(key);
1057
+ const dir = join(base, entry.name);
1058
+ if (!existsSync(join(dir, 'SKILL.md'))) continue;
1059
+ const fm = readSkillFrontmatter(dir);
1060
+ out.push({
1061
+ dir: entry.name,
1062
+ name: fm.name || entry.name,
1063
+ description: fm.description || '',
1064
+ target: base
1065
+ });
1066
+ }
1067
+ }
1068
+ return out;
1069
+ }
1070
+
1071
+ function runCommand(command, args, timeout = 180000) {
1072
+ return new Promise((resolvePromise, reject) => {
1073
+ const child = spawn(command, args, { windowsHide: true });
1074
+ let stdout = '';
1075
+ let stderr = '';
1076
+ const timer = setTimeout(() => {
1077
+ child.kill();
1078
+ reject(new Error(command + ' 超时'));
1079
+ }, timeout);
1080
+ child.stdout.on('data', (d) => {
1081
+ stdout += d.toString();
1082
+ });
1083
+ child.stderr.on('data', (d) => {
1084
+ stderr += d.toString();
1085
+ });
1086
+ child.on('error', (err) => {
1087
+ clearTimeout(timer);
1088
+ reject(err);
1089
+ });
1090
+ child.on('close', (code) => {
1091
+ clearTimeout(timer);
1092
+ if (code === 0) resolvePromise(stdout);
1093
+ else reject(new Error((stderr || stdout || command + ' 退出码 ' + code).trim().slice(0, 500)));
1094
+ });
1095
+ });
1096
+ }
1097
+
1098
+ async function copySkillIntoPlace(sourceDir, targetName, force, targetDir) {
1099
+ const base = targetDir || skillsDir;
1100
+ mkdirSync(base, { recursive: true });
1101
+ const target = join(base, targetName);
1102
+ let lastError = null;
1103
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
1104
+ try {
1105
+ if (existsSync(target)) {
1106
+ let isEmpty = false;
1107
+ try {
1108
+ isEmpty = readdirSync(target).length === 0;
1109
+ } catch {
1110
+ isEmpty = false;
1111
+ }
1112
+ if (!isEmpty && !force) {
1113
+ return { conflict: true, path: target };
1114
+ }
1115
+ rmSync(target, { recursive: true, force: true });
1116
+ }
1117
+ cpSync(sourceDir, target, { recursive: true });
1118
+ return { conflict: false, path: target };
1119
+ } catch (err) {
1120
+ lastError = err;
1121
+ try {
1122
+ rmSync(target, { recursive: true, force: true });
1123
+ } catch {}
1124
+ if (attempt < 3) await sleep(250 * attempt);
1125
+ }
1126
+ }
1127
+ throw lastError;
1128
+ }
1129
+
1130
+ async function installSkill(source, skillId, force = false, targetDir) {
1131
+ if (!source) throw new Error('源不存在');
1132
+
1133
+ if (source.type === 'cherryin') {
1134
+ const raws = await fetchCherryinAll(source);
1135
+ const raw = raws.find((r) => r.id === skillId);
1136
+ if (!raw) throw new Error('技能不存在');
1137
+ const mapped = mapCherryin(source, raw);
1138
+ if (!mapped.downloadUrl) throw new Error('该技能没有可下载的安装包');
1139
+ const zip = await fetchBuffer(mapped.downloadUrl, {}, 120000);
1140
+ const tmp = mkdtempSync(join(tmpdir(), 'skill-bazaar-'));
1141
+ try {
1142
+ unzipBuffer(zip, tmp);
1143
+ const roots = findSkillRoots(tmp);
1144
+ if (roots.length === 0) throw new Error('安装包中没有找到 SKILL.md');
1145
+ if (roots.length > 1) {
1146
+ return installSkillPackage(roots, force, targetDir);
1147
+ }
1148
+ const root = roots[0];
1149
+ const fm = readSkillFrontmatter(root);
1150
+ const targetName = sanitizeDirName(
1151
+ fm.name || basename(root).replace(/-HEAD$/i, '') || mapped.name
1152
+ );
1153
+ return copySkillIntoPlace(root, targetName, force, targetDir);
1154
+ } finally {
1155
+ rmSync(tmp, { recursive: true, force: true });
1156
+ }
1157
+ }
1158
+
1159
+ if (source.type === 'skills-sh' || source.type === 'github') {
1160
+ let repo = '';
1161
+ let skillKey = '';
1162
+ if (source.type === 'skills-sh') {
1163
+ const parts = String(skillId).split('/');
1164
+ if (parts.length !== 3) throw new Error('技能标识格式应为 owner/repo/skill');
1165
+ repo = parts[0] + '/' + parts[1];
1166
+ skillKey = parts[2];
1167
+ } else {
1168
+ const list = await fetchGithubList(source);
1169
+ const item = list.find((s) => s.id === skillId);
1170
+ if (!item) throw new Error('技能不存在');
1171
+ repo = item.repo;
1172
+ skillKey = item.skillId;
1173
+ }
1174
+ const tmp = mkdtempSync(join(tmpdir(), 'skill-bazaar-'));
1175
+ try {
1176
+ await fetchRepoTree(repo, tmp);
1177
+ const candidates = [];
1178
+ const walk = (dir, depth) => {
1179
+ if (depth > 6) return;
1180
+ let entries;
1181
+ try {
1182
+ entries = readdirSync(dir, { withFileTypes: true });
1183
+ } catch {
1184
+ return;
1185
+ }
1186
+ if (entries.some((e) => e.isFile() && e.name.toLowerCase() === 'skill.md')) candidates.push(dir);
1187
+ for (const entry of entries) {
1188
+ if (entry.isDirectory() && entry.name !== '.git' && entry.name !== 'node_modules') {
1189
+ walk(join(dir, entry.name), depth + 1);
1190
+ }
1191
+ }
1192
+ };
1193
+ walk(tmp, 0);
1194
+ let chosen = candidates.find((dir) => {
1195
+ const fm = readSkillFrontmatter(dir);
1196
+ const fmName = String(fm.name || '').toLowerCase();
1197
+ const base = basename(dir).toLowerCase();
1198
+ return fmName === String(skillKey).toLowerCase() || base === String(skillKey).toLowerCase();
1199
+ });
1200
+ if (!chosen && candidates.length === 1) chosen = candidates[0];
1201
+ if (!chosen) throw new Error('仓库中没有找到技能 ' + skillKey);
1202
+ const fm = readSkillFrontmatter(chosen);
1203
+ return copySkillIntoPlace(chosen, sanitizeDirName(fm.name || skillKey), force, targetDir);
1204
+ } finally {
1205
+ rmSync(tmp, { recursive: true, force: true });
1206
+ }
1207
+ }
1208
+
1209
+ if (source.type === 'json') {
1210
+ const items = await fetchJsonSourceList(source);
1211
+ const item = items.find((s) => s.id === skillId);
1212
+ if (!item) throw new Error('技能不存在');
1213
+ if (item.repo) {
1214
+ const tmp = mkdtempSync(join(tmpdir(), 'skill-bazaar-'));
1215
+ try {
1216
+ await fetchRepoTree(item.repo, tmp);
1217
+ const roots = findSkillRoots(tmp);
1218
+ if (roots.length === 0) throw new Error('仓库中没有找到 SKILL.md');
1219
+ if (roots.length > 1) return installSkillPackage(roots, force, targetDir);
1220
+ const root = roots[0];
1221
+ const fm = readSkillFrontmatter(root);
1222
+ return copySkillIntoPlace(root, sanitizeDirName(fm.name || item.skillId), force, targetDir);
1223
+ } finally {
1224
+ rmSync(tmp, { recursive: true, force: true });
1225
+ }
1226
+ }
1227
+ if (item.downloadUrl) {
1228
+ const zip = await fetchBuffer(item.downloadUrl, {}, 120000);
1229
+ const tmp = mkdtempSync(join(tmpdir(), 'skill-bazaar-'));
1230
+ try {
1231
+ unzipBuffer(zip, tmp);
1232
+ const roots = findSkillRoots(tmp);
1233
+ if (roots.length === 0) throw new Error('安装包中没有找到 SKILL.md');
1234
+ if (roots.length > 1) return installSkillPackage(roots, force, targetDir);
1235
+ const root = roots[0];
1236
+ const fm = readSkillFrontmatter(root);
1237
+ return copySkillIntoPlace(root, sanitizeDirName(fm.name || item.skillId), force, targetDir);
1238
+ } finally {
1239
+ rmSync(tmp, { recursive: true, force: true });
1240
+ }
1241
+ }
1242
+ throw new Error('该技能没有配置安装方式');
1243
+ }
1244
+
1245
+ throw new Error('该源不支持安装');
1246
+ }
1247
+
1248
+ // -------------------------------------------------------------------------
1249
+ // 路由
1250
+ // -------------------------------------------------------------------------
1251
+
1252
+ function isLoopback(req) {
1253
+ const address = req.socket?.remoteAddress || '';
1254
+ return (
1255
+ address === '127.0.0.1' ||
1256
+ address === '::1' ||
1257
+ address === '::ffff:127.0.0.1'
1258
+ );
1259
+ }
1260
+
1261
+ function guard(req, res, method) {
1262
+ if (!isLoopback(req)) {
1263
+ writeJson(res, 403, { error: 'forbidden: loopback-only' });
1264
+ return false;
1265
+ }
1266
+ if (req.method !== method) {
1267
+ writeJson(res, 405, { error: 'method not allowed: ' + req.method });
1268
+ return false;
1269
+ }
1270
+ return true;
1271
+ }
1272
+
1273
+ const routes = [
1274
+ {
1275
+ kind: 'exact',
1276
+ path: '/api/skill-bazaar/sources',
1277
+ auth: 'anonymous',
1278
+ handler: async (req, res) => {
1279
+ if (!isLoopback(req)) return writeJson(res, 403, { error: 'forbidden: loopback-only' });
1280
+ try {
1281
+ const url = new URL(req.url ?? '/', HOST_ORIGIN);
1282
+ const data = loadSourcesConfig();
1283
+ if (req.method === 'GET') {
1284
+ return writeJson(res, 200, { sources: data.sources.map(publicSource) });
1285
+ }
1286
+ if (req.method === 'DELETE') {
1287
+ const id = url.searchParams.get('id');
1288
+ const index = data.sources.findIndex((s) => s.id === id);
1289
+ if (index < 0) return writeJson(res, 404, { error: '源不存在' });
1290
+ if (data.sources[index].builtin) {
1291
+ return writeJson(res, 400, { error: '默认源不能删除,可以停用' });
1292
+ }
1293
+ data.sources.splice(index, 1);
1294
+ saveSourcesConfig(data);
1295
+ return writeJson(res, 200, { ok: true });
1296
+ }
1297
+ if (req.method === 'POST') {
1298
+ const body = await readBody(req);
1299
+ if (body.id) {
1300
+ const existing = data.sources.find((s) => s.id === body.id);
1301
+ if (!existing) return writeJson(res, 404, { error: '源不存在' });
1302
+ Object.assign(existing, {
1303
+ name: body.name || existing.name,
1304
+ enabled: body.enabled !== undefined ? Boolean(body.enabled) : existing.enabled
1305
+ });
1306
+ saveSourcesConfig(data);
1307
+ return writeJson(res, 200, { ok: true, source: publicSource(existing) });
1308
+ }
1309
+ const type = body.type;
1310
+ if (!['cherryin', 'skills-sh', 'github', 'json'].includes(type)) {
1311
+ return writeJson(res, 400, { error: '不支持的源类型' });
1312
+ }
1313
+ const sourceName = String(body.name || '').trim();
1314
+ if (!sourceName) return writeJson(res, 400, { error: '源名称不能为空' });
1315
+ const source = {
1316
+ id: 'custom-' + randomBytes(4).toString('hex'),
1317
+ name: sourceName,
1318
+ type,
1319
+ enabled: true,
1320
+ builtin: false
1321
+ };
1322
+ if (type === 'github') {
1323
+ source.repo = String(body.repo || '').trim();
1324
+ source.path = String(body.path || 'skills').trim();
1325
+ if (!/^[^/\s]+\/[^/\s]+$/.test(source.repo)) {
1326
+ return writeJson(res, 400, { error: 'GitHub 仓库格式应为 owner/repo' });
1327
+ }
1328
+ } else if (type === 'json') {
1329
+ source.listUrl = String(body.listUrl || '').trim();
1330
+ source.fields = body.fields || {};
1331
+ if (!source.listUrl) return writeJson(res, 400, { error: '自定义源需要 listUrl' });
1332
+ } else {
1333
+ source.baseUrl = String(body.baseUrl || '').trim();
1334
+ if (!/^https?:\/\//.test(source.baseUrl)) {
1335
+ return writeJson(res, 400, { error: '源地址需要以 http(s):// 开头' });
1336
+ }
1337
+ }
1338
+ data.sources.push(source);
1339
+ saveSourcesConfig(data);
1340
+ return writeJson(res, 200, { ok: true, source: publicSource(source) });
1341
+ }
1342
+ return writeJson(res, 405, { error: 'method not allowed: ' + req.method });
1343
+ } catch (err) {
1344
+ writeJson(res, 500, { error: err.message });
1345
+ }
1346
+ }
1347
+ },
1348
+ {
1349
+ kind: 'exact',
1350
+ path: '/api/skill-bazaar/skills',
1351
+ auth: 'anonymous',
1352
+ handler: async (req, res) => {
1353
+ if (!guard(req, res, 'GET')) return;
1354
+ try {
1355
+ const url = new URL(req.url ?? '/', HOST_ORIGIN);
1356
+ const sourceId = url.searchParams.get('source') || 'all';
1357
+ const q = (url.searchParams.get('q') || '').trim();
1358
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 30, 1), 300);
1359
+ const force = url.searchParams.get('refresh') === '1';
1360
+ const onlyPackage = url.searchParams.get('package') === '1';
1361
+ const result = await loadSkills({ sourceId, q, limit, force, onlyPackage });
1362
+ writeJson(res, 200, result);
1363
+ } catch (err) {
1364
+ writeJson(res, 500, { error: err.message });
1365
+ }
1366
+ }
1367
+ },
1368
+ {
1369
+ kind: 'exact',
1370
+ path: '/api/skill-bazaar/skill',
1371
+ auth: 'anonymous',
1372
+ handler: async (req, res) => {
1373
+ if (!guard(req, res, 'GET')) return;
1374
+ try {
1375
+ const url = new URL(req.url ?? '/', HOST_ORIGIN);
1376
+ const sourceId = url.searchParams.get('source');
1377
+ const id = url.searchParams.get('id');
1378
+ const source = getSource(sourceId);
1379
+ if (!source) return writeJson(res, 404, { error: '源不存在' });
1380
+ let item;
1381
+ if (source.type === 'cherryin') {
1382
+ const raws = await fetchCherryinAll(source);
1383
+ const raw = raws.find((r) => r.id === id);
1384
+ if (raw) item = mapCherryin(source, raw);
1385
+ } else if (source.type === 'skills-sh') {
1386
+ const parts = String(id).split('/');
1387
+ if (parts.length === 3) {
1388
+ const [owner, repo, skillId] = parts;
1389
+ let description = '';
1390
+ let installs = 0;
1391
+ try {
1392
+ const found = (await fetchSkillsShList(source)).find((s) => s.id === id);
1393
+ if (found) installs = found.installs;
1394
+ } catch {}
1395
+ try {
1396
+ description = await fetchSkillsShDetail(source, { id, owner, repo, skillId });
1397
+ } catch {}
1398
+ item = {
1399
+ source: source.id,
1400
+ id,
1401
+ name: skillId,
1402
+ nameZh: '',
1403
+ description,
1404
+ descriptionZh: '',
1405
+ url: source.baseUrl.replace(/\/$/, '') + '/' + id,
1406
+ tags: [],
1407
+ installs,
1408
+ author: owner,
1409
+ domain: '',
1410
+ version: '',
1411
+ downloadUrl: '',
1412
+ repo: owner + '/' + repo,
1413
+ skillId
1414
+ };
1415
+ }
1416
+ } else if (source.type === 'github') {
1417
+ const list = await fetchGithubList(source);
1418
+ item = list.find((s) => s.id === id);
1419
+ } else if (source.type === 'json') {
1420
+ const list = await fetchJsonSourceList(source);
1421
+ item = list.find((s) => s.id === id);
1422
+ }
1423
+ if (!item) return writeJson(res, 404, { error: '技能不存在' });
1424
+ if (!item.nameZh && item.name) {
1425
+ try {
1426
+ const t = await translateTexts([item.name]);
1427
+ item.nameZh = t[item.name] || '';
1428
+ } catch {}
1429
+ }
1430
+ if (!item.descriptionZh && item.description) {
1431
+ try {
1432
+ const t = await translateTexts([item.description]);
1433
+ item.descriptionZh = t[item.description] || '';
1434
+ } catch {}
1435
+ }
1436
+ writeJson(res, 200, { item });
1437
+ } catch (err) {
1438
+ writeJson(res, 500, { error: err.message });
1439
+ }
1440
+ }
1441
+ },
1442
+ {
1443
+ kind: 'exact',
1444
+ path: '/api/skill-bazaar/install',
1445
+ auth: 'anonymous',
1446
+ handler: async (req, res) => {
1447
+ if (!guard(req, res, 'POST')) return;
1448
+ try {
1449
+ const body = await readBody(req);
1450
+ const source = getSource(body.source);
1451
+ if (!source) return writeJson(res, 404, { error: '源不存在' });
1452
+ const folder = String(body.folder || '').trim() || join(homedir(), '.agents');
1453
+ if (existsSync(folder) && !statSync(folder).isDirectory()) {
1454
+ return writeJson(res, 400, { error: '所选路径不是文件夹:' + folder });
1455
+ }
1456
+ const skillsRoot = resolveSkillsDir(folder);
1457
+ const result = await installSkill(source, body.id, Boolean(body.force), skillsRoot);
1458
+ if (result.conflict) {
1459
+ return writeJson(res, 409, {
1460
+ conflict: true,
1461
+ path: result.path,
1462
+ paths: result.paths || [result.path],
1463
+ message: '目标目录已存在同名技能,确认覆盖?'
1464
+ });
1465
+ }
1466
+ rememberTarget(folder, skillsRoot);
1467
+ return writeJson(res, 200, {
1468
+ ok: true,
1469
+ path: result.path,
1470
+ folder,
1471
+ skillsDir: skillsRoot,
1472
+ package: Boolean(result.package),
1473
+ skillCount: result.skillCount || 1,
1474
+ installed: result.installed || null
1475
+ });
1476
+ } catch (err) {
1477
+ writeJson(res, 500, { error: err.message });
1478
+ }
1479
+ }
1480
+ },
1481
+ {
1482
+ kind: 'exact',
1483
+ path: '/api/skill-bazaar/targets',
1484
+ auth: 'anonymous',
1485
+ handler: async (req, res) => {
1486
+ if (!guard(req, res, 'GET')) return;
1487
+ try {
1488
+ writeJson(res, 200, listTargetOptions());
1489
+ } catch (err) {
1490
+ writeJson(res, 500, { error: err.message });
1491
+ }
1492
+ }
1493
+ },
1494
+ {
1495
+ kind: 'exact',
1496
+ path: '/api/skill-bazaar/resolve',
1497
+ auth: 'anonymous',
1498
+ handler: async (req, res) => {
1499
+ if (!guard(req, res, 'GET')) return;
1500
+ try {
1501
+ const url = new URL(req.url ?? '/', HOST_ORIGIN);
1502
+ const folder = (url.searchParams.get('folder') || '').trim();
1503
+ if (!folder) return writeJson(res, 400, { error: '缺少 folder' });
1504
+ const skillsRoot = resolveSkillsDir(folder);
1505
+ writeJson(res, 200, {
1506
+ folder: resolve(folder),
1507
+ skillsDir: skillsRoot,
1508
+ exists: existsSync(skillsRoot),
1509
+ gitRoot: findGitRoot(folder)
1510
+ });
1511
+ } catch (err) {
1512
+ writeJson(res, 500, { error: err.message });
1513
+ }
1514
+ }
1515
+ },
1516
+ {
1517
+ kind: 'exact',
1518
+ path: '/api/skill-bazaar/installed',
1519
+ auth: 'anonymous',
1520
+ handler: async (req, res) => {
1521
+ if (!guard(req, res, 'GET')) return;
1522
+ try {
1523
+ writeJson(res, 200, {
1524
+ dir: skillsDir,
1525
+ dirs: [...scanDirs()],
1526
+ workspace: getWorkspaceDir(),
1527
+ items: scanInstalled()
1528
+ });
1529
+ } catch (err) {
1530
+ writeJson(res, 500, { error: err.message });
1531
+ }
1532
+ }
1533
+ }
1534
+ ];
1535
+
1536
+ ctx.effect(() => {
1537
+ const disposers = routes.map((route) => ctx.webServer.register(route));
1538
+ return () => {
1539
+ for (const dispose of disposers) dispose();
1540
+ };
1541
+ }, 'skill-bazaar: routes');
1542
+
1543
+ ctx.logger?.info?.('[skill-bazaar] 技能市场已挂载,安装目录:' + skillsDir);
1544
+ }
1545
+
1546
+ export { name, inject };