refactor(hermes_cli): doctor — collapse trivial early-returns/ternaries in connectivity, live, tools, platform, dump
This commit is contained in:
@@ -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";
|
||||
@@ -231,17 +226,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 +256,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 +272,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."
|
||||
|
||||
@@ -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))")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -374,8 +372,7 @@ def _check_security_advisories(should_fix: bool, f: Finding) -> None:
|
||||
@doctor_check()
|
||||
def _check_python_environment(should_fix: bool, f: Finding) -> None:
|
||||
"""Interpreter, linked SQLite, venv, macOS TCC anchors/FDA/grants, version-file drift."""
|
||||
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):
|
||||
|
||||
@@ -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,9 +118,7 @@ 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]
|
||||
|
||||
|
||||
@doctor_check()
|
||||
|
||||
+2
-5
@@ -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)"
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user