@workskills/getskill 1.1.8 → 1.1.10

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 DELETED
@@ -1,1057 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const https = require('https');
4
- const http = require('http');
5
- const fs = require('fs');
6
- const path = require('path');
7
- const os = require('os');
8
- const { exec } = require('child_process');
9
-
10
- /**
11
- * 基础 URL 配置
12
- * 可以通过环境变量 GETSKILL_BASE_URL 自定义
13
- */
14
- let BASE_URL = process.env.GETSKILL_BASE_URL || 'https://getskill.work';
15
- const REQUEST_TIMEOUT_MS = 60000;
16
- const MAX_COPY_FILE_SIZE_BYTES = 2 * 1024 * 1024;
17
-
18
- /**
19
- * 设置自定义 BASE_URL
20
- * @param {string} url - 自定义的基础 URL
21
- */
22
- function setBaseUrl(url) {
23
- BASE_URL = url.replace(/\/$/, ''); // 移除末尾的斜杠
24
- console.log(`BASE_URL 已设置为: ${BASE_URL}`);
25
- }
26
-
27
- /**
28
- * 获取当前 BASE_URL
29
- * @returns {string} 当前的基础 URL
30
- */
31
- function getBaseUrl() {
32
- return BASE_URL;
33
- }
34
-
35
- /**
36
- * 检查 Git 是否已安装
37
- */
38
- async function checkGitInstalled() {
39
- try {
40
- await executeCommand('git --version');
41
- return true;
42
- } catch (error) {
43
- return false;
44
- }
45
- }
46
-
47
- /**
48
- * 获取 Git 下载链接(根据操作系统)
49
- */
50
- function getGitDownloadUrl() {
51
- const platform = os.platform();
52
- const arch = os.arch();
53
-
54
- switch (platform) {
55
- case 'win32':
56
- // Windows
57
- if (arch === 'x64') {
58
- return 'https://github.com/git-for-windows/git/releases/download/v2.44.0.windows.1/Git-2.44.0-64-bit.exe';
59
- } else {
60
- return 'https://github.com/git-for-windows/git/releases/download/v2.44.0.windows.1/Git-2.44.0-32-bit.exe';
61
- }
62
- case 'darwin':
63
- // macOS - 提示使用 Homebrew
64
- return 'homebrew'; // 特殊标记
65
- case 'linux':
66
- // Linux - 提示使用包管理器
67
- return 'package-manager'; // 特殊标记
68
- default:
69
- return null;
70
- }
71
- }
72
-
73
- /**
74
- * 下载文件
75
- */
76
- function downloadFile(url, destPath) {
77
- return new Promise((resolve, reject) => {
78
- const urlObj = new URL(url);
79
- const protocol = urlObj.protocol === 'https:' ? https : http;
80
-
81
- const file = fs.createWriteStream(destPath);
82
-
83
- protocol.get(url, (response) => {
84
- // 处理重定向
85
- if (response.statusCode === 301 || response.statusCode === 302) {
86
- file.close();
87
- fs.unlinkSync(destPath);
88
- return downloadFile(response.headers.location, destPath)
89
- .then(resolve)
90
- .catch(reject);
91
- }
92
-
93
- if (response.statusCode !== 200) {
94
- file.close();
95
- fs.unlinkSync(destPath);
96
- return reject(new Error(`下载失败,状态码: ${response.statusCode}`));
97
- }
98
-
99
- const totalSize = parseInt(response.headers['content-length'], 10);
100
- let downloadedSize = 0;
101
-
102
- response.on('data', (chunk) => {
103
- downloadedSize += chunk.length;
104
- const percent = ((downloadedSize / totalSize) * 100).toFixed(2);
105
- process.stdout.write(`\r下载进度: ${percent}%`);
106
- });
107
-
108
- response.pipe(file);
109
-
110
- file.on('finish', () => {
111
- file.close();
112
- console.log('\n下载完成!');
113
- resolve(destPath);
114
- });
115
- }).on('error', (err) => {
116
- file.close();
117
- fs.unlinkSync(destPath);
118
- reject(err);
119
- });
120
- });
121
- }
122
-
123
- /**
124
- * 安装 Git
125
- */
126
- async function installGit() {
127
- const platform = os.platform();
128
- const downloadUrl = getGitDownloadUrl();
129
-
130
- console.log('检测到系统未安装 Git,正在准备安装...\n');
131
-
132
- if (downloadUrl === 'homebrew') {
133
- console.log('macOS 系统检测到未安装 Git');
134
- console.log('请使用以下命令安装 Git:\n');
135
- console.log(' brew install git');
136
- console.log('\n如果未安装 Homebrew,请访问: https://brew.sh/');
137
- throw new Error('请先安装 Git 后再运行此命令');
138
- }
139
-
140
- if (downloadUrl === 'package-manager') {
141
- console.log('Linux 系统检测到未安装 Git');
142
- console.log('请使用系统包管理器安装 Git:\n');
143
- console.log(' Ubuntu/Debian: sudo apt-get install git');
144
- console.log(' CentOS/RHEL: sudo yum install git');
145
- console.log(' Fedora: sudo dnf install git');
146
- console.log(' Arch: sudo pacman -S git');
147
- throw new Error('请先安装 Git 后再运行此命令');
148
- }
149
-
150
- if (platform === 'win32') {
151
- console.log('Windows 系统检测到未安装 Git');
152
- console.log('正在下载 Git 安装程序...\n');
153
-
154
- const tempDir = os.tmpdir();
155
- const installerPath = path.join(tempDir, 'git-installer.exe');
156
-
157
- try {
158
- await downloadFile(downloadUrl, installerPath);
159
- console.log(`\nGit 安装程序已下载到: ${installerPath}`);
160
- console.log('\n正在启动安装程序,请按照提示完成安装...');
161
- console.log('安装完成后,请重新运行此命令。\n');
162
-
163
- // 启动安装程序
164
- exec(`"${installerPath}"`, (error) => {
165
- if (error) {
166
- console.error('启动安装程序失败:', error.message);
167
- }
168
- });
169
-
170
- throw new Error('请完成 Git 安装后重新运行此命令');
171
- } catch (error) {
172
- console.error('\n下载 Git 安装程序失败:', error.message);
173
- console.log('\n您可以手动访问以下网址下载 Git:');
174
- console.log('https://git-scm.com/download/win');
175
- throw new Error('请先安装 Git 后再运行此命令');
176
- }
177
- }
178
- }
179
-
180
- /**
181
- * 确保 Git 已安装
182
- */
183
- async function ensureGitInstalled() {
184
- const isInstalled = await checkGitInstalled();
185
- if (!isInstalled) {
186
- await installGit();
187
- }
188
- return true;
189
- }
190
-
191
- /**
192
- * 获取 OpenClaw skills 目录路径(根据操作系统)
193
- */
194
- function getSkillsDirectory() {
195
- const platform = os.platform();
196
- const homeDir = os.homedir();
197
-
198
- switch (platform) {
199
- case 'win32':
200
- // Windows: %USERPROFILE%\.openclaw\skills
201
- return path.join(homeDir, '.openclaw', 'skills');
202
- case 'darwin':
203
- // macOS: ~/.openclaw/skills
204
- return path.join(homeDir, '.openclaw', 'skills');
205
- case 'linux':
206
- // Linux: ~/.openclaw/skills
207
- return path.join(homeDir, '.openclaw', 'skills');
208
- default:
209
- // 默认使用 ~/.openclaw/skills
210
- return path.join(homeDir, '.openclaw', 'skills');
211
- }
212
- }
213
-
214
- /**
215
- * 确保目录存在
216
- */
217
- function ensureDirectoryExists(dirPath) {
218
- if (!fs.existsSync(dirPath)) {
219
- fs.mkdirSync(dirPath, { recursive: true });
220
- }
221
- }
222
-
223
- /**
224
- * HTTP/HTTPS 请求封装(支持重定向和错误处理)
225
- * @param {string} url - 请求 URL
226
- * @param {Object} options - 请求选项
227
- * @param {number} redirectCount - 重定向次数(内部使用)
228
- * @returns {Promise<Object>} 响应对象
229
- */
230
- function request(url, options = {}, redirectCount = 0) {
231
- const MAX_REDIRECTS = 5; // 最大重定向次数
232
-
233
- return new Promise((resolve, reject) => {
234
- // 检查重定向次数
235
- if (redirectCount >= MAX_REDIRECTS) {
236
- return reject(new Error(`Too many redirects (${MAX_REDIRECTS})`));
237
- }
238
-
239
- let urlObj;
240
- try {
241
- urlObj = new URL(url);
242
- } catch (error) {
243
- return reject(new Error(`Invalid URL: ${url}`));
244
- }
245
-
246
- const protocol = urlObj.protocol === 'https:' ? https : http;
247
-
248
- const reqOptions = {
249
- hostname: urlObj.hostname,
250
- port: urlObj.port,
251
- path: urlObj.pathname + urlObj.search,
252
- method: options.method || 'GET',
253
- headers: options.headers || {},
254
- timeout: options.timeout || REQUEST_TIMEOUT_MS // 默认 60 秒超时
255
- };
256
-
257
- const req = protocol.request(reqOptions, (res) => {
258
- // 处理重定向 (301, 302, 303, 307, 308)
259
- if ([301, 302, 303, 307, 308].includes(res.statusCode)) {
260
- const redirectUrl = res.headers.location;
261
-
262
- if (!redirectUrl) {
263
- return reject(new Error(`Redirect location header missing (${res.statusCode})`));
264
- }
265
-
266
- // 解析重定向 URL(可能是相对路径)
267
- let newUrl;
268
- try {
269
- newUrl = new URL(redirectUrl, url).toString();
270
- } catch (error) {
271
- return reject(new Error(`Invalid redirect URL: ${redirectUrl}`));
272
- }
273
-
274
- // 递归处理重定向
275
- return request(newUrl, options, redirectCount + 1)
276
- .then(resolve)
277
- .catch(reject);
278
- }
279
-
280
- let data = '';
281
-
282
- res.on('data', (chunk) => {
283
- data += chunk;
284
- });
285
-
286
- res.on('end', () => {
287
- if (res.statusCode >= 200 && res.statusCode < 300) {
288
- resolve({
289
- statusCode: res.statusCode,
290
- headers: res.headers,
291
- body: data
292
- });
293
- } else {
294
- reject(new Error(`Request failed with status code ${res.statusCode}: ${data.substring(0, 200)}`));
295
- }
296
- });
297
-
298
- res.on('error', (err) => {
299
- reject(new Error(`Response error: ${err.message}`));
300
- });
301
- });
302
-
303
- req.on('error', (err) => {
304
- if (err.code === 'ECONNREFUSED') {
305
- reject(new Error(`Connection refused: ${urlObj.hostname}`));
306
- } else if (err.code === 'ENOTFOUND') {
307
- reject(new Error(`Host not found: ${urlObj.hostname}`));
308
- } else if (err.code === 'ETIMEDOUT' || err.code === 'ESOCKETTIMEDOUT') {
309
- reject(new Error(`Request timeout: ${url}`));
310
- } else {
311
- reject(new Error(`Network error: ${err.message}`));
312
- }
313
- });
314
-
315
- req.on('timeout', () => {
316
- req.destroy();
317
- reject(new Error(`Request timeout after ${reqOptions.timeout}ms`));
318
- });
319
-
320
- if (options.body) {
321
- req.write(options.body);
322
- }
323
-
324
- req.end();
325
- });
326
- }
327
-
328
- /**
329
- * 执行命令
330
- */
331
- function executeCommand(command, cwd) {
332
- return new Promise((resolve, reject) => {
333
- exec(command, { cwd, maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {
334
- if (error) {
335
- reject(error);
336
- } else {
337
- resolve({ stdout, stderr });
338
- }
339
- });
340
- });
341
- }
342
-
343
- /**
344
- * 搜索技能(从配置的 BASE_URL API)
345
- * @param {string} keyword - 搜索关键词
346
- * @param {Object} options - 搜索选项
347
- * @param {string} options.sort - 排序字段,默认 'updated'
348
- * @param {string} options.order - 排序顺序,默认 'desc'
349
- * @param {number} options.page - 页码,默认 1
350
- * @param {number} options.limit - 每页数量,默认 20
351
- * @returns {Promise<Array>} 技能列表(包含 git 地址)
352
- */
353
- async function searchSkills(keyword, options = {}) {
354
- // 参数验证
355
- if (!keyword || typeof keyword !== 'string') {
356
- console.error('搜索失败: 关键词无效');
357
- return [];
358
- }
359
-
360
- const {
361
- sort = 'updated',
362
- order = 'desc',
363
- page = 1,
364
- limit = 20
365
- } = options;
366
-
367
- const fixedSearchParams = [
368
- 'private=false',
369
- 'is_private=false',
370
- 'archived=false',
371
- 'template=false'
372
- ].join('&');
373
- const url = `${BASE_URL}/api/v1/repos/search?q=${encodeURIComponent(keyword)}&${fixedSearchParams}&sort=${sort}&order=${order}&page=${page}&limit=${limit}`;
374
-
375
- try {
376
- const response = await request(url, { timeout: REQUEST_TIMEOUT_MS });
377
-
378
- // 检查响应体是否为空
379
- if (!response.body || response.body.trim() === '') {
380
- console.warn('搜索警告: 服务器返回空响应');
381
- return [];
382
- }
383
-
384
- // 尝试解析 JSON
385
- let result;
386
- try {
387
- result = JSON.parse(response.body);
388
- } catch (parseError) {
389
- console.error('搜索失败: JSON 解析错误', parseError.message);
390
- console.debug('响应内容:', response.body.substring(0, 200));
391
- return [];
392
- }
393
-
394
- // 解析返回格式: { ok: true, data: [{ repository: {...} }] }
395
- if (!result) {
396
- console.warn('搜索警告: 结果为空');
397
- return [];
398
- }
399
-
400
- // 检查 API 响应状态
401
- if (result.ok === false) {
402
- console.warn('搜索警告: API 返回失败状态', result.message || '');
403
- return [];
404
- }
405
-
406
- // 检查 data 字段
407
- if (!result.data) {
408
- console.warn('搜索警告: 响应中缺少 data 字段');
409
- return [];
410
- }
411
-
412
- // 确保 data 是数组
413
- if (!Array.isArray(result.data)) {
414
- console.warn('搜索警告: data 不是数组类型');
415
- return [];
416
- }
417
-
418
- // 固定过滤条件:仅保留公开、非空、非归档、非模板仓库;允许 mirror,但排除 fork,且要求仓库根目录包含 SKILL.md
419
- const filteredCandidates = result.data
420
- .map(item => item && item.repository ? item.repository : item)
421
- .filter(item => item && (item.full_name || item.name))
422
- .filter(item => !item.private && !item.empty && !item.archived && !item.template && !item.fork);
423
-
424
- const skillChecks = await Promise.all(filteredCandidates.map(async (item) => {
425
- const repoFullName = item.full_name || item.name || '';
426
- const hasSkillFile = await repositoryHasSkillFile(repoFullName);
427
- return hasSkillFile ? {
428
- name: item.full_name || item.name || '',
429
- full_name: item.full_name || '',
430
- description: item.description || '',
431
- html_url: item.html_url || '',
432
- git_url: item.clone_url || (item.html_url ? `${item.html_url}.git` : ''),
433
- clone_url: item.clone_url || ''
434
- } : null;
435
- }));
436
-
437
- return skillChecks.filter(Boolean);
438
-
439
- } catch (error) {
440
- // 友好的错误提示
441
- if (error.message.includes('Host not found')) {
442
- console.error('搜索失败: 无法连接到服务器,请检查网络或 API 地址配置');
443
- } else if (error.message.includes('timeout')) {
444
- console.error('搜索失败: 请求超时,请稍后重试');
445
- } else if (error.message.includes('Connection refused')) {
446
- console.error('搜索失败: 服务器拒绝连接,请检查 API 地址是否正确');
447
- } else if (error.message.includes('status code')) {
448
- console.error('搜索失败: 服务器返回错误', error.message);
449
- } else {
450
- console.error('搜索失败:', error.message);
451
- }
452
-
453
- // 返回空数组而不是抛出异常,避免程序崩溃
454
- return [];
455
- }
456
- }
457
-
458
- /**
459
- * 获取技能仓库缓存目录
460
- */
461
- function getSkillsCacheDirectory() {
462
- const homeDir = os.homedir();
463
- return path.join(homeDir, '.openclaw', 'skills-cache');
464
- }
465
-
466
- /**
467
- * 获取 getskill 本地状态文件路径
468
- */
469
- function getStateFilePath() {
470
- const homeDir = os.homedir();
471
- return path.join(homeDir, '.openclaw', 'getskill', 'state.json');
472
- }
473
-
474
- /**
475
- * 规范化技能名称(用于本地目录)
476
- * @param {string} skillName - 原始技能名称
477
- * @returns {string} 本地目录名
478
- */
479
- function normalizeSkillName(skillName) {
480
- return skillName.replace(/^skills\//, '').replace(/[\\/]/g, '_');
481
- }
482
-
483
- /**
484
- * 获取远程仓库路径(用于拼接 git URL)
485
- * @param {string} skillName - 原始技能名称
486
- * @returns {string} 远程仓库路径
487
- */
488
- function getRemoteSkillPath(skillName) {
489
- return skillName.includes('/') ? skillName : `skills/${skillName}`;
490
- }
491
-
492
- /**
493
- * 判断仓库根目录是否包含 SKILL.md
494
- * @param {string} repoFullName - 仓库全名,例如 skills/example-skill
495
- * @returns {Promise<boolean>} 是否包含 SKILL.md
496
- */
497
- async function repositoryHasSkillFile(repoFullName) {
498
- if (!repoFullName || typeof repoFullName !== 'string' || !repoFullName.includes('/')) {
499
- return false;
500
- }
501
-
502
- const segments = repoFullName.split('/');
503
- const owner = segments.shift();
504
- const repo = segments.join('/');
505
-
506
- if (!owner || !repo) {
507
- return false;
508
- }
509
-
510
- const url = `${BASE_URL}/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/SKILL.md`;
511
-
512
- try {
513
- await request(url, { timeout: Math.min(REQUEST_TIMEOUT_MS, 15000) });
514
- return true;
515
- } catch (error) {
516
- return false;
517
- }
518
- }
519
-
520
- /**
521
- * 规范化 CLI 输入参数
522
- */
523
- function normalizeCliSkillArgument(rawSkillName) {
524
- if (!rawSkillName || typeof rawSkillName !== 'string') {
525
- throw new Error('请提供技能名称,例如: getskill install pdf-extract 或 getskill install skills/xejrax_pdf-extract');
526
- }
527
-
528
- const value = rawSkillName.trim();
529
- if (!value) {
530
- throw new Error('技能名称不能为空');
531
- }
532
-
533
- if (/^https?:\/\//i.test(value) || value.endsWith('.git')) {
534
- throw new Error('请传入技能名称而不是 Git URL,例如: getskill install pdf-extract');
535
- }
536
-
537
- return value.replace(/^\/+|\/+$/g, '');
538
- }
539
-
540
- /**
541
- * 克隆或更新 Git 仓库
542
- * @param {string} skillName - 技能名称
543
- * @returns {Promise<string>} 本地仓库路径
544
- */
545
- async function cloneOrUpdateRepo(skillName) {
546
- // 首先检查并确保 Git 已安装
547
- await ensureGitInstalled();
548
-
549
- const cacheDir = getSkillsCacheDirectory();
550
- ensureDirectoryExists(cacheDir);
551
-
552
- const localSkillName = normalizeSkillName(skillName);
553
- const remoteSkillPath = getRemoteSkillPath(skillName);
554
-
555
- const repoPath = path.join(cacheDir, localSkillName);
556
-
557
- if (fs.existsSync(repoPath)) {
558
- // 仓库已存在,执行 git pull
559
- console.log(`更新仓库: ${skillName}...`);
560
- try {
561
- await executeCommand('git pull', repoPath);
562
- console.log(`仓库更新成功: ${repoPath}`);
563
- } catch (error) {
564
- console.error(`更新失败: ${error.message}`);
565
- throw error;
566
- }
567
- } else {
568
- // 克隆新仓库
569
- const gitUrl = `${BASE_URL}/${remoteSkillPath}.git`;
570
- console.log(`克隆仓库: ${gitUrl}...`);
571
- try {
572
- await executeCommand(`git clone "${gitUrl}" "${localSkillName}"`, cacheDir);
573
- console.log(`仓库克隆成功: ${repoPath}`);
574
- } catch (error) {
575
- console.error(`克隆失败: ${error.message}`);
576
- throw error;
577
- }
578
- }
579
-
580
- return repoPath;
581
- }
582
-
583
- /**
584
- * 递归查找技能 Markdown 文件(排除 README)
585
- */
586
- function collectSkillMarkdownFiles(dirPath, baseDir = dirPath, result = []) {
587
- const entries = fs.readdirSync(dirPath, { withFileTypes: true });
588
-
589
- entries.forEach(entry => {
590
- if (entry.name === '.git') {
591
- return;
592
- }
593
-
594
- const fullPath = path.join(dirPath, entry.name);
595
- const relativePath = path.relative(baseDir, fullPath);
596
-
597
- if (entry.isDirectory()) {
598
- collectSkillMarkdownFiles(fullPath, baseDir, result);
599
- return;
600
- }
601
-
602
- if (!entry.isFile()) {
603
- return;
604
- }
605
-
606
- const isMarkdown = entry.name.toLowerCase().endsWith('.md');
607
- const isReadme = entry.name.toLowerCase().startsWith('readme');
608
- if (isMarkdown && !isReadme) {
609
- result.push(relativePath);
610
- }
611
- });
612
-
613
- return result;
614
- }
615
-
616
- /**
617
- * 获取仓库当前 commit hash
618
- */
619
- async function getGitCommitHash(repoPath) {
620
- try {
621
- const { stdout } = await executeCommand('git rev-parse HEAD', repoPath);
622
- return stdout.trim();
623
- } catch (error) {
624
- return null;
625
- }
626
- }
627
-
628
- /**
629
- * 读取本地安装状态
630
- */
631
- function readInstallState() {
632
- const stateFilePath = getStateFilePath();
633
- if (!fs.existsSync(stateFilePath)) {
634
- return { skills: {} };
635
- }
636
-
637
- try {
638
- const content = fs.readFileSync(stateFilePath, 'utf8');
639
- const parsed = JSON.parse(content);
640
- if (!parsed || typeof parsed !== 'object') {
641
- return { skills: {} };
642
- }
643
- if (!parsed.skills || typeof parsed.skills !== 'object') {
644
- parsed.skills = {};
645
- }
646
- return parsed;
647
- } catch (error) {
648
- return { skills: {} };
649
- }
650
- }
651
-
652
- /**
653
- * 写入本地安装状态
654
- */
655
- function writeInstallState(state) {
656
- const stateFilePath = getStateFilePath();
657
- ensureDirectoryExists(path.dirname(stateFilePath));
658
- fs.writeFileSync(stateFilePath, JSON.stringify(state, null, 2), 'utf8');
659
- }
660
-
661
- /**
662
- * 更新技能安装状态
663
- */
664
- async function updateInstallState(skillName, repoPath, installDir, action) {
665
- const localSkillName = normalizeSkillName(skillName);
666
- const remoteSkillPath = getRemoteSkillPath(skillName);
667
- const now = new Date().toISOString();
668
- const commitHash = await getGitCommitHash(repoPath);
669
-
670
- const state = readInstallState();
671
- const previous = state.skills[localSkillName] || {};
672
-
673
- state.skills[localSkillName] = {
674
- inputSkillName: skillName,
675
- localSkillName,
676
- remoteSkillPath,
677
- repoPath,
678
- installDir,
679
- lastAction: action,
680
- installedAt: previous.installedAt || now,
681
- updatedAt: now,
682
- gitCommitHash: commitHash || previous.gitCommitHash || null
683
- };
684
-
685
- writeInstallState(state);
686
- }
687
-
688
- /**
689
- * 递归复制目录(排除 .git)
690
- * @param {string} sourceDir - 源目录
691
- * @param {string} targetDir - 目标目录
692
- */
693
- function copyDirectoryRecursive(sourceDir, targetDir) {
694
- ensureDirectoryExists(targetDir);
695
-
696
- const entries = fs.readdirSync(sourceDir, { withFileTypes: true });
697
- entries.forEach(entry => {
698
- if (entry.name === '.git') {
699
- return;
700
- }
701
-
702
- const sourcePath = path.join(sourceDir, entry.name);
703
- const targetPath = path.join(targetDir, entry.name);
704
-
705
- const stat = fs.lstatSync(sourcePath);
706
- if (stat.isSymbolicLink()) {
707
- console.warn(`跳过符号链接: ${sourcePath}`);
708
- return;
709
- }
710
-
711
- if (entry.isDirectory()) {
712
- copyDirectoryRecursive(sourcePath, targetPath);
713
- } else if (entry.isFile()) {
714
- if (stat.size > MAX_COPY_FILE_SIZE_BYTES) {
715
- console.warn(`跳过超大文件 (${MAX_COPY_FILE_SIZE_BYTES} bytes): ${sourcePath}`);
716
- return;
717
- }
718
- fs.copyFileSync(sourcePath, targetPath);
719
- }
720
- });
721
- }
722
-
723
- /**
724
- * 原子替换目标技能目录
725
- */
726
- function replaceDirectoryAtomically(sourceDir, targetDir) {
727
- const parentDir = path.dirname(targetDir);
728
- const dirName = path.basename(targetDir);
729
- const tempDir = path.join(parentDir, `.${dirName}.tmp-${process.pid}-${Date.now()}`);
730
- const backupDir = path.join(parentDir, `.${dirName}.bak-${process.pid}-${Date.now()}`);
731
-
732
- ensureDirectoryExists(parentDir);
733
- copyDirectoryRecursive(sourceDir, tempDir);
734
-
735
- try {
736
- if (fs.existsSync(targetDir)) {
737
- fs.renameSync(targetDir, backupDir);
738
- }
739
-
740
- fs.renameSync(tempDir, targetDir);
741
-
742
- if (fs.existsSync(backupDir)) {
743
- fs.rmSync(backupDir, { recursive: true, force: true });
744
- }
745
- } catch (error) {
746
- if (fs.existsSync(tempDir)) {
747
- fs.rmSync(tempDir, { recursive: true, force: true });
748
- }
749
-
750
- if (!fs.existsSync(targetDir) && fs.existsSync(backupDir)) {
751
- fs.renameSync(backupDir, targetDir);
752
- }
753
-
754
- throw error;
755
- }
756
- }
757
-
758
- /**
759
- * 从仓库复制整个技能目录到 skills 目录
760
- * @param {string} repoPath - 仓库路径
761
- * @param {string} skillName - 技能名称
762
- */
763
- function copySkillFiles(repoPath, skillName) {
764
- const skillsDir = getSkillsDirectory();
765
- ensureDirectoryExists(skillsDir);
766
- const localSkillName = normalizeSkillName(skillName);
767
-
768
- // 安装前做产物校验,确保仓库中存在技能 Markdown
769
- const sourceSkillFiles = collectSkillMarkdownFiles(repoPath);
770
- if (sourceSkillFiles.length === 0) {
771
- throw new Error('在仓库中未找到技能 .md 文件');
772
- }
773
-
774
- const targetSkillDir = path.join(skillsDir, localSkillName);
775
- replaceDirectoryAtomically(repoPath, targetSkillDir);
776
-
777
- // 安装后再校验一次,防止复制后目录不完整
778
- const installedSkillFiles = collectSkillMarkdownFiles(targetSkillDir);
779
- if (installedSkillFiles.length === 0) {
780
- throw new Error('复制后技能目录校验失败:未发现技能 .md 文件');
781
- }
782
-
783
- console.log(`已复制技能目录: ${repoPath} -> ${targetSkillDir}`);
784
-
785
- return [targetSkillDir];
786
- }
787
-
788
- /**
789
- * 复制完成后尝试重启 OpenClaw Gateway,使新技能立即生效
790
- */
791
- async function restartOpenClawGateway() {
792
- const restartCommand = 'openclaw gateway restart';
793
- console.log(`尝试执行: ${restartCommand}`);
794
-
795
- try {
796
- await executeCommand(restartCommand);
797
- console.log('OpenClaw Gateway 重启成功,新技能应已生效。');
798
- } catch (error) {
799
- // 不阻断安装/更新主流程,给出手动操作提示
800
- console.warn('自动重启 OpenClaw Gateway 失败,请手动执行: openclaw gateway restart');
801
- console.warn(`失败原因: ${error.message}`);
802
- }
803
- }
804
-
805
- /**
806
- * 下载技能(通过 Git)
807
- * @param {string} skillName - 技能名称
808
- */
809
- async function downloadSkill(skillName) {
810
- try {
811
- console.log(`下载技能: ${skillName}...`);
812
- const normalizedSkillName = normalizeCliSkillArgument(skillName);
813
- const repoPath = await cloneOrUpdateRepo(normalizedSkillName);
814
- const copiedFiles = copySkillFiles(repoPath, normalizedSkillName);
815
- await updateInstallState(normalizedSkillName, repoPath, copiedFiles[0], 'install');
816
- await restartOpenClawGateway();
817
-
818
- return {
819
- skillName: normalizedSkillName,
820
- repoPath,
821
- files: copiedFiles
822
- };
823
- } catch (error) {
824
- console.error(`下载技能失败: ${error.message}`);
825
- throw error;
826
- }
827
- }
828
-
829
- /**
830
- * 更新技能(通过 Git)
831
- * @param {string} skillName - 技能名称
832
- */
833
- async function updateSkill(skillName) {
834
- try {
835
- const normalizedSkillName = normalizeCliSkillArgument(skillName);
836
- console.log(`正在更新技能: ${normalizedSkillName}...`);
837
-
838
- const cacheDir = getSkillsCacheDirectory();
839
- const localSkillName = normalizeSkillName(normalizedSkillName);
840
- const repoPath = path.join(cacheDir, localSkillName);
841
-
842
- if (!fs.existsSync(repoPath)) {
843
- console.log(`技能仓库不存在,将重新下载...`);
844
- return await downloadSkill(normalizedSkillName);
845
- }
846
-
847
- // 执行 git pull
848
- await executeCommand('git pull', repoPath);
849
- console.log(`Git 仓库已更新`);
850
-
851
- // 复制技能目录到 skills 目录
852
- const copiedFiles = copySkillFiles(repoPath, normalizedSkillName);
853
- await updateInstallState(normalizedSkillName, repoPath, copiedFiles[0], 'update');
854
- await restartOpenClawGateway();
855
-
856
- console.log(`技能 ${normalizedSkillName} 更新成功!`);
857
- return {
858
- skillName: normalizedSkillName,
859
- repoPath,
860
- files: copiedFiles
861
- };
862
- } catch (error) {
863
- console.error(`更新技能 ${skillName} 失败:`, error.message);
864
- throw error;
865
- }
866
- }
867
-
868
- /**
869
- * 列出本地已安装的技能
870
- */
871
- function listLocalSkills() {
872
- const skillsDir = getSkillsDirectory();
873
-
874
- if (!fs.existsSync(skillsDir)) {
875
- console.log('技能目录不存在');
876
- return [];
877
- }
878
-
879
- const entries = fs.readdirSync(skillsDir, { withFileTypes: true });
880
- const skillDirs = entries.filter(entry => entry.isDirectory()).map(entry => entry.name);
881
- return skillDirs;
882
- }
883
-
884
- /**
885
- * 命令行接口
886
- */
887
- function printHelp() {
888
- console.log('GetSkill - OpenClaw 技能管理工具');
889
- console.log('');
890
- console.log('用法:');
891
- console.log(' getskill --help - 显示帮助信息');
892
- console.log(' getskill --version - 显示版本号');
893
- console.log(' getskill search <关键词> - 从 API 搜索技能');
894
- console.log(' getskill install <技能名称> - 通过 git clone 安装技能');
895
- console.log(' getskill update <技能名称> - 通过 git pull 更新技能');
896
- console.log(' getskill list - 列出本地技能');
897
- console.log(' getskill path - 显示目录路径');
898
- console.log(' getskill config set <URL> - 设置自定义 API 地址');
899
- console.log(' getskill config get - 查看当前 API 地址');
900
- console.log(' getskill clean - 清理 git 缓存');
901
- console.log('');
902
- console.log('示例:');
903
- console.log(' getskill install pdf-extract');
904
- console.log(' getskill install skills/xejrax_pdf-extract');
905
- console.log(' getskill update pdf-extract');
906
- console.log('');
907
- console.log(`当前 API: ${getBaseUrl()}`);
908
- console.log(`技能目录: ${getSkillsDirectory()}`);
909
- console.log(`缓存目录: ${getSkillsCacheDirectory()}`);
910
- }
911
-
912
- function getCliVersion() {
913
- try {
914
- const packageJsonPath = path.join(__dirname, 'package.json');
915
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
916
- return packageJson.version || 'unknown';
917
- } catch (error) {
918
- return 'unknown';
919
- }
920
- }
921
-
922
- async function cli() {
923
- const args = process.argv.slice(2);
924
- const command = args[0];
925
-
926
- try {
927
- switch (command) {
928
- case '--help':
929
- case '-h':
930
- case 'help':
931
- printHelp();
932
- break;
933
-
934
- case '--version':
935
- case '-v':
936
- case 'version':
937
- console.log(getCliVersion());
938
- break;
939
-
940
- case 'search':
941
- if (!args[1]) {
942
- console.error('请提供搜索关键词');
943
- console.log('用法: getskill search <关键词>');
944
- process.exit(1);
945
- }
946
- const results = await searchSkills(args[1]);
947
-
948
- if (results.length === 0) {
949
- console.log('未找到相关技能');
950
- console.log('提示: 尝试使用不同的关键词,或访问 ' + BASE_URL + ' 查看所有可用技能');
951
- } else {
952
- console.log(`找到 ${results.length} 个技能:\n`);
953
- results.forEach((skill, index) => {
954
- console.log(`${index + 1}. ${skill.full_name}`);
955
- if (skill.description) {
956
- console.log(` 描述: ${skill.description}`);
957
- }
958
- if (skill.git_url) {
959
- console.log(` Git: ${skill.git_url}`);
960
- }
961
- console.log('');
962
- });
963
- }
964
- break;
965
-
966
- case 'install':
967
- case 'get':
968
- case 'download':
969
- if (!args[1]) {
970
- console.error('请提供技能ID或名称');
971
- console.log('用法: getskill install <技能名称>');
972
- console.log('示例: getskill install pdf-extract');
973
- process.exit(1);
974
- }
975
- const result = await downloadSkill(args[1]);
976
- console.log(`\n技能已安装到 skills 目录:`);
977
- result.files.forEach(file => console.log(` - ${file}`));
978
- console.log(`\nGit 仓库缓存: ${result.repoPath}`);
979
- break;
980
-
981
- case 'update':
982
- if (!args[1]) {
983
- console.error('请提供技能名称');
984
- console.log('用法: getskill update <技能名称>');
985
- console.log('示例: getskill update pdf-extract');
986
- process.exit(1);
987
- }
988
- const updateResult = await updateSkill(args[1]);
989
- console.log(`\n技能已更新到 skills 目录:`);
990
- updateResult.files.forEach(file => console.log(` - ${file}`));
991
- break;
992
-
993
- case 'list':
994
- const skills = listLocalSkills();
995
- console.log(`本地已安装的技能 (${skills.length}):`);
996
- skills.forEach((skill, index) => {
997
- console.log(`${index + 1}. ${skill}`);
998
- });
999
- break;
1000
-
1001
- case 'path':
1002
- console.log(`技能目录: ${getSkillsDirectory()}`);
1003
- console.log(`缓存目录: ${getSkillsCacheDirectory()}`);
1004
- break;
1005
-
1006
- case 'config':
1007
- if (args[1] === 'set' && args[2]) {
1008
- setBaseUrl(args[2]);
1009
- } else if (args[1] === 'get') {
1010
- console.log(`当前 BASE_URL: ${getBaseUrl()}`);
1011
- } else {
1012
- console.log('用法:');
1013
- console.log(' getskill config set <URL> - 设置自定义 API 地址');
1014
- console.log(' getskill config get - 查看当前 API 地址');
1015
- }
1016
- break;
1017
-
1018
- case 'clean':
1019
- const cacheDir = getSkillsCacheDirectory();
1020
- if (fs.existsSync(cacheDir)) {
1021
- fs.rmSync(cacheDir, { recursive: true, force: true });
1022
- console.log(`已清理缓存目录: ${cacheDir}`);
1023
- } else {
1024
- console.log('缓存目录不存在');
1025
- }
1026
- break;
1027
-
1028
- default:
1029
- printHelp();
1030
- }
1031
- } catch (error) {
1032
- console.error('执行命令时出错:', error.message);
1033
- process.exit(1);
1034
- }
1035
- }
1036
-
1037
- // 导出模块函数
1038
- module.exports = {
1039
- searchSkills,
1040
- downloadSkill,
1041
- updateSkill,
1042
- listLocalSkills,
1043
- getSkillsDirectory,
1044
- getSkillsCacheDirectory,
1045
- cloneOrUpdateRepo,
1046
- copySkillFiles,
1047
- repositoryHasSkillFile,
1048
- checkGitInstalled,
1049
- ensureGitInstalled,
1050
- setBaseUrl,
1051
- getBaseUrl
1052
- };
1053
-
1054
- // 如果直接运行此文件,执行 CLI
1055
- if (require.main === module) {
1056
- cli();
1057
- }