hermes_ecosystem.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """Read-only bundled catalogs. Explicit import is separate from skill discovery/admission."""
  2. import base64
  3. import hashlib
  4. import importlib.util
  5. import json
  6. import os
  7. from pathlib import Path
  8. import shutil
  9. import sys
  10. ROOT=Path(__file__).resolve().parent/'hermes'
  11. EXCLUDED={'__pycache__','.git','.DS_Store','node_modules'}
  12. def skill_bundle(source_path, expected=None):
  13. parts=source_path.split(':',1)
  14. if len(parts)!=2 or parts[0] not in ('builtin','optional'):raise ValueError('技能来源无效')
  15. base=ROOT/('skills' if parts[0]=='builtin' else 'optional-skills')
  16. relative=Path(parts[1])
  17. if relative.is_absolute() or any(p in ('..','.') or p.startswith('.') for p in relative.parts):raise ValueError('技能路径无效')
  18. directory=base/relative
  19. if not directory.is_dir() or not directory.resolve().is_relative_to(base.resolve()):raise ValueError('技能不存在')
  20. for p in [directory,*directory.parents]:
  21. if p==base:break
  22. if p.is_symlink():raise ValueError('技能目录不能包含符号链接')
  23. files={}
  24. for p in sorted(directory.rglob('*')):
  25. if any(part in EXCLUDED for part in p.relative_to(directory).parts):continue
  26. if p.is_symlink():raise ValueError('技能包不能包含符号链接')
  27. if p.is_file():
  28. if p.stat().st_size>1048576:raise ValueError('资源超过单文件 1 MiB 限制')
  29. files[p.relative_to(directory).as_posix()]=p.read_bytes()
  30. if 'SKILL.md' not in files or len(files)>101 or sum(map(len,files.values()))>4000000:raise ValueError('技能包超过资源限额或缺少 SKILL.md')
  31. fingerprint=hashlib.sha256(b''.join(k.encode()+b'\0'+hashlib.sha256(v).digest() for k,v in sorted(files.items()))).hexdigest()
  32. if expected and expected!=fingerprint:raise ValueError('源技能已更新,请刷新目录后导入')
  33. resources={};encodings={}
  34. content=files.pop('SKILL.md').decode('utf8')
  35. for name,data in files.items():
  36. try:resources[name]=data.decode('utf8')
  37. except UnicodeDecodeError:resources[name]=base64.b64encode(data).decode();encodings[name]='base64'
  38. if len(json.dumps(resources))+len(content)>3900000:raise ValueError('技能编码后超过包限额')
  39. from agent.skill_utils import parse_frontmatter
  40. meta,_=parse_frontmatter(content)
  41. return {'sourcePath':source_path,'fingerprint':fingerprint,'nativePath':relative.as_posix(),
  42. 'name':str(meta.get('name') or directory.name),'description':str(meta.get('description') or directory.name),
  43. 'content':content,'resources':resources,'resourceEncodings':encodings}
  44. def skills_catalog():
  45. from agent.skill_utils import parse_frontmatter
  46. rows=[]
  47. for source,top in [('builtin','skills'),('optional','optional-skills')]:
  48. for p in sorted((ROOT/top).rglob('SKILL.md')):
  49. path=source+':'+p.parent.relative_to(ROOT/top).as_posix()
  50. meta,_=parse_frontmatter(p.read_text());missing=[]
  51. declared=meta.get('metadata',{});declared=declared if isinstance(declared,dict) else {}
  52. commands=meta.get('required_commands') or declared.get('commands') or []
  53. if isinstance(commands,list):missing=[str(c) for c in commands if isinstance(c,str) and not shutil.which(c)]
  54. env=meta.get('required_environment_variables') or [];creds=meta.get('required_credential_files') or []
  55. missing_env=[v for v in env if isinstance(v,str) and not os.environ.get(v)]
  56. from hermes_constants import get_hermes_home
  57. credential_root=Path(get_hermes_home())
  58. missing_creds=[]
  59. for value in creds:
  60. credential_path=value.get('path','') if isinstance(value,dict) else str(value)
  61. relative=Path(credential_path)
  62. if relative.is_absolute() or '..' in relative.parts or not (credential_root/relative).is_file():missing_creds.append(credential_path)
  63. platform={'darwin':'macos','win32':'windows'}.get(sys.platform,'linux')
  64. platforms=meta.get('platforms') or []
  65. unsupported=isinstance(platforms,list) and bool(platforms) and platform not in platforms
  66. row={'sourcePath':path,'source':source,'name':str(meta.get('name') or p.parent.name),
  67. 'description':str(meta.get('description') or p.parent.name),'missingCommands':missing,
  68. 'readiness':'unsupported' if unsupported else 'needs_setup' if missing or missing_env or missing_creds else 'not_checked','missingEnvironment':missing_env,'missingCredentials':missing_creds,'importable':True}
  69. try:
  70. b=skill_bundle(path);row.update({'fingerprint':b['fingerprint'],'fileCount':1+len(b['resources'])})
  71. except (ValueError,UnicodeError) as e:row.update({'importable':False,'reason':str(e)})
  72. rows.append(row)
  73. return {'skills':rows,'environment':'Host','note':'准备状态只检查声明项;导入不会自动安装依赖或授权。'}