doctor.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. """``hermes doctor`` — diagnose (and with --fix, repair) a Hermes install.
  2. ``run_doctor`` walks ``DOCTOR_CHECKS`` in order; each check prints its own rows and returns a ``Finding``.
  3. Check bodies live in the ``doctor_*`` siblings.
  4. """
  5. import os
  6. import sys
  7. from hermes_cli.config import get_env_path, get_hermes_home, get_project_root
  8. from hermes_cli.env_loader import load_hermes_dotenv
  9. from hermes_constants import display_hermes_home
  10. PROJECT_ROOT = get_project_root()
  11. HERMES_HOME = get_hermes_home()
  12. _DHH = display_hermes_home() # user-facing display path (e.g. ~/.hermes or ~/.hermes/profiles/coder)
  13. # Load environment variables from ~/.hermes/.env so API key checks work
  14. _env_path = get_env_path()
  15. load_hermes_dotenv(hermes_home=_env_path.parent, project_env=PROJECT_ROOT / ".env")
  16. from hermes_cli.colors import Colors, color
  17. from hermes_cli.doctor_report import Finding, _section, check_bool, check_info, doctor_check, warn_on_error
  18. from hermes_cli.doctor_connectivity import _has_healthy_oauth_fallback_for_apikey_provider, build_probes, run_probes
  19. from hermes_cli.doctor_tools import _safe_which
  20. from hermes_cli.doctor_config import (
  21. _check_config_drift,
  22. _check_config_file,
  23. _check_env_file,
  24. _check_mcp_security,
  25. _check_relay_plugins,
  26. _check_xai_retirement,
  27. _check_retired_session_reset,
  28. )
  29. from hermes_cli.doctor_platform import (
  30. _check_certificates,
  31. _check_command_installation,
  32. _check_gateway_supervision,
  33. _check_python_environment,
  34. _check_required_packages,
  35. _check_security_advisories,
  36. _check_web_dashboard_import,
  37. )
  38. from hermes_cli.doctor_tools import (
  39. _check_git_and_rg,
  40. _check_node_and_browser,
  41. _check_npm_audit,
  42. _check_terminal_backend,
  43. _check_tool_availability,
  44. )
  45. from hermes_cli.doctor_state import (
  46. _check_checkpoint_store,
  47. _check_cron_store,
  48. _check_directory_structure,
  49. _check_memory_provider,
  50. _check_plugins_disabled_by_update,
  51. _check_plugins_in_both_lists,
  52. _check_profiles,
  53. _check_skills_hub,
  54. _check_state_db,
  55. )
  56. _PROVIDER_ENV_HINTS = (
  57. "DEEPINFRA_API_KEY", "OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN",
  58. "OPENAI_BASE_URL", "NOUS_API_KEY", "GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY", "KIMI_API_KEY",
  59. "KIMI_CN_API_KEY", "GMI_API_KEY", "FIREWORKS_API_KEY", "ACTUAL_API_KEY", "ACTUAL_BASE_URL", "MINIMAX_API_KEY",
  60. "MINIMAX_CN_API_KEY", "KILOCODE_API_KEY", "DEEPSEEK_API_KEY", "DASHSCOPE_API_KEY", "HF_TOKEN",
  61. "AI_GATEWAY_API_KEY", "OPENCODE_ZEN_API_KEY", "OPENCODE_GO_API_KEY", "COMMANDCODE_API_KEY", "XIAOMI_API_KEY",
  62. "TOKENHUB_API_KEY", "TOKENPLAN_API_KEY",
  63. )
  64. @doctor_check()
  65. def _check_auth_providers(should_fix: bool, f: Finding) -> None:
  66. """Refresh-free OAuth status snapshot (doctor must never trigger a token refresh)."""
  67. with warn_on_error("Auth provider status", "(could not check: {e})"):
  68. from hermes_cli.auth import get_nous_auth_status_local, get_codex_auth_status, get_minimax_oauth_auth_status
  69. _login_row("Nous Portal auth", get_nous_auth_status_local())
  70. # Native OAuth is Hermes' own device-code flow; the Codex CLI only imports existing ~/.codex/auth.json
  71. # tokens, so the hint sits under the Codex row (not as another provider's remedy).
  72. if not _login_row("OpenAI Codex auth", get_codex_auth_status(), show_error=True) and not _safe_which("codex"):
  73. check_info("codex CLI not installed (optional — only required to import tokens from an existing Codex CLI login)")
  74. minimax_status = get_minimax_oauth_auth_status()
  75. _login_row("MiniMax OAuth", minimax_status, f"(logged in, region={minimax_status.get('region', 'global')})")
  76. with warn_on_error(""): # xAI OAuth separately, so an import failure cannot disrupt the rows already printed
  77. from hermes_cli.auth import get_xai_oauth_auth_status
  78. _login_row("xAI OAuth", get_xai_oauth_auth_status() or {}, show_error=True)
  79. def _login_row(label: str, status: dict, ok_detail: str = "(logged in)", show_error: bool = False) -> bool:
  80. """ok/warn row for an OAuth status dict; with show_error, its ``error`` hint prints under a not-logged-in row."""
  81. logged_in = check_bool(status.get("logged_in"), (label, ok_detail), (label, "(not logged in)"))
  82. if not logged_in and show_error and status.get("error"):
  83. check_info(status["error"])
  84. return logged_in
  85. @doctor_check()
  86. def _check_api_connectivity(should_fix: bool, f: Finding) -> None:
  87. """Parallel HTTP/SDK probes for every configured provider; results printed in submission order."""
  88. probes = build_probes()
  89. # Single status line so users see something happening; ``\r`` clears it once results land.
  90. print(f" {color(f'Running {len(probes)} connectivity checks in parallel…', Colors.DIM)}", end="", flush=True)
  91. results = run_probes(probes)
  92. print("\r" + " " * 70 + "\r", end="")
  93. for r in results:
  94. for glyph, label, detail in r.lines:
  95. print(f" {glyph} {label}" + (f" {detail}" if detail else ""))
  96. if r.issues and not _has_healthy_oauth_fallback_for_apikey_provider(r.label):
  97. f.issues.extend(r.issues)
  98. # Ordered (section title, check). None title = check prints its own header (or none); order is user-visible.
  99. DOCTOR_CHECKS = (
  100. ('Security Advisories', _check_security_advisories), ('MCP Server Security', _check_mcp_security),
  101. ('Python Environment', _check_python_environment), ('SSL / CA Certificates', _check_certificates),
  102. ('Required Packages', _check_required_packages), (None, _check_web_dashboard_import),
  103. ('Configuration Files', _check_env_file),
  104. (None, _check_config_file), (None, _check_config_drift),
  105. ('xAI Model Retirement (May 15, 2026)', _check_xai_retirement),
  106. ('Session Reset (timers removed Sep 7, 2026)', _check_retired_session_reset),
  107. ('Auth Providers', _check_auth_providers),
  108. ('Directory Structure', _check_directory_structure), (None, _check_state_db), (None, _check_cron_store),
  109. (None, _check_checkpoint_store),
  110. (None, _check_gateway_supervision), (None, _check_command_installation),
  111. ('External Tools', _check_git_and_rg), (None, _check_terminal_backend), (None, _check_node_and_browser),
  112. (None, _check_npm_audit), ('API Connectivity', _check_api_connectivity),
  113. ('Tool Availability', _check_tool_availability), ('Skills Hub', _check_skills_hub),
  114. ('Memory Provider', _check_memory_provider), (None, _check_plugins_disabled_by_update),
  115. (None, _check_plugins_in_both_lists),
  116. ('NeMo Relay Plugins', _check_relay_plugins),
  117. (None, _check_profiles),
  118. )
  119. def _ack_advisory(ack_target: str) -> None:
  120. """`hermes doctor --ack <id>`: persist the ack and return without running diagnostics."""
  121. from hermes_cli.security_advisories import ADVISORIES, ack_advisory
  122. valid_ids = {a.id for a in ADVISORIES}
  123. if ack_target not in valid_ids:
  124. print(color(f"Unknown advisory ID: {ack_target!r}. Known IDs: {', '.join(sorted(valid_ids)) or '(none)'}", Colors.RED))
  125. sys.exit(2)
  126. if ack_advisory(ack_target):
  127. print(color(f" ✓ Acknowledged advisory {ack_target}. It will no longer trigger startup banners.", Colors.GREEN))
  128. else:
  129. print(color(f" ✗ Could not save the acknowledgement for {ack_target}. Make sure {_DHH}/config.yaml is "
  130. f"writable (`hermes config path` prints the exact file), then re-run "
  131. f"`hermes doctor --ack {ack_target}`.", Colors.RED))
  132. sys.exit(1)
  133. def _print_summary(should_fix: bool, total: Finding) -> None:
  134. print()
  135. remaining = total.issues + total.manual_issues
  136. numbered = "".join(f" {i}. {issue}\n" for i, issue in enumerate(remaining, 1))
  137. if should_fix and total.fixed > 0:
  138. print(color("─" * 60, Colors.GREEN))
  139. print(color(f" Fixed {total.fixed} issue(s).", Colors.GREEN, Colors.BOLD), end="")
  140. print(color(f" {len(remaining)} issue(s) require manual intervention.", Colors.YELLOW, Colors.BOLD) if remaining else "")
  141. print()
  142. if remaining:
  143. print(numbered)
  144. elif remaining:
  145. print(color("─" * 60, Colors.YELLOW))
  146. print(color(f" Found {len(remaining)} issue(s) to address:", Colors.YELLOW, Colors.BOLD))
  147. print()
  148. print(numbered)
  149. if not should_fix and total.issues:
  150. print(color(" Tip: run 'hermes doctor --fix' to auto-fix what's possible.", Colors.DIM))
  151. else:
  152. print(color("─" * 60, Colors.GREEN))
  153. print(color(" All checks passed! 🎉", Colors.GREEN, Colors.BOLD))
  154. print()
  155. def run_doctor(args):
  156. """Run diagnostic checks."""
  157. should_fix = getattr(args, 'fix', False)
  158. # Doctor runs from the interactive CLI, so CLI-gated tool checks (e.g. cronjob) see the same context.
  159. os.environ.setdefault("HERMES_INTERACTIVE", "1")
  160. if getattr(args, 'ack', None):
  161. return _ack_advisory(args.ack)
  162. print()
  163. for line in ("┌─────────────────────────────────────────────────────────┐",
  164. "│ 🩺 Hermes Doctor │",
  165. "└─────────────────────────────────────────────────────────┘"):
  166. print(color(line, Colors.CYAN))
  167. total = Finding()
  168. from hermes_cli.left_core_migration import installs_held
  169. with installs_held(): # a diagnostic: provider checks resolve through the runtime, which would install
  170. for title, check in DOCTOR_CHECKS:
  171. if title:
  172. _section(title)
  173. total.merge(check(should_fix))
  174. # Opt-in live probes run AFTER all static checks (`--live`: real network calls; bounded + read-only).
  175. with warn_on_error(""):
  176. from hermes_cli.doctor_live import maybe_run_live_checks
  177. maybe_run_live_checks(args, total.manual_issues)
  178. _print_summary(should_fix, total)
  179. return int(bool(total.issues or total.manual_issues))