Merge branch 'simp/r3-19-D' into simp/integration3

This commit is contained in:
Teknium
2026-09-02 23:11:03 -07:00
9 changed files with 128 additions and 216 deletions
+5 -7
View File
@@ -51,7 +51,7 @@ from hermes_cli.doctor_state import ( # noqa: F401 (re-exported; tests use her
_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_bool, check_fail, check_info, check_ok, check_warn,
Finding, _fail_and_issue, _section, check_bool, check_fail, check_info, check_ok, check_warn, doctor_check,
)
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,
@@ -72,9 +72,9 @@ _PROVIDER_ENV_HINTS = (
from hermes_cli.sizefmt import format_bytes as _human_bytes # noqa: F401 (tests import doctor._human_bytes)
def _check_auth_providers(should_fix: bool) -> Finding:
@doctor_check()
def _check_auth_providers(should_fix: bool, f: Finding) -> None:
"""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.
@@ -93,7 +93,6 @@ def _check_auth_providers(should_fix: bool) -> Finding:
_login_row("xAI OAuth", get_xai_oauth_auth_status() or {}, show_error=True)
except Exception:
pass
return f
def _login_row(label: str, status: dict, ok_detail: str = "(logged in)", show_error: bool = False) -> bool:
@@ -104,9 +103,9 @@ def _login_row(label: str, status: dict, ok_detail: str = "(logged in)", show_er
return logged_in
def _check_api_connectivity(should_fix: bool) -> Finding:
@doctor_check()
def _check_api_connectivity(should_fix: bool, f: Finding) -> None:
"""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 results land.
print(f" {color(f'Running {len(probes)} connectivity checks in parallel…', Colors.DIM)}", end="", flush=True)
@@ -117,7 +116,6 @@ def _check_api_connectivity(should_fix: bool) -> Finding:
print(f" {glyph} {label}" + (f" {detail}" if detail else ""))
if r.issues and not _has_healthy_oauth_fallback_for_apikey_provider(r.label):
f.issues.extend(r.issues)
return f
# Ordered (section title, check). None title = check prints its own header (or none); order is user-visible.
+21 -39
View File
@@ -137,10 +137,10 @@ def _check_mcp_security(should_fix: bool, f: Finding) -> None:
check_ok("No suspicious MCP stdio commands")
def _check_env_file(should_fix: bool) -> Finding:
@doctor_check()
def _check_env_file(should_fix: bool, f: Finding) -> None:
"""Managed scope plus ~/.hermes/.env presence and provider credentials."""
from hermes_cli.doctor import HERMES_HOME, PROJECT_ROOT, _DHH
f = Finding()
managed_scope_check()
env_path = HERMES_HOME / '.env'
if env_path.exists():
@@ -170,7 +170,6 @@ def _check_env_file(should_fix: bool) -> Finding:
else:
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]:
@@ -186,11 +185,7 @@ def _known_provider_ids(cfg: dict) -> tuple[set, list, object, object, object]:
pass
try:
from hermes_cli.config import get_compatible_custom_providers
from hermes_cli.providers import (
custom_provider_aliases as aliases,
normalize_provider as normalize,
resolve_provider_full as resolve_full,
)
from hermes_cli.providers import custom_provider_aliases as aliases, normalize_provider as normalize, resolve_provider_full as resolve_full
try:
custom_providers = get_compatible_custom_providers(cfg)
except Exception:
@@ -258,16 +253,12 @@ def _validate_model_config(config_path, issues: list) -> None:
if resolve_full is not None:
provider_def = resolve_full(provider, cfg.get("providers"), custom_providers)
catalog_provider = provider_def.id if provider_def is not None else None
if catalog_provider is not None:
accept.add(catalog_provider)
accept.update({catalog_provider} - {None})
if provider and provider != "auto" and (catalog_provider is None or (known_providers and not (accept & valid_provider_ids))):
known_list = ", ".join(sorted(known_providers)) if known_providers else "(unavailable)"
_fail_and_issue(
f"model.provider '{provider_raw}' is not a recognised provider", f"(known: {known_list})",
f"model.provider '{provider_raw}' is unknown. Valid providers: {known_list}. "
f"Fix: run 'hermes config set model.provider <valid_provider>'",
issues,
)
_fail_and_issue(f"model.provider '{provider_raw}' is not a recognised provider", f"(known: {known_list})",
f"model.provider '{provider_raw}' is unknown. Valid providers: {known_list}. "
f"Fix: run 'hermes config set model.provider <valid_provider>'", issues)
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:")
if default_model and "/" in default_model and policy_id and not accepts_vendor_slug:
@@ -279,22 +270,18 @@ def _validate_model_config(config_path, issues: list) -> None:
from hermes_cli.doctor import _DHH
try:
if not _provider_has_credentials(runtime_provider):
_fail_and_issue(
f"model.provider '{runtime_provider}' is set but no API key is configured",
"(check ~/.hermes/.env or run 'hermes setup')",
f"No credentials found for provider '{runtime_provider}'. "
f"Run 'hermes setup' or set the provider's API key in {_DHH}/.env, "
f"or switch providers with 'hermes config set model.provider <name>'",
issues,
)
_fail_and_issue(f"model.provider '{runtime_provider}' is set but no API key is configured",
"(check ~/.hermes/.env or run 'hermes setup')",
f"No credentials found for provider '{runtime_provider}'. Run 'hermes setup' or set the provider's "
f"API key in {_DHH}/.env, or switch providers with 'hermes config set model.provider <name>'", issues)
except Exception:
pass
def _check_config_file(should_fix: bool) -> Finding:
@doctor_check()
def _check_config_file(should_fix: bool, f: Finding) -> None:
"""config.yaml presence (project cli-config.yaml as fallback); model/provider validation."""
from hermes_cli.doctor import HERMES_HOME, PROJECT_ROOT, _DHH
f = Finding()
config_path = HERMES_HOME / 'config.yaml'
if config_path.exists():
check_ok(f"{_DHH}/config.yaml exists")
@@ -316,7 +303,6 @@ def _check_config_file(should_fix: bool) -> Finding:
f.fixed += 1
else:
check_warn("config.yaml not found", "(using defaults)")
return f
def _drift_config_version(f: Finding, should_fix: bool, config_path) -> None:
@@ -350,15 +336,12 @@ def _drift_stale_root_keys(f: Finding, should_fix: bool, config_path) -> None:
return
# Coerce scalar/None ``model:`` into a dict before mutation (setdefault would hand back a scalar).
raw_model = raw_config.get("model")
if isinstance(raw_model, dict):
model_section = raw_model
else:
model_section = {"default": raw_model.strip()} if isinstance(raw_model, str) and raw_model.strip() else {}
raw_config["model"] = model_section
if not isinstance(raw_model, dict):
raw_model = raw_config["model"] = {"default": raw_model.strip()} if isinstance(raw_model, str) and raw_model.strip() else {}
for k in stale_root_keys:
value = raw_config.pop(k)
if not model_section.get(k):
model_section[k] = value
if not raw_model.get(k):
raw_model[k] = value
atomic_config_write(config_path, raw_config)
check_ok("Migrated stale root-level keys into model section")
f.fixed += 1
@@ -376,8 +359,8 @@ def _drift_max_iterations_ghost(f: Finding, should_fix: bool, config_path) -> No
raw_config = read_user_config_raw(config_path)
agent_cfg = raw_config.get("agent")
cfg_max_turns = agent_cfg.get("max_turns") if isinstance(agent_cfg, dict) else None
if cfg_max_turns is None: # legacy root-level key counts too
cfg_max_turns = raw_config.get("max_turns")
if cfg_max_turns is None:
cfg_max_turns = raw_config.get("max_turns") # legacy root-level key counts too
env_ghost = load_env().get("HERMES_MAX_ITERATIONS")
if cfg_max_turns is None or env_ghost is None or str(cfg_max_turns).strip() == str(env_ghost).strip():
return
@@ -427,13 +410,13 @@ _CONFIG_DRIFT_STEPS = (
)
def _check_config_drift(should_fix: bool) -> Finding:
@doctor_check()
def _check_config_drift(should_fix: bool, f: Finding) -> None:
"""Config version, stale root keys, HERMES_MAX_ITERATIONS ghost, deprecations, structure.
Each step is independent and best-effort: a failure in one never hides the next.
"""
from hermes_cli.doctor import HERMES_HOME
f = Finding()
config_path = HERMES_HOME / 'config.yaml'
if not config_path.exists():
config_path = None
@@ -442,7 +425,6 @@ def _check_config_drift(should_fix: bool) -> Finding:
step(f, should_fix, config_path)
except Exception:
pass
return f
@doctor_check("xAI retirement check skipped", "({e})")
+10 -25
View File
@@ -42,8 +42,7 @@ def _skip(name: str) -> ProbeResult:
def _has_healthy_oauth_fallback_for_apikey_provider(provider_label: str) -> bool:
"""True when a failed direct API-key probe is non-blocking because the same provider family's OAuth
runtime path is already healthy: the failed row is still shown, but not promoted into the summary."""
normalized = (provider_label or "").strip().lower()
getter = {"minimax": "get_minimax_oauth_auth_status", "xai": "get_xai_oauth_auth_status"}.get(normalized)
getter = {"minimax": "get_minimax_oauth_auth_status", "xai": "get_xai_oauth_auth_status"}.get((provider_label or "").strip().lower())
if not getter:
return False
try:
@@ -156,13 +155,9 @@ def _probe_anthropic() -> ProbeResult:
try:
import httpx
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:
headers["Authorization"] = f"Bearer {key}"
headers["anthropic-beta"] = ",".join(_COMMON_BETAS + _OAUTH_ONLY_BETAS)
else:
headers["x-api-key"] = key
headers = {"anthropic-version": "2023-06-01", **({"Authorization": f"Bearer {key}", "anthropic-beta": ",".join(_COMMON_BETAS + _OAUTH_ONLY_BETAS)}
if is_oauth else {"x-api-key": key})}
url = "https://api.anthropic.com/v1/models"
r = httpx.get(url, headers=headers, timeout=10)
# OAuth subscriptions without 1M context reject with 400 "long context beta is not yet available";
@@ -172,9 +167,7 @@ def _probe_anthropic() -> ProbeResult:
r = httpx.get(url, headers=headers, timeout=10)
except Exception as e:
return _row(name, "warn", f"({e})")
if r.status_code == 200:
return _row(name, "ok")
return _row(name, "fail", "(invalid API key)") if r.status_code == 401 else _row(name, "warn", "(couldn't verify)")
return _row(name, *{200: ("ok",), 401: ("fail", "(invalid API key)")}.get(r.status_code, ("warn", "(couldn't verify)")))
def _probe_apikey_provider(pname, env_vars, default_url, base_env, supports_health_check) -> ProbeResult:
@@ -192,11 +185,9 @@ def _probe_apikey_provider(pname, env_vars, default_url, base_env, supports_heal
r = httpx.get("https://dashscope.aliyuncs.com/compatible-mode/v1/models", headers=headers, timeout=10)
except Exception as e:
return _row(pname, "warn", f"({e})", label=label)
if r.status_code == 200:
return _row(pname, "ok", label=label)
if r.status_code == 401:
return _row(pname, "fail", "(invalid API key)", [f"Check {env_vars[0]} in .env"], label=label)
return _row(pname, "warn", f"(HTTP {r.status_code})", label=label)
return _row(pname, "ok", label=label) if r.status_code == 200 else _row(pname, "warn", f"(HTTP {r.status_code})", label=label)
def _apikey_request(key: str, base_env, default_url) -> tuple:
@@ -231,17 +222,13 @@ def _probe_bedrock() -> ProbeResult:
return _skip(name)
if not has_aws_credentials():
return _skip(name)
auth_var = resolve_aws_auth_env_var()
region = resolve_bedrock_region()
label = name.ljust(20)
auth_var, region, label = resolve_aws_auth_env_var(), resolve_bedrock_region(), name.ljust(20)
try:
import boto3
from botocore.config import Config as _BotoConfig
# 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()
n = len(resp.get("modelSummaries", []))
client = boto3.client("bedrock", region_name=region, config=_BotoConfig(connect_timeout=5, read_timeout=10, retries={"max_attempts": 1}))
n = len(client.list_foundation_models().get("modelSummaries", []))
return _row(name, "ok", f"({auth_var}, {region}, {n} models)", label=label)
except ImportError:
pip = f"{sys.executable} -m pip install boto3"
@@ -265,8 +252,7 @@ def _probe_azure_entra() -> ProbeResult:
model_cfg = cfg.get("model") if isinstance(cfg, dict) else {}
if not isinstance(model_cfg, dict):
return _skip(name)
cfg_provider, auth_mode = (str(model_cfg.get(k) or "").strip().lower() for k in ("provider", "auth_mode"))
if cfg_provider != "azure-foundry" or auth_mode != "entra_id":
if [str(model_cfg.get(k) or "").strip().lower() for k in ("provider", "auth_mode")] != ["azure-foundry", "entra_id"]:
return _skip(name)
except Exception:
return _skip(name)
@@ -282,8 +268,7 @@ def _probe_azure_entra() -> ProbeResult:
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 []
tag = ", ".join(env_sources) if env_sources else "default credential chain"
tag = ", ".join(info.get("env_sources") or []) or "default credential chain"
return _row(name, "ok", f"({tag}, scope={scope})", label=label)
err = info.get("error") or "credential chain exhausted"
hint = info.get("hint") or "Run `az login`, set AZURE_TENANT_ID/AZURE_CLIENT_ID/AZURE_CLIENT_SECRET, or attach a managed identity to this VM."
+4 -8
View File
@@ -106,9 +106,7 @@ 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})")
return ProbeResult(name, "fail", f"(HTTP {code} — check {key_hint})" if code in (401, 403) else f"(HTTP {code})")
def _keyed_probe(name: str, url: str, env_var: str, scheme: str, timeout: float) -> ProbeResult:
@@ -133,10 +131,9 @@ def _probe_audio(kind: str, config: dict, timeout: float) -> ProbeResult:
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)")
entry = _AUDIO_PROBES.get(provider)
if entry is None:
if provider not in _AUDIO_PROBES:
return ProbeResult(name, "skip", f"(provider '{provider}' — no live probe implemented)")
url, env_var, scheme = entry
url, env_var, scheme = _AUDIO_PROBES[provider]
key = os.getenv(env_var, "").strip()
if not key:
return ProbeResult(name, "warn", f"(provider '{provider}' configured but {env_var} is not set)")
@@ -192,8 +189,7 @@ def run_live_checks(issues: List[str]) -> List[ProbeResult]:
servers = config.get("mcp_servers") or {}
if isinstance(servers, dict) and servers:
for name in sorted(servers):
entry = servers[name]
def _probe(n=name, e=entry) -> ProbeResult:
def _probe(n=name, e=servers[name]) -> ProbeResult:
if not isinstance(e, dict):
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))")
+37 -62
View File
@@ -130,12 +130,10 @@ def _read_pyproject_version() -> str | None:
except OSError:
return None
in_project = False
for raw in text.splitlines():
line = raw.strip()
for line in map(str.strip, text.splitlines()):
if line.startswith("[") and line.endswith("]"):
in_project = line == "[project]"
continue
if in_project and line.startswith("version") and "=" in line:
elif in_project and line.startswith("version") and "=" in line:
return line.split("=", 1)[1].split("#", 1)[0].strip().strip("\"'") or None
return None
@@ -151,12 +149,9 @@ def _check_version_consistency(issues: list[str]) -> None:
if pyproject_version is None:
return
if pyproject_version == init_version:
check_ok("Version files consistent", f"({init_version})")
else:
_fail_and_issue("Version mismatch between source files",
f"(pyproject.toml {pyproject_version} != hermes_cli/__init__.py {init_version})",
"Re-sync version files (e.g. run 'hermes update', or set "
"hermes_cli/__init__.py __version__ to match pyproject.toml)", issues)
return check_ok("Version files consistent", f"({init_version})")
_fail_and_issue("Version mismatch between source files", f"(pyproject.toml {pyproject_version} != hermes_cli/__init__.py {init_version})",
"Re-sync version files (e.g. run 'hermes update', or set hermes_cli/__init__.py __version__ to match pyproject.toml)", issues)
def _check_s6_supervision(issues: list[str]) -> None:
@@ -246,14 +241,11 @@ def _check_gateway_service_linger(issues: list[str]) -> None:
return
_section("Gateway Service")
linger_enabled, linger_detail = get_systemd_linger_status()
if linger_enabled is True:
check_ok("Systemd linger enabled", "(gateway service survives logout)")
elif linger_enabled is False:
check_warn("Systemd linger disabled", "(gateway may stop after logout)")
if linger_enabled is None:
return check_warn("Could not verify systemd linger", f"({linger_detail})")
if not check_bool(linger_enabled, ("Systemd linger enabled", "(gateway service survives logout)"), ("Systemd linger disabled", "(gateway may stop after logout)")):
check_info("Run: sudo loginctl enable-linger $USER")
issues.append("Enable linger for the gateway user service: sudo loginctl enable-linger $USER")
else:
check_warn("Could not verify systemd linger", f"({linger_detail})")
def check_macos_tcc_grants() -> None:
@@ -339,17 +331,12 @@ def check_macos_full_disk_access() -> None:
except OSError as e:
if not isinstance(e, PermissionError):
return
check_info(
"One switch silences all macOS folder prompts: grant your terminal "
"app Full Disk Access and Hermes will never trip per-folder dialogs "
"(Desktop/Downloads/Documents/...) again. Open: System Settings → "
"Privacy & Security → Full Disk Access — or run:\n"
" open \"x-apple.systempreferences:com.apple.preference"
".security?Privacy_AllFiles\"\n"
" then enable your terminal (and Hermes.app if you use Desktop), "
"and restart them once. With Hermes' stable signing identities the "
"grant survives every update."
)
check_info("One switch silences all macOS folder prompts: grant your terminal app Full Disk Access and Hermes "
"will never trip per-folder dialogs (Desktop/Downloads/Documents/...) again. Open: System Settings → "
"Privacy & Security → Full Disk Access — or run:\n"
" open \"x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles\"\n"
" then enable your terminal (and Hermes.app if you use Desktop), and restart them once. "
"With Hermes' stable signing identities the grant survives every update.")
else:
check_ok("macOS Full Disk Access granted", "(no per-folder permission prompts will occur)")
@@ -361,8 +348,7 @@ def _check_security_advisories(should_fix: bool, f: Finding) -> None:
all_hits = detect_compromised()
fresh_hits = filter_unacked(all_hits)
if not fresh_hits:
check_ok("No active security advisories")
return
return check_ok("No active security advisories")
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
@@ -376,11 +362,10 @@ def _check_security_advisories(should_fix: bool, f: Finding) -> None:
check_warn(f"{h.package}=={h.installed_version} still installed (advisory {h.advisory.id} acknowledged)")
def _check_python_environment(should_fix: bool) -> Finding:
@doctor_check()
def _check_python_environment(should_fix: bool, f: Finding) -> None:
"""Interpreter, linked SQLite, venv, macOS TCC anchors/FDA/grants, version-file drift."""
f = Finding()
v = sys.version_info
label = f"Python {v.major}.{v.minor}.{v.micro}"
v, label = sys.version_info, f"Python {'.'.join(map(str, sys.version_info[:3]))}"
if v >= (3, 10):
check_ok(label)
if v < (3, 11):
@@ -410,7 +395,6 @@ def _check_python_environment(should_fix: bool) -> Finding:
check_macos_full_disk_access()
_check_version_consistency(f.issues)
check_macos_tcc_grants()
return f
@doctor_check()
@@ -426,8 +410,8 @@ _PACKAGES = (
)
def _check_required_packages(should_fix: bool) -> Finding:
f = Finding()
@doctor_check()
def _check_required_packages(should_fix: bool, f: Finding) -> None:
for module, name, optional in _PACKAGES:
try:
__import__(module)
@@ -437,7 +421,6 @@ def _check_required_packages(should_fix: bool) -> Finding:
check_warn(name, "(optional, not installed)")
else:
_fail_and_issue(name, "(missing)", f"Install {name}: {_python_install_cmd()} {module}", f.issues)
return f
@doctor_check()
@@ -446,14 +429,18 @@ def _check_gateway_supervision(should_fix: bool, f: Finding) -> None:
_check_s6_supervision(f.issues)
def _check_command_installation(should_fix: bool) -> Finding:
@doctor_check()
def _check_command_installation(should_fix: bool, f: Finding) -> None:
"""Venv entry point and the ~/.local/bin (or $PREFIX/bin) symlink; skipped on Windows."""
from hermes_cli.doctor import PROJECT_ROOT
f = Finding()
if sys.platform == "win32":
return f
return
_section("Command Installation")
venv_bin = next((c for c in (PROJECT_ROOT / n / "bin" / "hermes" for n in ("venv", ".venv")) if c.exists()), None)
if venv_bin is None:
check_warn("Venv entry point not found", "(hermes not in venv/bin/ or .venv/bin/ — reinstall with pip install -e '.[all]')")
return f.manual_issues.append(f"Reinstall entry point: cd {PROJECT_ROOT} && source venv/bin/activate && pip install -e '.[all]'")
check_ok(f"Venv entry point exists ({venv_bin.relative_to(PROJECT_ROOT)})")
# Expected command link directory (mirrors install.sh logic).
prefix = os.environ.get("PREFIX", "")
if prefix and (os.environ.get("TERMUX_VERSION") or "com.termux/files/usr" in prefix):
@@ -461,38 +448,26 @@ def _check_command_installation(should_fix: bool) -> Finding:
else:
link_dir, display = Path.home() / ".local" / "bin", "~/.local/bin"
link = link_dir / "hermes"
if venv_bin is None:
check_warn("Venv entry point not found", "(hermes not in venv/bin/ or .venv/bin/ — reinstall with pip install -e '.[all]')")
f.manual_issues.append(f"Reinstall entry point: cd {PROJECT_ROOT} && source venv/bin/activate && pip install -e '.[all]'")
return f
check_ok(f"Venv entry point exists ({venv_bin.relative_to(PROJECT_ROOT)})")
if link.is_symlink():
target, expected = link.resolve(), venv_bin.resolve()
if target == expected:
check_ok(f"{display}/hermes → correct target")
return f
return check_ok(f"{display}/hermes → correct target")
check_warn(f"{display}/hermes points to wrong target", f"(→ {target}, expected → {expected})")
if not should_fix:
f.issues.append(f"Broken symlink at {display}/hermes — run 'hermes doctor --fix'")
return f
return f.issues.append(f"Broken symlink at {display}/hermes — run 'hermes doctor --fix'")
link.unlink()
_link_venv(f, link, venv_bin, f"Fixed symlink: {display}/hermes → {venv_bin}")
verb = "Fixed"
elif link.exists(): # regular file (wrapper script), not a symlink
check_ok(f"{display}/hermes exists (non-symlink)")
return check_ok(f"{display}/hermes exists (non-symlink)")
else:
check_fail(f"{display}/hermes not found", "(hermes command may not work outside the venv)")
if not should_fix:
f.issues.append(f"Missing {display}/hermes symlink — run 'hermes doctor --fix'")
return f
return f.issues.append(f"Missing {display}/hermes symlink — run 'hermes doctor --fix'")
link_dir.mkdir(parents=True, exist_ok=True)
_link_venv(f, link, venv_bin, f"Created symlink: {display}/hermes → {venv_bin}")
if str(link_dir) not in os.environ.get("PATH", "").split(os.pathsep):
check_warn(f"{display} is not on your PATH", "(add it to your shell config: export PATH=\"$HOME/.local/bin:$PATH\")")
f.manual_issues.append(f"Add {display} to your PATH")
return f
def _link_venv(f: Finding, link: Path, venv_bin: Path, msg: str) -> None:
verb = "Created"
link.symlink_to(venv_bin)
check_ok(msg)
check_ok(f"{verb} symlink: {display}/hermes → {venv_bin}")
f.fixed += 1
if verb == "Created" and str(link_dir) not in os.environ.get("PATH", "").split(os.pathsep):
check_warn(f"{display} is not on your PATH", "(add it to your shell config: export PATH=\"$HOME/.local/bin:$PATH\")")
f.manual_issues.append(f"Add {display} to your PATH")
+9 -6
View File
@@ -9,9 +9,7 @@ from hermes_cli.colors import Colors, color
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
return lambda text, detail="": print(f" {color(glyph, col)} {text}" + (f" {color(detail, Colors.DIM)}" if detail else ""))
check_ok, check_warn, check_fail = _mark("✓", Colors.GREEN), _mark("⚠", Colors.YELLOW), _mark("✗", Colors.RED)
@@ -57,8 +55,11 @@ class Finding:
def doctor_check(on_error: str | None = None, detail: str = ""):
"""Turn ``fn(should_fix, f: Finding)`` into a ``(should_fix) -> Finding`` doctor check.
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."""
*on_error* None: exceptions propagate (as they always did for that check). Otherwise the check is
best-effort: a crash prints ``check_warn(on_error.format(e=e), detail.format(e=e))`` (nothing for
``""``) and 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:
@@ -66,7 +67,9 @@ def doctor_check(on_error: str | None = None, detail: str = ""):
try:
fn(should_fix, f)
except Exception as e:
if on_error is not None:
if on_error is None:
raise
if on_error:
check_warn(on_error.format(e=e), detail.format(e=e))
return f
return check
+19 -28
View File
@@ -100,14 +100,14 @@ def _memory_store_flags(hermes_home: Path) -> tuple:
return get_builtin_memory_store_flags({"memory": _doctor_memory_config(hermes_home)})
def _check_directory_structure(should_fix: bool) -> Finding:
@doctor_check()
def _check_directory_structure(should_fix: bool, f: Finding) -> None:
"""HERMES_HOME, expected subdirs, SOUL.md, and the enabled built-in memory files."""
from hermes_cli.doctor import HERMES_HOME, _DHH
f = Finding()
hermes_home = HERMES_HOME
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
memory_on = bool(_memory_enabled or _user_profile_enabled)
# The built-in file store neither creates nor consumes memories/ when both targets are disabled.
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",
@@ -115,9 +115,9 @@ def _check_directory_structure(should_fix: bool) -> Finding:
# SOUL.md persona file
soul_path = hermes_home / "SOUL.md"
if soul_path.exists():
content = soul_path.read_text(encoding="utf-8").strip()
# Template comments only (no real content)?
if any(l.strip() and not l.strip().startswith(("<!--", "-->", "#")) for l in content.splitlines()):
lines = soul_path.read_text(encoding="utf-8").strip().splitlines()
if any(l.strip() and not l.strip().startswith(("<!--", "-->", "#")) for l in lines):
check_ok(f"{_DHH}/SOUL.md exists (persona configured)")
else:
check_info(f"{_DHH}/SOUL.md exists but is empty — edit it to customize personality")
@@ -142,13 +142,11 @@ def _check_directory_structure(should_fix: bool) -> Finding:
f.fixed += 1
else:
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 enabled and mem_file.exists():
check_ok(f"{fname} exists ({len(mem_file.read_text(encoding='utf-8').strip())} chars)")
elif enabled:
for fname in [n for on, n in ((_memory_enabled, "MEMORY.md"), (_user_profile_enabled, "USER.md")) if on]:
if (memories_dir / fname).exists():
check_ok(f"{fname} exists ({len((memories_dir / fname).read_text(encoding='utf-8').strip())} chars)")
else:
check_info(f"{fname} not created yet (will be created when the agent first writes a memory)")
return f
def _session_count(state_db_path: Path):
@@ -183,8 +181,7 @@ def _repair_state_db(f: Finding, should_fix: bool, state_db_path: Path, kind: st
report = repair_state_db_schema(state_db_path)
if not report.get("repaired"):
check_warn(not_fixed_label, f"({report.get('error')}; backup: {report.get('backup_path')})")
f.issues.append(failed_issue)
return
return f.issues.append(failed_issue)
if "{count}" in ok_label:
try:
ok_label = ok_label.format(count=_session_count(state_db_path))
@@ -258,10 +255,10 @@ def _state_db_wal(f: Finding, should_fix: bool, state_db_path: Path) -> None:
pass
def _check_state_db(should_fix: bool) -> Finding:
@doctor_check()
def _check_state_db(should_fix: bool, f: Finding) -> None:
"""state.db session count, FTS write health, schema repair, stats snapshot, WAL size."""
from hermes_cli.doctor import HERMES_HOME, _DHH
f = Finding()
state_db_path = HERMES_HOME / "state.db"
if state_db_path.exists():
_state_db_health(f, should_fix, state_db_path, _DHH)
@@ -269,7 +266,6 @@ def _check_state_db(should_fix: bool) -> Finding:
else:
check_info(f"{_DHH}/state.db not created yet (will be created on first session)")
_state_db_wal(f, should_fix, state_db_path)
return f
def _gh_authenticated() -> bool:
@@ -281,14 +277,11 @@ def _gh_authenticated() -> bool:
return False
def _check_skills_hub(should_fix: bool) -> Finding:
@doctor_check()
def _check_skills_hub(should_fix: bool, f: Finding) -> None:
from hermes_cli.doctor import HERMES_HOME, _DHH
f = Finding()
hub_dir = HERMES_HOME / "skills" / ".hub"
if not hub_dir.exists():
check_warn("Skills Hub directory not initialized", "(run: hermes skills list)")
else:
check_ok("Skills Hub directory exists")
if check_bool(hub_dir.exists(), "Skills Hub directory exists", ("Skills Hub directory not initialized", "(run: hermes skills list)")):
lock_file = hub_dir / "lock.json"
if lock_file.exists():
try:
@@ -307,7 +300,6 @@ def _check_skills_hub(should_fix: bool) -> Finding:
else:
check_bool(_gh_authenticated(), ("GitHub authenticated via gh CLI", "(full API access — no GITHUB_TOKEN needed)"),
("No GITHUB_TOKEN", f"(60 req/hr rate limit — set in {_DHH}/.env for better rates)"))
return f
def _memory_provider_honcho(issues: list) -> None:
@@ -367,13 +359,13 @@ def _memory_provider_generic(name: str) -> None:
check_warn(f"{name} plugin not found", "run: hermes memory setup")
def _check_memory_provider(should_fix: bool) -> Finding:
@doctor_check()
def _check_memory_provider(should_fix: bool, f: Finding) -> None:
from hermes_cli.doctor import HERMES_HOME
f = Finding()
name = _doctor_memory_config(HERMES_HOME).get("provider", "")
if not name:
check_ok("Built-in memory active", "(no external provider configured — this is fine)")
return f
return
checker, missing_row, missing_issue, label = _MEMORY_PROVIDER_CHECKS.get(name, (None, None, None, name))
try:
checker(f.issues) if checker else _memory_provider_generic(name)
@@ -384,10 +376,9 @@ def _check_memory_provider(should_fix: bool) -> Finding:
_fail_and_issue(*missing_row, missing_issue, f.issues)
except Exception as _e:
check_warn(f"{label} check failed", str(_e))
return f
@doctor_check()
@doctor_check("") # best-effort: profile enumeration must never break doctor
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
+14 -21
View File
@@ -31,9 +31,9 @@ def _run_ok(cmd: list[str], timeout: int, **kw) -> bool:
def _termux_browser_setup_steps(node_installed: bool) -> list[str]:
steps = [] if node_installed else ["1) pkg install nodejs"]
n = len(steps) + 1
return steps + [f"{n}) npm install -g agent-browser", f"{n + 1}) agent-browser install"]
steps = [] if node_installed else ["pkg install nodejs"]
steps += ["npm install -g agent-browser", "agent-browser install"]
return [f"{i}) {step}" for i, step in enumerate(steps, 1)]
_TERMUX_INSTALL_ALL_FALLBACK_NOTES = (
@@ -46,10 +46,9 @@ _TERMUX_INSTALL_ALL_FALLBACK_NOTES = (
def _is_kanban_worker_env_gate(item: dict) -> bool:
"""Return True when Kanban is unavailable only because this is not a worker process."""
if item.get("name") != "kanban" or os.environ.get("HERMES_KANBAN_TASK"):
return False
tools = item.get("tools") or []
return bool(tools) and all(str(tool).startswith("kanban_") for tool in tools)
return (item.get("name") == "kanban" and not os.environ.get("HERMES_KANBAN_TASK")
and bool(tools) and all(str(tool).startswith("kanban_") for tool in tools))
def _doctor_tool_availability_detail(toolset: str) -> str:
@@ -119,18 +118,15 @@ def _missing_api_key_toolsets_for_summary(unavailable: list[dict]) -> list[dict]
from hermes_cli.doctor import _enabled_cli_toolsets_for_doctor
api_key_unavailable = [item for item in unavailable if item.get("missing_vars") or item.get("env_vars")]
enabled_toolsets = _enabled_cli_toolsets_for_doctor()
if enabled_toolsets is None:
return api_key_unavailable
return [item for item in api_key_unavailable if str(item.get("name") or "") in enabled_toolsets]
return api_key_unavailable if enabled_toolsets is None else [i for i in api_key_unavailable if str(i.get("name") or "") in enabled_toolsets]
def _check_git_and_rg(should_fix: bool) -> Finding:
f = Finding()
@doctor_check()
def _check_git_and_rg(should_fix: bool, f: Finding) -> None:
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
_BUILTIN_TERMINAL_BACKENDS = {"local", "docker", "singularity", "modal", "managed_modal", "daytona", "vercel_sandbox", "ssh"}
@@ -226,9 +222,9 @@ def _check_plugin_backend(terminal_env: str, issues: list[str]) -> None:
_BACKEND_CHECKS = {"ssh": _check_ssh_backend, "daytona": _check_daytona_backend, "vercel_sandbox": _check_vercel_backend}
def _check_terminal_backend(should_fix: bool) -> Finding:
@doctor_check()
def _check_terminal_backend(should_fix: bool, f: Finding) -> None:
"""Docker/SSH/Daytona/Vercel/plugin terminal backends, gated on TERMINAL_ENV."""
f = Finding()
terminal_env = os.getenv("TERMINAL_ENV", "local")
try:
from hermes_constants import is_container as _is_container
@@ -245,7 +241,6 @@ def _check_terminal_backend(should_fix: bool) -> Finding:
_BACKEND_CHECKS[terminal_env](f.issues)
elif terminal_env not in _BUILTIN_TERMINAL_BACKENDS:
_check_plugin_backend(terminal_env, f.issues)
return f
def _check_agent_browser(should_fix: bool) -> bool:
@@ -331,9 +326,9 @@ def _check_lightpanda() -> None:
check_info(LIGHTPANDA_INSTALL_HINT)
def _check_node_and_browser(should_fix: bool) -> Finding:
@doctor_check()
def _check_node_and_browser(should_fix: bool, f: Finding) -> None:
"""Node.js, agent-browser resolution, Playwright Chromium, Lightpanda engine."""
f = Finding()
if _safe_which("node"):
check_ok("Node.js")
if _check_agent_browser(should_fix) and not _is_termux(): # Chromium check is not a tested Termux path
@@ -344,7 +339,6 @@ def _check_node_and_browser(should_fix: bool) -> Finding:
else:
check_warn("Node.js not found", "(optional, needed for browser tools)")
_check_lightpanda()
return f
def _plural(n: int) -> str:
@@ -384,7 +378,8 @@ def _audit_one(npm_bin: str, npm_dir, label: str, audit_extra: list[str], issues
pass
def _check_npm_audit(should_fix: bool) -> Finding:
@doctor_check()
def _check_npm_audit(should_fix: bool, f: Finding) -> None:
"""npm audit per Node package tree (root, web/ui-tui workspaces, WhatsApp bridge).
PROJECT_ROOT is audited with --workspaces=false so the apps/* glob (Electron, node-pty, ...) is never
@@ -392,7 +387,6 @@ def _check_npm_audit(should_fix: bool) -> Finding:
HERMES_HOME mirror rather than the (possibly read-only) Docker install tree, hence the shared resolver.
"""
from hermes_cli.doctor import PROJECT_ROOT
f = Finding()
npm_bin = _safe_which("npm")
if npm_bin:
try:
@@ -413,7 +407,6 @@ def _check_npm_audit(should_fix: bool) -> Finding:
check_info("Termux compatibility fallbacks:")
for note in _TERMUX_INSTALL_ALL_FALLBACK_NOTES:
check_info(note)
return f
@doctor_check("Could not check tool availability", "({e})")
+9 -20
View File
@@ -83,9 +83,7 @@ def _gateway_status() -> str:
def _count_skills(hermes_home: Path) -> int:
"""Count installed skills."""
skills_dir = hermes_home / "skills"
if not skills_dir.is_dir():
return 0
return sum(1 for item in skills_dir.rglob("SKILL.md") if not is_excluded_skill_path(item))
return sum(1 for item in skills_dir.rglob("SKILL.md") if not is_excluded_skill_path(item)) if skills_dir.is_dir() else 0
def _cron_summary(hermes_home: Path) -> str:
@@ -117,8 +115,7 @@ 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)"
return (model_cfg.get("default") or model_cfg.get("model") or model_cfg.get("name") or "(not set)", model_cfg.get("provider") or "(auto)")
return (model_cfg if isinstance(model_cfg, str) else "") or "(not set)", "(auto)"
@@ -227,8 +224,7 @@ def run_dump(args):
show_keys = getattr(args, "show_keys", False)
# Load env from .env file so key checks work
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()
project_root, hermes_home = get_project_root(), get_hermes_home()
try:
config = load_config()
except Exception:
@@ -239,27 +235,21 @@ def run_dump(args):
profile = get_active_profile_name() or "(default)"
except Exception:
profile = "(default)"
openai_ver = _openai_version()
toolsets = config.get("toolsets", ["hermes-cli"])
platforms = [name for name, env in _PLATFORM_ENV_VARS.items() if os.getenv(env)]
lines = [
"--- hermes dump ---",
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"openai_sdk: {_openai_version()}",
f"profile: {profile}",
f"hermes_home: {display_hermes_home()}",
f"model: {model}",
f"provider: {provider}",
f"terminal: {_effective_terminal_backend(config)}",
"",
"api_keys:",
*_api_key_lines(show_keys),
]
toolsets = config.get("toolsets", ["hermes-cli"])
platforms = [name for name, env in _PLATFORM_ENV_VARS.items() if os.getenv(env)]
lines += [
"",
"features:",
"", "api_keys:", *_api_key_lines(show_keys),
"", "features:",
f" toolsets: {', '.join(toolsets) if toolsets else '(default)'}",
f" mcp_servers: {len(config.get('mcp', {}).get('servers', {}))}",
f" memory_provider: {config.get('memory', {}).get('provider', '') or 'built-in'}",
@@ -271,5 +261,4 @@ def run_dump(args):
overrides = _config_overrides(config)
if overrides:
lines += ["", "config_overrides:"] + [f" {key}: {val}" for key, val in overrides.items()]
lines.append("--- end dump ---")
print("\n".join(lines))
print("\n".join(lines + ["--- end dump ---"]))