Skip to content

The agent that grows with you

refactor(hermes_cli): doctor check helpers (doctor_check/check_bool/ensure_dir), dump phase helpers, compact tables

Teknium8b19d3315773
diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.py
index f336f9c95d2..73ff8a85967 100644
--- a/hermes_cli/doctor.py
+++ b/hermes_cli/doctor.py
@@ -16,10 +16,7 @@ import importlib.util # noqa: F401
from pathlib import Path # noqa: F401
from hermes_cli.config import ( # noqa: F401 (detect_install_method: tests patch doctor.detect_install_method)
- detect_install_method,
- get_env_path,
- get_hermes_home,
- get_project_root,
+ detect_install_method, get_env_path, get_hermes_home, get_project_root,
)
from hermes_cli.env_loader import load_hermes_dotenv
from hermes_constants import display_hermes_home
@@ -34,107 +31,43 @@ load_hermes_dotenv(hermes_home=_env_path.parent, project_env=PROJECT_ROOT / ".en
from hermes_cli.colors import Colors, color
from hermes_cli.doctor_config import ( # noqa: F401 (re-exported; tests use hermes_cli.doctor.<name>)
- _check_config_drift,
- _check_config_file,
- _check_env_file,
- _check_mcp_security,
- _check_xai_retirement,
- _has_provider_env_config,
- collect_deprecated_env_vars,
- collect_relay_plugin_cutover_findings,
- managed_scope_check,
- report_deprecated_config_and_env,
+ _check_config_drift, _check_config_file, _check_env_file, _check_mcp_security,
+ _check_xai_retirement, _has_provider_env_config, collect_deprecated_env_vars,
+ collect_relay_plugin_cutover_findings, managed_scope_check, report_deprecated_config_and_env,
)
from hermes_cli.doctor_platform import ( # noqa: F401 (re-exported; tests use hermes_cli.doctor.<name>)
- _check_certificates,
- _check_command_installation,
- _check_gateway_supervision,
- _check_python_environment,
- _check_required_packages,
- _check_s6_supervision,
- _check_security_advisories,
- _desktop_app_bundle,
- _format_db_size,
- _macos_desktop_dr,
- _python_install_cmd,
- _read_journal_mode,
- _report_database_journal_modes,
- _sqlite_upgrade_hint,
- _system_package_install_cmd,
- _unreadable_reason,
- check_certificates,
- check_macos_full_disk_access,
- check_macos_tcc_anchor,
- check_macos_tcc_grants,
+ _check_certificates, _check_command_installation, _check_gateway_supervision,
+ _check_python_environment, _check_required_packages, _check_s6_supervision,
+ _check_security_advisories, _desktop_app_bundle, _format_db_size, _macos_desktop_dr,
+ _python_install_cmd, _read_journal_mode, _report_database_journal_modes, _sqlite_upgrade_hint,
+ _system_package_install_cmd, _unreadable_reason, check_certificates, check_macos_full_disk_access,
+ check_macos_tcc_anchor, check_macos_tcc_grants,
)
from hermes_cli.doctor_tools import ( # noqa: F401 (re-exported; tests use hermes_cli.doctor.<name>)
- _apply_doctor_tool_availability_overrides,
- _check_git_and_rg,
- _check_node_and_browser,
- _check_npm_audit,
- _check_terminal_backend,
- _check_tool_availability,
- _doctor_web_capability_rows,
- _enabled_cli_toolsets_for_doctor,
- _missing_api_key_toolsets_for_summary,
- _safe_which,
+ _apply_doctor_tool_availability_overrides, _check_git_and_rg, _check_node_and_browser,
+ _check_npm_audit, _check_terminal_backend, _check_tool_availability, _doctor_web_capability_rows,
+ _enabled_cli_toolsets_for_doctor, _missing_api_key_toolsets_for_summary, _safe_which,
)
from hermes_cli.doctor_state import ( # noqa: F401 (re-exported; tests use hermes_cli.doctor.<name>)
- STATE_DB_SIZE_WARN_BYTES,
- _check_directory_structure,
- _check_memory_provider,
- _check_profiles,
- _check_skills_hub,
- _check_state_db,
- _honcho_is_configured_for_doctor,
- _render_state_db_stats,
+ STATE_DB_SIZE_WARN_BYTES, _check_directory_structure, _check_memory_provider, _check_profiles,
+ _check_skills_hub, _check_state_db, _honcho_is_configured_for_doctor, _render_state_db_stats,
)
from hermes_cli.doctor_report import ( # noqa: F401 (re-exported for doctor_live and tests)
- Finding,
- _fail_and_issue,
- _section,
- check_fail,
- check_info,
- check_ok,
- check_warn,
+ Finding, _fail_and_issue, _section, check_bool, check_fail, check_info, check_ok, check_warn,
)
from hermes_cli.doctor_connectivity import ( # noqa: F401 (re-exported; tests import from hermes_cli.doctor)
- _build_apikey_providers_list,
- _has_healthy_oauth_fallback_for_apikey_provider,
- build_probes,
+ _build_apikey_providers_list, _has_healthy_oauth_fallback_for_apikey_provider, build_probes,
run_probes,
)
_PROVIDER_ENV_HINTS = (
- "DEEPINFRA_API_KEY",
- "OPENROUTER_API_KEY",
- "OPENAI_API_KEY",
- "ANTHROPIC_API_KEY",
- "ANTHROPIC_TOKEN",
- "OPENAI_BASE_URL",
- "NOUS_API_KEY",
- "GLM_API_KEY",
- "ZAI_API_KEY",
- "Z_AI_API_KEY",
- "KIMI_API_KEY",
- "KIMI_CN_API_KEY",
- "GMI_API_KEY",
- "FIREWORKS_API_KEY",
- "ACTUAL_API_KEY",
- "ACTUAL_BASE_URL",
- "MINIMAX_API_KEY",
- "MINIMAX_CN_API_KEY",
- "KILOCODE_API_KEY",
- "DEEPSEEK_API_KEY",
- "DASHSCOPE_API_KEY",
- "HF_TOKEN",
- "AI_GATEWAY_API_KEY",
- "OPENCODE_ZEN_API_KEY",
- "OPENCODE_GO_API_KEY",
- "COMMANDCODE_API_KEY",
- "XIAOMI_API_KEY",
- "TOKENHUB_API_KEY",
+ "DEEPINFRA_API_KEY", "OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY",
+ "ANTHROPIC_TOKEN", "OPENAI_BASE_URL", "NOUS_API_KEY", "GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY",
+ "KIMI_API_KEY", "KIMI_CN_API_KEY", "GMI_API_KEY", "FIREWORKS_API_KEY", "ACTUAL_API_KEY",
+ "ACTUAL_BASE_URL", "MINIMAX_API_KEY", "MINIMAX_CN_API_KEY", "KILOCODE_API_KEY", "DEEPSEEK_API_KEY",
+ "DASHSCOPE_API_KEY", "HF_TOKEN", "AI_GATEWAY_API_KEY", "OPENCODE_ZEN_API_KEY",
+ "OPENCODE_GO_API_KEY", "COMMANDCODE_API_KEY", "XIAOMI_API_KEY", "TOKENHUB_API_KEY",
"TOKENPLAN_API_KEY",
)
@@ -147,71 +80,46 @@ def _check_auth_providers(should_fix: bool) -> Finding:
"""Refresh-free OAuth status snapshot (doctor must never trigger a token refresh)."""
f = Finding()
try:
- from hermes_cli.auth import (
- get_nous_auth_status_local,
- get_codex_auth_status,
- get_minimax_oauth_auth_status,
- )
-
- # Read-only display: refresh-free snapshot — doctor must never
- # trigger an OAuth refresh as a side effect of a health check.
- nous_status = get_nous_auth_status_local()
- if nous_status.get("logged_in"):
- check_ok("Nous Portal auth", "(logged in)")
- else:
- check_warn("Nous Portal auth", "(not logged in)")
+ from hermes_cli.auth import get_nous_auth_status_local, get_codex_auth_status, get_minimax_oauth_auth_status
+ # Read-only display: refresh-free snapshot — doctor must never trigger an OAuth refresh.
+ _login_row("Nous Portal auth", get_nous_auth_status_local())
codex_status = get_codex_auth_status()
- if codex_status.get("logged_in"):
- check_ok("OpenAI Codex auth", "(logged in)")
- else:
- check_warn("OpenAI Codex auth", "(not logged in)")
+ if not _login_row("OpenAI Codex auth", codex_status):
if codex_status.get("error"):
check_info(codex_status["error"])
- # Native OAuth uses Hermes' own device-code flow — the Codex CLI is
- # only needed to import existing tokens from ~/.codex/auth.json.
- # Attach the hint to the Codex auth row so it doesn't read as
- # remediation for whichever provider happens to print next (#27975).
+ # Native OAuth uses Hermes' own device-code flow — the Codex CLI is only needed to import
+ # existing tokens from ~/.codex/auth.json. Attach the hint to the Codex auth row so it
+ # doesn't read as remediation for whichever provider happens to print next.
if not _safe_which("codex"):
- check_info(
- "codex CLI not installed "
- "(optional — only required to import tokens "
- "from an existing Codex CLI login)"
- )
-
+ check_info("codex CLI not installed (optional — only required to import tokens from an existing Codex CLI login)")
minimax_status = get_minimax_oauth_auth_status()
- if minimax_status.get("logged_in"):
- region = minimax_status.get("region", "global")
- check_ok("MiniMax OAuth", f"(logged in, region={region})")
- else:
- check_warn("MiniMax OAuth", "(not logged in)")
+ _login_row("MiniMax OAuth", minimax_status, f"(logged in, region={minimax_status.get('region', 'global')})")
except Exception as e:
check_warn("Auth provider status", f"(could not check: {e})")
# xAI OAuth — separate try/except so an import failure here cannot
- # disrupt the already-printed Nous/Codex/Gemini/MiniMax rows above.
+ # disrupt the already-printed Nous/Codex/MiniMax rows above.
try:
from hermes_cli.auth import get_xai_oauth_auth_status
xai_oauth_status = get_xai_oauth_auth_status() or {}
- if xai_oauth_status.get("logged_in"):
- check_ok("xAI OAuth", "(logged in)")
- else:
- check_warn("xAI OAuth", "(not logged in)")
- if xai_oauth_status.get("error"):
- check_info(xai_oauth_status["error"])
+ if not _login_row("xAI OAuth", xai_oauth_status) and xai_oauth_status.get("error"):
+ check_info(xai_oauth_status["error"])
except Exception:
pass
return f
+def _login_row(label: str, status: dict, ok_detail: str = "(logged in)") -> bool:
+ return check_bool(status.get("logged_in"), (label, ok_detail), (label, "(not logged in)"))
+
+
def _check_api_connectivity(should_fix: bool) -> Finding:
"""Parallel HTTP/SDK probes for every configured provider; results printed in submission order."""
f = Finding()
probes = build_probes()
- # Single status line so users see something happening; ``\r`` clears it
- # once the first real result line lands.
- print(f" {color(f'Running {len(probes)} connectivity checks in parallel…', Colors.DIM)}",
- end="", flush=True)
+ # Single status line so users see something happening; ``\r`` clears it once results land.
+ print(f" {color(f'Running {len(probes)} connectivity checks in parallel…', Colors.DIM)}", end="", flush=True)
results = run_probes(probes)
print("\r" + " " * 70 + "\r", end="")
for r in results:
@@ -222,8 +130,7 @@ def _check_api_connectivity(should_fix: bool) -> Finding:
return f
-# Ordered (section title, check). A None title means the check prints its own
-# header (or none) — order is the user-visible output order, keep it.
+# Ordered (section title, check). None title = check prints its own header (or none); order is user-visible.
DOCTOR_CHECKS = (
('Security Advisories', _check_security_advisories),
('MCP Server Security', _check_mcp_security),
@@ -253,62 +160,39 @@ DOCTOR_CHECKS = (
def _ack_advisory(ack_target: str) -> None:
"""`hermes doctor --ack <id>`: persist the ack and return without running diagnostics."""
- from hermes_cli.security_advisories import (
- ADVISORIES,
- ack_advisory,
- )
+ from hermes_cli.security_advisories import ADVISORIES, ack_advisory
valid_ids = {a.id for a in ADVISORIES}
if ack_target not in valid_ids:
- print(color(
- f"Unknown advisory ID: {ack_target!r}. Known IDs: "
- f"{', '.join(sorted(valid_ids)) or '(none)'}",
- Colors.RED,
- ))
+ print(color(f"Unknown advisory ID: {ack_target!r}. Known IDs: {', '.join(sorted(valid_ids)) or '(none)'}", Colors.RED))
sys.exit(2)
if ack_advisory(ack_target):
- print(color(
- f" ✓ Acknowledged advisory {ack_target}. "
- f"It will no longer trigger startup banners.",
- Colors.GREEN,
- ))
+ print(color(f" ✓ Acknowledged advisory {ack_target}. It will no longer trigger startup banners.", Colors.GREEN))
else:
- print(color(
- f" ✗ Failed to persist ack for {ack_target}. "
- f"Check ~/.hermes/config.yaml is writable.",
- Colors.RED,
- ))
+ print(color(f" ✗ Failed to persist ack for {ack_target}. Check ~/.hermes/config.yaml is writable.", Colors.RED))
sys.exit(1)
def _print_summary(should_fix: bool, total: Finding) -> None:
print()
- remaining_issues = total.issues + total.manual_issues
- fixed_count = total.fixed
- if should_fix and fixed_count > 0:
+ remaining = total.issues + total.manual_issues
+ numbered = "".join(f" {i}. {issue}\n" for i, issue in enumerate(remaining, 1))
+ if should_fix and total.fixed > 0:
print(color("─" * 60, Colors.GREEN))
- print(color(f" Fixed {fixed_count} issue(s).", Colors.GREEN, Colors.BOLD), end="")
- if remaining_issues:
- print(color(f" {len(remaining_issues)} issue(s) require manual intervention.", Colors.YELLOW, Colors.BOLD))
- else:
- print()
+ print(color(f" Fixed {total.fixed} issue(s).", Colors.GREEN, Colors.BOLD), end="")
+ print(color(f" {len(remaining)} issue(s) require manual intervention.", Colors.YELLOW, Colors.BOLD) if remaining else "")
print()
- if remaining_issues:
- for i, issue in enumerate(remaining_issues, 1):
- print(f" {i}. {issue}")
- print()
- elif remaining_issues:
+ if remaining:
+ print(numbered)
+ elif remaining:
print(color("─" * 60, Colors.YELLOW))
- print(color(f" Found {len(remaining_issues)} issue(s) to address:", Colors.YELLOW, Colors.BOLD))
- print()
- for i, issue in enumerate(remaining_issues, 1):
- print(f" {i}. {issue}")
+ print(color(f" Found {len(remaining)} issue(s) to address:", Colors.YELLOW, Colors.BOLD))
print()
+ print(numbered)
if not should_fix:
print(color(" Tip: run 'hermes doctor --fix' to auto-fix what's possible.", Colors.DIM))
else:
print(color("─" * 60, Colors.GREEN))
print(color(" All checks passed! 🎉", Colors.GREEN, Colors.BOLD))
-
print()
@@ -317,8 +201,7 @@ def run_doctor(args):
should_fix = getattr(args, 'fix', False)
ack_target = getattr(args, 'ack', None)
- # Doctor runs from the interactive CLI, so CLI-gated tool availability
- # checks (like cronjob management) should see the same context as `hermes`.
+ # Doctor runs from the interactive CLI, so CLI-gated tool checks (e.g. cronjob) see the same context.
os.environ.setdefault("HERMES_INTERACTIVE", "1")
if ack_target:
@@ -335,8 +218,7 @@ def run_doctor(args):
_section(title)
total.merge(check(should_fix))
- # Opt-in live backend probes run AFTER all static checks, only with
- # `hermes doctor --live` (real network calls; bounded + read-only).
+ # Opt-in live probes run AFTER all static checks (`--live`: real network calls; bounded + read-only).
try:
from hermes_cli.doctor_live import maybe_run_live_checks
maybe_run_live_checks(args, total.manual_issues)
diff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.py
index db4ed037d04..eb1cd3174f4 100644
--- a/hermes_cli/doctor_config.py
+++ b/hermes_cli/doctor_config.py
@@ -9,13 +9,7 @@ from __future__ import annotations
import os
import shutil
from hermes_cli.doctor_report import (
- Finding,
- _fail_and_issue,
- _section,
- check_fail,
- check_info,
- check_ok,
- check_warn,
+ Finding, _fail_and_issue, _section, check_fail, check_info, check_ok, check_warn, doctor_check,
)
@@ -25,31 +19,23 @@ def _has_provider_env_config(content: str) -> bool:
return any(key in content for key in _PROVIDER_ENV_HINTS)
-# Deprecated / legacy config keys still read for back-compat. Doctor surfaces
-# them as non-failing warnings with the modern replacement — it does not
-# auto-migrate or delete (migrations live in config.py version steps).
+# Deprecated / legacy config keys still read for back-compat. Doctor surfaces them as non-failing
+# warnings with the modern replacement — it does not auto-migrate (migrations live in config.py).
_DEPRECATED_CONFIG_KEYS: tuple[tuple[str, str, str], ...] = (
# (section, key, replacement)
("display", "tool_progress_overrides", "display.platforms"),
("delegation", "max_async_children", "delegation.max_concurrent_children"),
-)
-
-
-# compression.summary_* → auxiliary.compression (model/provider/base_url)
-_DEPRECATED_COMPRESSION_SUMMARY_KEYS: tuple[str, ...] = (
- "summary_model",
- "summary_provider",
- "summary_base_url",
+ ("compression", "summary_model", "auxiliary.compression"),
+ ("compression", "summary_provider", "auxiliary.compression"),
+ ("compression", "summary_base_url", "auxiliary.compression"),
)
# Deprecated env vars (checked in the .env file, not process env, so config→env
# bridges like terminal.cwd → TERMINAL_CWD do not false-positive).
_DEPRECATED_ENV_VARS: tuple[tuple[str, str], ...] = (
- # HERMES_TOOL_PROGRESS is fully unsupported since the v12 config support
- # floor removed its only consumer (the v3→4 migration) — it is silently
- # ignored. HERMES_TOOL_PROGRESS_MODE is still read by the gateway as a
- # back-compat fallback but remains deprecated.
+ # HERMES_TOOL_PROGRESS is silently ignored since the v12 config floor removed its only consumer;
+ # HERMES_TOOL_PROGRESS_MODE is still read by the gateway as a back-compat fallback.
("HERMES_TOOL_PROGRESS", "display.tool_progress in config.yaml — ignored/unsupported since config floor v12"),
("HERMES_TOOL_PROGRESS_MODE", "display.tool_progress in config.yaml"),
("TERMINAL_CWD", "terminal.cwd in config.yaml"),
@@ -60,28 +46,17 @@ _DEPRECATED_ENV_VARS: tuple[tuple[str, str], ...] = (
def collect_deprecated_config_keys(raw_config: dict | None) -> list[tuple[str, str]]:
- """Return ``(legacy_path, replacement)`` for deprecated keys present in *raw_config*.
+ """Return ``(legacy_path, replacement)`` for deprecated keys present in the on-disk YAML.
- Only keys that appear in the on-disk YAML are reported (raw file load, not
- merged defaults). Empty containers still count — presence of the legacy
- key is the signal that the user should migrate.
+ Empty containers still count — presence of the legacy key is the signal to migrate.
"""
- findings: list[tuple[str, str]] = []
if not isinstance(raw_config, dict):
- return findings
-
- for section, key, replacement in _DEPRECATED_CONFIG_KEYS:
- section_val = raw_config.get(section)
- if isinstance(section_val, dict) and key in section_val:
- findings.append((f"{section}.{key}", replacement))
-
- compression = raw_config.get("compression")
- if isinstance(compression, dict):
- for key in _DEPRECATED_COMPRESSION_SUMMARY_KEYS:
- if key in compression:
- findings.append((f"compression.{key}", "auxiliary.compression"))
-
- return findings
+ return []
+ return [
+ (f"{section}.{key}", replacement)
+ for section, key, replacement in _DEPRECATED_CONFIG_KEYS
+ if isinstance(raw_config.get(section), dict) and key in raw_config[section]
+ ]
def collect_deprecated_env_vars(env_map: dict | None) -> list[tuple[str, str]]:
@@ -90,20 +65,13 @@ def collect_deprecated_env_vars(env_map: dict | None) -> list[tuple[str, str]]:
*env_map* should come from the on-disk ``.env`` (e.g. ``load_env()``), not
``os.environ``, so bridged runtime vars do not trigger false positives.
"""
- findings: list[tuple[str, str]] = []
if not isinstance(env_map, dict):
- return findings
- for name, replacement in _DEPRECATED_ENV_VARS:
- val = env_map.get(name)
- if val is not None and str(val).strip() != "":
- findings.append((name, replacement))
- return findings
+ return []
+ return [(name, replacement) for name, replacement in _DEPRECATED_ENV_VARS
+ if env_map.get(name) is not None and str(env_map[name]).strip() != ""]
-def collect_relay_plugin_cutover_findings(
- raw_config: dict | None,
- env_map: dict | None,
-) -> list[tuple[str, str]]:
+def collect_relay_plugin_cutover_findings(raw_config: dict | None, env_map: dict | None) -> list[tuple[str, str]]:
"""Return actionable findings for the removed Hermes Relay plugin."""
from hermes_cli.relay_plugin_cutover import (
LEGACY_RELAY_EXPORT_ENV_VARS,
@@ -113,51 +81,32 @@ def collect_relay_plugin_cutover_findings(
)
findings: list[tuple[str, str]] = []
- if isinstance(raw_config, dict):
- plugins = raw_config.get("plugins")
- if isinstance(plugins, dict):
- for key in legacy_relay_plugin_keys(plugins.get("enabled")):
- findings.append(
- (
- f"plugins.enabled: {key}",
- f"remove it and configure {RELAY_PLUGINS_CONFIG_ENV}",
- )
- )
+ plugins = raw_config.get("plugins") if isinstance(raw_config, dict) else None
+ if isinstance(plugins, dict):
+ findings += [(f"plugins.enabled: {key}", f"remove it and configure {RELAY_PLUGINS_CONFIG_ENV}")
+ for key in legacy_relay_plugin_keys(plugins.get("enabled"))]
effective_env = dict(env_map or {})
- # Fall through to process-level env ONLY when no explicit env_map was
- # given: run_doctor passes None and wants live-process vars included, but
- # callers (and tests) that hand in an explicit map are describing a
- # complete environment — merging os.environ on top breaks hermeticity on
- # any box that exports legacy relay vars (10-vs-2 findings, Aug 2026).
+ # Fall through to process-level env ONLY when no explicit env_map was given: run_doctor passes
+ # None and wants live-process vars included, but callers (and tests) handing in an explicit map
+ # describe a complete environment — merging os.environ on top breaks hermeticity.
if env_map is None:
for name in (*LEGACY_RELAY_EXPORT_ENV_VARS, RELAY_PLUGINS_CONFIG_ENV):
if name not in effective_env and os.environ.get(name) is not None:
effective_env[name] = os.environ[name]
if not str(effective_env.get(RELAY_PLUGINS_CONFIG_ENV, "")).strip():
- for name in configured_legacy_relay_env_vars(effective_env):
- findings.append(
- (
- name,
- f"move exporter settings to {RELAY_PLUGINS_CONFIG_ENV}; "
- "this variable is now ignored",
- )
- )
+ findings += [(name, f"move exporter settings to {RELAY_PLUGINS_CONFIG_ENV}; this variable is now ignored")
+ for name in configured_legacy_relay_env_vars(effective_env)]
return findings
-def report_deprecated_config_and_env(
- raw_config: dict | None = None,
- env_map: dict | None = None,
-) -> list[tuple[str, str]]:
+def report_deprecated_config_and_env(raw_config: dict | None = None, env_map: dict | None = None) -> list[tuple[str, str]]:
"""Emit non-failing doctor warnings for deprecated config keys and env vars.
- Returns the list of ``(legacy, replacement)`` findings that were reported
- (empty when nothing deprecated is present). Does not mutate config/env and
- does not append to the blocking ``issues`` list.
+ Returns the ``(legacy, replacement)`` findings reported (empty when nothing deprecated
+ is present). Does not mutate config/env and does not append to the blocking ``issues`` list.
"""
- deprecated = collect_deprecated_config_keys(raw_config)
- deprecated.extend(collect_deprecated_env_vars(env_map))
+ deprecated = collect_deprecated_config_keys(raw_config) + collect_deprecated_env_vars(env_map)
relay_cutover = collect_relay_plugin_cutover_findings(raw_config, env_map)
findings = deprecated + relay_cutover
if not findings:
@@ -165,27 +114,19 @@ def report_deprecated_config_and_env(
return findings
for legacy, replacement in deprecated:
- check_warn(
- f"Deprecated: {legacy}",
- f"(use {replacement} instead)",
- )
+ check_warn(f"Deprecated: {legacy}", f"(use {replacement} instead)")
check_info(f"Replace {legacy} → {replacement} (warn-only; not auto-migrated here)")
for legacy, replacement in relay_cutover:
- check_warn(
- f"Breaking Relay migration: {legacy}",
- f"({replacement})",
- )
+ check_warn(f"Breaking Relay migration: {legacy}", f"({replacement})")
check_info(f"Migrate {legacy}: {replacement}")
return findings
def managed_scope_check() -> None:
- """Report the active managed scope (resolved dir + pinned key counts).
+ """Report the active managed scope (resolved dir + pinned key counts); silent when none.
- Silent when no managed scope is present. When the managed directory was
- resolved from the HERMES_MANAGED_DIR override (rather than the system
- default), that is surfaced too — a redirected scope is the documented
- foot-gun (see docs/design/managed-scope.md §7) and an operator should see it.
+ A managed dir resolved from the HERMES_MANAGED_DIR override (rather than the system default) is
+ surfaced too — a redirected scope is the documented foot-gun (docs/design/managed-scope.md §7).
"""
try:
from hermes_cli import managed_scope
@@ -196,57 +137,43 @@ def managed_scope_check() -> None:
return
n_cfg = len(managed_scope.managed_config_keys())
n_env = len(managed_scope.load_managed_env())
- check_ok(
- f"Managed scope active: {n_cfg} config key(s), {n_env} env key(s) "
- f"pinned by {managed_dir}"
- )
+ check_ok(f"Managed scope active: {n_cfg} config key(s), {n_env} env key(s) pinned by {managed_dir}")
if os.environ.get("HERMES_MANAGED_DIR", "").strip():
check_info(f"managed dir set via HERMES_MANAGED_DIR={managed_dir}")
-def _check_mcp_security(should_fix: bool) -> Finding:
+@doctor_check("MCP security check failed: {e}")
+def _check_mcp_security(should_fix: bool, f: Finding) -> None:
"""Flag mcp_servers entries with suspicious stdio commands."""
- f = Finding()
- manual_issues = f.manual_issues
- try:
- from hermes_cli.config import load_config
- from hermes_cli.mcp_security import validate_mcp_server_entry
-
- servers = load_config().get("mcp_servers") or {}
- suspicious = 0
- if isinstance(servers, dict):
- for name, entry in sorted(servers.items()):
- if not isinstance(entry, dict):
- continue
- issues_found = validate_mcp_server_entry(name, entry)
- if not issues_found:
- continue
- suspicious += 1
- check_warn(f"MCP server '{name}' has suspicious stdio command", "; ".join(issues_found))
- manual_issues.append(
- f"Review/remove mcp_servers.{name} in config.yaml; rotate any credentials that may have been exposed."
- )
- if suspicious == 0:
- check_ok("No suspicious MCP stdio commands")
- except Exception as e:
- check_warn(f"MCP security check failed: {e}")
- return f
+ from hermes_cli.config import load_config
+ from hermes_cli.mcp_security import validate_mcp_server_entry
+
+ servers = load_config().get("mcp_servers") or {}
+ suspicious = 0
+ if isinstance(servers, dict):
+ for name, entry in sorted(servers.items()):
+ issues_found = validate_mcp_server_entry(name, entry) if isinstance(entry, dict) else None
+ if not issues_found:
+ continue
+ suspicious += 1
+ check_warn(f"MCP server '{name}' has suspicious stdio command", "; ".join(issues_found))
+ f.manual_issues.append(
+ f"Review/remove mcp_servers.{name} in config.yaml; rotate any credentials that may have been exposed."
+ )
+ if suspicious == 0:
+ check_ok("No suspicious MCP stdio commands")
def _check_env_file(should_fix: bool) -> Finding:
"""Managed scope plus ~/.hermes/.env presence and provider credentials."""
from hermes_cli.doctor import HERMES_HOME, PROJECT_ROOT, _DHH
f = Finding()
- issues = f.issues
managed_scope_check()
- # Check ~/.hermes/.env (primary location for user config)
env_path = HERMES_HOME / '.env'
if env_path.exists():
check_ok(f"{_DHH}/.env file exists")
-
- # Prefer UTF-8 (.env is written as UTF-8 elsewhere). Fall back to
- # latin-1 for Windows Notepad/cp1252 files that are not valid UTF-8 —
- # matches hermes_cli.env_loader._load_dotenv_with_fallback.
+ # Prefer UTF-8 (.env is written as UTF-8 elsewhere); latin-1 fallback for Windows
+ # Notepad/cp1252 files — matches hermes_cli.env_loader._load_dotenv_with_fallback.
try:
content = env_path.read_text(encoding="utf-8")
except UnicodeDecodeError:
@@ -255,39 +182,33 @@ def _check_env_file(should_fix: bool) -> Finding:
check_ok("API key or custom endpoint configured")
else:
check_warn(f"No API key found in {_DHH}/.env")
- issues.append("Run 'hermes setup' to configure API keys")
+ f.issues.append("Run 'hermes setup' to configure API keys")
+ elif (PROJECT_ROOT / '.env').exists(): # project root as fallback
+ check_ok(".env file exists (in project directory)")
else:
- # Also check project root as fallback
- fallback_env = PROJECT_ROOT / '.env'
- if fallback_env.exists():
- check_ok(".env file exists (in project directory)")
+ check_fail(f"{_DHH}/.env file missing")
+ if should_fix:
+ env_path.parent.mkdir(parents=True, exist_ok=True)
+ env_path.touch()
+ # .env holds API keys — touch() obeys umask (commonly 0o022, world-readable); tighten explicitly.
+ try:
+ os.chmod(str(env_path), 0o600)
+ except OSError:
+ pass
+ check_ok(f"Created empty {_DHH}/.env")
+ check_info("Run 'hermes setup' to configure API keys")
+ f.fixed += 1
else:
- check_fail(f"{_DHH}/.env file missing")
- if should_fix:
- env_path.parent.mkdir(parents=True, exist_ok=True)
- env_path.touch()
- # .env holds API keys — restrict to owner-only access from
- # creation. touch() obeys umask which is commonly 0o022,
- # leaving the file world-readable; tighten explicitly.
- try:
- os.chmod(str(env_path), 0o600)
- except OSError:
- pass
- check_ok(f"Created empty {_DHH}/.env")
- check_info("Run 'hermes setup' to configure API keys")
- f.fixed += 1
- else:
- check_info("Run 'hermes setup' to create one")
- issues.append("Run 'hermes setup' to create .env")
+ check_info("Run 'hermes setup' to create one")
+ f.issues.append("Run 'hermes setup' to create .env")
return f
def _known_provider_ids(cfg: dict) -> tuple[set, list, object, object, object]:
"""Return (known ids, custom providers, resolve_auth, normalize, resolve_full).
- Registry lookups are best-effort: any import failure leaves the matching
- resolver as None so validation degrades to "unavailable" rather than
- crashing doctor.
+ Registry lookups are best-effort: any import failure leaves the matching resolver as None so
+ validation degrades to "unavailable" rather than crashing doctor.
"""
known: set = set()
resolve_auth = normalize = resolve_full = None
@@ -322,16 +243,14 @@ def _known_provider_ids(cfg: dict) -> tuple[set, list, object, object, object]:
)
if aliases is not None:
for entry in custom_providers:
- if isinstance(entry, dict):
- name = str(entry.get("name") or "").strip()
- if name:
- known.update(aliases(name, str(entry.get("provider_key") or "").strip()))
+ name = str(entry.get("name") or "").strip() if isinstance(entry, dict) else ""
+ if name:
+ known.update(aliases(name, str(entry.get("provider_key") or "").strip()))
return known, custom_providers, resolve_auth, normalize, resolve_full
-# Vendor/model slugs are valid on aggregator-style providers and on any custom
-# provider. Fireworks' native IDs are slash-form (accounts/fireworks/models/...);
-# DeepInfra's catalog is exclusively vendor/model slugs.
+# Vendor/model slugs are valid on aggregator-style providers and on any custom provider. Fireworks'
+# native IDs are slash-form (accounts/fireworks/models/...); DeepInfra's catalog is exclusively vendor/model.
_VENDOR_SLUG_PROVIDERS = {
"openrouter", "auto", "ai-gateway", "kilocode", "opencode-zen", "huggingface",
"lmstudio", "nous", "nvidia", "fireworks", "deepinfra",
@@ -339,17 +258,14 @@ _VENDOR_SLUG_PROVIDERS = {
def _provider_has_credentials(runtime_provider: str) -> bool:
- """Only API-key providers in PROVIDER_REGISTRY are checked — OAuth/SDK/custom
- providers have their own env-var checks elsewhere in doctor, and
- get_auth_status() returns a bare {logged_in: False} for anything it doesn't
- dispatch, which would false-positive."""
+ """Only API-key providers in PROVIDER_REGISTRY are checked — OAuth/SDK/custom providers have their
+ own env-var checks elsewhere in doctor, and get_auth_status() returns a bare {logged_in: False}
+ for anything it doesn't dispatch, which would false-positive."""
if runtime_provider == "openrouter":
from hermes_cli.config import get_env_value
- return bool(
- str(get_env_value("OPENROUTER_API_KEY") or "").strip()
- or str(get_env_value("OPENAI_API_KEY") or "").strip()
- )
+ return bool(str(get_env_value("OPENROUTER_API_KEY") or "").strip()
+ or str(get_env_value("OPENAI_API_KEY") or "").strip())
from hermes_cli.auth import PROVIDER_REGISTRY, get_auth_status
pconfig = PROVIDER_REGISTRY.get(runtime_provider)
@@ -408,9 +324,7 @@ def _validate_model_config(config_path, issues: list) -> None:
)
policy_id = str(runtime_provider or catalog_provider or "").strip().lower()
- accepts_vendor_slug = (
- policy_id in _VENDOR_SLUG_PROVIDERS or policy_id == "custom" or policy_id.startswith("custom:")
- )
+ accepts_vendor_slug = policy_id in _VENDOR_SLUG_PROVIDERS or policy_id == "custom" or policy_id.startswith("custom:")
if default_model and "/" in default_model and policy_id and not accepts_vendor_slug:
check_warn(
f"model.default '{default_model}' uses a vendor/model slug but provider is '{provider_raw}'",
@@ -518,12 +432,10 @@ def _drift_stale_root_keys(f: Finding, should_fix: bool, config_path) -> None:
def _drift_max_iterations_ghost(f: Finding, should_fix: bool, config_path) -> None:
"""A stale HERMES_MAX_ITERATIONS in .env shadows agent.max_turns in config.yaml.
- The setup wizard used to dual-write the budget to both stores. The gateway
- bridge normally derives HERMES_MAX_ITERATIONS from agent.max_turns, but if
- that bridge bails on an earlier config-parse error the .env value silently
- wins (config says 400, activity line reads N/90). Read the .env FILE
- (load_env), not get_env_value/os.environ, which the bridge may have
- overridden already.
+ The setup wizard used to dual-write the budget to both stores. The gateway bridge normally derives
+ HERMES_MAX_ITERATIONS from agent.max_turns, but if that bridge bails on an earlier config-parse
+ error the .env value silently wins. Read the .env FILE (load_env), not get_env_value/os.environ,
+ which the bridge may have overridden already.
"""
from hermes_cli.doctor import _DHH
from hermes_cli.config import load_env, read_user_config_raw, remove_env_value
@@ -598,38 +510,28 @@ def _check_config_drift(should_fix: bool) -> Finding:
from hermes_cli.doctor import HERMES_HOME
f = Finding()
config_path = HERMES_HOME / 'config.yaml'
- steps = _CONFIG_DRIFT_STEPS if config_path.exists() else (_drift_deprecations,)
- for step in steps:
+ if not config_path.exists():
+ config_path = None
+ for step in _CONFIG_DRIFT_STEPS if config_path else (_drift_deprecations,):
try:
- step(f, should_fix, config_path if config_path.exists() else None)
+ step(f, should_fix, config_path)
except Exception:
pass
return f
-def _check_xai_retirement(should_fix: bool) -> Finding:
- f = Finding()
- manual_issues = f.manual_issues
- try:
- from hermes_cli.config import load_config
- from hermes_cli.xai_retirement import (
- MIGRATION_GUIDE_URL,
- find_retired_xai_refs,
- format_issue,
- )
+@doctor_check("xAI retirement check skipped", "({e})")
+def _check_xai_retirement(should_fix: bool, f: Finding) -> None:
+ from hermes_cli.config import load_config
+ from hermes_cli.xai_retirement import MIGRATION_GUIDE_URL, find_retired_xai_refs, format_issue
- _xai_cfg = load_config()
- retired_refs = find_retired_xai_refs(_xai_cfg)
- if not retired_refs:
- check_ok("No retired xAI models in config")
- else:
- for ref in retired_refs:
- check_warn(format_issue(ref))
- check_info(f"Migration guide: {MIGRATION_GUIDE_URL}")
- manual_issues.append(
- f"Update {len(retired_refs)} retired xAI model reference(s) "
- f"in config.yaml — see {MIGRATION_GUIDE_URL}"
- )
- except Exception as _xai_check_err:
- check_warn("xAI retirement check skipped", f"({_xai_check_err})")
- return f
+ retired_refs = find_retired_xai_refs(load_config())
+ if not retired_refs:
+ check_ok("No retired xAI models in config")
+ return
+ for ref in retired_refs:
+ check_warn(format_issue(ref))
+ check_info(f"Migration guide: {MIGRATION_GUIDE_URL}")
+ f.manual_issues.append(
+ f"Update {len(retired_refs)} retired xAI model reference(s) in config.yaml — see {MIGRATION_GUIDE_URL}"
+ )
diff --git a/hermes_cli/doctor_connectivity.py b/hermes_cli/doctor_connectivity.py
index 65bde69e9e8..774bdaac49e 100644
--- a/hermes_cli/doctor_connectivity.py
+++ b/hermes_cli/doctor_connectivity.py
@@ -31,11 +31,8 @@ _GLYPH = {"ok": ("✓", Colors.GREEN), "warn": ("⚠", Colors.YELLOW), "fail": (
def _row(name: str, status: str, detail: str = "", issues: list | None = None, label: str | None = None) -> ProbeResult:
glyph, col = _GLYPH[status]
- return ProbeResult(
- name,
- [(color(glyph, col), label if label is not None else name, color(detail, Colors.DIM) if detail else "")],
- list(issues or []),
- )
+ return ProbeResult(name, [(color(glyph, col), name if label is None else label, color(detail, Colors.DIM) if detail else "")],
+ list(issues or []))
def _skip(name: str) -> ProbeResult:
@@ -61,9 +58,9 @@ def _has_healthy_oauth_fallback_for_apikey_provider(provider_label: str) -> bool
def _build_apikey_providers_list() -> list:
"""Build the API-key provider health-check list once and cache it.
- Tuple format: (name, env_vars, default_url, base_env, supports_models_endpoint)
- Base list augmented with any ProviderProfile with auth_type="api_key" not
- already present — adding plugins/model-providers/<name>/ is sufficient to get into doctor.
+ Tuple format: (name, env_vars, default_url, base_env, supports_models_endpoint). Base list augmented
+ with any ProviderProfile with auth_type="api_key" not already present — adding
+ plugins/model-providers/<name>/ is sufficient to get into doctor.
"""
_static = [
("Z.AI / GLM", ("GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"), "https://api.z.ai/api/paas/v4/models", "GLM_BASE_URL", True),
@@ -113,30 +110,17 @@ def _build_apikey_providers_list() -> list:
_label = _pp.display_name or _pp.name
if _label in _known_names or _pp.name in _known_canonical:
continue
- _candidates = {_normalize_provider(_pp.name)}
- for _alias in (_pp.aliases or ()):
- _candidates.add(_normalize_provider(_alias))
- if _candidates & _dedicated_canonical:
+ if {_normalize_provider(a) for a in (_pp.name, *(_pp.aliases or ()))} & _dedicated_canonical:
continue
- # Separate API-key vars from base-URL override vars — the health-check
- # loop sends the first found value as Authorization: Bearer, so a URL
- # string must never be picked.
- _key_vars = tuple(
- v for v in _pp.env_vars
- if not v.endswith("_BASE_URL") and not v.endswith("_URL")
- )
- _base_var = next(
- (v for v in _pp.env_vars if v.endswith("_BASE_URL") or v.endswith("_URL")),
- None,
- )
+ # Separate API-key vars from base-URL override vars — the health-check loop sends the
+ # first found value as Authorization: Bearer, so a URL string must never be picked.
+ _is_url = lambda v: v.endswith("_BASE_URL") or v.endswith("_URL") # noqa: E731
+ _key_vars = tuple(v for v in _pp.env_vars if not _is_url(v))
if not _key_vars:
continue
- _models_url = (
- (_pp.models_url or (_pp.base_url.rstrip("/") + "/models"))
- if _pp.base_url else None
- )
- _hc = getattr(_pp, "supports_health_check", True)
- _static.append((_label, _key_vars, _models_url, _base_var, _hc))
+ _base_var = next((v for v in _pp.env_vars if _is_url(v)), None)
+ _models_url = (_pp.models_url or (_pp.base_url.rstrip("/") + "/models")) if _pp.base_url else None
+ _static.append((_label, _key_vars, _models_url, _base_var, getattr(_pp, "supports_health_check", True)))
except Exception:
pass
return _static
@@ -176,12 +160,7 @@ def _probe_anthropic() -> ProbeResult:
return _skip(name)
try:
import httpx
- from agent.anthropic_adapter import (
- _is_oauth_token,
- _COMMON_BETAS,
- _OAUTH_ONLY_BETAS,
- _CONTEXT_1M_BETA,
- )
+ from agent.anthropic_adapter import _is_oauth_token, _COMMON_BETAS, _OAUTH_ONLY_BETAS, _CONTEXT_1M_BETA
headers = {"anthropic-version": "2023-06-01"}
is_oauth = _is_oauth_token(key)
if is_oauth:
@@ -191,19 +170,11 @@ def _probe_anthropic() -> ProbeResult:
headers["x-api-key"] = key
url = "https://api.anthropic.com/v1/models"
r = httpx.get(url, headers=headers, timeout=10)
- # Reactive recovery: OAuth subscriptions without 1M context reject the
- # request with 400 "long context beta is not yet available for this
- # subscription". Retry once with that beta stripped so the doctor
- # check doesn't falsely report Anthropic as unreachable.
- if (
- is_oauth
- and r.status_code == 400
- and "long context beta" in r.text.lower()
- and "not yet available" in r.text.lower()
- ):
- headers["anthropic-beta"] = ",".join(
- [b for b in _COMMON_BETAS if b != _CONTEXT_1M_BETA] + list(_OAUTH_ONLY_BETAS)
- )
+ # Reactive recovery: OAuth subscriptions without 1M context reject with 400 "long context beta
+ # is not yet available for this subscription". Retry once with that beta stripped so doctor
+ # doesn't falsely report Anthropic as unreachable.
+ if is_oauth and r.status_code == 400 and "long context beta" in r.text.lower() and "not yet available" in r.text.lower():
+ headers["anthropic-beta"] = ",".join([b for b in _COMMON_BETAS if b != _CONTEXT_1M_BETA] + list(_OAUTH_ONLY_BETAS))
r = httpx.get(url, headers=headers, timeout=10)
except Exception as e:
return _row(name, "warn", f"({e})")
@@ -215,11 +186,7 @@ def _probe_anthropic() -> ProbeResult:
def _probe_apikey_provider(pname, env_vars, default_url, base_env, supports_health_check) -> ProbeResult:
- key = ""
- for ev in env_vars:
- key = os.getenv(ev, "")
- if key:
- break
+ key = next((k for k in (os.getenv(ev, "") for ev in env_vars) if k), "")
if not key:
return _skip(pname)
label = pname.ljust(20)
@@ -241,10 +208,7 @@ def _probe_apikey_provider(pname, env_vars, default_url, base_env, supports_heal
if base_url_host_matches(base, "api.kimi.com") and base.rstrip("/").endswith("/coding"):
base = base.rstrip("/") + "/v1"
url = (base.rstrip("/") + "/models") if base else default_url
- headers = {
- "Authorization": f"Bearer {key}",
- "User-Agent": _HERMES_USER_AGENT,
- }
+ headers = {"Authorization": f"Bearer {key}", "User-Agent": _HERMES_USER_AGENT}
if base_url_host_matches(base, "api.kimi.com"):
headers["User-Agent"] = "claude-code/0.1.0"
# Google's Generative Language API rejects ``Authorization: Bearer
@@ -268,11 +232,7 @@ def _probe_apikey_provider(pname, env_vars, default_url, base_env, supports_heal
def _probe_bedrock() -> ProbeResult:
name = "AWS Bedrock"
try:
- from agent.bedrock_adapter import (
- has_aws_credentials,
- resolve_aws_auth_env_var,
- resolve_bedrock_region,
- )
+ from agent.bedrock_adapter import has_aws_credentials, resolve_aws_auth_env_var, resolve_bedrock_region
except ImportError:
return _skip(name)
if not has_aws_credentials():
@@ -283,8 +243,7 @@ def _probe_bedrock() -> ProbeResult:
try:
import boto3
from botocore.config import Config as _BotoConfig
- # Trim retries on the actual Bedrock API call so a transient
- # failure doesn't pad the doctor run by 30+ seconds.
+ # Trim retries so a transient failure doesn't pad the doctor run by 30+ seconds.
cfg = _BotoConfig(connect_timeout=5, read_timeout=10, retries={"max_attempts": 1})
client = boto3.client("bedrock", region_name=region, config=cfg)
resp = client.list_foundation_models()
@@ -302,10 +261,8 @@ def _probe_bedrock() -> ProbeResult:
def _probe_azure_entra() -> ProbeResult:
"""Probe Azure Foundry Entra ID auth, parallel to ``_probe_bedrock``.
- Skipped unless the active config has ``model.provider: azure-foundry`` AND
- ``model.auth_mode: entra_id`` — we don't probe the token-service / CLI
- chain for users on plain API-key Azure. Bounded by a 10s timeout (via
- :func:`agent.azure_identity_adapter.describe_active_credential`).
+ Skipped unless the active config has ``model.provider: azure-foundry`` AND ``model.auth_mode: entra_id``
+ — we don't probe the token-service / CLI chain for plain API-key Azure. Bounded by a 10s timeout.
"""
name = "Azure Foundry (Entra ID)"
label = name.ljust(28)
@@ -337,9 +294,7 @@ def _probe_azure_entra() -> ProbeResult:
[f"Install azure-identity: {sys.executable} -m pip install azure-identity"], label=label)
entra_cfg = model_cfg.get("entra") or {}
- if not isinstance(entra_cfg, dict):
- entra_cfg = {}
- scope = str(entra_cfg.get("scope") or "").strip() or SCOPE_AI_AZURE_DEFAULT
+ scope = (str(entra_cfg.get("scope") or "").strip() if isinstance(entra_cfg, dict) else "") or SCOPE_AI_AZURE_DEFAULT
info = describe_active_credential(config=EntraIdentityConfig(scope=scope), timeout_seconds=10.0)
if info.get("ok"):
env_sources = info.get("env_sources") or []
@@ -371,15 +326,12 @@ def build_probes() -> list:
def run_probes(probes: list) -> list:
"""Run every probe in a thread pool; results in submission order.
- Probes are independent HTTP calls, so running them in series cost ~5s wall
- (2s of it boto3's IMDS lookup). Parallel collapses the section to roughly
- the slowest single probe without changing the output.
+ Probes are independent HTTP calls (series cost ~5s wall, 2s of it boto3's IMDS lookup);
+ parallel collapses the section to roughly the slowest single probe without changing the output.
"""
- # Disable boto3's EC2 instance-metadata probe for the parallel block: the
- # default credential chain tries 169.254.169.254 with a multi-second
- # timeout off-EC2. Set on the parent thread before submitting so the env
- # mutation never races a worker; has_aws_credentials() already gates on
- # real env creds, so IMDS is never the legitimate source for doctor.
+ # Disable boto3's EC2 instance-metadata probe (169.254.169.254, multi-second timeout off-EC2).
+ # Set on the parent thread before submitting so the env mutation never races a worker;
+ # has_aws_credentials() already gates on real env creds, so IMDS is never legitimate for doctor.
_imds_prev = os.environ.get("AWS_EC2_METADATA_DISABLED")
os.environ["AWS_EC2_METADATA_DISABLED"] = "true"
try:
diff --git a/hermes_cli/doctor_live.py b/hermes_cli/doctor_live.py
index b23147f4f79..9b2807ff883 100644
--- a/hermes_cli/doctor_live.py
+++ b/hermes_cli/doctor_live.py
@@ -1,6 +1,6 @@
"""``hermes doctor --live`` — opt-in bounded real-call tool-backend probes.
-- **Opt-in only.** These probes make real (cheap, metadata/read-only) network calls and may spend a
+Opt-in only: these probes make real (cheap, metadata/read-only) network calls and may spend a
trivial amount of quota. They run ONLY when the user passes ``hermes doctor --live``.
"""
@@ -10,13 +10,7 @@ import os
from dataclasses import dataclass
from typing import Callable, List, Optional
-from hermes_cli.doctor import (
- _section,
- check_fail,
- check_info,
- check_ok,
- check_warn,
-)
+from hermes_cli.doctor import _section, check_fail, check_info, check_ok, check_warn
DEFAULT_PROBE_TIMEOUT = 10.0
@@ -45,9 +39,7 @@ class ProbeResult:
detail: str = ""
-# ---------------------------------------------------------------------------
-# Small seams (monkeypatchable in tests, and single points of control).
-# ---------------------------------------------------------------------------
+# ── Small seams (monkeypatchable in tests, and single points of control) ──
def _load_config() -> dict:
try:
@@ -58,8 +50,7 @@ def _load_config() -> dict:
return {}
-def _http_get(url: str, headers: Optional[dict] = None,
- timeout: Optional[float] = None):
+def _http_get(url: str, headers: Optional[dict] = None, timeout: Optional[float] = None):
"""Single HTTP GET seam for all metadata probes."""
import httpx
@@ -77,18 +68,14 @@ def _browser_available() -> bool:
if (PROJECT_ROOT / "node_modules" / "agent-browser").exists():
return True
- for candidate in (HERMES_HOME / "node" / "bin",
- HERMES_HOME / "node",
- HERMES_HOME / "node_modules" / ".bin"):
+ for candidate in (HERMES_HOME / "node" / "bin", HERMES_HOME / "node", HERMES_HOME / "node_modules" / ".bin"):
if shutil.which("agent-browser", path=str(candidate)):
return True
except Exception:
pass
- # agent-browser resolves lazily via npx on the default install (#43564),
- # invisible to the PATH/node_modules probes above. Mirror the rung
- # hermes_cli.doctor uses so this probe can't diverge from it, including
- # the Termux carve-out (bare npx is too fragile to advertise as ready
- # there — see check_browser_requirements).
+ # agent-browser resolves lazily via npx on the default install, invisible to the PATH/node_modules
+ # probes above. Mirror the rung hermes_cli.doctor uses so this probe can't diverge from it, including
+ # the Termux carve-out (bare npx is too fragile to advertise as ready there).
try:
from tools.browser_tool import (
_find_agent_browser,
@@ -98,9 +85,7 @@ def _browser_available() -> bool:
browser_cmd = _find_agent_browser(validate=False)
except Exception:
return False
- if not _is_npx_agent_browser_sentinel(browser_cmd):
- return False
- return not _requires_real_termux_browser_install(browser_cmd)
+ return _is_npx_agent_browser_sentinel(browser_cmd) and not _requires_real_termux_browser_install(browser_cmd)
def _launch_browser_probe(timeout: float) -> tuple:
@@ -115,11 +100,9 @@ def _launch_browser_probe(timeout: float) -> tuple:
return (False, "playwright not installed")
with sync_playwright() as p:
- browser = p.chromium.launch(headless=True,
- timeout=timeout * 1000)
+ browser = p.chromium.launch(headless=True, timeout=timeout * 1000)
try:
- page = browser.new_page()
- page.goto("about:blank", timeout=timeout * 1000)
+ browser.new_page().goto("about:blank", timeout=timeout * 1000)
finally:
browser.close()
return (True, "launched + about:blank + closed")
@@ -132,40 +115,26 @@ def _probe_mcp_server(name: str, config: dict, timeout: float):
return _probe_single_server(name, config, connect_timeout=timeout)
-# ---------------------------------------------------------------------------
-# Per-backend probes. Each returns a ProbeResult and never raises upward
-# beyond what run_live_checks' catch-all handles.
-# ---------------------------------------------------------------------------
+# ── Per-backend probes. Each returns a ProbeResult; _run_one's catch-all handles crashes. ──
def _classify_http(name: str, resp, key_hint: str) -> ProbeResult:
code = getattr(resp, "status_code", None)
if code is not None and 200 <= code < 300:
return ProbeResult(name, "pass", f"(HTTP {code})")
if code in (401, 403):
- return ProbeResult(name, "fail",
- f"(HTTP {code} — check {key_hint})")
+ return ProbeResult(name, "fail", f"(HTTP {code} — check {key_hint})")
return ProbeResult(name, "fail", f"(HTTP {code})")
-def _keyed_probe(name: str, url: str, env_var: str, scheme: str,
- timeout: float) -> ProbeResult:
+def _keyed_probe(name: str, url: str, env_var: str, scheme: str, timeout: float) -> ProbeResult:
"""Metadata GET authenticated by one env var (never a generation call)."""
key = os.getenv(env_var, "").strip()
if not key:
return ProbeResult(name, "skip", "(not configured)")
- resp = _http_get(url, headers={"Authorization": f"{scheme} {key}"},
- timeout=timeout)
+ resp = _http_get(url, headers={"Authorization": f"{scheme} {key}"}, timeout=timeout)
return _classify_http(name, resp, env_var)
-def _probe_firecrawl(timeout: float) -> ProbeResult:
- return _keyed_probe("Firecrawl", FIRECRAWL_HEALTH_URL, "FIRECRAWL_API_KEY", "Bearer", timeout)
-
-
-def _probe_fal(timeout: float) -> ProbeResult:
- return _keyed_probe("FAL", FAL_MODELS_URL, "FAL_KEY", "Key", timeout)
-
-
def _probe_browser(timeout: float) -> ProbeResult:
if not _browser_available():
return ProbeResult("Browser", "skip", "(not configured)")
@@ -173,45 +142,27 @@ def _probe_browser(timeout: float) -> ProbeResult:
return ProbeResult("Browser", "pass" if ok else "fail", f"({detail})")
-def _audio_provider_probe(kind: str, provider: str,
- timeout: float) -> ProbeResult:
+def _probe_audio(kind: str, config: dict, timeout: float) -> ProbeResult:
"""Shared TTS/STT metadata probe (voices/models list GET only)."""
name = kind.upper()
- provider = (provider or "").strip().lower()
+ provider = (((config.get(kind) or {}).get("provider")) or "").strip().lower()
if provider in _LOCAL_AUDIO_PROVIDERS:
- return ProbeResult(name, "skip",
- f"(provider '{provider or 'local'}' — no remote "
- "backend to probe)")
+ return ProbeResult(name, "skip", f"(provider '{provider or 'local'}' — no remote backend to probe)")
entry = _AUDIO_PROBES.get(provider)
if entry is None:
- return ProbeResult(name, "skip",
- f"(provider '{provider}' — no live probe "
- "implemented)")
+ return ProbeResult(name, "skip", f"(provider '{provider}' — no live probe implemented)")
url, env_var, scheme = entry
key = os.getenv(env_var, "").strip()
if not key:
- return ProbeResult(name, "warn",
- f"(provider '{provider}' configured but "
- f"{env_var} is not set)")
- if scheme == "xi":
- headers = {"xi-api-key": key}
- else:
- headers = {"Authorization": f"Bearer {key}"}
- resp = _http_get(url, headers=headers, timeout=timeout)
- result = _classify_http(name, resp, env_var)
+ return ProbeResult(name, "warn", f"(provider '{provider}' configured but {env_var} is not set)")
+ headers = {"xi-api-key": key} if scheme == "xi" else {"Authorization": f"Bearer {key}"}
+ result = _classify_http(name, _http_get(url, headers=headers, timeout=timeout), env_var)
result.detail = f"({provider}) {result.detail}"
return result
-def _probe_audio(kind: str, config: dict, timeout: float) -> ProbeResult:
- provider = ((config.get(kind) or {}).get("provider")) or ""
- return _audio_provider_probe(kind, provider, timeout)
-
-
-# ---------------------------------------------------------------------------
-# Orchestration
-# ---------------------------------------------------------------------------
+# ── Orchestration ──
_REPORTERS = {"pass": check_ok, "warn": check_warn, "fail": check_fail}
@@ -226,8 +177,7 @@ def _report(result: ProbeResult, issues: List[str]) -> None:
issues.append(f"Live probe failed: {result.name} {result.detail}")
-def _run_one(name: str, fn: Callable[[], ProbeResult],
- issues: List[str]) -> ProbeResult:
+def _run_one(name: str, fn: Callable[[], ProbeResult], issues: List[str]) -> ProbeResult:
"""Run one probe with a catch-all so a crash never kills doctor."""
try:
result = fn()
@@ -235,10 +185,7 @@ def _run_one(name: str, fn: Callable[[], ProbeResult],
result = ProbeResult(name, "fail", f"(timed out: {exc})")
except Exception as exc:
msg = str(exc) or exc.__class__.__name__
- if "time" in msg.lower():
- result = ProbeResult(name, "fail", f"(timed out: {msg})")
- else:
- result = ProbeResult(name, "fail", f"({msg})")
+ result = ProbeResult(name, "fail", f"(timed out: {msg})" if "time" in msg.lower() else f"({msg})")
_report(result, issues)
return result
@@ -251,45 +198,35 @@ def run_live_checks(issues: List[str]) -> List[ProbeResult]:
"""
config = _load_config()
try:
- timeout = float(
- (config.get("doctor") or {}).get("live_probe_timeout",
- DEFAULT_PROBE_TIMEOUT))
+ timeout = float((config.get("doctor") or {}).get("live_probe_timeout", DEFAULT_PROBE_TIMEOUT))
except (TypeError, ValueError):
timeout = DEFAULT_PROBE_TIMEOUT
timeout = max(1.0, timeout)
_section("Live Backend Probes (opt-in, real calls)")
- results: List[ProbeResult] = []
-
- results.append(_run_one(
- "Firecrawl", lambda: _probe_firecrawl(timeout), issues))
- results.append(_run_one(
- "FAL", lambda: _probe_fal(timeout), issues))
- results.append(_run_one(
- "Browser", lambda: _probe_browser(timeout), issues))
+ results: List[ProbeResult] = [
+ _run_one("Firecrawl", lambda: _keyed_probe("Firecrawl", FIRECRAWL_HEALTH_URL, "FIRECRAWL_API_KEY", "Bearer", timeout), issues),
+ _run_one("FAL", lambda: _keyed_probe("FAL", FAL_MODELS_URL, "FAL_KEY", "Key", timeout), issues),
+ _run_one("Browser", lambda: _probe_browser(timeout), issues),
+ ]
servers = config.get("mcp_servers") or {}
if isinstance(servers, dict) and servers:
for name in sorted(servers):
entry = servers[name]
- label = f"MCP: {name}"
def _probe(n=name, e=entry) -> ProbeResult:
if not isinstance(e, dict):
- return ProbeResult(f"MCP: {n}", "skip",
- "(malformed config entry)")
- tools = _probe_mcp_server(n, e, timeout)
- return ProbeResult(f"MCP: {n}", "pass",
- f"({len(tools)} tool(s))")
+ return ProbeResult(f"MCP: {n}", "skip", "(malformed config entry)")
+ return ProbeResult(f"MCP: {n}", "pass", f"({len(_probe_mcp_server(n, e, timeout))} tool(s))")
- results.append(_run_one(label, _probe, issues))
+ results.append(_run_one(f"MCP: {name}", _probe, issues))
else:
results.append(ProbeResult("MCP", "skip", "(no servers configured)"))
_report(results[-1], issues)
for kind in ("tts", "stt"):
- results.append(_run_one(
- kind.upper(), lambda k=kind: _probe_audio(k, config, timeout), issues))
+ results.append(_run_one(kind.upper(), lambda k=kind: _probe_audio(k, config, timeout), issues))
return results
diff --git a/hermes_cli/doctor_platform.py b/hermes_cli/doctor_platform.py
index 71894ddd191..085ea23cc03 100644
--- a/hermes_cli/doctor_platform.py
+++ b/hermes_cli/doctor_platform.py
@@ -12,7 +12,9 @@ import sys
from pathlib import Path
from hermes_cli.colors import Colors, color
from hermes_cli.config import is_nix_install_method, recommended_update_command_for_method
-from hermes_cli.doctor_report import Finding, _fail_and_issue, _section, check_fail, check_info, check_ok, check_warn
+from hermes_cli.doctor_report import (
+ Finding, _fail_and_issue, _section, check_bool, check_fail, check_info, check_ok, check_warn, doctor_check,
+)
from hermes_constants import is_termux as _is_termux
@@ -23,9 +25,7 @@ def _python_install_cmd() -> str:
def _system_package_install_cmd(pkg: str) -> str:
if _is_termux():
return f"pkg install {pkg}"
- if sys.platform == "darwin":
- return f"brew install {pkg}"
- return f"sudo apt install {pkg}"
+ return f"brew install {pkg}" if sys.platform == "darwin" else f"sudo apt install {pkg}"
def _sqlite_upgrade_hint(install_method: str | None = None) -> str:
@@ -40,10 +40,7 @@ def _sqlite_upgrade_hint(install_method: str | None = None) -> str:
action = f"run `{recommended_update_command_for_method(method)}`"
else:
action = "run `hermes update`"
- return (
- f"({action}; fixed versions: 3.51.3+ / 3.50.7 / 3.44.6 — "
- "see https://sqlite.org/wal.html#walresetbug)"
- )
+ return f"({action}; fixed versions: 3.51.3+ / 3.50.7 / 3.44.6 — see https://sqlite.org/wal.html#walresetbug)"
def _hermes_database_paths(hermes_home: Path) -> list[tuple[str, Path]]:
@@ -62,18 +59,15 @@ _SQLITE_HEADER_MAGIC = b"SQLite format 3\x00"
def _unreadable_reason(db_path: Path) -> str:
"""Explain why a database file could not be read, without opening it.
- ``read_header_bytes_preopen`` collapses every ``OSError`` into ``None``, but
- doctor must say *which* problem it hit. ``stat()`` and ``access()`` answer
- that from directory metadata alone — neither takes a file descriptor, so
- neither can cancel the file's POSIX advisory locks.
+ ``read_header_bytes_preopen`` collapses every ``OSError`` into ``None``, but doctor must say *which*
+ problem it hit. ``stat()`` and ``access()`` answer that from directory metadata alone — neither takes
+ a file descriptor, so neither can cancel the file's POSIX advisory locks.
"""
try:
db_path.stat()
except OSError as exc:
return str(exc)
- if not os.access(db_path, os.R_OK):
- return f"permission denied: {db_path}"
- return "file could not be read"
+ return "file could not be read" if os.access(db_path, os.R_OK) else f"permission denied: {db_path}"
def _read_journal_mode(db_path: Path) -> tuple[str | None, str | None]:
@@ -89,17 +83,13 @@ def _read_journal_mode(db_path: Path) -> tuple[str | None, str | None]:
header = read_header_bytes_preopen(db_path, length=20)
if header is None:
- if has_live_connection(db_path):
- return None, "database is open in this process"
- return None, _unreadable_reason(db_path)
+ return None, "database is open in this process" if has_live_connection(db_path) else _unreadable_reason(db_path)
if len(header) == 0:
return None, "file is empty"
if len(header) < 20 or not header.startswith(_SQLITE_HEADER_MAGIC):
return None, "file is not a database"
mode = {2: "wal", 1: "rollback"}.get(header[18])
- if mode:
- return mode, None
- return None, f"unrecognized file-format version {header[18]}"
+ return (mode, None) if mode else (None, f"unrecognized file-format version {header[18]}")
def _format_db_size(db_path: Path) -> str:
@@ -111,18 +101,14 @@ def _format_db_size(db_path: Path) -> str:
return "size unknown"
-def _report_database_journal_modes(
- hermes_home: Path | None = None,
- version_info: tuple[int, ...] | None = None,
-) -> None:
+def _report_database_journal_modes(hermes_home: Path | None = None, version_info: tuple[int, ...] | None = None) -> None:
"""List each database's journal mode; warn on WAL under a vulnerable SQLite."""
from hermes_cli.doctor import HERMES_HOME
from hermes_state import _wal_reset_repair_hint, is_sqlite_wal_reset_vulnerable
vulnerable = is_sqlite_wal_reset_vulnerable(version_info)
- home = hermes_home if hermes_home is not None else HERMES_HOME
try:
- databases = _hermes_database_paths(home)
+ databases = _hermes_database_paths(hermes_home if hermes_home is not None else HERMES_HOME)
except Exception as exc:
check_warn(f"Could not list Hermes databases: {exc}")
return
@@ -143,10 +129,8 @@ def _report_database_journal_modes(
check_warn(f"{name} is in WAL mode ({size})", "(exposed to the WAL-reset bug until SQLite is upgraded)")
else:
check_info(f"{name}: WAL journal mode ({size})")
- elif vulnerable:
- check_info(f"{name}: rollback journal mode ({size}, not exposed)")
else:
- check_info(f"{name}: rollback journal mode ({size})")
+ check_info(f"{name}: rollback journal mode ({size}, not exposed)" if vulnerable else f"{name}: rollback journal mode ({size})")
if exposed:
check_info(f"To clear the exposure: {_wal_reset_repair_hint()}")
@@ -165,8 +149,7 @@ def _read_pyproject_version() -> str | None:
in_project = line == "[project]"
continue
if in_project and line.startswith("version") and "=" in line:
- value = line.split("=", 1)[1].split("#", 1)[0].strip().strip("\"'")
- return value or None
+ return line.split("=", 1)[1].split("#", 1)[0].strip().strip("\"'") or None
return None
@@ -219,10 +202,8 @@ def _check_s6_supervision(issues: list[str]) -> None:
check_info("No per-profile gateways registered yet — create one with `hermes profile create <name>`")
return
up_count = sum(1 for p in profiles if mgr.is_running(f"gateway-{p}"))
- check_ok(
- f"Per-profile gateways: {up_count}/{len(profiles)} supervised up"
- + (f" ({', '.join(sorted(profiles))})" if len(profiles) <= 8 else "")
- )
+ check_ok(f"Per-profile gateways: {up_count}/{len(profiles)} supervised up"
+ + (f" ({', '.join(sorted(profiles))})" if len(profiles) <= 8 else ""))
def check_certificates(should_fix: bool = False, issues: "list | None" = None) -> None:
@@ -260,10 +241,8 @@ def check_certificates(should_fix: bool = False, issues: "list | None" = None) -
print(" → Repairing: force-reinstalling certifi...")
try:
- result = subprocess.run(
- [sys.executable, "-m", "pip", "install", "--force-reinstall", "certifi"],
- capture_output=True, text=True, timeout=300,
- )
+ result = subprocess.run([sys.executable, "-m", "pip", "install", "--force-reinstall", "certifi"],
+ capture_output=True, text=True, timeout=300)
except Exception as exc:
check_fail("certifi repair could not run pip", str(exc))
add_issue(f"Reinstall certifi manually: {pip_cmd}")
@@ -369,9 +348,7 @@ def _desktop_app_bundle() -> Path | None:
"""
release_dir = Path(__file__).resolve().parents[1] / "apps" / "desktop" / "release"
candidates = [p for p in release_dir.glob("mac*/Hermes.app") if p.is_dir()]
- if not candidates:
- return None
- return max(candidates, key=lambda p: p.stat().st_mtime)
+ return max(candidates, key=lambda p: p.stat().st_mtime) if candidates else None
def _macos_desktop_dr(app: Path) -> str | None:
@@ -383,9 +360,7 @@ def _macos_desktop_dr(app: Path) -> str | None:
proc = subprocess.run([codesign, "-d", "--requirements", "-", str(app)], capture_output=True, text=True, timeout=15)
except (FileNotFoundError, subprocess.TimeoutExpired):
return None
- if proc.returncode != 0:
- return None
- return (proc.stdout or "") + (proc.stderr or "")
+ return None if proc.returncode != 0 else (proc.stdout or "") + (proc.stderr or "")
def check_macos_tcc_anchor(should_fix: bool = False) -> None:
@@ -442,34 +417,30 @@ def check_macos_full_disk_access() -> None:
check_ok("macOS Full Disk Access granted", "(no per-folder permission prompts will occur)")
-def _check_security_advisories(should_fix: bool) -> Finding:
+@doctor_check("Security advisory check failed: {e}")
+def _check_security_advisories(should_fix: bool, f: Finding) -> None:
"""Compromised-package advisories, funnelled into manual issues; a bug here must never block the rest of doctor."""
- f = Finding()
- try:
- from hermes_cli.security_advisories import detect_compromised, filter_unacked, full_remediation_text, get_acked_ids
- all_hits = detect_compromised()
- fresh_hits = filter_unacked(all_hits)
- if not fresh_hits:
- check_ok("No active security advisories")
- return f
- for hit in fresh_hits:
- check_fail(f"{hit.advisory.title}", f"({hit.package}=={hit.installed_version})")
- for line in full_remediation_text(hit): # indented under the header as one section
- print(f" {color(line, Colors.YELLOW)}" if line else "")
- # Also into the action list so the summary block surfaces it.
- f.manual_issues.append(
- f"Resolve security advisory {hit.advisory.id}: "
- f"uninstall {hit.package}=={hit.installed_version} and "
- f"rotate credentials, then run "
- f"`hermes doctor --ack {hit.advisory.id}`."
- )
- acked_ids = get_acked_ids() # acked-but-still-installed stays visible
- for h in all_hits:
- if h.advisory.id in acked_ids:
- check_warn(f"{h.package}=={h.installed_version} still installed (advisory {h.advisory.id} acknowledged)")
- except Exception as e:
- check_warn(f"Security advisory check failed: {e}")
- return f
+ from hermes_cli.security_advisories import detect_compromised, filter_unacked, full_remediation_text, get_acked_ids
+ all_hits = detect_compromised()
+ fresh_hits = filter_unacked(all_hits)
+ if not fresh_hits:
+ check_ok("No active security advisories")
+ return
+ for hit in fresh_hits:
+ check_fail(f"{hit.advisory.title}", f"({hit.package}=={hit.installed_version})")
+ for line in full_remediation_text(hit): # indented under the header as one section
+ print(f" {color(line, Colors.YELLOW)}" if line else "")
+ # Also into the action list so the summary block surfaces it.
+ f.manual_issues.append(
+ f"Resolve security advisory {hit.advisory.id}: "
+ f"uninstall {hit.package}=={hit.installed_version} and "
+ f"rotate credentials, then run "
+ f"`hermes doctor --ack {hit.advisory.id}`."
+ )
+ acked_ids = get_acked_ids() # acked-but-still-installed stays visible
+ for h in all_hits:
+ if h.advisory.id in acked_ids:
+ check_warn(f"{h.package}=={h.installed_version} still installed (advisory {h.advisory.id} acknowledged)")
def _check_python_environment(should_fix: bool) -> Finding:
@@ -506,11 +477,7 @@ def _check_python_environment(should_fix: bool) -> Finding:
except Exception as e:
check_warn(f"SQLite version probe failed: {e}")
- if sys.prefix != sys.base_prefix:
- check_ok("Virtual environment active")
- else:
- check_warn("Not in virtual environment", "(recommended)")
-
+ check_bool(sys.prefix != sys.base_prefix, "Virtual environment active", ("Not in virtual environment", "(recommended)"))
check_macos_tcc_anchor(should_fix=should_fix)
check_macos_full_disk_access()
_check_version_consistency(f.issues)
diff --git a/hermes_cli/doctor_report.py b/hermes_cli/doctor_report.py
index 6c4cdaa41ae..93e08175d38 100644
--- a/hermes_cli/doctor_report.py
+++ b/hermes_cli/doctor_report.py
@@ -2,27 +2,38 @@
from __future__ import annotations
+import functools
from dataclasses import dataclass, field
from hermes_cli.colors import Colors, color
-def check_ok(text: str, detail: str = ""):
- print(f" {color('✓', Colors.GREEN)} {text}" + (f" {color(detail, Colors.DIM)}" if detail else ""))
+def _mark(glyph: str, col: str):
+ def check(text: str, detail: str = ""):
+ print(f" {color(glyph, col)} {text}" + (f" {color(detail, Colors.DIM)}" if detail else ""))
+ return check
-def check_warn(text: str, detail: str = ""):
- print(f" {color('⚠', Colors.YELLOW)} {text}" + (f" {color(detail, Colors.DIM)}" if detail else ""))
-
-
-def check_fail(text: str, detail: str = ""):
- print(f" {color('✗', Colors.RED)} {text}" + (f" {color(detail, Colors.DIM)}" if detail else ""))
+check_ok, check_warn, check_fail = _mark("✓", Colors.GREEN), _mark("⚠", Colors.YELLOW), _mark("✗", Colors.RED)
+CHECK_ROW = {"ok": check_ok, "warn": check_warn, "fail": check_fail}
def check_info(text: str):
print(f" {color('→', Colors.CYAN)} {text}")
+def check_bool(cond, ok, bad, *, fail: bool = False):
+ """``check_ok(*ok)`` when *cond* else ``check_warn(*bad)`` (``check_fail`` with fail=True); returns bool(cond).
+
+ *ok* / *bad* are a text string or a ``(text, detail)`` tuple.
+ """
+ args = ok if cond else bad
+ if isinstance(args, str):
+ args = (args,)
+ (check_ok if cond else (check_fail if fail else check_warn))(*args)
+ return bool(cond)
+
+
def _section(title: str) -> None:
"""Print a doctor section banner: blank line + bold cyan ◆ title."""
print()
@@ -47,3 +58,36 @@ class Finding:
self.issues.extend(other.issues)
self.manual_issues.extend(other.manual_issues)
self.fixed += other.fixed
+
+
+def doctor_check(on_error: str | None = None, detail: str = ""):
+ """Turn ``fn(should_fix, f: Finding)`` into a ``(should_fix) -> Finding`` doctor check.
+
+ Creates the Finding, and if *fn* raises prints ``check_warn(on_error.format(e=e), detail.format(e=e))``
+ (nothing when *on_error* is None) — the partial Finding is still returned, so issues recorded
+ before the crash survive.
+ """
+ def deco(fn):
+ @functools.wraps(fn)
+ def check(should_fix: bool) -> Finding:
+ f = Finding()
+ try:
+ fn(should_fix, f)
+ except Exception as e:
+ if on_error is not None:
+ check_warn(on_error.format(e=e), detail.format(e=e))
+ return f
+ return check
+ return deco
+
+
+def ensure_dir(f: Finding, should_fix: bool, path, exists_msg: str, created_msg: str, missing_msg: str) -> None:
+ """ok when *path* exists; with --fix create it (counts as fixed); else warn "(will be created on first use)"."""
+ if path.exists():
+ check_ok(exists_msg)
+ elif should_fix:
+ path.mkdir(parents=True, exist_ok=True)
+ check_ok(created_msg)
+ f.fixed += 1
+ else:
+ check_warn(missing_msg, "(will be created on first use)")
diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py
index aecad03ef5f..c79f3aa6ac4 100644
--- a/hermes_cli/doctor_state.py
+++ b/hermes_cli/doctor_state.py
@@ -9,12 +9,7 @@ from __future__ import annotations
import subprocess
from pathlib import Path
from hermes_cli.doctor_report import (
- Finding,
- _fail_and_issue,
- _section,
- check_info,
- check_ok,
- check_warn,
+ Finding, _fail_and_issue, _section, check_info, check_ok, check_warn, doctor_check, ensure_dir,
)
from hermes_cli.sizefmt import format_bytes as _human_bytes
@@ -53,17 +48,15 @@ def _doctor_memory_config(hermes_home: Path | None = None) -> dict:
return {}
-# ── state.db health/stats thresholds (advisory only — module constants,
-# deliberately NOT config: doctor warnings are guidance, not policy) ──
+# state.db size threshold (advisory only — deliberately a module constant, not config:
+# doctor warnings are guidance, not policy).
STATE_DB_SIZE_WARN_BYTES = 1 * 1024 * 1024 * 1024 # 1 GiB logical size
def _render_state_db_stats(stats: dict, holders=None) -> list:
- """Turn a collect_state_db_stats() dict into doctor output lines.
+ """Turn a collect_state_db_stats() dict into ``(kind, text, detail)`` rows, kind 'info' / 'warn'.
- Returns a list of ``(kind, text, detail)`` tuples where kind is one of
- 'info' / 'warn'. Pure formatting — no I/O — so it is unit-testable
- without spawning the doctor CLI. Tolerates None in every field.
+ Pure formatting — no I/O — so it is unit-testable without the doctor CLI. Tolerates None in every field.
"""
lines: list = []
stats = stats or {}
@@ -99,11 +92,7 @@ def _render_state_db_stats(stats: dict, holders=None) -> list:
fts = stats.get("fts_tables")
if fts:
present = [t for t, ok in fts.items() if ok]
- lines.append((
- "info",
- "FTS tables: " + (", ".join(present) if present else "none"),
- "",
- ))
+ lines.append(("info", "FTS tables: " + (", ".join(present) if present else "none"), ""))
deferral = stats.get("fts_rebuild_deferral")
if isinstance(deferral, dict):
@@ -111,42 +100,22 @@ def _render_state_db_stats(stats: dict, holders=None) -> list:
pids = deferral.get("holder_pids") or []
lines.append((
"warn",
- f"state.db FTS repair is blocked after {attempts or '?'} "
- f"deferral(s) by PID(s) {pids or 'unknown'}",
- "(stop the listed processes, then run 'hermes sessions "
- "optimize-storage' with the gateway stopped)",
+ f"state.db FTS repair is blocked after {attempts or '?'} deferral(s) by PID(s) {pids or 'unknown'}",
+ "(stop the listed processes, then run 'hermes sessions optimize-storage' with the gateway stopped)",
))
- # Advisory: oversized database. Suggest auto_prune, and — when the v23
- # FTS rebuild is pending OR the DB still carries the legacy inline
- # trigram layout (fts_storage_version marker absent) — the offline
- # optimize-storage pass that migrates/compacts the FTS indexes.
+ # Advisory: oversized database. Suggest auto_prune, and — when the v23 FTS rebuild is pending OR
+ # the DB still carries the legacy inline trigram layout (fts_storage_version marker absent) —
+ # the offline optimize-storage pass that migrates/compacts the FTS indexes.
if logical is not None and logical > STATE_DB_SIZE_WARN_BYTES:
- detail = (
- "consider enabling sessions.auto_prune in config.yaml "
- "to bound growth"
- )
- legacy_trigram = (
- fts is not None
- and fts.get("messages_fts_trigram")
- and stats.get("fts_storage_version") is None
- )
+ detail = "consider enabling sessions.auto_prune in config.yaml to bound growth"
+ legacy_trigram = fts is not None and fts.get("messages_fts_trigram") and stats.get("fts_storage_version") is None
if stats.get("fts_rebuild_pending") or legacy_trigram:
- detail += (
- "; run 'hermes sessions optimize-storage' offline "
- "(with the gateway stopped) to compact FTS storage"
- )
- lines.append((
- "warn",
- f"state.db is large ({_human_bytes(logical)})",
- f"({detail})",
- ))
-
- # WAL runaway is deliberately NOT warned here: the pre-existing WAL
- # check later in the state.db section already warns above 50 MB and
- # offers a checkpoint via --fix; a second warning at a higher threshold
- # would only duplicate it.
+ detail += "; run 'hermes sessions optimize-storage' offline (with the gateway stopped) to compact FTS storage"
+ lines.append(("warn", f"state.db is large ({_human_bytes(logical)})", f"({detail})"))
+ # WAL runaway is deliberately NOT warned here: the WAL check later in the state.db section already
+ # warns above 50 MB and offers a checkpoint via --fix; a second warning would only duplicate it.
return lines
@@ -161,39 +130,22 @@ def _check_directory_structure(should_fix: bool) -> Finding:
from hermes_cli.doctor import HERMES_HOME, _DHH
f = Finding()
hermes_home = HERMES_HOME
- if hermes_home.exists():
- check_ok(f"{_DHH} directory exists")
- elif should_fix:
- hermes_home.mkdir(parents=True, exist_ok=True)
- check_ok(f"Created {_DHH} directory")
- f.fixed += 1
- else:
- check_warn(f"{_DHH} not found", "(will be created on first use)")
+ ensure_dir(f, should_fix, hermes_home, f"{_DHH} directory exists", f"Created {_DHH} directory", f"{_DHH} not found")
_memory_enabled, _user_profile_enabled = _memory_store_flags(hermes_home)
+ memory_on = _memory_enabled or _user_profile_enabled
- # Check expected subdirectories. The built-in file store does not create or
- # consume memories/ when both targets are disabled, so stale migration files
- # are not an active diagnostic surface.
- expected_subdirs = ["cron", "sessions", "logs", "skills"]
- if _memory_enabled or _user_profile_enabled:
- expected_subdirs.append("memories")
- for subdir_name in expected_subdirs:
- subdir_path = hermes_home / subdir_name
- if subdir_path.exists():
- check_ok(f"{_DHH}/{subdir_name}/ exists")
- elif should_fix:
- subdir_path.mkdir(parents=True, exist_ok=True)
- check_ok(f"Created {_DHH}/{subdir_name}/")
- f.fixed += 1
- else:
- check_warn(f"{_DHH}/{subdir_name}/ not found", "(will be created on first use)")
+ # Expected subdirectories. The built-in file store does not create or consume memories/ when
+ # both targets are disabled, so stale migration files are not an active diagnostic surface.
+ for subdir_name in ["cron", "sessions", "logs", "skills"] + (["memories"] if memory_on else []):
+ ensure_dir(f, should_fix, hermes_home / subdir_name, f"{_DHH}/{subdir_name}/ exists",
+ f"Created {_DHH}/{subdir_name}/", f"{_DHH}/{subdir_name}/ not found")
- # Check for SOUL.md persona file
+ # SOUL.md persona file
soul_path = hermes_home / "SOUL.md"
if soul_path.exists():
content = soul_path.read_text(encoding="utf-8").strip()
- # Check if it's just the template comments (no real content)
+ # Template comments only (no real content)?
lines = [l for l in content.splitlines() if l.strip() and not l.strip().startswith(("<!--", "-->", "#"))]
if lines:
check_ok(f"{_DHH}/SOUL.md exists (persona configured)")
@@ -212,18 +164,17 @@ def _check_directory_structure(should_fix: bool) -> Finding:
check_ok(f"Created {_DHH}/SOUL.md with basic template")
f.fixed += 1
- # Check only enabled built-in stores. External providers are additive, but
- # users can explicitly disable either legacy file target; stale files left
- # by a migration must not be presented as active memory usage.
+ # Check only enabled built-in stores. External providers are additive, but users can explicitly
+ # disable either legacy file target; stale migration files must not read as active memory usage.
memories_dir = hermes_home / "memories"
- if not (_memory_enabled or _user_profile_enabled):
+ if not memory_on:
check_info("Built-in memory files disabled by config")
elif memories_dir.exists():
check_ok(f"{_DHH}/memories/ directory exists")
for enabled, fname in ((_memory_enabled, "MEMORY.md"), (_user_profile_enabled, "USER.md")):
+ mem_file = memories_dir / fname
if not enabled:
continue
- mem_file = memories_dir / fname
if mem_file.exists():
check_ok(f"{fname} exists ({len(mem_file.read_text(encoding='utf-8').strip())} chars)")
else:
@@ -272,112 +223,104 @@ def _repair_state_db(f: Finding, should_fix: bool, state_db_path: Path, *,
f.fixed += 1
+def _state_db_health(f: Finding, should_fix: bool, state_db_path: Path, _DHH: str) -> None:
+ """Session count + FTS write-health probe; malformed-schema path when even COUNT(*) fails."""
+ try:
+ check_ok(f"{_DHH}/state.db exists ({_session_count(state_db_path)} sessions)")
+ # `SELECT COUNT(*)` succeeds even when the FTS index is corrupt and every message write
+ # fails through the triggers; _db_opens_cleanly drives a rolled-back write to surface that.
+ from hermes_state import _db_opens_cleanly
+
+ _write_reason = _db_opens_cleanly(state_db_path)
+ if _write_reason is not None:
+ check_warn(f"{_DHH}/state.db fails a write-health probe (FTS index may be corrupt)", f"({_write_reason})")
+ _repair_state_db(
+ f, should_fix, state_db_path,
+ ok_label="Repaired state.db FTS write health",
+ not_fixed_label="state.db FTS write-health repair did not recover automatically",
+ failed_issue="state.db FTS write corruption and auto-repair failed — "
+ "restore from the backup copy beside state.db",
+ fix_hint="state.db FTS write corruption — run 'hermes doctor --fix' "
+ "(or 'hermes sessions repair') to rebuild the FTS index",
+ )
+ except Exception as e:
+ from hermes_state import is_malformed_db_error
+
+ if not is_malformed_db_error(e):
+ check_warn(f"{_DHH}/state.db exists but has issues: {e}")
+ return
+ # sqlite_master itself is malformed (e.g. duplicate messages_fts): every statement fails
+ # before it runs, so this is NOT a plain FTS rebuild — repair sqlite_master in place (backup first).
+ check_warn(f"{_DHH}/state.db schema is malformed (sessions hidden until repaired)", f"({e})")
+ _repair_state_db(
+ f, should_fix, state_db_path,
+ ok_label=lambda count: f"Repaired state.db schema ({count} sessions recovered)",
+ not_fixed_label="state.db schema repair did not recover automatically",
+ failed_issue="state.db schema malformed and auto-repair failed — "
+ "restore from the backup copy beside state.db",
+ fix_hint="state.db schema malformed — run 'hermes doctor --fix' "
+ "(or 'hermes sessions repair') to recover hidden sessions",
+ )
+
+
+def _state_db_stats(issues: list, state_db_path: Path) -> None:
+ """Health/stats snapshot: strictly read-only (mode=ro) so it is safe against a live DB held by
+ the gateway; any failure degrades to one info line rather than failing doctor."""
+ try:
+ from hermes_state import collect_state_db_stats, count_db_holders
+
+ rows = _render_state_db_stats(collect_state_db_stats(state_db_path), holders=count_db_holders(state_db_path))
+ for _kind, _text, _detail in rows:
+ if _kind != "warn":
+ check_info(_text + (f" {_detail}" if _detail else ""))
+ continue
+ check_warn(_text, _detail)
+ if "auto_prune" in _detail:
+ issues.append(
+ "state.db is large — enable sessions.auto_prune in config.yaml"
+ + (" and run 'hermes sessions optimize-storage' offline (gateway stopped)"
+ if "optimize-storage" in _detail else "")
+ )
+ except Exception as _stats_exc:
+ check_info(f"state.db stats unavailable ({_stats_exc})")
+
+
+def _state_db_wal(f: Finding, should_fix: bool, state_db_path: Path) -> None:
+ """WAL file size (unbounded growth indicates missed checkpoints)."""
+ wal_path = state_db_path.parent / "state.db-wal"
+ if not wal_path.exists():
+ return
+ try:
+ wal_size = wal_path.stat().st_size
+ if wal_size > 50 * 1024 * 1024: # 50 MB
+ check_warn(f"WAL file is large ({wal_size // (1024*1024)} MB)", "(may indicate missed checkpoints)")
+ if should_fix:
+ import sqlite3
+ conn = sqlite3.connect(str(state_db_path))
+ conn.execute("PRAGMA wal_checkpoint(PASSIVE)")
+ conn.close()
+ new_size = wal_path.stat().st_size if wal_path.exists() else 0
+ check_ok(f"WAL checkpoint performed ({wal_size // 1024}K → {new_size // 1024}K)")
+ f.fixed += 1
+ else:
+ f.issues.append("Large WAL file — run 'hermes doctor --fix' to checkpoint")
+ elif wal_size > 10 * 1024 * 1024: # 10 MB
+ check_info(f"WAL file is {wal_size // (1024*1024)} MB (normal for active sessions)")
+ except Exception:
+ pass
+
+
def _check_state_db(should_fix: bool) -> Finding:
"""state.db session count, FTS write health, schema repair, stats snapshot, WAL size."""
from hermes_cli.doctor import HERMES_HOME, _DHH
f = Finding()
- issues = f.issues
- hermes_home = HERMES_HOME
- state_db_path = hermes_home / "state.db"
+ state_db_path = HERMES_HOME / "state.db"
if state_db_path.exists():
- try:
- check_ok(f"{_DHH}/state.db exists ({_session_count(state_db_path)} sessions)")
- # `SELECT COUNT(*)` succeeds even when the FTS index is corrupt and
- # every message write fails through the triggers; _db_opens_cleanly
- # drives a rolled-back write to surface that silent class.
- from hermes_state import _db_opens_cleanly
-
- _write_reason = _db_opens_cleanly(state_db_path)
- if _write_reason is not None:
- check_warn(
- f"{_DHH}/state.db fails a write-health probe (FTS index may be corrupt)",
- f"({_write_reason})",
- )
- _repair_state_db(
- f, should_fix, state_db_path,
- ok_label="Repaired state.db FTS write health",
- not_fixed_label="state.db FTS write-health repair did not recover automatically",
- failed_issue="state.db FTS write corruption and auto-repair failed — "
- "restore from the backup copy beside state.db",
- fix_hint="state.db FTS write corruption — run 'hermes doctor --fix' "
- "(or 'hermes sessions repair') to rebuild the FTS index",
- )
- except Exception as e:
- from hermes_state import is_malformed_db_error
-
- if is_malformed_db_error(e):
- # sqlite_master itself is malformed (e.g. duplicate messages_fts):
- # every statement fails before it runs, so this is NOT a plain FTS
- # rebuild — repair sqlite_master in place (backup first).
- check_warn(f"{_DHH}/state.db schema is malformed (sessions hidden until repaired)", f"({e})")
- _repair_state_db(
- f, should_fix, state_db_path,
- ok_label=lambda count: f"Repaired state.db schema ({count} sessions recovered)",
- not_fixed_label="state.db schema repair did not recover automatically",
- failed_issue="state.db schema malformed and auto-repair failed — "
- "restore from the backup copy beside state.db",
- fix_hint="state.db schema malformed — run 'hermes doctor --fix' "
- "(or 'hermes sessions repair') to recover hidden sessions",
- )
- else:
- check_warn(f"{_DHH}/state.db exists but has issues: {e}")
-
- # Health/stats snapshot (#statedb-visibility): a multi-GB state.db
- # with a runaway WAL was previously invisible to every Hermes
- # surface. Strictly read-only (mode=ro) so it is safe against a
- # live DB held by the gateway; any failure degrades to one info
- # line rather than failing doctor.
- try:
- from hermes_state import collect_state_db_stats, count_db_holders
-
- _db_stats = collect_state_db_stats(state_db_path)
- _db_holders = count_db_holders(state_db_path)
- for _kind, _text, _detail in _render_state_db_stats(
- _db_stats, holders=_db_holders
- ):
- if _kind == "warn":
- check_warn(_text, _detail)
- if "auto_prune" in _detail:
- issues.append(
- "state.db is large — enable sessions.auto_prune "
- "in config.yaml"
- + (
- " and run 'hermes sessions optimize-storage' "
- "offline (gateway stopped)"
- if "optimize-storage" in _detail else ""
- )
- )
- else:
- check_info(_text + (f" {_detail}" if _detail else ""))
- except Exception as _stats_exc:
- check_info(f"state.db stats unavailable ({_stats_exc})")
+ _state_db_health(f, should_fix, state_db_path, _DHH)
+ _state_db_stats(f.issues, state_db_path)
else:
check_info(f"{_DHH}/state.db not created yet (will be created on first session)")
-
- # Check WAL file size (unbounded growth indicates missed checkpoints)
- wal_path = hermes_home / "state.db-wal"
- if wal_path.exists():
- try:
- wal_size = wal_path.stat().st_size
- if wal_size > 50 * 1024 * 1024: # 50 MB
- check_warn(
- f"WAL file is large ({wal_size // (1024*1024)} MB)",
- "(may indicate missed checkpoints)"
- )
- if should_fix:
- import sqlite3
- conn = sqlite3.connect(str(state_db_path))
- conn.execute("PRAGMA wal_checkpoint(PASSIVE)")
- conn.close()
- new_size = wal_path.stat().st_size if wal_path.exists() else 0
- check_ok(f"WAL checkpoint performed ({wal_size // 1024}K → {new_size // 1024}K)")
- f.fixed += 1
- else:
- issues.append("Large WAL file — run 'hermes doctor --fix' to checkpoint")
- elif wal_size > 10 * 1024 * 1024: # 10 MB
- check_info(f"WAL file is {wal_size // (1024*1024)} MB (normal for active sessions)")
- except Exception:
- pass
+ _state_db_wal(f, should_fix, state_db_path)
return f
@@ -400,8 +343,7 @@ def _check_skills_hub(should_fix: bool) -> Finding:
if lock_file.exists():
try:
import json
- lock_data = json.loads(lock_file.read_text(encoding="utf-8"))
- count = len(lock_data.get("installed", {}))
+ count = len(json.loads(lock_file.read_text(encoding="utf-8")).get("installed", {}))
check_ok(f"Lock file OK ({count} hub-installed skill(s))")
except Exception:
check_warn("Lock file", "(corrupted or unreadable)")
@@ -501,46 +443,39 @@ def _check_memory_provider(should_fix: bool) -> Finding:
return f
-def _check_profiles(should_fix: bool) -> Finding:
- f = Finding()
- try:
- from hermes_cli.profiles import list_profiles, _get_wrapper_dir, profile_exists
- import re as _re
-
- named_profiles = [p for p in list_profiles() if not p.is_default]
- if named_profiles:
- _section("Profiles")
- check_ok(f"{len(named_profiles)} profile(s) found")
- wrapper_dir = _get_wrapper_dir()
- for p in named_profiles:
- parts = []
- if p.gateway_running:
- parts.append("gateway running")
- if p.model:
- parts.append(p.model[:30])
- if not (p.path / "config.yaml").exists():
- parts.append("⚠ missing config")
- if not (p.path / ".env").exists():
- parts.append("no .env")
- wrapper = wrapper_dir / p.name
- if not wrapper.exists():
- parts.append("no alias")
- status = ", ".join(parts) if parts else "configured"
- check_ok(f" {p.name}: {status}")
-
- # Check for orphan wrappers
- if wrapper_dir.is_dir():
- for wrapper in wrapper_dir.iterdir():
- if not wrapper.is_file():
- continue
- try:
- content = wrapper.read_text(encoding="utf-8")
- if "hermes -p" in content:
- _m = _re.search(r"hermes -p (\S+)", content)
- if _m and not profile_exists(_m.group(1)):
- check_warn(f"Orphan alias: {wrapper.name} → profile '{_m.group(1)}' no longer exists")
- except Exception:
- pass
- except Exception:
- pass
- return f
+@doctor_check()
+def _check_profiles(should_fix: bool, f: Finding) -> None:
+ from hermes_cli.profiles import list_profiles, _get_wrapper_dir, profile_exists
+ import re as _re
+
+ named_profiles = [p for p in list_profiles() if not p.is_default]
+ if not named_profiles:
+ return
+ _section("Profiles")
+ check_ok(f"{len(named_profiles)} profile(s) found")
+ wrapper_dir = _get_wrapper_dir()
+ for p in named_profiles:
+ parts = []
+ if p.gateway_running:
+ parts.append("gateway running")
+ if p.model:
+ parts.append(p.model[:30])
+ if not (p.path / "config.yaml").exists():
+ parts.append("⚠ missing config")
+ if not (p.path / ".env").exists():
+ parts.append("no .env")
+ if not (wrapper_dir / p.name).exists():
+ parts.append("no alias")
+ check_ok(f" {p.name}: {', '.join(parts) if parts else 'configured'}")
+
+ # Orphan wrappers
+ if wrapper_dir.is_dir():
+ for wrapper in wrapper_dir.iterdir():
+ if not wrapper.is_file():
+ continue
+ try:
+ _m = _re.search(r"hermes -p (\S+)", wrapper.read_text(encoding="utf-8"))
+ if _m and not profile_exists(_m.group(1)):
+ check_warn(f"Orphan alias: {wrapper.name} → profile '{_m.group(1)}' no longer exists")
+ except Exception:
+ pass
diff --git a/hermes_cli/doctor_tools.py b/hermes_cli/doctor_tools.py
index 87e0a2af1f0..14433a12896 100644
--- a/hermes_cli/doctor_tools.py
+++ b/hermes_cli/doctor_tools.py
@@ -11,7 +11,7 @@ import shutil
import subprocess
import sys
from hermes_cli.doctor_platform import _system_package_install_cmd
-from hermes_cli.doctor_report import Finding, _fail_and_issue, check_info, check_ok, check_warn
+from hermes_cli.doctor_report import CHECK_ROW, Finding, _fail_and_issue, check_bool, check_info, check_ok, check_warn, doctor_check
from hermes_cli.vercel_auth import describe_vercel_auth
from hermes_constants import agent_browser_runnable, is_termux as _is_termux
@@ -38,13 +38,12 @@ def _termux_browser_setup_steps(node_installed: bool) -> list[str]:
return steps + [f"{n}) npm install -g agent-browser", f"{n + 1}) agent-browser install"]
-def _termux_install_all_fallback_notes() -> list[str]:
- return [
- "Termux install profile: use .[termux-all] for broad compatibility (installer default on Termux).",
- "Matrix E2EE extra is excluded on Termux (python-olm currently fails to build).",
- "Local faster-whisper extra is excluded on Termux (ctranslate2/av build path unavailable).",
- "STT fallback: use Groq Whisper (set GROQ_API_KEY) or OpenAI Whisper (set VOICE_TOOLS_OPENAI_KEY).",
- ]
+_TERMUX_INSTALL_ALL_FALLBACK_NOTES = (
+ "Termux install profile: use .[termux-all] for broad compatibility (installer default on Termux).",
+ "Matrix E2EE extra is excluded on Termux (python-olm currently fails to build).",
+ "Local faster-whisper extra is excluded on Termux (ctranslate2/av build path unavailable).",
+ "STT fallback: use Groq Whisper (set GROQ_API_KEY) or OpenAI Whisper (set VOICE_TOOLS_OPENAI_KEY).",
+)
def _is_kanban_worker_env_gate(item: dict) -> bool:
@@ -136,14 +135,9 @@ def _missing_api_key_toolsets_for_summary(unavailable: list[dict]) -> list[dict]
def _check_git_and_rg(should_fix: bool) -> Finding:
f = Finding()
- if _safe_which("git"):
- check_ok("git")
- else:
- check_warn("git not found", "(optional)")
- if _safe_which("rg"):
- check_ok("ripgrep (rg)", "(faster file search)")
- else:
- check_warn("ripgrep (rg) not found", "(file search uses grep fallback)")
+ check_bool(_safe_which("git"), "git", ("git not found", "(optional)"))
+ if not check_bool(_safe_which("rg"), ("ripgrep (rg)", "(faster file search)"),
+ ("ripgrep (rg) not found", "(file search uses grep fallback)")):
check_info(f"Install for faster search: {_system_package_install_cmd('ripgrep')}")
return f
@@ -256,6 +250,9 @@ def _check_plugin_backend(terminal_env: str, issues: list[str]) -> None:
_fail_and_issue(label, detail, detail.strip("()"), issues)
+_BACKEND_CHECKS = {"ssh": _check_ssh_backend, "daytona": _check_daytona_backend, "vercel_sandbox": _check_vercel_backend}
+
+
def _check_terminal_backend(should_fix: bool) -> Finding:
"""Docker/SSH/Daytona/Vercel/plugin terminal backends, gated on TERMINAL_ENV."""
f = Finding()
@@ -273,12 +270,8 @@ def _check_terminal_backend(should_fix: bool) -> Finding:
check_info("Running inside a container — using local terminal backend (docker-in-docker is not configured by default)")
terminal_env = "local"
_check_docker_backend(terminal_env, running_in_container, f.issues)
- if terminal_env == "ssh":
- _check_ssh_backend(f.issues)
- elif terminal_env == "daytona":
- _check_daytona_backend(f.issues)
- elif terminal_env == "vercel_sandbox":
- _check_vercel_backend(f.issues)
+ if terminal_env in _BACKEND_CHECKS:
+ _BACKEND_CHECKS[terminal_env](f.issues)
elif terminal_env not in _BUILTIN_TERMINAL_BACKENDS:
_check_plugin_backend(terminal_env, f.issues)
return f
@@ -316,16 +309,24 @@ def _check_agent_browser(should_fix: bool) -> bool:
# postinstall after `hermes update` wiped node_modules.
check_warn("agent-browser found but not runnable", f"(broken symlink at {resolved}? run: npx agent-browser --version)")
elif _is_termux():
- check_info("agent-browser is not installed (expected in the tested Termux path)")
- check_info("Install it manually later with: npm install -g agent-browser && agent-browser install")
- check_info("Termux browser setup:")
- for step in _termux_browser_setup_steps(node_installed=True):
- check_info(step)
+ _termux_browser_hints(
+ "agent-browser is not installed (expected in the tested Termux path)",
+ "Install it manually later with: npm install -g agent-browser && agent-browser install",
+ node_installed=True,
+ )
else:
check_warn("agent-browser not installed", "(requires npm/npx on PATH)")
return False
+def _termux_browser_hints(*lines: str, node_installed: bool) -> None:
+ for line in lines:
+ check_info(line)
+ check_info("Termux browser setup:")
+ for step in _termux_browser_setup_steps(node_installed=node_installed):
+ check_info(step)
+
+
def _check_chromium() -> None:
"""Playwright Chromium presence, using the exact predicate browser_tool uses to hide browser_* tools.
@@ -381,11 +382,11 @@ def _check_node_and_browser(should_fix: bool) -> Finding:
if _check_agent_browser(should_fix) and not _is_termux(): # Chromium check is not a tested Termux path
_check_chromium()
elif _is_termux():
- check_info("Node.js not found (browser tools are optional in the tested Termux path)")
- check_info("Install Node.js on Termux with: pkg install nodejs")
- check_info("Termux browser setup:")
- for step in _termux_browser_setup_steps(node_installed=False):
- check_info(step)
+ _termux_browser_hints(
+ "Node.js not found (browser tools are optional in the tested Termux path)",
+ "Install Node.js on Termux with: pkg install nodejs",
+ node_installed=False,
+ )
else:
check_warn("Node.js not found", "(optional, needed for browser tools)")
_check_lightpanda()
@@ -464,43 +465,38 @@ def _check_npm_audit(should_fix: bool) -> Finding:
if _is_termux():
check_info("Termux compatibility fallbacks:")
- for note in _termux_install_all_fallback_notes():
+ for note in _TERMUX_INSTALL_ALL_FALLBACK_NOTES:
check_info(note)
return f
-def _check_tool_availability(should_fix: bool) -> Finding:
+@doctor_check("Could not check tool availability", "({e})")
+def _check_tool_availability(should_fix: bool, f: Finding) -> None:
from hermes_cli.doctor import PROJECT_ROOT, _doctor_web_capability_rows
- f = Finding()
- try:
- sys.path.insert(0, str(PROJECT_ROOT))
- from model_tools import check_tool_availability, TOOLSET_REQUIREMENTS
-
- available, unavailable = check_tool_availability()
- available, unavailable = _apply_doctor_tool_availability_overrides(available, unavailable)
-
- # Web is split into search/extract readiness rows so an explicitly
- # selected but unconfigured backend cannot look healthy.
- web_rows = []
- if "web" in available or any(item.get("name") == "web" for item in unavailable):
- web_rows = _doctor_web_capability_rows()
- if web_rows:
- available = [tid for tid in available if tid != "web"]
- unavailable = [item for item in unavailable if item.get("name") != "web"]
-
- for tid in available:
- check_ok(TOOLSET_REQUIREMENTS.get(tid, {}).get("name", tid), _doctor_tool_availability_detail(tid))
- for status, label, detail in web_rows:
- (check_ok if status == "ok" else check_warn)(label, detail)
- for item in unavailable:
- env_vars = item.get("missing_vars") or item.get("env_vars") or []
- check_warn(item["name"], f"(missing {', '.join(env_vars)})" if env_vars else "(system dependency not met)")
-
- # Only toolsets enabled for the CLI count toward the summary; default-off or
- # disabled toolsets may warn above but must not pollute it.
- api_disabled = _missing_api_key_toolsets_for_summary(unavailable)
- if api_disabled or any(status != "ok" for status, _, _ in web_rows):
- f.issues.append("Run 'hermes setup' to configure missing API keys for full tool access")
- except Exception as e:
- check_warn("Could not check tool availability", f"({e})")
- return f
+ sys.path.insert(0, str(PROJECT_ROOT))
+ from model_tools import check_tool_availability, TOOLSET_REQUIREMENTS
+
+ available, unavailable = _apply_doctor_tool_availability_overrides(*check_tool_availability())
+
+ # Web is split into search/extract readiness rows so an explicitly
+ # selected but unconfigured backend cannot look healthy.
+ web_rows = []
+ if "web" in available or any(item.get("name") == "web" for item in unavailable):
+ web_rows = _doctor_web_capability_rows()
+ if web_rows:
+ available = [tid for tid in available if tid != "web"]
+ unavailable = [item for item in unavailable if item.get("name") != "web"]
+
+ for tid in available:
+ check_ok(TOOLSET_REQUIREMENTS.get(tid, {}).get("name", tid), _doctor_tool_availability_detail(tid))
+ for status, label, detail in web_rows:
+ CHECK_ROW[status](label, detail)
+ for item in unavailable:
+ env_vars = item.get("missing_vars") or item.get("env_vars") or []
+ check_warn(item["name"], f"(missing {', '.join(env_vars)})" if env_vars else "(system dependency not met)")
+
+ # Only toolsets enabled for the CLI count toward the summary; default-off or
+ # disabled toolsets may warn above but must not pollute it.
+ api_disabled = _missing_api_key_toolsets_for_summary(unavailable)
+ if api_disabled or any(status != "ok" for status, _, _ in web_rows):
+ f.issues.append("Run 'hermes setup' to configure missing API keys for full tool access")
diff --git a/hermes_cli/dump.py b/hermes_cli/dump.py
index d636eeaddf8..d0ea246ddb7 100644
--- a/hermes_cli/dump.py
+++ b/hermes_cli/dump.py
@@ -16,14 +16,11 @@ from agent.skill_utils import is_excluded_skill_path
def _dotenv_key_names() -> set[str]:
"""Return the set of env-var names assigned a non-empty value in ~/.hermes/.env.
- The managed backends (launchd / systemd / the desktop-spawned ``serve`` process) load
- credentials from this file — NOT from an interactive shell's exports. ``hermes debug share``
- runs in a terminal, so ``os.getenv`` reflects the shell's environment, which can include
- exported keys the managed backend never sees.
+ The managed backends (launchd / systemd / the desktop-spawned ``serve`` process) load credentials
+ from this file — NOT from an interactive shell's exports, which ``os.getenv`` reflects here.
"""
try:
- env_path = get_env_path()
- text = env_path.read_text(encoding="utf-8", errors="ignore")
+ text = get_env_path().read_text(encoding="utf-8", errors="ignore")
except (OSError, UnicodeError):
return set()
@@ -45,11 +42,8 @@ def _dotenv_key_names() -> set[str]:
def _git_output(project_root: Path, *args: str) -> str:
"""Stripped stdout of ``git <args>`` run in *project_root*, or '' on any failure."""
try:
- result = subprocess.run(
- ["git", *args],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,
- cwd=str(project_root),
- )
+ result = subprocess.run(["git", *args], capture_output=True, text=True, encoding='utf-8', errors='replace',
+ timeout=5, cwd=str(project_root))
if result.returncode == 0:
return result.stdout.strip()
except Exception:
@@ -60,44 +54,26 @@ def _git_output(project_root: Path, *args: str) -> str:
def _get_git_commit(project_root: Path) -> str:
"""Return short git commit hash, or '(unknown)'.
- Source installs resolve live via ``git rev-parse``. The published Docker image excludes
- ``.git``, so fall back to the build SHA baked into ``<project_root>/.hermes_build_sha`` by the
- Dockerfile. Output format is identical either way.
+ Source installs resolve live via ``git rev-parse``. The published Docker image excludes ``.git``,
+ so fall back to the build SHA baked into ``<project_root>/.hermes_build_sha`` by the Dockerfile.
"""
value = _git_output(project_root, "rev-parse", "--short=8", "HEAD")
if value:
return value
-
- # Fall back to the build-time baked SHA (populated in published Docker
- # images, absent otherwise). Defers the import so the dump module
- # stays cheap on non-dump code paths.
try:
- from hermes_cli.build_info import get_build_sha
- baked = get_build_sha(short=8)
- if baked:
- return baked
+ from hermes_cli.build_info import get_build_sha # deferred: keeps dump cheap on non-dump paths
+ return get_build_sha(short=8) or "(unknown)"
except Exception:
- pass
-
- return "(unknown)"
+ return "(unknown)"
def _get_git_commit_date(project_root: Path) -> str:
- """Return the date the HEAD commit was authored (YYYY-MM-DD), or ''.
-
- The published Docker image excludes ``.git``, so this returns '' there and the dump line
- drops the date suffix; the baked SHA still identifies the build.
- """
+ """Return the date the HEAD commit was authored (YYYY-MM-DD), or '' (Docker images have no .git)."""
return _git_output(project_root, "log", "-1", "--format=%cd", "--date=short", "HEAD")
def _redact(value: str) -> str:
- """Redact all but first 4 and last 4 chars.
-
- Thin wrapper over :func:`agent.redact.mask_secret`. Returns ``""`` for an empty value (matches
- the historical behavior of this helper — ``hermes dump`` formats empty values as blank, not as
- ``"(not set)"``).
- """
+ """Redact all but first 4 and last 4 chars; ``""`` for an empty value (dump formats empties as blank)."""
from agent.redact import mask_secret
return mask_secret(value)
@@ -124,22 +100,15 @@ def _count_skills(hermes_home: Path) -> int:
return sum(1 for item in skills_dir.rglob("SKILL.md") if not is_excluded_skill_path(item))
-def _count_mcp_servers(config: dict) -> int:
- """Count configured MCP servers."""
- return len(config.get("mcp", {}).get("servers", {}))
-
-
def _cron_summary(hermes_home: Path) -> str:
"""Return cron jobs summary."""
jobs_file = hermes_home / "cron" / "jobs.json"
if not jobs_file.exists():
return "0"
try:
- # utf-8-sig: same dialect as cron/jobs.load_jobs — Windows editors
- # may leave a UTF-8 BOM that plain utf-8 json.load rejects.
+ # utf-8-sig: same dialect as cron/jobs.load_jobs — Windows editors may leave a UTF-8 BOM.
with open(jobs_file, encoding="utf-8-sig") as f:
- data = json.load(f)
- jobs = data.get("jobs", [])
+ jobs = json.load(f).get("jobs", [])
active = sum(1 for j in jobs if j.get("enabled", True))
return f"{active} active / {len(jobs)} total"
except Exception:
@@ -147,43 +116,33 @@ def _cron_summary(hermes_home: Path) -> str:
_PLATFORM_ENV_VARS = {
- "telegram": "TELEGRAM_BOT_TOKEN",
- "discord": "DISCORD_BOT_TOKEN",
- "slack": "SLACK_BOT_TOKEN",
- "whatsapp": "WHATSAPP_ENABLED",
- "signal": "SIGNAL_HTTP_URL",
- "email": "EMAIL_ADDRESS",
- "sms": "TWILIO_ACCOUNT_SID",
- "matrix": "MATRIX_HOMESERVER_URL",
- "mattermost": "MATTERMOST_URL",
- "homeassistant": "HASS_TOKEN",
- "dingtalk": "DINGTALK_CLIENT_ID",
- "feishu": "FEISHU_APP_ID",
- "wecom": "WECOM_BOT_ID",
- "wecom_callback": "WECOM_CALLBACK_CORP_ID",
- "weixin": "WEIXIN_ACCOUNT_ID",
+ "telegram": "TELEGRAM_BOT_TOKEN", "discord": "DISCORD_BOT_TOKEN", "slack": "SLACK_BOT_TOKEN",
+ "whatsapp": "WHATSAPP_ENABLED", "signal": "SIGNAL_HTTP_URL", "email": "EMAIL_ADDRESS",
+ "sms": "TWILIO_ACCOUNT_SID", "matrix": "MATRIX_HOMESERVER_URL", "mattermost": "MATTERMOST_URL",
+ "homeassistant": "HASS_TOKEN", "dingtalk": "DINGTALK_CLIENT_ID", "feishu": "FEISHU_APP_ID",
+ "wecom": "WECOM_BOT_ID", "wecom_callback": "WECOM_CALLBACK_CORP_ID", "weixin": "WEIXIN_ACCOUNT_ID",
"qqbot": "QQ_APP_ID",
}
-def _configured_platforms() -> list[str]:
- """Return list of configured messaging platform names."""
- return [name for name, env in _PLATFORM_ENV_VARS.items() if os.getenv(env)]
-
-
-def _memory_provider(config: dict) -> str:
- """Return the active memory provider name."""
- return config.get("memory", {}).get("provider", "") or "built-in"
-
-
def _get_model_and_provider(config: dict) -> tuple[str, str]:
"""Extract model and provider from config."""
model_cfg = config.get("model", "")
if isinstance(model_cfg, dict):
model = model_cfg.get("default") or model_cfg.get("model") or model_cfg.get("name") or "(not set)"
return model, model_cfg.get("provider") or "(auto)"
- model = model_cfg if isinstance(model_cfg, str) else ""
- return model or "(not set)", "(auto)"
+ return (model_cfg if isinstance(model_cfg, str) else "") or "(not set)", "(auto)"
+
+
+# Sections with interesting user-facing overrides
+_INTERESTING_PATHS = (
+ ("agent", "max_turns"), ("agent", "gateway_timeout"), ("agent", "session_stall_timeout"),
+ ("agent", "sanitizer_heal_escalation_threshold"), ("agent", "tool_use_enforcement"),
+ ("agent", "execution_guidance"), ("terminal", "backend"), ("terminal", "docker_image"),
+ ("terminal", "persistent_shell"), ("browser", "allow_private_urls"), ("compression", "enabled"),
+ ("compression", "threshold"), ("compression", "in_place"), ("display", "streaming"),
+ ("display", "skin"), ("display", "show_reasoning"), ("privacy", "redact_pii"), ("tts", "provider"),
+)
def _config_overrides(config: dict) -> dict[str, str]:
@@ -191,218 +150,144 @@ def _config_overrides(config: dict) -> dict[str, str]:
from hermes_cli.config import DEFAULT_CONFIG
overrides = {}
-
- # Sections with interesting user-facing overrides
- interesting_paths = [
- ("agent", "max_turns"),
- ("agent", "gateway_timeout"),
- ("agent", "session_stall_timeout"),
- ("agent", "sanitizer_heal_escalation_threshold"),
- ("agent", "tool_use_enforcement"),
- ("agent", "execution_guidance"),
- ("terminal", "backend"),
- ("terminal", "docker_image"),
- ("terminal", "persistent_shell"),
- ("browser", "allow_private_urls"),
- ("compression", "enabled"),
- ("compression", "threshold"),
- ("compression", "in_place"),
- ("display", "streaming"),
- ("display", "skin"),
- ("display", "show_reasoning"),
- ("privacy", "redact_pii"),
- ("tts", "provider"),
- ]
-
- for section, key in interesting_paths:
+ for section, key in _INTERESTING_PATHS:
default_section = DEFAULT_CONFIG.get(section, {})
user_section = config.get(section, {})
if not isinstance(default_section, dict) or not isinstance(user_section, dict):
continue
- default_val = default_section.get(key)
user_val = user_section.get(key)
- if user_val is not None and user_val != default_val:
+ if user_val is not None and user_val != default_section.get(key):
overrides[f"{section}.{key}"] = str(user_val)
- # Toolsets (if different from default)
- default_toolsets = DEFAULT_CONFIG.get("toolsets", [])
user_toolsets = config.get("toolsets", [])
- if user_toolsets != default_toolsets:
+ if user_toolsets != DEFAULT_CONFIG.get("toolsets", []):
overrides["toolsets"] = str(user_toolsets)
-
- # Fallback providers
fallbacks = config.get("fallback_providers", [])
if fallbacks:
overrides["fallback_providers"] = str(fallbacks)
-
return overrides
# (env var, dump label) in display order.
_API_KEYS = [
- ("OPENROUTER_API_KEY", "openrouter"),
- ("OPENAI_API_KEY", "openai"),
- ("ANTHROPIC_API_KEY", "anthropic"),
- ("ANTHROPIC_TOKEN", "anthropic_token"),
- ("NOUS_API_KEY", "nous"),
- ("GOOGLE_API_KEY", "google/gemini"),
- ("GEMINI_API_KEY", "gemini"),
- ("GLM_API_KEY", "glm/zai"),
- ("ZAI_API_KEY", "zai"),
- ("KIMI_API_KEY", "kimi"),
- ("MINIMAX_API_KEY", "minimax"),
- ("DEEPSEEK_API_KEY", "deepseek"),
- ("DASHSCOPE_API_KEY", "dashscope"),
- ("HF_TOKEN", "huggingface"),
- ("NVIDIA_API_KEY", "nvidia"),
- ("AI_GATEWAY_API_KEY", "ai_gateway"),
- ("OPENCODE_ZEN_API_KEY", "opencode_zen"),
- ("OPENCODE_GO_API_KEY", "opencode_go"),
- ("COMMANDCODE_API_KEY", "commandcode"),
- ("KILOCODE_API_KEY", "kilocode"),
- ("FIRECRAWL_API_KEY", "firecrawl"),
- ("TAVILY_API_KEY", "tavily"),
- ("KEENABLE_API_KEY", "keenable"),
- ("BROWSERBASE_API_KEY", "browserbase"),
- ("FAL_KEY", "fal"),
- ("ELEVENLABS_API_KEY", "elevenlabs"),
- ("GITHUB_TOKEN", "github"),
+ ("OPENROUTER_API_KEY", "openrouter"), ("OPENAI_API_KEY", "openai"),
+ ("ANTHROPIC_API_KEY", "anthropic"), ("ANTHROPIC_TOKEN", "anthropic_token"),
+ ("NOUS_API_KEY", "nous"), ("GOOGLE_API_KEY", "google/gemini"), ("GEMINI_API_KEY", "gemini"),
+ ("GLM_API_KEY", "glm/zai"), ("ZAI_API_KEY", "zai"), ("KIMI_API_KEY", "kimi"),
+ ("MINIMAX_API_KEY", "minimax"), ("DEEPSEEK_API_KEY", "deepseek"),
+ ("DASHSCOPE_API_KEY", "dashscope"), ("HF_TOKEN", "huggingface"), ("NVIDIA_API_KEY", "nvidia"),
+ ("AI_GATEWAY_API_KEY", "ai_gateway"), ("OPENCODE_ZEN_API_KEY", "opencode_zen"),
+ ("OPENCODE_GO_API_KEY", "opencode_go"), ("COMMANDCODE_API_KEY", "commandcode"),
+ ("KILOCODE_API_KEY", "kilocode"), ("FIRECRAWL_API_KEY", "firecrawl"), ("TAVILY_API_KEY", "tavily"),
+ ("KEENABLE_API_KEY", "keenable"), ("BROWSERBASE_API_KEY", "browserbase"), ("FAL_KEY", "fal"),
+ ("ELEVENLABS_API_KEY", "elevenlabs"), ("GITHUB_TOKEN", "github"),
]
+def _version_line(project_root: Path) -> str:
+ """``<version> [<commit>] (<commit date>)`` — the commit date is the real "as-of" date;
+ __release_date__ is intentionally NOT shown (reads like a wall-clock timestamp, confuses triage)."""
+ try:
+ from hermes_cli import __version__
+ except ImportError:
+ __version__ = "(unknown)"
+ ver_str = f"{__version__} [{_get_git_commit(project_root)}]"
+ commit_date = _get_git_commit_date(project_root)
+ return f"{ver_str} ({commit_date})" if commit_date else ver_str
+
+
+def _effective_terminal_backend(config: dict) -> str:
+ """The EFFECTIVE backend, not just config.yaml: a TERMINAL_ENV set directly in .env / the shell
+ overrides ``terminal.backend`` and is what terminal_tool actually uses. run_dump() has already
+ loaded .env, so os.environ reflects the real override here."""
+ config_backend = config.get("terminal", {}).get("backend", "local")
+ env_backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
+ if env_backend and env_backend != str(config_backend).strip().lower():
+ return f"{env_backend} (TERMINAL_ENV overrides config.yaml terminal.backend={config_backend})"
+ return config_backend
+
+
+def _api_key_lines(show_keys: bool) -> list[str]:
+ dotenv_keys = _dotenv_key_names()
+ lines = []
+ for env_var, label in _API_KEYS:
+ val = os.getenv(env_var, "")
+ display = _redact(val) if show_keys and val else ("set" if val else "not set")
+ # Set in this (shell) process but absent from ~/.hermes/.env: a managed backend
+ # (launchd/systemd/desktop `serve`) loads .env, not the login shell, so it likely can't
+ # see this key — flag it so support doesn't chase a phantom "key is configured".
+ if val and env_var not in dotenv_keys:
+ display += " (shell only — not in .env; managed/desktop backend may not see it)"
+ # A credential added via `hermes auth add openrouter` lives in the credential pool, not as an
+ # env var — surface it so the dump doesn't read "not set" while `hermes auth list` shows it.
+ if not val and label == "openrouter":
+ try:
+ from agent.credential_pool import load_pool as _load_pool
+
+ if _load_pool("openrouter").has_credentials():
+ display = "set (auth pool)"
+ except Exception:
+ pass
+ lines.append(f" {label:<20} {display}")
+ return lines
+
+
def run_dump(args):
"""Output a compact, copy-pasteable setup summary."""
show_keys = getattr(args, "show_keys", False)
# Load env from .env file so key checks work
- env_path = get_env_path()
- load_hermes_dotenv(
- hermes_home=env_path.parent,
- project_env=get_project_root() / ".env",
- )
-
+ load_hermes_dotenv(hermes_home=get_env_path().parent, project_env=get_project_root() / ".env")
project_root = get_project_root()
hermes_home = get_hermes_home()
-
- try:
- from hermes_cli import __version__
- except ImportError:
- __version__ = "(unknown)"
-
- commit = _get_git_commit(project_root)
- commit_date = _get_git_commit_date(project_root)
-
try:
config = load_config()
except Exception:
config = {}
-
model, provider = _get_model_and_provider(config)
-
- # Profile
try:
from hermes_cli.profiles import get_active_profile_name
profile = get_active_profile_name() or "(default)"
except Exception:
profile = "(default)"
-
- # Terminal backend — report the EFFECTIVE backend, not just config.yaml.
- # ``terminal.backend`` in config.yaml is bridged to the TERMINAL_ENV env var,
- # but a TERMINAL_ENV set directly in .env / the shell overrides config and is
- # what terminal_tool actually uses (tools/terminal_tool.py reads TERMINAL_ENV).
- # Reporting only the config value hides that override and sends users chasing
- # the wrong cause when the agent runs in a docker/podman sandbox even though
- # config says "local" (and vice-versa). run_dump() has already loaded .env,
- # so os.environ reflects the real override here.
- terminal_cfg = config.get("terminal", {})
- config_backend = terminal_cfg.get("backend", "local")
- env_backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
- if env_backend and env_backend != str(config_backend).strip().lower():
- backend = (
- f"{env_backend} (TERMINAL_ENV overrides config.yaml "
- f"terminal.backend={config_backend})"
- )
- else:
- backend = config_backend
-
- # OpenAI SDK version
try:
import openai
openai_ver = openai.__version__
except ImportError:
openai_ver = "not installed"
- # OS info
- os_info = f"{platform.system()} {platform.release()} {platform.machine()}"
-
- # Identify the build by commit + the date that commit was made, resolved
- # live via git. __release_date__ (the package release date) is
- # intentionally NOT shown here — it reads like a wall-clock timestamp and
- # confuses support triage. The commit date is the real "as-of" date.
- ver_str = f"{__version__} [{commit}]"
- if commit_date:
- ver_str += f" ({commit_date})"
lines = [
"--- hermes dump ---",
- f"version: {ver_str}",
- f"os: {os_info}",
+ f"version: {_version_line(project_root)}",
+ f"os: {platform.system()} {platform.release()} {platform.machine()}",
f"python: {sys.version.split()[0]}",
f"openai_sdk: {openai_ver}",
f"profile: {profile}",
f"hermes_home: {display_hermes_home()}",
f"model: {model}",
f"provider: {provider}",
- f"terminal: {backend}",
+ f"terminal: {_effective_terminal_backend(config)}",
"",
"api_keys:",
+ *_api_key_lines(show_keys),
]
- dotenv_keys = _dotenv_key_names()
-
- for env_var, label in _API_KEYS:
- val = os.getenv(env_var, "")
- display = _redact(val) if show_keys and val else ("set" if val else "not set")
- # Set in this (shell) process but absent from ~/.hermes/.env: a managed
- # backend (launchd/systemd/desktop `serve`) loads .env, not the login
- # shell, so it likely can't see this key — even though the dump reads
- # "set". Flag it so support doesn't chase a phantom "key is configured"
- # (the actual cause of gated tools like web_search going missing).
- if val and env_var not in dotenv_keys:
- display += " (shell only — not in .env; managed/desktop backend may not see it)"
- # A credential added via `hermes auth add openrouter` lives in the
- # credential pool, not as an env var — surface it so the dump doesn't
- # misleadingly read "not set" while `hermes auth list` shows it (#42130).
- if not val and label == "openrouter":
- try:
- from agent.credential_pool import load_pool as _load_pool
-
- if _load_pool("openrouter").has_credentials():
- display = "set (auth pool)"
- except Exception:
- pass
- lines.append(f" {label:<20} {display}")
- # Features summary
toolsets = config.get("toolsets", ["hermes-cli"])
+ platforms = [name for name, env in _PLATFORM_ENV_VARS.items() if os.getenv(env)]
lines += [
"",
"features:",
f" toolsets: {', '.join(toolsets) if toolsets else '(default)'}",
- f" mcp_servers: {_count_mcp_servers(config)}",
- f" memory_provider: {_memory_provider(config)}",
+ f" mcp_servers: {len(config.get('mcp', {}).get('servers', {}))}",
+ f" memory_provider: {config.get('memory', {}).get('provider', '') or 'built-in'}",
f" gateway: {_gateway_status()}",
- ]
- platforms = _configured_platforms()
- lines += [
f" platforms: {', '.join(platforms) if platforms else 'none'}",
f" cron_jobs: {_cron_summary(hermes_home)}",
f" skills: {_count_skills(hermes_home)}",
]
- # Config overrides (non-default values)
overrides = _config_overrides(config)
if overrides:
- lines += ["", "config_overrides:"]
- lines += [f" {key}: {val}" for key, val in overrides.items()]
-
+ lines += ["", "config_overrides:"] + [f" {key}: {val}" for key, val in overrides.items()]
lines.append("--- end dump ---")
print("\n".join(lines))