main_agent_cmds.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. """Agent-facing subcommand handlers: memory, acp, tools, insights, monitoring, skills (+trust).
  2. Split out of ``hermes_cli/main.py``. Names that still live in main (``PROJECT_ROOT``, ...)
  3. are imported lazily inside the functions that use them (avoids an import cycle).
  4. """
  5. from pm import install_hint
  6. import sys
  7. def _cmd_memory_off():
  8. from hermes_cli.config import load_config, save_config
  9. config = load_config()
  10. if not isinstance(config.get("memory"), dict):
  11. config["memory"] = {}
  12. config["memory"]["provider"] = ""
  13. save_config(config)
  14. print("\n ✓ Memory provider: built-in only")
  15. print(" Saved to config.yaml\n")
  16. def _cmd_memory_reset(args):
  17. from hermes_constants import get_hermes_home, display_hermes_home
  18. mem_dir = get_hermes_home() / "memories"
  19. target = getattr(args, "target", "all")
  20. files_to_reset = []
  21. if target in {"all", "memory"}:
  22. files_to_reset.append(("MEMORY.md", "agent notes"))
  23. if target in {"all", "user"}:
  24. files_to_reset.append(("USER.md", "user profile"))
  25. existing = [(f, desc) for f, desc in files_to_reset if (mem_dir / f).exists()]
  26. if not existing:
  27. print(f"\n Nothing to reset — no memory files found in {display_hermes_home()}/memories/\n")
  28. return
  29. print("\n This will permanently erase the following memory files:")
  30. for f, desc in existing:
  31. size = (mem_dir / f).stat().st_size
  32. print(f" ◆ {f} ({desc}) — {size:,} bytes")
  33. if not getattr(args, "yes", False):
  34. try:
  35. answer = input("\n Type 'yes' to confirm: ").strip().lower()
  36. except (EOFError, KeyboardInterrupt):
  37. print("\n Cancelled.\n")
  38. return
  39. if answer != "yes":
  40. print(" Cancelled.\n")
  41. return
  42. for f, desc in existing:
  43. (mem_dir / f).unlink()
  44. print(f" ✓ Deleted {f} ({desc})")
  45. print("\n Memory reset complete. New sessions will start with a blank slate.")
  46. print(f" Files were in: {display_hermes_home()}/memories/\n")
  47. def cmd_memory(args):
  48. sub = getattr(args, "memory_command", None)
  49. if sub == "off":
  50. _cmd_memory_off()
  51. elif sub == "reset":
  52. _cmd_memory_reset(args)
  53. else:
  54. from hermes_cli.memory_setup import memory_command
  55. memory_command(args)
  56. # (args attribute, acp flag) — forwarded in this order.
  57. _ACP_FLAGS = (
  58. ("acp_version", "--version"),
  59. ("check", "--check"),
  60. ("setup", "--setup"),
  61. ("setup_browser", "--setup-browser"),
  62. ("assume_yes", "--yes"))
  63. def cmd_acp(args):
  64. """Launch Hermes Agent as an ACP server."""
  65. import os
  66. # The gateway-backed ACP server forwards launch flags from their documented env equivalents
  67. # (main() already exported --yolo / --safe-mode / --ignore-user-config).
  68. for attr, name in (("accept_hooks", "HERMES_ACCEPT_HOOKS"), ("ignore_rules", "HERMES_IGNORE_RULES")):
  69. if getattr(args, attr, False):
  70. os.environ[name] = "1"
  71. # -m / --provider: the route a --safe-mode / --ignore-user-config session freezes (it reads no
  72. # profile default), carried like the TUI launcher's.
  73. for attr, name in (("model", "HERMES_MODEL"), ("provider", "HERMES_INFERENCE_PROVIDER")):
  74. if getattr(args, attr, None):
  75. os.environ[name] = getattr(args, attr)
  76. try:
  77. from acp_adapter.entry import main as acp_main
  78. acp_main([flag for attr, flag in _ACP_FLAGS if getattr(args, attr, False)])
  79. except ImportError as e:
  80. print("The ACP server can't start: its protocol packages are missing from this install.", file=sys.stderr)
  81. print("From the Hermes environment, run: "
  82. f"{install_hint('acp')}", file=sys.stderr)
  83. print("Then restart Hermes.", file=sys.stderr)
  84. print(f"Details: {e}", file=sys.stderr)
  85. sys.exit(1)
  86. def cmd_tools(args):
  87. from hermes_cli.main import _require_tty
  88. action = getattr(args, "tools_action", None)
  89. if action in {"list", "disable", "enable"}:
  90. from hermes_cli.tools_config import tools_disable_enable_command
  91. tools_disable_enable_command(args)
  92. elif action == "post-setup":
  93. from hermes_cli.tools_config import run_post_setup_command
  94. sys.exit(run_post_setup_command(args))
  95. else:
  96. _require_tty("tools")
  97. from hermes_cli.tools_config import tools_command
  98. tools_command(args)
  99. def cmd_insights(args):
  100. db = None
  101. try:
  102. from hermes_state import SessionDB
  103. from agent.insights import InsightsEngine
  104. from hermes_cli.config import get_hermes_home
  105. path = get_hermes_home() / "state.db"
  106. if not path.exists():
  107. from agent.i18n import t
  108. print(f" {t('cli.insights.no_session_data')}")
  109. return
  110. db = SessionDB(db_path=path, read_only=True)
  111. engine = InsightsEngine(db)
  112. report = engine.generate(days=args.days, source=args.source)
  113. print(engine.format_terminal(report))
  114. except Exception as e:
  115. # Interactive /insights delegates here, so keep main's localized error line.
  116. from agent.i18n import t
  117. print(t("gateway.insights.error", error=str(e)))
  118. finally:
  119. if db is not None:
  120. try:
  121. db.close()
  122. except Exception:
  123. pass
  124. def _dict_or_empty(value) -> dict:
  125. return value if isinstance(value, dict) else {}
  126. def cmd_monitoring(args):
  127. """Gateway monitoring status: health & diagnostics export posture."""
  128. from hermes_cli.config import load_config
  129. action = getattr(args, "monitoring_action", None) or "status"
  130. mon = _dict_or_empty(load_config().get("monitoring"))
  131. if action == "status":
  132. from agent.monitoring import otlp_exporter
  133. gh = _dict_or_empty(mon.get("gateway_health_export"))
  134. otlp = _dict_or_empty(_dict_or_empty(mon.get("export")).get("otlp"))
  135. print("Gateway monitoring")
  136. print(f" Health export: {'enabled' if gh.get('enabled') else 'disabled'} "
  137. f"(monitoring.gateway_health_export.enabled)")
  138. if gh.get("enabled"):
  139. print(f" Metrics: {'on' if gh.get('metrics_enabled', True) else 'off'} "
  140. f"(interval {gh.get('export_interval_seconds', 60)}s)")
  141. print(f" Diagnostic events: {'on' if gh.get('diagnostic_events_enabled', True) else 'off'}")
  142. print(f" Warning/error logs: {'on' if gh.get('warning_error_events_enabled', True) else 'off'} "
  143. f"(interval {gh.get('logs_export_interval_seconds', 5)}s)")
  144. print(" Content safety: always on "
  145. "(rendered messages are never exported; not configurable)")
  146. endpoint = otlp.get("endpoint") or ""
  147. if otlp.get("enabled") and endpoint:
  148. print(f" OTLP endpoint: {endpoint}")
  149. else:
  150. print(" OTLP endpoint: not configured (monitoring.export.otlp)")
  151. print(f" OTel SDK: {'installed' if otlp_exporter.is_available() else 'not installed'} "
  152. f"(optional extra: hermes-agent[otlp])")
  153. print("\n Scope: gateway service health + redacted diagnostics only.")
  154. print(" No prompts, messages, tool args/results, usage analytics, or traces.")
  155. return
  156. print(f"Unknown monitoring action: {action}", file=sys.stderr)
  157. sys.exit(2)
  158. def cmd_skills(args):
  159. from hermes_cli.main import _require_tty
  160. action = getattr(args, "skills_action", None)
  161. if action == "config":
  162. _require_tty("skills config")
  163. from hermes_cli.skills_config import skills_command as skills_config_command
  164. skills_config_command(args)
  165. elif action in ("trust", "untrust"):
  166. _cmd_skills_trust(args)
  167. else:
  168. from hermes_cli.skills_hub import skills_command
  169. return skills_command(args)
  170. def _cmd_skills_trust(args):
  171. """``hermes skills trust|untrust [path]`` — manage ``skills.trusted_project_dirs``.
  172. With no path, operates on the project root enclosing the current directory
  173. (nearest ancestor with ``.git``).
  174. """
  175. from pathlib import Path
  176. from agent.skill_utils import (
  177. PROJECT_SKILLS_SUBDIRS,
  178. _candidate_project_skills_dirs,
  179. find_project_root,
  180. iter_skill_index_files)
  181. from hermes_cli.config import load_config, save_config
  182. action = args.skills_action
  183. raw_path = getattr(args, "path", None)
  184. if raw_path:
  185. root = Path(raw_path).expanduser().resolve()
  186. if not root.is_dir():
  187. print(f"Not a directory: {root}")
  188. return
  189. else:
  190. root = find_project_root()
  191. if root is None:
  192. print(
  193. "Not inside a git checkout. Run from a project directory or "
  194. "pass the project root path explicitly.")
  195. return
  196. config = load_config()
  197. skills_cfg = config.setdefault("skills", {})
  198. trusted = skills_cfg.get("trusted_project_dirs") or []
  199. if not isinstance(trusted, list):
  200. trusted = [trusted]
  201. trusted = [str(t) for t in trusted]
  202. root_str = str(root)
  203. def _same(t: str) -> bool:
  204. return str(Path(t).expanduser().resolve()) == root_str
  205. if action == "untrust":
  206. kept = [t for t in trusted if not _same(t)]
  207. if len(kept) == len(trusted):
  208. print(f"{root} was not trusted.")
  209. return
  210. skills_cfg["trusted_project_dirs"] = kept
  211. save_config(config)
  212. print(f"Untrusted: {root}")
  213. print("Project skills from this repo will no longer load.")
  214. return
  215. if any(_same(t) for t in trusted):
  216. print(f"Already trusted: {root}")
  217. else:
  218. trusted.append(root_str)
  219. skills_cfg["trusted_project_dirs"] = trusted
  220. save_config(config)
  221. print(f"Trusted: {root}")
  222. # Show what this unlocks
  223. count = sum(
  224. sum(1 for _ in iter_skill_index_files(d, "SKILL.md"))
  225. for d in _candidate_project_skills_dirs(root))
  226. if count:
  227. print(
  228. f"{count} project skill(s) will load in sessions started inside "
  229. "this repo (they take precedence over same-named profile skills).")
  230. else:
  231. subdirs = " or ".join(PROJECT_SKILLS_SUBDIRS)
  232. print(f"No project skills found yet — add them under {subdirs}.")