doctor_tools.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. """External-tool checks for hermes doctor: terminal backends, git/rg, Node + Chromium, npm audit, tool availability.
  2. Split out of ``hermes_cli/doctor.py``, which re-exports every name so ``hermes_cli.doctor.<name>`` keeps resolving (and monkeypatching)."""
  3. from __future__ import annotations
  4. import importlib.util
  5. import os
  6. import shutil
  7. import subprocess
  8. import sys
  9. from pathlib import Path
  10. from hermes_cli.doctor_platform import _system_package_install_cmd
  11. from hermes_cli.doctor_report import Finding, _fail_and_issue, check_bool, check_info, check_ok, check_warn, doctor_check
  12. from hermes_cli.vercel_auth import describe_vercel_auth
  13. from hermes_constants import is_termux as _is_termux
  14. from tools.environments.docker import docker_runtime_name, docker_runtime_start_hint, find_docker
  15. def _safe_which(cmd: str) -> str | None:
  16. """shutil.which wrapper resilient to platform monkeypatching in tests."""
  17. try:
  18. return shutil.which(cmd)
  19. except Exception:
  20. return None
  21. def _pm_tool_path(name: str) -> Path | None:
  22. """Use PM's current selection, including writable payload extensions.
  23. Old facts are diagnostic evidence, not an available runtime tool.
  24. """
  25. try:
  26. from pm import installed_package
  27. installed = installed_package(name)
  28. except Exception:
  29. return None
  30. return installed.binary if installed is not None else None
  31. def _pm_package_for_command(command: str) -> str | None:
  32. """The pm package that provisions *command*, derived from pm's own
  33. package definitions (binary_rel → executable basename) — no restated
  34. name table, so new pm packages are covered without doctor changes."""
  35. try:
  36. import pm
  37. from pm import registry, store
  38. from pm.packages import BinaryPackage
  39. target = store.current_target()
  40. for package_name in registry.all_packages():
  41. package = registry.get_package(package_name)
  42. if isinstance(package, BinaryPackage):
  43. rel = package._rel(target)
  44. if rel and Path(rel).name.removesuffix(".exe").removesuffix(".cmd") == command:
  45. return package_name
  46. except Exception:
  47. return None
  48. return None
  49. def _doctor_tool(name: str) -> tuple[str | None, str]:
  50. """Resolve the tool Hermes would actually run: the pm store first
  51. (pinned installs run tools out of the store, which nothing puts on
  52. PATH), then PATH. *name* is the command ("rg"); its pm package
  53. ("ripgrep") is resolved from pm's own definitions. Returns
  54. ``(path, ok-row detail)``."""
  55. for package_name in (name, _pm_package_for_command(name)):
  56. if not package_name:
  57. continue
  58. staged = _pm_tool_path(package_name)
  59. if staged:
  60. return str(staged), "(pm store)"
  61. return _safe_which(name), ""
  62. def _run_ok(cmd: list[str], timeout: int, **kw) -> bool:
  63. """True when *cmd* exits 0 within *timeout*; a timeout counts as failure."""
  64. try:
  65. return subprocess.run(cmd, capture_output=True, timeout=timeout, **kw).returncode == 0 # noqa: PLW1510 -- forwarding wrapper: callers pass subprocess kwargs via **kwargs (check may arrive through it); an explicit check=False would raise TypeError
  66. except subprocess.TimeoutExpired:
  67. return False
  68. _TERMUX_INSTALL_ALL_FALLBACK_NOTES = (
  69. "Termux uses the Hermes APT package: pkg install hermes-agent.",
  70. "Matrix E2EE extra is excluded on Termux (python-olm currently fails to build).",
  71. "Local faster-whisper extra is excluded on Termux (ctranslate2/av build path unavailable).",
  72. "STT fallback: use Groq Whisper (set GROQ_API_KEY) or OpenAI Whisper (set VOICE_TOOLS_OPENAI_KEY).",
  73. )
  74. def _is_kanban_worker_env_gate(item: dict) -> bool:
  75. """Return True when Kanban is unavailable only because this is not a worker process."""
  76. tools = item.get("tools") or []
  77. return (item.get("name") == "kanban" and not os.environ.get("HERMES_KANBAN_TASK")
  78. and bool(tools) and all(str(tool).startswith("kanban_") for tool in tools))
  79. def _doctor_tool_availability_detail(toolset: str) -> str:
  80. """Optional explanatory suffix for toolsets whose doctor status needs context."""
  81. if toolset == "kanban" and not os.environ.get("HERMES_KANBAN_TASK"):
  82. return "(runtime-gated; loaded only for dispatcher-spawned workers)"
  83. return ""
  84. def _doctor_web_capability_rows() -> list[tuple[str, str, str]]:
  85. """Return ``(status, label, detail)`` rows (status ``ok``/``warn``) for web search/extract readiness.
  86. Uses the same active-provider resolvers as the tools but reports ``is_available()``
  87. readiness, so an explicitly selected but unconfigured backend does not look healthy.
  88. See #78412.
  89. """
  90. rows: list[tuple[str, str, str]] = []
  91. try:
  92. from agent.web_search_registry import get_active_extract_provider, get_active_search_provider
  93. from tools.web_tools import _ensure_web_plugins_loaded, _provider_is_ready
  94. # Fresh process: bundled web providers only register during plugin discovery (idempotent, cheap).
  95. _ensure_web_plugins_loaded()
  96. except Exception:
  97. return rows
  98. for capability, getter in (("web search", get_active_search_provider), ("web extract", get_active_extract_provider)):
  99. try:
  100. provider = getter()
  101. except Exception:
  102. provider = None
  103. if provider is None:
  104. rows.append(("warn", capability, "(no provider selected or registered)"))
  105. continue
  106. name = getattr(provider, "name", None) or type(provider).__name__
  107. rows.append(("ok", capability, f"({name})") if _provider_is_ready(provider)
  108. else ("warn", capability, f"({name} selected; provider not configured)"))
  109. return rows
  110. def _apply_doctor_tool_availability_overrides(available: list[str], unavailable: list[dict]) -> tuple[list[str], list[dict]]:
  111. """Adjust runtime-gated tool availability for doctor diagnostics."""
  112. updated_available, updated_unavailable = list(available), []
  113. for item in unavailable:
  114. if not _is_kanban_worker_env_gate(item):
  115. updated_unavailable.append(item)
  116. elif "kanban" not in updated_available:
  117. updated_available.append("kanban")
  118. return updated_available, updated_unavailable
  119. def _enabled_cli_toolsets_for_doctor() -> set[str] | None:
  120. """Return toolsets enabled for the CLI, or None if config resolution fails."""
  121. try:
  122. from hermes_cli.config import load_config
  123. from hermes_cli.tools_config import _get_platform_tools
  124. return {str(toolset) for toolset in _get_platform_tools(load_config() or {}, "cli")}
  125. except Exception:
  126. return None
  127. # Toolsets gated by a multi-path setup (several providers / managed auth) declare no single
  128. # `requires_env`, so the generic branch would call a missing credential a "system dependency".
  129. # Name the real fix instead (#9516).
  130. _TOOLSET_SETUP_HINTS: dict[str, str] = {
  131. "image_gen": "(image generation unavailable — check the provider selection and its key or SDK with 'hermes tools')",
  132. }
  133. def _setup_gated(item: dict) -> bool:
  134. return bool(item.get("missing_vars") or item.get("env_vars") or item.get("name") in _TOOLSET_SETUP_HINTS)
  135. def _missing_api_key_toolsets_for_summary(unavailable: list[dict]) -> list[dict]:
  136. """Filter unavailable setup-gated toolsets (missing key OR setup hint) to those enabled for the CLI."""
  137. api_key_unavailable = [item for item in unavailable if _setup_gated(item)]
  138. enabled_toolsets = _enabled_cli_toolsets_for_doctor()
  139. 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]
  140. @doctor_check()
  141. def _check_git_and_rg(should_fix: bool, f: Finding) -> None:
  142. git, git_detail = _doctor_tool("git")
  143. rg, rg_detail = _doctor_tool("rg")
  144. check_bool(git, ("git", git_detail), ("git not found", "(optional)"))
  145. if not check_bool(rg, ("ripgrep (rg)", f"{rg_detail} (faster file search)".strip()),
  146. ("ripgrep (rg) not found", "(file search uses grep fallback)")):
  147. check_info(f"Install for faster search: {_system_package_install_cmd('ripgrep')}")
  148. _BUILTIN_TERMINAL_BACKENDS = {"local", "docker", "modal", "managed_modal", "daytona", "vercel_sandbox", "ssh"}
  149. def _check_docker_backend(terminal_env: str, running_in_container: bool, issues: list[str]) -> None:
  150. docker_exe = find_docker()
  151. if terminal_env == "docker":
  152. if not docker_exe:
  153. _fail_and_issue("Docker or Podman not installed", "(needed for the 'docker' terminal backend)",
  154. "Install Docker or Podman, or run `hermes setup terminal` to switch backend.", issues)
  155. else:
  156. runtime = docker_runtime_name(docker_exe)
  157. hint = docker_runtime_start_hint(docker_exe)
  158. unreachable = (
  159. f"{runtime} daemon not running" if runtime == "Docker" else f"{runtime} not reachable")
  160. # `<cli> version` hits /version, which socket proxies (tecnativa) allow by default; `docker info`
  161. # needs /info and is commonly blocked, giving a false "daemon not running". The backend itself
  162. # probes with `<cli> version` too (environments/docker.py).
  163. _require(_run_ok([docker_exe, "version"], timeout=10),
  164. (runtime, "(daemon running)" if runtime == "Docker" else "(reachable)"),
  165. (unreachable, "(needed for the 'docker' terminal backend)"),
  166. f"{hint[0].upper()}{hint[1:]}, or run `hermes setup terminal` to switch backend.", issues)
  167. elif docker_exe:
  168. check_ok(docker_runtime_name(docker_exe), "(optional)")
  169. elif _is_termux():
  170. check_info("Docker backend is not available inside Termux (expected on Android)")
  171. elif not running_in_container: # in-container case already explained by the caller
  172. check_warn("Docker/Podman not found", "(optional)")
  173. def _check_ssh_backend(issues: list[str]) -> None:
  174. ssh_host = os.getenv("TERMINAL_SSH_HOST")
  175. if not ssh_host:
  176. return _fail_and_issue("SSH host not configured", "(needed for the 'ssh' terminal backend)",
  177. "run `hermes setup terminal` and enter the SSH host and user.", issues)
  178. ssh_user, ssh_port, ssh_key = (os.getenv(f"TERMINAL_SSH_{k}") for k in ("USER", "PORT", "KEY"))
  179. cmd = ["ssh", "-o", "ConnectTimeout=5", "-o", "BatchMode=yes"]
  180. if ssh_port:
  181. cmd += ["-p", ssh_port]
  182. if ssh_key:
  183. cmd += ["-i", os.path.expanduser(ssh_key)]
  184. cmd += [f"{ssh_user}@{ssh_host}" if ssh_user else ssh_host, "echo ok"]
  185. _require(_run_ok(cmd, timeout=15, text=True, encoding='utf-8', errors='replace'),
  186. f"SSH connection to {ssh_host}", (f"SSH connection to {ssh_host}", ""), f"Check SSH configuration for {ssh_host}", issues)
  187. def _require(cond, ok, bad, issue: str, issues: list[str]) -> None:
  188. """``check_ok(*ok)`` when *cond*, else ``check_fail(*bad)`` and record *issue*."""
  189. if not check_bool(cond, ok, bad, fail=True):
  190. issues.append(issue)
  191. def _check_daytona_backend(issues: list[str]) -> None:
  192. _require(os.getenv("DAYTONA_API_KEY"), ("Daytona API key", "(configured)"),
  193. ("Daytona API key missing", "(needed for the 'daytona' terminal backend)"),
  194. "run `hermes setup terminal` (Daytona) to enter it.", issues)
  195. try:
  196. from daytona import Daytona
  197. check_ok("daytona SDK", "(installed)")
  198. except ImportError:
  199. _fail_and_issue("daytona SDK not installed", "(run hermes setup terminal)", "Run hermes setup terminal and select Daytona, then restart Hermes", issues)
  200. def _check_vercel_backend(issues: list[str]) -> None:
  201. from tools.terminal_tool_backends import _SUPPORTED_VERCEL_RUNTIMES
  202. runtime = os.getenv("TERMINAL_VERCEL_RUNTIME", "node24").strip() or "node24"
  203. supported = ", ".join(_SUPPORTED_VERCEL_RUNTIMES)
  204. _require(runtime in _SUPPORTED_VERCEL_RUNTIMES, ("Vercel runtime", f"({runtime})"),
  205. ("Vercel runtime unsupported", f"({runtime}; use {supported})"), f"Set TERMINAL_VERCEL_RUNTIME to one of: {supported}", issues)
  206. _require(os.getenv("TERMINAL_CONTAINER_DISK", "51200").strip() in {"", "0", "51200"},
  207. ("Vercel disk setting", "(uses platform default)"), ("Vercel custom disk unsupported", "(reset terminal.container_disk to 51200)"),
  208. "Vercel Sandbox does not support custom container_disk; use the shared default 51200", issues)
  209. _require(importlib.util.find_spec("vercel") is not None, ("vercel SDK", "(installed)"),
  210. ("vercel SDK not installed", "(run hermes setup terminal)"),
  211. "Run hermes setup terminal and select Vercel Sandbox, then restart Hermes", issues)
  212. auth_status = describe_vercel_auth()
  213. if auth_status.ok:
  214. check_ok("Vercel auth", f"({auth_status.label})")
  215. elif auth_status.label.startswith("partial"):
  216. _fail_and_issue("Vercel auth incomplete", f"({auth_status.label})", "Set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID together", issues)
  217. else:
  218. _fail_and_issue("Vercel auth not configured", f"({auth_status.label})", "Configure Vercel Sandbox auth with VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID", issues)
  219. for line in auth_status.detail_lines:
  220. check_info(f"Vercel auth {line}")
  221. persistent = os.getenv("TERMINAL_CONTAINER_PERSISTENT", "true").lower() in {"1", "true", "yes", "on"}
  222. check_info("Vercel persistence: snapshot filesystem only; live processes do not survive sandbox recreation"
  223. if persistent else "Vercel persistence: ephemeral filesystem")
  224. def _check_plugin_backend(terminal_env: str, issues: list[str]) -> None:
  225. try:
  226. from hermes_cli.plugins import discover_plugins
  227. discover_plugins()
  228. from agent.terminal_env_registry import get_provider
  229. provider = get_provider(terminal_env)
  230. except Exception:
  231. provider = None
  232. if provider is None:
  233. return _fail_and_issue(f"Unknown terminal backend '{terminal_env}'", "(no built-in or plugin backend by that name)",
  234. "Fix terminal.backend in config.yaml, or install/enable the plugin that provides it", issues)
  235. for ok, label, detail in provider.doctor_checks():
  236. _require(ok, (label, detail), (label, detail), detail.strip("()"), issues)
  237. _BACKEND_CHECKS = {"ssh": _check_ssh_backend, "daytona": _check_daytona_backend, "vercel_sandbox": _check_vercel_backend}
  238. @doctor_check()
  239. def _check_terminal_backend(should_fix: bool, f: Finding) -> None:
  240. """Docker/SSH/Daytona/Vercel/plugin terminal backends, gated on TERMINAL_ENV."""
  241. terminal_env = os.getenv("TERMINAL_ENV", "local")
  242. try:
  243. from hermes_constants import is_container as _is_container
  244. running_in_container = _is_container()
  245. except Exception:
  246. running_in_container = False
  247. # In our container docker-in-docker isn't set up, so local is intended: skip the noisy "Docker/Podman not found"
  248. # warning. An explicit TERMINAL_ENV=docker (mounted docker.sock) still gets checked.
  249. if running_in_container and terminal_env != "docker":
  250. check_info("Running inside a container — using local terminal backend (docker-in-docker is not configured by default)")
  251. terminal_env = "local"
  252. _check_docker_backend(terminal_env, running_in_container, f.issues)
  253. if terminal_env in _BACKEND_CHECKS:
  254. _BACKEND_CHECKS[terminal_env](f.issues)
  255. elif terminal_env not in _BUILTIN_TERMINAL_BACKENDS:
  256. _check_plugin_backend(terminal_env, f.issues)
  257. def _chromium_not_needed_reason() -> str:
  258. """Why this profile's config needs no local Chromium (``""`` when it does). Config-only, no I/O: a CDP
  259. override attaches to the user's browser, Lightpanda is its own engine, and a cloud provider hosts one."""
  260. from hermes_cli.config import cfg_get, load_config_readonly
  261. config = load_config_readonly()
  262. if os.environ.get("BROWSER_CDP_URL") or cfg_get(config, "browser", "cdp_url"):
  263. return "a CDP override is set"
  264. if str(cfg_get(config, "browser", "engine") or "").strip().lower() == "lightpanda":
  265. return "browser.engine is lightpanda"
  266. provider = str(cfg_get(config, "browser", "cloud_provider") or "").strip().lower()
  267. return f"cloud provider {provider} is selected" if provider not in ("", "local") else ""
  268. def _check_chromium(should_fix: bool) -> None:
  269. """The Chromium browser_exec launches for a local session (``chromium_executable()``: browser.executable_path,
  270. pm, the Docker image's baked build, a Termux system build). Only --fix may acquire it through PM."""
  271. import pm
  272. from hermes_cli.browser_runtime import chromium_executable, chromium_missing_hint
  273. found = chromium_executable()
  274. if not found and should_fix and not _is_termux():
  275. try:
  276. pm.ensure("chromium", explicit=True)
  277. except (RuntimeError, OSError) as exc: # pm.InstallError, a download or worker failure
  278. check_warn("Chromium install failed", f"({exc})")
  279. found = chromium_executable()
  280. if found:
  281. check_ok("Chromium", f"({found})")
  282. elif reason := _chromium_not_needed_reason():
  283. check_info(f"Chromium not installed (not needed: {reason})")
  284. else:
  285. check_warn("Chromium not installed", "(browser_exec cannot start a local browser)")
  286. check_info(chromium_missing_hint())
  287. def _check_lightpanda() -> None:
  288. """Lightpanda engine (browser.engine); browser_exec spawns ``lightpanda serve`` itself."""
  289. try:
  290. from tools.browser_lightpanda import (
  291. LIGHTPANDA_INSTALL_HINT, find_lightpanda_binary, lightpanda_engine_status, using_lightpanda_engine)
  292. except ImportError: # a broken browser module is surfaced by the tool-availability rows
  293. return
  294. # using_lightpanda_engine() is a cached config read — a failure there is exceptional, not hidden.
  295. if not using_lightpanda_engine():
  296. return
  297. try:
  298. used, reason = lightpanda_engine_status()
  299. except Exception as e:
  300. used, reason = False, f"status check failed: {e}"
  301. if not used:
  302. check_warn("browser.engine=lightpanda is shadowed", f"({reason})")
  303. check_info("Fix: pick Lightpanda in `hermes tools` → Browser Automation, or set browser.engine: auto")
  304. elif not check_bool(find_lightpanda_binary(), ("Lightpanda", f"({reason})"),
  305. ("Lightpanda selected but binary not found", "(browser tools will fail until it is installed)")):
  306. check_info(LIGHTPANDA_INSTALL_HINT)
  307. @doctor_check()
  308. def _check_node_and_browser(should_fix: bool, f: Finding) -> None:
  309. """Node.js, the Chromium browser_exec launches, Lightpanda engine."""
  310. # Only PM's Node counts; Termux's APT distribution is the one that relies on `pkg install nodejs`.
  311. if _pm_tool_path("node") or (_is_termux() and _safe_which("node")):
  312. check_ok("Node.js")
  313. elif _is_termux():
  314. check_info("Node.js not found (optional; install on Termux with: pkg install nodejs)")
  315. else:
  316. check_warn("Node.js not found", "(optional; run: hermes pm install node)")
  317. _check_chromium(should_fix)
  318. _check_lightpanda()
  319. def _plural(n: int) -> str:
  320. return "vulnerability" if n == 1 else "vulnerabilities"
  321. def _audit_one(npm_bin: str, npm_dir, label: str, audit_extra: list[str], manual_issues: list[str]) -> None:
  322. """Run one `npm audit --json` and report; any failure is silently skipped.
  323. Every row here audits a tree whose versions come from a COMMITTED lockfile
  324. (`npm ci` in `_run_npm_install_deterministic` reifies exactly that state on
  325. every `hermes update`), so a local `npm audit fix` never persists — the next
  326. update's deterministic install restores the pinned (vulnerable) versions and
  327. the finding reappears. The durable remedy in every case is a lockfile bump
  328. on main (update `package-lock.json` and ship it); the doctor therefore never
  329. prescribes a local mutating fix command. See #116774.
  330. """
  331. import json
  332. from hermes_constants import with_hermes_node_path
  333. try:
  334. # Resolved absolute path so Windows can execute npm.cmd (CreateProcessW can't run bare .cmd names).
  335. audit_result = subprocess.run([npm_bin, "audit", "--json", *audit_extra], cwd=str(npm_dir),
  336. capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=30,
  337. env=with_hermes_node_path(), check=False)
  338. audit_data = json.loads(audit_result.stdout) if audit_result.stdout.strip() else {}
  339. counts = audit_data.get("metadata", {}).get("vulnerabilities", {})
  340. critical, high, moderate = (counts.get(k, 0) for k in ("critical", "high", "moderate"))
  341. total = critical + high + moderate
  342. workspace_scoped = bool(audit_extra) and audit_extra[0] == "--workspace"
  343. if total == 0:
  344. check_ok(f"{label} deps", "(no known vulnerabilities)")
  345. elif critical > 0 or high > 0:
  346. remedy = ("fix is an upstream lockfile bump — a local manual fix does not persist"
  347. " (the next `hermes update` reinstalls from the committed lockfile)")
  348. check_warn(f"{label} deps", f"({critical} critical, {high} high, {moderate} moderate — {remedy})")
  349. if workspace_scoped:
  350. check_info(" ^ workspace audit includes runtime and build dependencies; if manual npm remediation "
  351. "errors with an arborist crash it's a known npm bug — clears via a lockfile bump")
  352. else:
  353. check_info(" ^ runtime dependency tree; report/pin the fix in package-lock.json — see #116774")
  354. manual_issues.append(
  355. f"{label} has {total} npm {_plural(total)}; wait for an upstream lockfile fix, then update "
  356. "your installation (Docker: pull a rebuilt image; recreating the same image restores the same dependencies)"
  357. )
  358. else:
  359. check_ok(f"{label} deps", f"({moderate} moderate {_plural(moderate)})")
  360. except Exception:
  361. pass
  362. @doctor_check()
  363. def _check_npm_audit(should_fix: bool, f: Finding) -> None:
  364. """npm audit per Node package tree (root, web/ui-tui workspaces, WhatsApp bridge).
  365. PROJECT_ROOT is audited with --workspaces=false so the apps/* glob (Electron, node-pty, ...) is never
  366. resolved for a routine check; web and ui-tui via --workspace. The WhatsApp bridge may live under a writable
  367. HERMES_HOME mirror rather than the (possibly read-only) Docker install tree, hence the shared resolver.
  368. """
  369. from hermes_cli.doctor import PROJECT_ROOT
  370. staged = _pm_tool_path("npm")
  371. npm_bin = str(staged) if staged else (_safe_which("npm") if _is_termux() else None)
  372. if npm_bin:
  373. try:
  374. # Each entry: (cwd, label, extra_audit_args) PROJECT_ROOT is audited with --workspaces=false so
  375. # that the apps/* glob (which pulls in Electron, node-pty, etc.) is never resolved for a routine
  376. # security check. The web and ui-tui workspaces are audited separately via --workspace flags.
  377. # See #38772. The WhatsApp bridge may live under a writable HERMES_HOME mirror instead of the
  378. # (possibly read-only) install tree in Docker — resolve it through the shared helper so we audit
  379. # the dir that actually holds node_modules. See #49561.
  380. from gateway.platforms.whatsapp_common import resolve_whatsapp_bridge_dir
  381. whatsapp_bridge_dir = resolve_whatsapp_bridge_dir()
  382. except Exception:
  383. whatsapp_bridge_dir = PROJECT_ROOT / "scripts" / "whatsapp-bridge"
  384. for npm_dir, label, audit_extra in (
  385. # The root package.json itself (js-yaml, semver, eslint tooling). See #122223.
  386. (PROJECT_ROOT, "Root npm package", ["--workspaces=false"]),
  387. (PROJECT_ROOT, "web workspace", ["--workspace", "web"]),
  388. (PROJECT_ROOT, "ui-tui workspace", ["--workspace", "ui-tui"]),
  389. (whatsapp_bridge_dir, "WhatsApp bridge", []),
  390. ):
  391. # Workspace-scoped audits check the root node_modules; standalone dirs check their own.
  392. if ((PROJECT_ROOT if audit_extra else npm_dir) / "node_modules").exists():
  393. _audit_one(npm_bin, npm_dir, label, audit_extra, f.manual_issues)
  394. if _is_termux():
  395. check_info("Termux compatibility fallbacks:")
  396. for note in _TERMUX_INSTALL_ALL_FALLBACK_NOTES:
  397. check_info(note)
  398. @doctor_check("Could not check tool availability", "({e})")
  399. def _check_tool_availability(should_fix: bool, f: Finding) -> None:
  400. from hermes_cli.doctor import PROJECT_ROOT
  401. sys.path.insert(0, str(PROJECT_ROOT))
  402. from model_tools import check_tool_availability, TOOLSET_REQUIREMENTS
  403. available, unavailable = _apply_doctor_tool_availability_overrides(*check_tool_availability())
  404. # Web is split into search/extract readiness rows so an explicitly
  405. # selected but unconfigured backend cannot look healthy.
  406. web_rows = []
  407. # See #78412.
  408. if "web" in available or any(item.get("name") == "web" for item in unavailable):
  409. web_rows = _doctor_web_capability_rows()
  410. if web_rows:
  411. available = [tid for tid in available if tid != "web"]
  412. unavailable = [item for item in unavailable if item.get("name") != "web"]
  413. for tid in available:
  414. check_ok(TOOLSET_REQUIREMENTS.get(tid, {}).get("name", tid), _doctor_tool_availability_detail(tid))
  415. for status, label, detail in web_rows:
  416. (check_ok if status == "ok" else check_warn)(label, detail)
  417. for item in unavailable:
  418. env_vars = item.get("missing_vars") or item.get("env_vars") or []
  419. detail = f"(missing {', '.join(env_vars)})" if env_vars else _TOOLSET_SETUP_HINTS.get(item["name"], "(system dependency not met)")
  420. check_warn(item["name"], detail)
  421. # Only toolsets enabled for the CLI count toward the summary; default-off or
  422. # disabled toolsets may warn above but must not pollute it.
  423. api_disabled = _missing_api_key_toolsets_for_summary(unavailable)
  424. if api_disabled or any(status != "ok" for status, _, _ in web_rows):
  425. f.issues.append("Run 'hermes setup' to configure missing API keys for full tool access")
  426. _warn_partially_stripped_toolsets(f)
  427. def _warn_partially_stripped_toolsets(f: Finding) -> None:
  428. """An enabled CLI toolset that agent.disabled_toolsets cuts down still reads as available above;
  429. name the missing tools and the entry removing them (#134593)."""
  430. from hermes_cli.config import load_config
  431. from hermes_cli.tools_config import _get_platform_tools, toolsets_partially_stripped
  432. config = load_config() or {}
  433. for ts, (tools, by, hint) in toolsets_partially_stripped(config, _get_platform_tools(config, "cli")).items():
  434. check_warn(f"{ts} (partly disabled)", f"({', '.join(tools)} removed by agent.disabled_toolsets: {', '.join(by)})")
  435. f.issues.append(f"{ts}: {hint[0].upper()}{hint[1:]} {', '.join(tools)}")