@workskills/getskill 1.1.6 → 1.1.8

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.
Files changed (2) hide show
  1. package/index.js +303 -38
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -13,6 +13,7 @@ const { exec } = require('child_process');
13
13
  */
14
14
  let BASE_URL = process.env.GETSKILL_BASE_URL || 'https://getskill.work';
15
15
  const REQUEST_TIMEOUT_MS = 60000;
16
+ const MAX_COPY_FILE_SIZE_BYTES = 2 * 1024 * 1024;
16
17
 
17
18
  /**
18
19
  * 设置自定义 BASE_URL
@@ -363,7 +364,13 @@ async function searchSkills(keyword, options = {}) {
363
364
  limit = 20
364
365
  } = options;
365
366
 
366
- const url = `${BASE_URL}/api/v1/repos/search?q=${encodeURIComponent(keyword)}&sort=${sort}&order=${order}&page=${page}&limit=${limit}`;
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}`;
367
374
 
368
375
  try {
369
376
  const response = await request(url, { timeout: REQUEST_TIMEOUT_MS });
@@ -408,18 +415,26 @@ async function searchSkills(keyword, options = {}) {
408
415
  return [];
409
416
  }
410
417
 
411
- // 提取需要的字段
412
- // 新 API 数据直接在根层级,不再嵌套在 repository 中
413
- return result.data.map(item => {
414
- return {
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 ? {
415
428
  name: item.full_name || item.name || '',
416
429
  full_name: item.full_name || '',
417
430
  description: item.description || '',
418
431
  html_url: item.html_url || '',
419
432
  git_url: item.clone_url || (item.html_url ? `${item.html_url}.git` : ''),
420
433
  clone_url: item.clone_url || ''
421
- };
422
- }).filter(item => item.full_name); // 过滤掉没有 full_name 的项
434
+ } : null;
435
+ }));
436
+
437
+ return skillChecks.filter(Boolean);
423
438
 
424
439
  } catch (error) {
425
440
  // 友好的错误提示
@@ -448,6 +463,14 @@ function getSkillsCacheDirectory() {
448
463
  return path.join(homeDir, '.openclaw', 'skills-cache');
449
464
  }
450
465
 
466
+ /**
467
+ * 获取 getskill 本地状态文件路径
468
+ */
469
+ function getStateFilePath() {
470
+ const homeDir = os.homedir();
471
+ return path.join(homeDir, '.openclaw', 'getskill', 'state.json');
472
+ }
473
+
451
474
  /**
452
475
  * 规范化技能名称(用于本地目录)
453
476
  * @param {string} skillName - 原始技能名称
@@ -466,6 +489,54 @@ function getRemoteSkillPath(skillName) {
466
489
  return skillName.includes('/') ? skillName : `skills/${skillName}`;
467
490
  }
468
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
+
469
540
  /**
470
541
  * 克隆或更新 Git 仓库
471
542
  * @param {string} skillName - 技能名称
@@ -509,6 +580,111 @@ async function cloneOrUpdateRepo(skillName) {
509
580
  return repoPath;
510
581
  }
511
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
+
512
688
  /**
513
689
  * 递归复制目录(排除 .git)
514
690
  * @param {string} sourceDir - 源目录
@@ -526,14 +702,59 @@ function copyDirectoryRecursive(sourceDir, targetDir) {
526
702
  const sourcePath = path.join(sourceDir, entry.name);
527
703
  const targetPath = path.join(targetDir, entry.name);
528
704
 
705
+ const stat = fs.lstatSync(sourcePath);
706
+ if (stat.isSymbolicLink()) {
707
+ console.warn(`跳过符号链接: ${sourcePath}`);
708
+ return;
709
+ }
710
+
529
711
  if (entry.isDirectory()) {
530
712
  copyDirectoryRecursive(sourcePath, targetPath);
531
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
+ }
532
718
  fs.copyFileSync(sourcePath, targetPath);
533
719
  }
534
720
  });
535
721
  }
536
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
+
537
758
  /**
538
759
  * 从仓库复制整个技能目录到 skills 目录
539
760
  * @param {string} repoPath - 仓库路径
@@ -544,17 +765,21 @@ function copySkillFiles(repoPath, skillName) {
544
765
  ensureDirectoryExists(skillsDir);
545
766
  const localSkillName = normalizeSkillName(skillName);
546
767
 
547
- // 确保仓库目录中至少有一个技能 .md 文件
548
- const hasSkillMd = fs.readdirSync(repoPath)
549
- .some(file => file.endsWith('.md') && !file.toLowerCase().startsWith('readme'));
550
-
551
- if (!hasSkillMd) {
768
+ // 安装前做产物校验,确保仓库中存在技能 Markdown
769
+ const sourceSkillFiles = collectSkillMarkdownFiles(repoPath);
770
+ if (sourceSkillFiles.length === 0) {
552
771
  throw new Error('在仓库中未找到技能 .md 文件');
553
772
  }
554
773
 
555
774
  const targetSkillDir = path.join(skillsDir, localSkillName);
556
- fs.rmSync(targetSkillDir, { recursive: true, force: true });
557
- copyDirectoryRecursive(repoPath, targetSkillDir);
775
+ replaceDirectoryAtomically(repoPath, targetSkillDir);
776
+
777
+ // 安装后再校验一次,防止复制后目录不完整
778
+ const installedSkillFiles = collectSkillMarkdownFiles(targetSkillDir);
779
+ if (installedSkillFiles.length === 0) {
780
+ throw new Error('复制后技能目录校验失败:未发现技能 .md 文件');
781
+ }
782
+
558
783
  console.log(`已复制技能目录: ${repoPath} -> ${targetSkillDir}`);
559
784
 
560
785
  return [targetSkillDir];
@@ -584,12 +809,14 @@ async function restartOpenClawGateway() {
584
809
  async function downloadSkill(skillName) {
585
810
  try {
586
811
  console.log(`下载技能: ${skillName}...`);
587
- const repoPath = await cloneOrUpdateRepo(skillName);
588
- const copiedFiles = copySkillFiles(repoPath, 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');
589
816
  await restartOpenClawGateway();
590
817
 
591
818
  return {
592
- skillName,
819
+ skillName: normalizedSkillName,
593
820
  repoPath,
594
821
  files: copiedFiles
595
822
  };
@@ -605,15 +832,16 @@ async function downloadSkill(skillName) {
605
832
  */
