skills_config.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """Skills configuration for Hermes Agent. `hermes skills` enters this module."""
  2. from typing import List, Optional, Set
  3. from hermes_cli.config import cfg_get, load_config, save_config
  4. from hermes_cli.colors import Colors, color
  5. from hermes_cli.platforms import PLATFORMS as _PLATFORMS
  6. # {key: label} view of the messaging platforms (``PLATFORMS.items()`` / ``.get(key)`` below).
  7. PLATFORMS = {k: info.label for k, info in _PLATFORMS.items() if k != "api_server"}
  8. def _normalize_skill_names(values) -> set[str]:
  9. """Config value -> set of skill names (mirrors ``agent.skill_utils._normalize_string_set``):
  10. ``None`` (YAML null) is empty and a bare scalar is a single-item list, NOT its characters.
  11. See #13026.
  12. """
  13. if values is None:
  14. return set()
  15. if isinstance(values, str):
  16. values = [values]
  17. try:
  18. return {str(v).strip() for v in values if str(v).strip()}
  19. except TypeError:
  20. return set()
  21. def get_disabled_skills(config: dict, platform: Optional[str] = None) -> set[str]:
  22. """Disabled skill names: the global list unioned with the platform list when given (globally
  23. disabled stays disabled everywhere; mirrors ``agent.skill_utils.get_disabled_skill_names``)."""
  24. skills_cfg = config.get("skills") or {}
  25. if not isinstance(skills_cfg, dict):
  26. return set()
  27. from agent.skill_utils import ESSENTIAL_SKILLS
  28. disabled = _normalize_skill_names(skills_cfg.get("disabled"))
  29. if platform is not None:
  30. platform_disabled = cfg_get(skills_cfg, "platform_disabled", platform)
  31. if platform_disabled is not None:
  32. disabled = disabled | _normalize_skill_names(platform_disabled)
  33. return disabled - ESSENTIAL_SKILLS
  34. def save_disabled_skills(config: dict, disabled: set[str], platform: Optional[str] = None):
  35. """Persist disabled skill names to config; essential skills (e.g. ``hermes-agent``) are
  36. silently dropped — they cannot be disabled from any surface."""
  37. from agent.skill_utils import ESSENTIAL_SKILLS
  38. disabled = set(disabled) - ESSENTIAL_SKILLS
  39. config.setdefault("skills", {})
  40. if platform is None:
  41. config["skills"]["disabled"] = sorted(disabled)
  42. else:
  43. config["skills"].setdefault("platform_disabled", {})
  44. config["skills"]["platform_disabled"][platform] = sorted(disabled)
  45. save_config(config)
  46. def _list_all_skills() -> list[dict]:
  47. """Return all installed skills (ignoring disabled state)."""
  48. try:
  49. from tools.skills_tool import find_all_skills
  50. return find_all_skills(skip_disabled=True)
  51. except Exception:
  52. return []
  53. def _get_categories(skills: list[dict]) -> list[str]:
  54. """Return sorted unique category names (None -> 'uncategorized')."""
  55. return sorted({s["category"] or "uncategorized" for s in skills})
  56. def _select_platform() -> Optional[str]:
  57. """Ask which platform to configure; None means global."""
  58. options = [("global", "All platforms (global default)")] + list(PLATFORMS.items())
  59. print()
  60. print(color(" Configure skills for:", Colors.BOLD))
  61. for i, (key, label) in enumerate(options, 1):
  62. print(f" {i}. {label}")
  63. print()
  64. try:
  65. raw = input(color(" Select [1]: ", Colors.YELLOW)).strip()
  66. except (KeyboardInterrupt, EOFError):
  67. return None
  68. try:
  69. idx = int(raw) - 1 # empty input -> ValueError -> global
  70. except ValueError:
  71. return None
  72. if 0 <= idx < len(options) and options[idx][0] != "global":
  73. return options[idx][0]
  74. return None
  75. def _toggle_by_category(skills: list[dict], disabled: set[str]) -> set[str]:
  76. """Toggle all skills in a category at once."""
  77. from hermes_cli.curses_ui import curses_checklist
  78. categories = _get_categories(skills)
  79. cat_skills = [{s["name"] for s in skills if (s["category"] or "uncategorized") == cat}
  80. for cat in categories]
  81. cat_labels = [f"{cat} ({len(names)} skills)" for cat, names in zip(categories, cat_skills)]
  82. # A category is "enabled" (checked) when NOT all its skills are disabled
  83. pre_selected = {i for i, names in enumerate(cat_skills)
  84. if not all(s in disabled for s in names)}
  85. chosen = curses_checklist("Categories — toggle entire categories",
  86. cat_labels, pre_selected, cancel_returns=pre_selected)
  87. new_disabled = set(disabled)
  88. for i, names in enumerate(cat_skills):
  89. if i in chosen:
  90. new_disabled -= names # category enabled → remove from disabled
  91. else:
  92. new_disabled |= names # category disabled → add to disabled
  93. return new_disabled
  94. def skills_command(args=None):
  95. """Entry point for `hermes skills`."""
  96. from hermes_cli.curses_ui import curses_checklist
  97. config = load_config()
  98. skills = _list_all_skills()
  99. if not skills:
  100. print(color(" No skills installed.", Colors.DIM))
  101. return
  102. platform = _select_platform()
  103. platform_label = PLATFORMS.get(platform, "All platforms") if platform else "All platforms"
  104. print()
  105. print(color(f" Configure for: {platform_label}", Colors.DIM))
  106. print()
  107. print(" 1. Toggle individual skills")
  108. print(" 2. Toggle by category")
  109. print()
  110. try:
  111. mode = input(color(" Select [1]: ", Colors.YELLOW)).strip() or "1"
  112. except (KeyboardInterrupt, EOFError):
  113. return
  114. disabled = get_disabled_skills(config, platform)
  115. if mode == "2":
  116. new_disabled = _toggle_by_category(skills, disabled)
  117. else:
  118. labels = [f"{s['name']} ({s['category'] or 'uncategorized'}) — {s['description'][:55]}"
  119. for s in skills]
  120. # "selected" = enabled (not disabled) — matches the [✓] convention
  121. pre_selected = {i for i, s in enumerate(skills) if s["name"] not in disabled}
  122. chosen = curses_checklist(f"Skills for {platform_label}",
  123. labels, pre_selected, cancel_returns=pre_selected)
  124. new_disabled = {skills[i]["name"] for i in range(len(skills)) if i not in chosen}
  125. if new_disabled == disabled:
  126. print(color(" No changes.", Colors.DIM))
  127. return
  128. save_disabled_skills(config, new_disabled, platform)
  129. enabled_count = len(skills) - len(new_disabled)
  130. print(color(f"✓ Saved: {enabled_count} enabled, {len(new_disabled)} disabled ({platform_label}).", Colors.GREEN))