606
833
  async function updateSkill(skillName) {
607
834
  try {
608
- console.log(`正在更新技能: ${skillName}...`);
835
+ const normalizedSkillName = normalizeCliSkillArgument(skillName);
836
+ console.log(`正在更新技能: ${normalizedSkillName}...`);
609
837
 
610
838
  const cacheDir = getSkillsCacheDirectory();
611
- const localSkillName = normalizeSkillName(skillName);
839
+ const localSkillName = normalizeSkillName(normalizedSkillName);
612
840
  const repoPath = path.join(cacheDir, localSkillName);
613
841
 
614
842
  if (!fs.existsSync(repoPath)) {
615
843
  console.log(`技能仓库不存在,将重新下载...`);
616
- return await downloadSkill(skillName);
844
+ return await downloadSkill(normalizedSkillName);
617
845
  }
618
846
 
619
847
  // 执行 git pull
@@ -621,12 +849,13 @@ async function updateSkill(skillName) {
621
849
  console.log(`Git 仓库已更新`);
622
850
 
623
851
  // 复制技能目录到 skills 目录
624
- const copiedFiles = copySkillFiles(repoPath, skillName);
852
+ const copiedFiles = copySkillFiles(repoPath, normalizedSkillName);
853
+ await updateInstallState(normalizedSkillName, repoPath, copiedFiles[0], 'update');
625
854
  await restartOpenClawGateway();
626
855
 
627
- console.log(`技能 ${skillName} 更新成功!`);
856
+ console.log(`技能 ${normalizedSkillName} 更新成功!`);
628
857
  return {
629
- skillName,
858
+ skillName: normalizedSkillName,
630
859
  repoPath,
631
860
  files: copiedFiles
632
861
  };
@@ -655,12 +884,59 @@ function listLocalSkills() {
655
884
  /**
656
885
  * 命令行接口
657
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
+
658
922
  async function cli() {
659
923
  const args = process.argv.slice(2);
660
924
  const command = args[0];
661
925
 
662
926
  try {
663
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
+
664
940
  case 'search':
665
941
  if (!args[1]) {
666
942
  console.error('请提供搜索关键词');
@@ -693,6 +969,7 @@ async function cli() {
693
969
  if (!args[1]) {
694
970
  console.error('请提供技能ID或名称');
695
971
  console.log('用法: getskill install <技能名称>');
972
+ console.log('示例: getskill install pdf-extract');
696
973
  process.exit(1);
697
974
  }
698
975
  const result = await downloadSkill(args[1]);
@@ -705,6 +982,7 @@ async function cli() {
705
982
  if (!args[1]) {
706
983
  console.error('请提供技能名称');
707
984
  console.log('用法: getskill update <技能名称>');
985
+ console.log('示例: getskill update pdf-extract');
708
986
  process.exit(1);
709
987
  }
710
988
  const updateResult = await updateSkill(args[1]);
@@ -748,21 +1026,7 @@ async function cli() {
748
1026
  break;
749
1027
 
750
1028
  default:
751
- console.log('GetSkill - OpenClaw 技能管理工具');
752
- console.log('');
753
- console.log('用法:');
754
- console.log(' getskill search <关键词> - 从 API 搜索技能');
755
- console.log(' getskill install <技能名称> - 通过 git clone 安装技能');
756
- console.log(' getskill update <技能名称> - 通过 git pull 更新技能');
757
- console.log(' getskill list - 列出本地技能');
758
- console.log(' getskill path - 显示目录路径');
759
- console.log(' getskill config set <URL> - 设置自定义 API 地址');
760
- console.log(' getskill config get - 查看当前 API 地址');
761
- console.log(' getskill clean - 清理 git 缓存');
762
- console.log('');
763
- console.log(`当前 API: ${getBaseUrl()}`);
764
- console.log(`技能目录: ${getSkillsDirectory()}`);
765
- console.log(`缓存目录: ${getSkillsCacheDirectory()}`);
1029
+ printHelp();
766
1030
  }
767
1031
  } catch (error) {
768
1032
  console.error('执行命令时出错:', error.message);
@@ -780,6 +1044,7 @@ module.exports = {
780
1044
  getSkillsCacheDirectory,
781
1045
  cloneOrUpdateRepo,
782
1046
  copySkillFiles,
1047
+ repositoryHasSkillFile,
783
1048
  checkGitInstalled,
784
1049
  ensureGitInstalled,
785
1050
  setBaseUrl,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workskills/getskill",
3
- "version": "1.1.6",
3
+ "version": "1.1.8",
4
4
  "description": "A skill management tool for OpenClaw that enables searching, downloading, and updating skill files from the getskill.work repository",
5
5
  "main": "index.js",
6
6
  "bin": {