From fc71f08df90ba8aa8c81042cf57d648f78bf2e99 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:22:34 -0700 Subject: [PATCH 1/2] refactor(hermes_cli): skills_hub opt_value/snapshot/tap dispatch compaction; docstring tightening --- hermes_cli/skills_hub.py | 42 ++++++++++++++-------------------------- 1 file changed, 15 insertions(+), 27 deletions(-) diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.py index c565aa8cd5..1712fe290a 100644 --- a/hermes_cli/skills_hub.py +++ b/hermes_cli/skills_hub.py @@ -186,10 +186,8 @@ def _format_extra_metadata_lines(extra: Dict[str, Any]) -> list[str]: # --- Identifier / source resolution --- def _resolve_short_name(name: str, sources, console: Console) -> str: - """Short name (e.g. 'pptx') -> full identifier via search; "" when ambiguous/missing. - - One exact match wins; several -> the single official one, else they are listed. - """ + """Short name -> full identifier via search; "" when ambiguous/missing (one exact match wins, + several -> the single official one, else they are listed).""" from tools.skills_hub import unified_search c = console or _console c.print(f"[dim]Resolving '{name}'...[/]") @@ -263,10 +261,9 @@ def _existing_categories() -> List[str]: """Sorted category buckets under ``~/.hermes/skills/`` (children without their own SKILL.md).""" from tools.skills_hub import SKILLS_DIR, _category_skill_dirs try: - return sorted( - name for name in set(_category_skill_dirs(SKILLS_DIR)) - if not (SKILLS_DIR / name / "SKILL.md").exists()) - except (FileNotFoundError, OSError): + return sorted(name for name in set(_category_skill_dirs(SKILLS_DIR)) + if not (SKILLS_DIR / name / "SKILL.md").exists()) + except OSError: # FileNotFoundError is an OSError return [] @@ -646,11 +643,9 @@ def do_install(identifier: str, category: str = "", force: bool = False, console: Optional[Console] = None, skip_confirm: bool = False, invalidate_cache: bool = True, name_override: str = "", source_id: Optional[str] = None) -> None: - """Fetch, quarantine, scan, confirm, and install a skill. - - ``source_id`` pins resolution to one adapter; callers that know the provenance (``do_update``) - must pass it so a bare identifier cannot resolve to a same-named skill elsewhere. - """ + """Fetch, quarantine, scan, confirm, and install a skill. ``source_id`` pins resolution to one + adapter; callers that know the provenance (``do_update``) must pass it so a bare identifier + cannot resolve to a same-named skill elsewhere.""" from tools.skills_hub import (ensure_hub_dirs, quarantine_bundle, install_from_quarantine, HubLockFile) from tools.skills_guard import should_allow_install @@ -1077,8 +1072,8 @@ def do_tap(action: str, repo: str = "", console: Optional[Console] = None) -> No return table = _table(("Repo", {"style": "bold cyan"}), "Path", title="Configured Taps") for t in taps: - label = t.get("repo") or t.get("name") or t.get("path", "unknown") - table.add_row(label, t.get("path", "skills/")) + table.add_row(t.get("repo") or t.get("name") or t.get("path", "unknown"), + t.get("path", "skills/")) c.print(table) c.print() elif action in _TAP_OPS: @@ -1229,9 +1224,8 @@ def do_snapshot_export(output_path: str, console: Optional[Console] = None) -> N if output_path == "-": sys.stdout.write(payload) return - out = Path(output_path) - out.write_text(payload, encoding="utf-8") - c.print(f"[bold green]Snapshot exported:[/] {out}") + Path(output_path).write_text(payload, encoding="utf-8") + c.print(f"[bold green]Snapshot exported:[/] {Path(output_path)}") c.print(f"[dim]{len(installed)} skill(s), {len(tap_list)} tap(s)[/]\n") @@ -1320,8 +1314,7 @@ _CLI_ACTIONS = { skip_confirm=getattr(a, "yes", False)), "publish": lambda a: do_publish(a.skill_path, target=getattr(a, "to", "github"), repo=getattr(a, "repo", "")), - "snapshot": lambda a: _snapshot_cli(a), - "tap": lambda a: _tap_cli(a)} + "snapshot": _snapshot_cli, "tap": _tap_cli} def skills_command(args) -> None: @@ -1339,13 +1332,8 @@ def skills_command(args) -> None: def _opt_value(args: List[str], flag: str, default: str, last: bool = False) -> str: """Value following `flag` (default if absent/trailing); `last` makes a repeated flag's final occurrence win (historical install/publish/browse behaviour), else the first.""" - found = default - for i, a in enumerate(args): - if a == flag and i + 1 < len(args): - found = args[i + 1] - if not last: - break - return found + hits = [args[i + 1] for i, a in enumerate(args) if a == flag and i + 1 < len(args)] + return (hits[-1] if last else hits[0]) if hits else default def _int_or(text: str, default: int) -> int: From 6ef7605fbbed2c905122164757518a06753d011a Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:22:50 -0700 Subject: [PATCH 2/2] =?UTF-8?q?refactor(hermes=5Fcli):=20tools=5Fconfig=20?= =?UTF-8?q?=E2=80=94=20drop=2043=20unreferenced=20re-exports,=20collapse?= =?UTF-8?q?=20prompt/one-use=20temporaries;=20tools=5Fconfig=5Fcua=20?= =?UTF-8?q?=E2=80=94=20=5Ffail()/=5Fprint=5Foutput=5Ftail()/=5Freport=5Fre?= =?UTF-8?q?pair=5For=5Fupgrade()=20helpers,=20install=5Fcua=5Fdriver=20+?= =?UTF-8?q?=20=5Frun=5Fcua=5Fdriver=5Finstaller=20phase=20extraction=20(te?= =?UTF-8?q?sts=20green)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hermes_cli/tools_config.py | 44 +- hermes_cli/tools_config_cua.py | 636 ++++++++++++--------------- hermes_cli/tools_config_providers.py | 26 +- 3 files changed, 316 insertions(+), 390 deletions(-) diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.py index 7b1b0e58d4..3386a5fef5 100644 --- a/hermes_cli/tools_config.py +++ b/hermes_cli/tools_config.py @@ -16,40 +16,26 @@ from hermes_cli.toolset_scope import ( _TOOLSET_PLATFORM_RESTRICTIONS, toolset_allowed_for_platform as _toolset_allowed_for_platform) # Re-exports: keep ``hermes_cli.tools_config.X`` callers and test patch targets resolving. from hermes_cli.tools_config_cua import ( # noqa: F401 - _post_setup_no_window_flags, _cua_driver_cmd, _cua_version_summary, _resolved_cua_driver_cmd, - _cua_driver_env, _CUA_DRIVER_CONTRACT_CACHE, _cua_driver_contract_status, _cua_driver_install_ready, - _pip_install, _cua_install_target_writable, _cua_driver_version, install_cua_driver, - _CUA_INSTALLER_TIMEOUT, _CUA_INSTALLER_DRAIN_GRACE, _CUA_BACKGROUND_UPDATE_TIMEOUT, _CUA_LOCK_STALE_AFTER, - _cua_install_home, _cua_install_lock_dir, _cua_windows_install_lock_file, + _post_setup_no_window_flags, _cua_driver_cmd, _cua_version_summary, _resolved_cua_driver_cmd, _cua_driver_env, + _cua_driver_contract_status, _cua_driver_install_ready, _pip_install, _cua_install_target_writable, + install_cua_driver, _CUA_INSTALLER_TIMEOUT, _CUA_INSTALLER_DRAIN_GRACE, _CUA_LOCK_STALE_AFTER, _clear_stale_windows_cua_install_lock, _clear_stale_cua_install_lock, _cua_install_lock_held, - _cua_release_endpoint_reachable, _ps_single_quote, _cua_driver_autostart_registered_windows, - _repair_cua_driver_autostart_windows, _remove_quietly, _print_cua_platform_notes, - _run_cua_driver_installer) + _cua_release_endpoint_reachable, _repair_cua_driver_autostart_windows, _run_cua_driver_installer) from hermes_cli.tools_config_post_setup import ( # noqa: F401 - _ensure_browser_use_cli, _post_setup_lightpanda, _post_setup_agent_browser, _post_setup_camofox, - _KITTENTTS_WHEEL_URL, _PIP_POST_SETUP_HOOKS, _post_setup_pip, _post_setup_spotify, _post_setup_langfuse, - _post_setup_xai_grok, _POST_SETUP_HOOKS, _run_post_setup, valid_post_setup_keys, run_post_setup_command, - _POST_SETUP_INSTALLED, _post_setup_already_installed, _module_installed, - _RESTORABLE_PYTHON_TOOL_DEPENDENCIES, active_restorable_python_tool_dependencies, - restorable_python_tool_dependency, _agent_browser_installed, _camofox_installed, _lightpanda_installed, - _cloud_agent_browser_installed, _POST_SETUP_READY) + _ensure_browser_use_cli, _run_post_setup, valid_post_setup_keys, run_post_setup_command, _POST_SETUP_INSTALLED, + _post_setup_already_installed, _module_installed, active_restorable_python_tool_dependencies, + restorable_python_tool_dependency, _POST_SETUP_READY) from hermes_cli.tools_config_providers import ( # noqa: F401 - _plugin_provider_rows, _plugin_image_gen_providers, _plugin_video_gen_providers, - _plugin_web_search_providers, _plugin_browser_providers, _plugin_tts_providers, web_provider_capabilities, - _PLUGIN_ROW_BUILDERS, _visible_providers, provider_readiness_status, _toolset_needs_configuration_prompt, - _any_plugin_provider_available, _configure_tool_category, _web_tier_matches, _is_provider_active, - _detect_active_provider_index, _fal_model_catalog, IMAGEGEN_BACKENDS, _plugin_model_catalog, - _plugin_image_gen_catalog, _plugin_video_gen_catalog, _pick_model_from_catalog, _configure_imagegen_model, - _configure_imagegen_model_for_plugin, _configure_videogen_model_for_plugin, - _configure_xai_imagine_storage, _select_plugin_gen_provider, _select_plugin_image_gen_provider, - _select_plugin_video_gen_provider, STT_MODEL_CATALOG, _STT_MODEL_CONFIG_KEY, _configure_stt_model, - _PROVIDER_MARKER_SECTIONS, _write_provider_config, apply_provider_selection, _nous_provider_gate, - _finish_provider_selection, _print_provider_selection, _configure_provider, _reconfigure_provider, + _plugin_image_gen_providers, _plugin_video_gen_providers, _plugin_web_search_providers, _plugin_browser_providers, + _plugin_tts_providers, web_provider_capabilities, _visible_providers, provider_readiness_status, + _toolset_needs_configuration_prompt, _configure_tool_category, _web_tier_matches, _is_provider_active, + _detect_active_provider_index, IMAGEGEN_BACKENDS, _plugin_image_gen_catalog, _plugin_video_gen_catalog, + _configure_imagegen_model, _configure_imagegen_model_for_plugin, _configure_videogen_model_for_plugin, + _select_plugin_image_gen_provider, _select_plugin_video_gen_provider, STT_MODEL_CATALOG, _configure_stt_model, + _write_provider_config, apply_provider_selection, _configure_provider, _reconfigure_provider, _configure_vision_backend, _configure_vision_provider_model, _configure_simple_requirements) from hermes_cli.tools_config_mcp import ( # noqa: F401 - _mcp_match_filter, _mcp_preselected, _apply_mcp_checklist, _configure_mcp_tools_interactive, - _apply_toolset_change, _apply_mcp_change, _print_tools_list, _known_tool_platforms, - tools_disable_enable_command) + _configure_mcp_tools_interactive, _apply_toolset_change, _apply_mcp_change, tools_disable_enable_command) logger = logging.getLogger(__name__) diff --git a/hermes_cli/tools_config_cua.py b/hermes_cli/tools_config_cua.py index 1db5ac6dae..dd73f58260 100644 --- a/hermes_cli/tools_config_cua.py +++ b/hermes_cli/tools_config_cua.py @@ -1,12 +1,17 @@ -"""cua-driver installer, lock hygiene and pip-install helper for `hermes tools` / `hermes computer-use install`.""" +"""cua-driver installer, lock hygiene and pip-install helper for `hermes tools` / +`hermes computer-use install`.""" from __future__ import annotations +import contextlib import logging import os +import platform +import re import shutil import subprocess import sys +import time from pathlib import Path from typing import List, Optional @@ -15,55 +20,64 @@ from hermes_cli.cli_output import ( logger = logging.getLogger("hermes_cli.tools_config") -# Ceiling for one upstream-installer run: must exceed the installer's own stale-lock recovery window -# (_install-rust.sh force-releases a dead holder's lock only after LOCK_STALE_AFTER_SECONDS=600; a shorter -# timeout kills every run before that fires — a permanent wedge). 660s = 600s + 60s headroom. +# One upstream-installer run must outlive the installer's own stale-lock recovery (_install-rust.sh +# force-releases a dead holder's lock only after LOCK_STALE_AFTER_SECONDS=600; a shorter timeout +# kills every run before that fires — a permanent wedge). 660s = 600s + 60s headroom. _CUA_INSTALLER_TIMEOUT = 660 - -# Grace for draining the installer's pipes after a timeout kill. The kill is best-effort (_reap_after_timeout) -# so the drain must be bounded: a surviving descendant holding the inherited stdout handle would otherwise -# make the read wait on an EOF that never comes. A successful kill closes the pipe at once, so this is free. +# Bounded pipe drain after a timeout kill: the kill is best-effort (_reap_after_timeout), and a +# surviving descendant holding the inherited stdout would otherwise block the read on an EOF that +# never comes. A successful kill closes the pipe at once, so this costs nothing. _CUA_INSTALLER_DRAIN_GRACE = 15 - -# Quiet unattended refreshes from ``hermes update``: bounded even when upstream waits on Read-Host or a -# consent prompt; explicit ``computer-use install --upgrade`` keeps the full ceiling. Safe because the -# lock/network preflights make a legitimate long wait impossible here. +# Quiet ``hermes update`` refreshes stay bounded even when upstream waits on Read-Host / a consent +# prompt (explicit ``install --upgrade`` keeps the full ceiling); safe because the lock/network +# preflights make a legitimate long wait impossible here. _CUA_BACKGROUND_UPDATE_TIMEOUT = 120 - -# Upstream installer's stale-lock threshold (LOCK_STALE_AFTER_SECONDS in _install-rust.sh), so the -# pre-clear never yanks a lock a live-but-slow install still holds. +# Upstream's LOCK_STALE_AFTER_SECONDS: the pre-clear never yanks a lock a live install still holds. _CUA_LOCK_STALE_AFTER = 600 -_CUA_INSTALL_PS1_URL = "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.ps1" -_CUA_INSTALL_SH_URL = "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.sh" +_CUA_INSTALL_PS1_URL = ( + "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.ps1") +_CUA_INSTALL_SH_URL = ( + "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.sh") _CUA_MANUAL_README = "https://github.com/trycua/cua/blob/main/libs/cua-driver/README.md" _UPGRADE_CMD = "hermes computer-use install --upgrade" -def _run_text(cmd: list, *, timeout, capture_output: bool = True, **kwargs) -> subprocess.CompletedProcess: +def _run_text(cmd: list, *, timeout, capture_output: bool = True, + **kwargs) -> subprocess.CompletedProcess: """``subprocess.run`` with the utf-8/replace text decoding every helper here uses.""" - return subprocess.run( - cmd, capture_output=capture_output, text=True, encoding="utf-8", errors="replace", timeout=timeout, **kwargs, - ) + return subprocess.run(cmd, capture_output=capture_output, text=True, encoding="utf-8", + errors="replace", timeout=timeout, **kwargs) + + +def _fail(message: str, *hints: str, warn: bool = True) -> bool: + """Print ``message`` (warning, or info when ``warn=False``) plus info hints; returns False.""" + (_print_warning if warn else _print_info)(message) + for hint in hints: + _print_info(hint) + return False + + +def _print_output_tail(result: subprocess.CompletedProcess, printer=None) -> None: + """Echo the last three lines of a failed command's stderr (or stdout) as indented info. + ``printer`` lets another module route through its own (test-patchable) ``_print_info``.""" + for line in (result.stderr or result.stdout or "").strip().splitlines()[-3:]: + (printer or _print_info)(f" {line[:200]}") def _post_setup_no_window_flags(*, streams_to_console: bool = False) -> int: - """Win32 creationflags that stop post-setup children flashing a console. - CREATE_NO_WINDOW hides console grandchildren (npm, pip, powershell) while keeping stdio inheritable - (unlike DETACHED_PROCESS). Returns 0 on POSIX. ``streams_to_console`` children are only hidden when - our own stdout is not a console, so live installer output is never swallowed.""" + """Win32 creationflags that stop post-setup children flashing a console (0 on POSIX). + CREATE_NO_WINDOW hides console grandchildren (npm, pip, powershell) while keeping stdio + inheritable (unlike DETACHED_PROCESS). ``streams_to_console`` children are only hidden when our + own stdout is not a console, so live installer output is never swallowed.""" from hermes_cli._subprocess_compat import windows_hide_flags - flags = windows_hide_flags() - if not flags: - return 0 - if streams_to_console: - try: - if sys.stdout is not None and sys.stdout.isatty(): - return 0 - except Exception: - pass - return flags + try: + if flags and streams_to_console and sys.stdout is not None and sys.stdout.isatty(): + return 0 + except Exception: + pass + return flags or 0 def _cua_driver_cmd() -> str: @@ -72,25 +86,21 @@ def _cua_driver_cmd() -> str: def _cua_version_summary(raw: str, *, limit: int = 120) -> str: - """First non-empty line of ``--version`` output, bounded (an override may print a multi-line banner).""" + """First non-empty line of ``--version`` output, bounded (an override may print a banner).""" return next((line.strip()[:limit] for line in (raw or "").splitlines() if line.strip()), "") def _resolved_cua_driver_cmd() -> Optional[str]: """Resolve cua-driver exactly as the runtime and Desktop status do.""" from tools.computer_use.cua_backend import resolve_cua_driver_cmd - return resolve_cua_driver_cmd() def _cua_driver_env() -> dict: - """cua-driver child env with the Hermes telemetry policy applied (``cua_backend.cua_driver_child_env``). - - Falls back to the current environment if the helper can't be imported, so install/status never break. - """ + """cua-driver child env with the Hermes telemetry policy applied; falls back to the current + environment if the helper can't be imported, so install/status never break.""" try: from tools.computer_use.cua_backend import cua_driver_child_env - return cua_driver_child_env() except Exception: return dict(os.environ) @@ -100,12 +110,9 @@ _CUA_DRIVER_CONTRACT_CACHE: dict = {} def _cua_driver_contract_status(binary: Optional[str] = None) -> dict: - """Inspect whether an installed driver supports Hermes' runtime contract (30s cache keyed on the binary's - path/mtime/size fingerprint).""" - import time - + """Inspect whether an installed driver supports Hermes' runtime contract (30s cache keyed on the + binary's path/mtime/size fingerprint).""" from tools.computer_use.cua_backend import cua_driver_runtime_contract_status - resolved = binary or _resolved_cua_driver_cmd() if not resolved: return cua_driver_runtime_contract_status(None) @@ -114,12 +121,10 @@ def _cua_driver_contract_status(binary: Optional[str] = None) -> dict: fingerprint = (resolved, stat.st_mtime_ns, stat.st_size) except OSError: return cua_driver_runtime_contract_status(resolved) - now = time.monotonic() cache = _CUA_DRIVER_CONTRACT_CACHE if cache.get("fingerprint") == fingerprint and now - cache.get("checked_at", 0.0) < 30.0: return dict(cache["state"]) - state = cua_driver_runtime_contract_status(resolved) cache.update(fingerprint=fingerprint, checked_at=now, state=dict(state)) return state @@ -127,60 +132,53 @@ def _cua_driver_contract_status(binary: Optional[str] = None) -> dict: def _cua_driver_install_ready() -> bool: """Return whether an existing driver needs no install-time repair.""" - if not _cua_driver_contract_status().get("ready"): - return False - return sys.platform != "win32" or _cua_driver_autostart_registered_windows() + return bool(_cua_driver_contract_status().get("ready")) and ( + sys.platform != "win32" or _cua_driver_autostart_registered_windows()) def _pip_install(args: List[str], *, timeout: int = 300, capture_output: bool = True): - """Install Python packages from a post-setup hook. - Order: ``uv pip install`` (fast, needs no pip in the venv), then ``python -m pip install``, then - ``python -m ensurepip --upgrade`` and retry pip. The last tier exists because the Windows installer - creates the venv via ``uv venv``, which does NOT seed pip, so bare ``-m pip`` failed on fresh - installs.""" + """Install Python packages: ``uv pip install`` (needs no pip in the venv), then ``python -m + pip``, then ``ensurepip --upgrade`` + retry — the Windows installer creates the venv via + ``uv venv``, which does NOT seed pip, so bare ``-m pip`` failed on fresh installs.""" venv_root = Path(sys.executable).parent.parent - uv_env = {**os.environ, "VIRTUAL_ENV": str(venv_root)} install_flags = _post_setup_no_window_flags(streams_to_console=not capture_output) - # Managed uv first: $HERMES_HOME/bin is never on PATH, so a bare which() misses the uv Hermes installed; - # ensure_uv() (not a pure lookup) because installing uv is in scope during setup. + # Managed uv first: $HERMES_HOME/bin is never on PATH, so a bare which() misses the uv Hermes + # installed; ensure_uv() (not a pure lookup) because installing uv is in scope during setup. from hermes_cli.managed_uv import ensure_uv - uv_bin = ensure_uv() - if uv_bin: - try: - result = _run_text([uv_bin, "pip", "install", *args], capture_output=capture_output, timeout=timeout, - env=uv_env, creationflags=install_flags) - if result.returncode == 0: - return result - # Fall through to pip — uv may have failed for a reason pip can handle. - except (subprocess.TimeoutExpired, FileNotFoundError): - pass - + try: # a failed uv run falls through to pip — it may have failed for a reason pip can handle + result = uv_bin and _run_text([uv_bin, "pip", "install", *args], timeout=timeout, + capture_output=capture_output, creationflags=install_flags, + env={**os.environ, "VIRTUAL_ENV": str(venv_root)}) + if result and result.returncode == 0: + return result + except (subprocess.TimeoutExpired, FileNotFoundError): + pass pip_cmd = [sys.executable, "-m", "pip"] try: # Probe for pip; bootstrap via ensurepip if missing (uv venv lacks it). - probe = _run_text(pip_cmd + ["--version"], timeout=15, creationflags=_post_setup_no_window_flags()) + probe = _run_text(pip_cmd + ["--version"], timeout=15, + creationflags=_post_setup_no_window_flags()) if probe.returncode != 0: raise FileNotFoundError("pip not in venv") except (subprocess.TimeoutExpired, FileNotFoundError): try: - _run_text([sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"], timeout=120, check=True, - creationflags=_post_setup_no_window_flags()) + _run_text([sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"], + timeout=120, check=True, creationflags=_post_setup_no_window_flags()) except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: # Synthesize a result so callers see a clean failure path. return subprocess.CompletedProcess( - pip_cmd, returncode=1, stdout="", stderr=f"pip not available and ensurepip failed: {e}", - ) - + pip_cmd, returncode=1, stdout="", + stderr=f"pip not available and ensurepip failed: {e}") return _run_text(pip_cmd + ["install", *args], capture_output=capture_output, timeout=timeout, creationflags=install_flags) # No pre-install release/asset probe: cua-driver-rs releases are all prereleases, which GitHub's # `/releases/latest` skips (zero binary assets → every non-arm64 host skipped the install), and -# re-implementing upstream's tag resolution here would drift. Fresh installs run install.sh directly (it -# errors clean on a missing-arch asset); upgrades ask the binary via `cua_driver_update_check()`. +# re-implementing upstream's tag resolution here would drift. Fresh installs run install.sh directly +# (it errors clean on a missing-arch asset); upgrades ask the binary via cua_driver_update_check(). def _cua_install_target_writable() -> bool: @@ -204,10 +202,11 @@ def _cua_driver_version(binary: str) -> Optional[str]: def _confirmed_update_check(driver_cmd: str, require_confirmed_update: bool) -> tuple: """Ask the installed driver whether a newer release exists; returns ``(proceed, pin_version)``. - ``proceed=False`` means stop with success (already latest, or indeterminate under - ``require_confirmed_update``). An old driver (no check-update verb) or offline check yields None: - `hermes update` then keeps the installed version — an indeterminate check must never cost a - multi-minute silent reinstall on every update — while explicit `install --upgrade` falls through.""" + ``proceed=False`` = stop with success (already latest, or indeterminate under + ``require_confirmed_update``). An old driver (no check-update verb) or offline check yields + None: `hermes update` then keeps the installed version — an indeterminate check must never + cost a multi-minute silent reinstall on every update — while explicit `install --upgrade` + falls through.""" try: from tools.computer_use.cua_backend import cua_driver_update_check _state = cua_driver_update_check() @@ -215,77 +214,80 @@ def _confirmed_update_check(driver_cmd: str, require_confirmed_update: bool) -> _state = None if _state is None: if require_confirmed_update: - _print_info( - f" Could not confirm a newer {driver_cmd} release " - "(offline, rate-limited, or driver too old to check); " - "keeping the installed version.") - _print_info(f" Force a refresh with: {_UPGRADE_CMD}") - return False, None - return True, None + _fail(f" Could not confirm a newer {driver_cmd} release (offline, rate-limited, or " + "driver too old to check); keeping the installed version.", + f" Force a refresh with: {_UPGRADE_CMD}", warn=False) + return not require_confirmed_update, None if not _state.get("update_available"): - _print_success( - f" {driver_cmd} is already on the latest release " - f"({_state.get('current_version') or 'unknown'}).") + _print_success(f" {driver_cmd} is already on the latest release " + f"({_state.get('current_version') or 'unknown'}).") return False, None # Windows routine upgrades run unattended-safe (stdin closed, version pinned, ceiling # _CUA_BACKGROUND_UPDATE_TIMEOUT, preflights skip in seconds); only contract repairs and fresh - # installs stay interactive-only, where upstream needs a human (autostart elevation, SmartScreen). - # Pin to the release check-update confirmed: `latest_version` comes from the GitHub Releases API so - # its assets exist, unlike the installer's baked version on `main`, which is bumped before assets - # are published and 404s unpinned. Malformed values are ignored → unpinned fallback. - import re as _re - + # installs stay interactive-only, where upstream needs a human (autostart elevation/SmartScreen). + # Pin to the release check-update confirmed: `latest_version` comes from the GitHub Releases API + # so its assets exist, unlike the installer's baked version on `main` (bumped before assets are + # published → 404s unpinned). Malformed values are ignored → unpinned fallback. _latest = str(_state.get("latest_version") or "").strip().lstrip("vV") - return True, (_latest if _re.fullmatch(r"\d+(\.\d+)*", _latest) else None) + return True, (_latest if re.fullmatch(r"\d+(\.\d+)*", _latest) else None) -def install_cua_driver( - upgrade: bool = False, require_confirmed_update: bool = False, show_installer_progress: bool = True, -) -> bool: +def _report_repair_or_upgrade(ok: bool, *, repair_existing: bool, binary, before: str, + driver_cmd: str) -> bool: + """Post-installer verdict: a repair must leave a usable contract; upgrades show before/after.""" + if ok and repair_existing: + repaired = _cua_driver_contract_status() + if not repaired.get("ready"): + return _fail(" cua-driver was reinstalled, but its runtime contract is still " + f"unusable: {repaired.get('reason') or 'unknown error'}.", + " Run: hermes computer-use doctor") + if ok and before: + after = _cua_driver_version(binary) + if after and after != before: + _print_success(f" {driver_cmd} upgraded: {before} → {after}") + elif after: + _print_info(f" {driver_cmd} up to date: {after}") + return ok + + +def install_cua_driver(upgrade: bool = False, require_confirmed_update: bool = False, + show_installer_progress: bool = True) -> bool: """Install or refresh the cua-driver binary used by Computer Use. - The upstream installer always pulls the latest release tag, so re-running it is the canonical way to - upgrade. ``upgrade=False`` (toolset enable flow) keeps a compatible installation, repairs an + Re-running the upstream installer (always the latest release tag) is the canonical upgrade. + ``upgrade=False`` (toolset enable flow) keeps a compatible installation, repairs an old/incomplete one and installs when missing; ``upgrade=True`` always refreshes.""" - import platform as _plat - - system = _plat.system() + system = platform.system() if system not in ("Darwin", "Windows", "Linux"): if not upgrade: # silent under `hermes update`, which calls this for every user - _print_warning(" Computer Use (cua-driver) is unsupported on this platform; skipping.") + _print_warning( + " Computer Use (cua-driver) is unsupported on this platform; skipping.") return False - - is_windows = system == "Windows" - is_linux = system == "Linux" + is_windows, is_linux = system == "Windows", system == "Linux" # install.ps1 is fetched via PowerShell's `irm`; macOS/Linux use curl | bash. fetch_tool = "powershell" if is_windows else "curl" - - driver_cmd = _cua_driver_cmd() - binary = _resolved_cua_driver_cmd() - + driver_cmd, binary = _cua_driver_cmd(), _resolved_cua_driver_cmd() # An explicit override is authoritative even when broken: installing the standard driver # cannot repair the configured path and would mutate an unrelated installation. override = os.environ.get("HERMES_CUA_DRIVER_CMD", "").strip() if override and not binary: - _print_warning(f" HERMES_CUA_DRIVER_CMD does not resolve to an executable: {override}") - _print_info(" Fix or unset the override before running computer-use install.") - return False + return _fail(f" HERMES_CUA_DRIVER_CMD does not resolve to an executable: {override}", + " Fix or unset the override before running computer-use install.") # Not installed → fresh install path (only when caller asked for it). if not binary and not upgrade: if not _cua_install_target_writable(): - _print_info(" /Applications is not writable; skipping cua-driver install.") - _print_info(" Run from an admin account or install cua-driver manually.") - return False + return _fail(" /Applications is not writable; skipping cua-driver install.", + " Run from an admin account or install cua-driver manually.", + warn=False) if not shutil.which(fetch_tool): - _print_warning(f" {fetch_tool} not found — install manually:") - _print_info(f" {_CUA_MANUAL_README}") - return False + return _fail(f" {fetch_tool} not found — install manually:", + f" {_CUA_MANUAL_README}") return _run_cua_driver_installer(label="Installing") # A driver failing Hermes' runtime contract (version floor, missing manifest verbs) is repaired - # regardless of mode. Hermes' minimum requirement IS the confirmation an upgrade is needed, so this - # path must not defer to the driver's `check-update` verb — a cached/indeterminate "no update" - # answer would pin users on an unusable driver forever. + # regardless of mode. Hermes' minimum requirement IS the confirmation an upgrade is needed, so + # this path must not defer to the driver's `check-update` verb — a cached/indeterminate "no + # update" answer would pin users on an unusable driver forever. contract = _cua_driver_contract_status(binary) if binary else None repair_existing = bool(binary and contract and not contract.get("ready")) @@ -295,22 +297,21 @@ def install_cua_driver( suffix = "" if version is None else f": {version or 'unknown version'}" _print_success(f" {driver_cmd} already installed{suffix}.") if is_windows and not _repair_cua_driver_autostart_windows(binary, verbose=False): - _print_warning(" cua-driver is compatible, but Windows autostart repair failed.") - return False + return _fail(" cua-driver is compatible, but Windows autostart repair failed.") _print_cua_platform_notes(is_windows, is_linux, fresh_install=False) return True - if repair_existing: - version = contract.get("version") or "unknown version" - reason = contract.get("reason") or "required runtime features are missing" - _print_warning(f" Found cua-driver {version}, but Hermes cannot use its current runtime contract: {reason}.") + _print_warning(f" Found cua-driver {contract.get('version') or 'unknown version'}, but " + "Hermes cannot use its current runtime contract: " + f"{contract.get('reason') or 'required runtime features are missing'}.") if override: - _print_info(f" Update the binary selected by HERMES_CUA_DRIVER_CMD, or unset the override and run: {_UPGRADE_CMD}") - return False + return _fail(" Update the binary selected by HERMES_CUA_DRIVER_CMD, or unset the " + f"override and run: {_UPGRADE_CMD}", warn=False) if is_windows and require_confirmed_update: - _print_info(" Automatic Windows updates cannot safely run cua-driver's interactive repair installer.") - _print_info(f" Repair it from an interactive terminal with: {_UPGRADE_CMD}") - return False + return _fail(" Automatic Windows updates cannot safely run cua-driver's interactive " + "repair installer.", + f" Repair it from an interactive terminal with: {_UPGRADE_CMD}", + warn=False) _print_info(" Repairing it with the current upstream installer.") # upgrade=True path — refresh to the latest upstream release. @@ -318,47 +319,29 @@ def install_cua_driver( _print_info(" /Applications is not writable; skipping cua-driver refresh.") _print_info(f" Run `{_UPGRADE_CMD}` from an admin account to update it.") return bool(binary) - if not shutil.which(fetch_tool): _print_warning(f" {fetch_tool} not found — cannot refresh cua-driver.") return bool(binary) - confirmed_version = None if binary and not repair_existing: proceed, confirmed_version = _confirmed_update_check(driver_cmd, require_confirmed_update) if not proceed: return True - if is_windows and require_confirmed_update and not binary: - # Missing binary (enabled but never installed, or wiped by a failed install): an automatic Windows - # update must never launch install.ps1, which can demand console/UAC consent the hidden updater - # cannot provide. - _print_info(" cua-driver is not installed; automatic Windows updates cannot safely run its interactive installer.") - _print_info(f" Install it from an interactive terminal with: {_UPGRADE_CMD}") - return False - - # Best-effort before/after version display. - before = (_cua_driver_version(binary) or "") if binary else "" - + # Missing binary (enabled but never installed, or wiped by a failed install): an automatic + # Windows update must never launch install.ps1, which can demand console/UAC consent the + # hidden updater cannot provide. + return _fail(" cua-driver is not installed; automatic Windows updates cannot safely run " + "its interactive installer.", + f" Install it from an interactive terminal with: {_UPGRADE_CMD}", + warn=False) + before = (_cua_driver_version(binary) or "") if binary else "" # best-effort before/after ok = _run_cua_driver_installer( - label="Repairing" if repair_existing else "Refreshing", verbose=False, pin_version=confirmed_version, - show_progress=show_installer_progress, + label="Repairing" if repair_existing else "Refreshing", verbose=False, + pin_version=confirmed_version, show_progress=show_installer_progress, installer_timeout=_CUA_BACKGROUND_UPDATE_TIMEOUT if require_confirmed_update else None) - if ok and repair_existing: - repaired = _cua_driver_contract_status() - if not repaired.get("ready"): - _print_warning( - " cua-driver was reinstalled, but its runtime contract is still " - f"unusable: {repaired.get('reason') or 'unknown error'}.") - _print_info(" Run: hermes computer-use doctor") - return False - if ok and before: - after = _cua_driver_version(binary) - if after and after != before: - _print_success(f" {driver_cmd} upgraded: {before} → {after}") - elif after: - _print_info(f" {driver_cmd} up to date: {after}") - return ok + return _report_repair_or_upgrade(ok, repair_existing=repair_existing, binary=binary, + before=before, driver_cmd=driver_cmd) def _cua_install_home() -> "Path": @@ -378,48 +361,39 @@ def _cua_windows_install_lock_file() -> "Path": def _clear_stale_windows_cua_install_lock() -> None: """Delete install.ps1's lock file only when no process still holds it. - install.ps1 locks with ``FileShare::None``; mirror it with a zero-share ``CreateFileW`` probe and - ``FILE_FLAG_DELETE_ON_CLOSE`` so an unlocked leftover is removed atomically, with no window in which - a new installer could acquire the file between probe and delete.""" + install.ps1 locks with ``FileShare::None``; mirror it with a zero-share ``CreateFileW`` probe + and ``FILE_FLAG_DELETE_ON_CLOSE`` so an unlocked leftover is removed atomically, with no window + in which a new installer could acquire the file between probe and delete.""" lock_file = _cua_windows_install_lock_file() try: if not lock_file.is_file(): return - import ctypes as _ctypes from ctypes import wintypes as _wintypes - # Win32 constants used by install.ps1's FileShare::None equivalent. delete_access, generic_read, generic_write = 0x00010000, 0x80000000, 0x40000000 open_existing, file_attribute_normal, file_flag_delete_on_close = 3, 0x00000080, 0x04000000 - kernel32 = _ctypes.WinDLL("kernel32", use_last_error=True) - create_file = kernel32.CreateFileW - create_file.argtypes = [ - _wintypes.LPCWSTR, _wintypes.DWORD, _wintypes.DWORD, _wintypes.LPVOID, - _wintypes.DWORD, _wintypes.DWORD, _wintypes.HANDLE] + create_file, close_handle = kernel32.CreateFileW, kernel32.CloseHandle + dword = _wintypes.DWORD + create_file.argtypes = [_wintypes.LPCWSTR, dword, dword, _wintypes.LPVOID, dword, dword, + _wintypes.HANDLE] create_file.restype = _wintypes.HANDLE - close_handle = kernel32.CloseHandle - close_handle.argtypes = [_wintypes.HANDLE] - close_handle.restype = _wintypes.BOOL - + close_handle.argtypes, close_handle.restype = [_wintypes.HANDLE], _wintypes.BOOL handle = create_file( str(lock_file), generic_read | generic_write | delete_access, 0, # 0 = FileShare::None None, open_existing, file_attribute_normal | file_flag_delete_on_close, None) if handle == _wintypes.HANDLE(-1).value: - logger.debug( - "Windows cua install lock at %s is still held or cannot be removed (winerror %s)", - lock_file, _ctypes.get_last_error()) + logger.debug("Windows cua install lock at %s is still held or cannot be removed " + "(winerror %s)", lock_file, _ctypes.get_last_error()) return if not close_handle(handle): - logger.debug( - "could not close Windows cua install lock probe at %s (winerror %s)", - lock_file, _ctypes.get_last_error()) + logger.debug("could not close Windows cua install lock probe at %s (winerror %s)", + lock_file, _ctypes.get_last_error()) return if lock_file.exists(): logger.debug("Windows cua install lock probe succeeded but %s remains", lock_file) return - logger.info("Cleared stale Windows cua-driver install lock at %s", lock_file) _print_info(f" Cleared stale cua-driver install lock ({lock_file}).") except Exception as e: @@ -429,8 +403,8 @@ def _clear_stale_windows_cua_install_lock() -> None: def _clear_stale_cua_install_lock() -> None: """Best-effort: remove a stale installer lock left by a dead holder. POSIX stamps the holder pid into ``~/.cua-driver/packages/.install.lock.d/info``; Windows holds - ``~/.cua-driver/install.lock`` open with ``FileShare::None``. Clear either artifact up front only - when its platform-specific liveness check proves that no install still holds it.""" + ``~/.cua-driver/install.lock`` open with ``FileShare::None``. Clear either artifact up front + only when its platform-specific liveness check proves that no install still holds it.""" if sys.platform == "win32": _clear_stale_windows_cua_install_lock() return @@ -438,15 +412,12 @@ def _clear_stale_cua_install_lock() -> None: try: if not lock_dir.is_dir(): return - holder_pid = None try: - for line in (lock_dir / "info").read_text(encoding="utf-8", errors="replace").splitlines(): - if line.startswith("pid="): - holder_pid = int(line.split("=", 1)[1].strip()) - break + lines = (lock_dir / "info").read_text(encoding="utf-8", errors="replace").splitlines() + holder_pid = next((int(line.split("=", 1)[1].strip()) for line in lines + if line.startswith("pid=")), None) except (OSError, ValueError): holder_pid = None - if holder_pid is not None: try: os.kill(holder_pid, 0) # windows-footgun: ok — function early-returns on win32 @@ -457,14 +428,11 @@ def _clear_stale_cua_install_lock() -> None: return # alive but owned by someone else — treat as live else: # No readable pid: only clear if old enough that upstream itself would reclaim it. - import time as _time try: - age = _time.time() - lock_dir.stat().st_mtime + if time.time() - lock_dir.stat().st_mtime < _CUA_LOCK_STALE_AFTER: + return except OSError: return - if age < _CUA_LOCK_STALE_AFTER: - return - shutil.rmtree(lock_dir, ignore_errors=True) logger.info("Cleared stale cua-driver install lock at %s", lock_dir) _print_info(f" Cleared stale cua-driver install lock ({lock_dir}).") @@ -482,8 +450,8 @@ def _cua_install_lock_held() -> bool: lock_file = _cua_windows_install_lock_file() if not lock_file.is_file(): return False - # install.ps1 holds the file with FileShare::None — any open fails with a sharing violation - # while held. Surviving the stale-clear = held; confirm with an open probe. + # install.ps1 holds the file with FileShare::None — any open fails with a sharing + # violation while held. Surviving the stale-clear = held; confirm with an open probe. try: with open(lock_file, "r+b"): return False # opened fine → not held (racy leftover) @@ -501,7 +469,6 @@ def _cua_release_endpoint_reachable(timeout: float = 5.0) -> bool: unreachable — any HTTP response (even 4xx/5xx) proves the path works.""" import urllib.error import urllib.request - try: req = urllib.request.Request("https://github.com/trycua/cua/releases", method="HEAD") with urllib.request.urlopen(req, timeout=timeout): @@ -523,65 +490,47 @@ def _cua_driver_autostart_registered_windows() -> bool: if sys.platform != "win32": return False try: - result = subprocess.run( - ["schtasks.exe", "/Query", "/TN", "cua-driver-serve"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10) + return subprocess.run(["schtasks.exe", "/Query", "/TN", "cua-driver-serve"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + timeout=10).returncode == 0 except Exception: return False - return result.returncode == 0 def _repair_cua_driver_autostart_windows(driver_cmd: str, *, verbose: bool) -> bool: """Best-effort repair for Windows installer autostart quoting failures. - Older install.ps1 builds interpolated the binary path into a PowerShell command string, which split - at the first space. If the scheduled task is missing, retry via Start-Process's structured - ``-FilePath`` / ``-ArgumentList`` parameters instead.""" + Older install.ps1 builds interpolated the binary path into a PowerShell command string, which + split at the first space. If the scheduled task is missing, retry via Start-Process's + structured ``-FilePath`` / ``-ArgumentList`` parameters instead.""" if sys.platform != "win32" or _cua_driver_autostart_registered_windows(): return True - binary = shutil.which(driver_cmd) if not binary: return False - ps = shutil.which("powershell") or shutil.which("powershell.exe") or "powershell" - ps_cmd = ( - f"$exe = {_ps_single_quote(binary)}; " - "$proc = Start-Process -FilePath $exe " - "-ArgumentList @('autostart','enable') " - "-Verb RunAs -Wait -PassThru -ErrorAction Stop; " - "exit $proc.ExitCode") - _print_info(" Registering cua-driver auto-start..." if verbose else " Repairing cua-driver auto-start registration...") - + ps_cmd = (f"$exe = {_ps_single_quote(binary)}; " + "$proc = Start-Process -FilePath $exe -ArgumentList @('autostart','enable') " + "-Verb RunAs -Wait -PassThru -ErrorAction Stop; exit $proc.ExitCode") + _print_info(" Registering cua-driver auto-start..." if verbose + else " Repairing cua-driver auto-start registration...") try: - result = _run_text([ps, "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps_cmd], timeout=300, - env=_cua_driver_env()) + result = _run_text([ps, "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps_cmd], + timeout=300, env=_cua_driver_env()) except subprocess.TimeoutExpired: - _print_warning(" cua-driver autostart registration timed out.") - return False + return _fail(" cua-driver autostart registration timed out.") except Exception as exc: - _print_warning(f" cua-driver autostart registration failed: {exc}") - return False - + return _fail(f" cua-driver autostart registration failed: {exc}") if result.returncode == 0: return True - _print_warning(" cua-driver autostart registration failed.") - for line in (result.stderr or result.stdout or "").strip().splitlines()[-3:]: - _print_info(f" {line[:200]}") + _print_output_tail(result) _print_info(" From an elevated shell, run: cua-driver autostart enable") return False def _remove_quietly(path: str) -> None: - try: + with contextlib.suppress(OSError): os.remove(path) - except OSError: - pass - - -_MAC_PERMISSION_PATHS = ( - " System Settings > Privacy & Security > Accessibility", - " System Settings > Privacy & Security > Screen Recording") def _print_cua_platform_notes(is_windows: bool, is_linux: bool, *, fresh_install: bool) -> None: @@ -594,8 +543,8 @@ def _print_cua_platform_notes(is_windows: bool, is_linux: bool, *, fresh_install else: _print_info(" IMPORTANT — grant macOS permissions now:" if fresh_install else " Grant macOS permissions if not done yet:") - for line in _MAC_PERMISSION_PATHS: - _print_info(line) + _print_info(" System Settings > Privacy & Security > Accessibility") + _print_info(" System Settings > Privacy & Security > Screen Recording") if fresh_install: _print_info(" Both must allow the terminal / Hermes process.") @@ -605,23 +554,22 @@ def _kill_installer_tree(proc, *, is_windows: bool) -> None: import signal as _signal try: if not is_windows: - os.killpg(os.getpgid(proc.pid), _signal.SIGKILL) # windows-footgun: ok — POSIX branch only + os.killpg(os.getpgid(proc.pid), _signal.SIGKILL) # windows-footgun: ok — POSIX only return - # PowerShell may leave download/install helpers alive after its direct process is killed. They - # inherit stdout and can keep communicate() and install.lock wedged, so kill the tree leaf-up. + # PowerShell may leave download/install helpers alive after its direct process is killed; + # they inherit stdout and can keep communicate() and install.lock wedged → kill leaf-up. import psutil as _psutil - try: parent = _psutil.Process(proc.pid) descendants = parent.children(recursive=True) except _psutil.NoSuchProcess: return except _psutil.Error as e: - logger.debug("could not enumerate cua-driver installer tree for pid %s: %s", proc.pid, e) + logger.debug("could not enumerate cua-driver installer tree for pid %s: %s", + proc.pid, e) proc.kill() return - - for target, pid in [(child, child.pid) for child in reversed(descendants)] + [(parent, proc.pid)]: + for target, pid in [(c, c.pid) for c in reversed(descendants)] + [(parent, proc.pid)]: try: target.kill() except _psutil.NoSuchProcess: @@ -637,38 +585,37 @@ def _kill_installer_tree(proc, *, is_windows: bool) -> None: def _reap_after_timeout(proc, *, is_windows: bool) -> None: """Kill the installer tree, then drain its pipes under a deadline. - An unbounded drain blocks on an EOF that only arrives when someone kills a surviving descendant by - hand, so ``_CUA_INSTALLER_TIMEOUT`` would stop bounding anything.""" + An unbounded drain blocks on an EOF that only arrives when someone kills a surviving descendant + by hand, so ``_CUA_INSTALLER_TIMEOUT`` would stop bounding anything.""" _kill_installer_tree(proc, is_windows=is_windows) try: drained_out, _ = proc.communicate(timeout=_CUA_INSTALLER_DRAIN_GRACE) - # The partial output names WHERE the installer was stuck (lock wait, consent prompt, download). + # Partial output names WHERE the installer was stuck (lock wait, consent prompt, download). if drained_out: - logger.warning("cua-driver installer timed out; last output before kill:\n%s", drained_out[-2000:]) + logger.warning("cua-driver installer timed out; last output before kill:\n%s", + drained_out[-2000:]) except subprocess.TimeoutExpired: - # Deliberately not closing proc.stdout: communicate()'s reader threads are still blocked on that - # handle and closing it underneath them races; they are daemon threads. - logger.debug( - "cua-driver installer pipes still open %ss after the kill — " - "abandoning the drain, a surviving descendant holds the inherited handle", - _CUA_INSTALLER_DRAIN_GRACE) + # Deliberately not closing proc.stdout: communicate()'s reader threads are still blocked on + # that handle and closing it underneath them races; they are daemon threads. + logger.debug("cua-driver installer pipes still open %ss after the kill — " + "abandoning the drain, a surviving descendant holds the inherited handle", + _CUA_INSTALLER_DRAIN_GRACE) except (OSError, ValueError) as e: logger.debug("cua-driver installer drain failed: %s", e) def _cua_installer_command(is_windows: bool): - """Return ``(install_cmd, manual_hint, script_path)`` or None when the POSIX download fails.""" + """Return ``(install_cmd, manual_hint, script_path)``; all None if the POSIX download fails.""" if is_windows: - # Mirror the one-liner printed by cua_driver_install_hint(). - ps_oneliner = f"irm {_CUA_INSTALL_PS1_URL} | iex" - install_cmd = ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps_oneliner] - return install_cmd, f'powershell -NoProfile -ExecutionPolicy Bypass -Command "{ps_oneliner}"', None + ps_oneliner = f"irm {_CUA_INSTALL_PS1_URL} | iex" # mirrors cua_driver_install_hint() + return (["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps_oneliner], + f'powershell -NoProfile -ExecutionPolicy Bypass -Command "{ps_oneliner}"', None) - # Download-then-exec instead of `bash -c "$(curl …)"`: no shell=True, no command substitution, and the - # script lands in a mkstemp file (unpredictable name, 0600) rather than a fixed /tmp path — avoiding - # both shell injection and a symlink/TOCTOU race. The manual hint stays the upstream one-liner. + # Download-then-exec instead of `bash -c "$(curl …)"`: no shell=True, no command substitution, + # and the script lands in a mkstemp file (unpredictable name, 0600) rather than a fixed /tmp + # path — avoiding both shell injection and a symlink/TOCTOU race. The manual hint stays the + # upstream one-liner. import tempfile as _tempfile - manual_hint = f'/bin/bash -c "$(curl -fsSL {_CUA_INSTALL_SH_URL})"' fd, script_path = _tempfile.mkstemp(prefix="cua-driver-install-", suffix=".sh") os.close(fd) @@ -680,66 +627,93 @@ def _cua_installer_command(is_windows: bool): if failure is not None: _print_warning(f" cua-driver installer download failed: {failure}") _remove_quietly(script_path) - return None + return None, None, None return ["/bin/bash", script_path], manual_hint, script_path def _unattended_installer_preflight(install_cmd: list, is_windows: bool): - """Fail FAST on the two conditions that otherwise consume the whole unattended ceiling. - 1. Install lock held by a live process — upstream would poll it for up to - LOCK_STALE_AFTER_SECONDS=600 before probing the holder (the 11-minute silent hang class). - 2. Release host unreachable — the installer would die slowly inside its own retries; a 5s HEAD - answers. Returns the (possibly rewritten) install command, or None to skip this refresh. Explicit - `computer-use install --upgrade` runs never come here and keep upstream's full lock-recovery.""" + """Fail FAST on the two conditions that otherwise consume the whole unattended ceiling: + (1) install lock held by a live process — upstream would poll it for up to + LOCK_STALE_AFTER_SECONDS=600 before probing the holder (the 11-minute silent hang class); + (2) release host unreachable — the installer dies slowly inside its own retries; a 5s HEAD + answers. Returns the (possibly rewritten) install command, or None to skip this refresh. + Explicit `install --upgrade` runs never come here and keep upstream's full lock-recovery.""" if _cua_install_lock_held(): - _print_info(" Another cua-driver install is in progress (upstream install lock is held) — skipping this refresh.") - _print_info(f" If no install is really running, retry with: {_UPGRADE_CMD}") + _fail(" Another cua-driver install is in progress (upstream install lock is held) — " + "skipping this refresh.", + f" If no install is really running, retry with: {_UPGRADE_CMD}", warn=False) return None if not _cua_release_endpoint_reachable(): - _print_info(" github.com is unreachable — skipping cua-driver refresh (will retry on the next update).") + _print_info(" github.com is unreachable — skipping cua-driver refresh " + "(will retry on the next update).") return None if is_windows: - # -NoAutoStart skips Register-CuaDriverAutostart — the ONLY branch of install.ps1 that self-elevates - # (UAC). Cost: an existing cua-driver-serve task keeps pointing at the previous binary until the - # next interactive upgrade. Scriptblock invocation (not `| iex`) is what lets us pass the parameter. + # -NoAutoStart skips Register-CuaDriverAutostart — the ONLY branch of install.ps1 that + # self-elevates (UAC). Cost: an existing cua-driver-serve task keeps pointing at the + # previous binary until the next interactive upgrade. Scriptblock invocation (not `| iex`) + # is what lets us pass the parameter. install_cmd = [ - "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", - "-Command", f"$sc = irm {_CUA_INSTALL_PS1_URL}; & ([scriptblock]::Create($sc)) -NoAutoStart", - ] + "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", + f"$sc = irm {_CUA_INSTALL_PS1_URL}; & ([scriptblock]::Create($sc)) -NoAutoStart"] return install_cmd -def _run_cua_driver_installer( - label: str = "Installing", verbose: bool = True, pin_version: Optional[str] = None, show_progress: bool = True, - installer_timeout: Optional[float] = None) -> bool: - """Run the upstream cua-driver installer for this platform. - The scripts are idempotent: they always download the latest release, so re-running on an - already-installed system performs an upgrade. ``installer_timeout`` lets quiet callers use a shorter - ceiling without weakening the explicit install path's stale-lock recovery window.""" - import platform as _plat +def _installer_popen_kwargs(is_windows: bool, verbose: bool, env: dict) -> dict: + """Popen kwargs for the upstream installer. + POSIX: own process group so a timeout kill takes out the whole `curl | bash` pipeline (and the + exec'd _install-rust.sh), not just the outer shell — surviving grandchildren would keep + holding the install lock and wedge every later run. Non-verbose (`hermes update` refresh): + capture the chatty "Next steps" wall and log it so a failure stays debuggable; verbose + interactive installs stream live.""" + kwargs: dict = {"shell": False, "env": env} + if not is_windows: + kwargs["start_new_session"] = True + if verbose: + kwargs["creationflags"] = _post_setup_no_window_flags(streams_to_console=True) + else: + kwargs.update(stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, encoding="utf-8", errors="replace", + creationflags=_post_setup_no_window_flags()) + return kwargs - system = _plat.system() - is_windows = system == "Windows" - is_linux = system == "Linux" - prepared = _cua_installer_command(is_windows) - if prepared is None: +def _record_installer_output(out: str, returncode: int) -> None: + """Keep a captured (non-verbose) installer transcript without echoing it to the terminal. + During `hermes update`, sys.stdout is the mirroring _UpdateOutputStream whose `_log` handle is + ~/.hermes/logs/update.log — write straight to it so the full output is kept (success AND + failure).""" + _update_log = getattr(sys.stdout, "_log", None) + if _update_log is not None: + try: + _update_log.write("\n--- cua-driver installer output ---\n" + out + "\n") + _update_log.flush() + except Exception: + pass + if returncode != 0: + logger.debug("cua-driver installer output:\n%s", out) + + +def _run_cua_driver_installer(label: str = "Installing", verbose: bool = True, + pin_version: Optional[str] = None, show_progress: bool = True, + installer_timeout: Optional[float] = None) -> bool: + """Run the upstream cua-driver installer (idempotent: always the latest release, so re-running + upgrades). ``installer_timeout`` lets quiet callers use a shorter ceiling without weakening the + explicit install path's stale-lock recovery window.""" + system = platform.system() + is_windows, is_linux = system == "Windows", system == "Linux" + install_cmd, manual_hint, script_path = _cua_installer_command(is_windows) + if install_cmd is None: return False - install_cmd, manual_hint, script_path = prepared - if show_progress: _print_info(f" {label} cua-driver (background computer-use)..." if verbose else f"→ {label} cua-driver (Computer Use)...") driver_cmd = _cua_driver_cmd() timeout = _CUA_INSTALLER_TIMEOUT if installer_timeout is None else installer_timeout - installer_env = _cua_driver_env() - if pin_version: - # Both upstream installers honour CUA_DRIVER_RS_VERSION over their baked default. + if pin_version: # both upstream installers honour CUA_DRIVER_RS_VERSION over the baked default installer_env["CUA_DRIVER_RS_VERSION"] = pin_version - - # A previous timed-out install can leave upstream's concurrent-install lock behind; clear it when - # provably stale so the refresh doesn't wedge waiting on a dead holder. + # A previous timed-out install can leave upstream's concurrent-install lock behind; clear it + # when provably stale so the refresh doesn't wedge waiting on a dead holder. _clear_stale_cua_install_lock() # Unattended refreshes (installer_timeout set by `hermes update`) preflight and may skip. @@ -747,23 +721,7 @@ def _run_cua_driver_installer( install_cmd = _unattended_installer_preflight(install_cmd, is_windows) if install_cmd is None: return False - - # POSIX: own process group so a timeout kill takes out the whole `curl | bash` pipeline (and the exec'd - # _install-rust.sh), not just the outer shell — surviving grandchildren would keep holding the install - # lock and wedge every later run. - popen_kwargs: dict = {"shell": False, "env": installer_env} - if not is_windows: - popen_kwargs["start_new_session"] = True - # Non-verbose (`hermes update` refresh): capture the installer's chatty "Next steps" wall and log it - # so a failure stays debuggable. Verbose interactive installs stream live. - if verbose: - popen_kwargs["creationflags"] = _post_setup_no_window_flags(streams_to_console=True) - else: - popen_kwargs.update( - stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - text=True, encoding="utf-8", errors="replace", creationflags=_post_setup_no_window_flags(), - ) - + popen_kwargs = _installer_popen_kwargs(is_windows, verbose, installer_env) try: proc = subprocess.Popen(install_cmd, **popen_kwargs) try: @@ -772,40 +730,28 @@ def _run_cua_driver_installer( _reap_after_timeout(proc, is_windows=is_windows) raise out = None if verbose else communicated[0] - result = subprocess.CompletedProcess(install_cmd, proc.returncode, stdout=out, stderr=None) - if not verbose and result.stdout: - # During `hermes update`, sys.stdout is the mirroring _UpdateOutputStream whose `_log` handle is - # ~/.hermes/logs/update.log — write straight to it so the full installer output is kept - # (success AND failure) without echoing it to the terminal. - _update_log = getattr(sys.stdout, "_log", None) - if _update_log is not None: - try: - _update_log.write("\n--- cua-driver installer output ---\n" + result.stdout + "\n") - _update_log.flush() - except Exception: - pass - if result.returncode != 0: - logger.debug("cua-driver installer output:\n%s", result.stdout) + if out: + _record_installer_output(out, proc.returncode) installed_binary = _resolved_cua_driver_cmd() - if result.returncode == 0 and installed_binary: - if is_windows and not _repair_cua_driver_autostart_windows(installed_binary, verbose=verbose): + if proc.returncode == 0 and installed_binary: + if is_windows and not _repair_cua_driver_autostart_windows(installed_binary, + verbose=verbose): _print_warning(" cua-driver installed, but auto-start was not registered.") if verbose: _print_success(f" {driver_cmd} installed.") _print_cua_platform_notes(is_windows, is_linux, fresh_install=True) return True - _print_warning(f" cua-driver {label.lower()} did not complete. Re-run manually:") - _print_info(f" {manual_hint}") - return False + return _fail(f" cua-driver {label.lower()} did not complete. Re-run manually:", + f" {manual_hint}") except subprocess.TimeoutExpired: _print_warning(f" cua-driver {label.lower()} timed out after {timeout}s.") if not is_windows: - _print_info(f" If this repeats, a stale installer lock may be present — check {_cua_install_lock_dir()}") + _print_info(" If this repeats, a stale installer lock may be present — check " + f"{_cua_install_lock_dir()}") _print_info(f" Re-run manually: {manual_hint}") return False except Exception as e: - _print_warning(f" cua-driver {label.lower()} failed: {e}") - return False + return _fail(f" cua-driver {label.lower()} failed: {e}") finally: if script_path: _remove_quietly(script_path) diff --git a/hermes_cli/tools_config_providers.py b/hermes_cli/tools_config_providers.py index c5875f1e32..bf7f524f10 100644 --- a/hermes_cli/tools_config_providers.py +++ b/hermes_cli/tools_config_providers.py @@ -277,7 +277,7 @@ def _configure_tool_category(ts_key: str, cat: dict, config: dict, *, force_fres try: _nous_logged_in = bool(get_nous_subscription_features(config, force_fresh=force_fresh).nous_auth_present) except Exception: - _nous_logged_in = False + pass provider_choices = [] # plain text labels only (no ANSI codes in menu items) for p in providers: @@ -349,8 +349,7 @@ def _managed_provider_active(provider: dict, config: dict, managed_feature: str, provider must be the row's vendor or ``nous``.""" from hermes_cli.tools_config import get_nous_subscription_features - features = get_nous_subscription_features(config, force_fresh=force_fresh) - feature = features.features.get(managed_feature) + feature = get_nous_subscription_features(config, force_fresh=force_fresh).features.get(managed_feature) if feature is None: return False if managed_feature in ("image_gen", "video_gen"): @@ -644,8 +643,7 @@ def _configure_stt_model(stt_provider: str, config: dict) -> None: model_key = _STT_MODEL_CONFIG_KEY.get(stt_provider, "model") current = str(prov_cfg.get(model_key) or "").strip() ordered = list(catalog) - default_idx = ordered.index(current) if current in ordered else 0 - chosen = ordered[_prompt_choice(" Select STT model:", ordered, default_idx)] + chosen = ordered[_prompt_choice(" Select STT model:", ordered, ordered.index(current) if current in ordered else 0)] prov_cfg[model_key] = chosen _print_success(f" STT model set to: {chosen}") @@ -846,9 +844,9 @@ def _prompt_secret( if url: _print_info(f" {url_label}: {url}") if reconfigure: - value = _prompt(f" {label} (Enter to keep current)", password=not default_val) - if value and value.strip(): - save_env_value(key, value.strip()) + value = (_prompt(f" {label} (Enter to keep current)", password=not default_val) or "").strip() + if value: + save_env_value(key, value) _print_success(" Updated") else: _print_info(" Kept current") @@ -1002,15 +1000,12 @@ def _configure_vision_provider_model(config: dict, vision_cfg: dict) -> None: providers = [] if not providers: - _print_warning( - " No authenticated providers found. Configure a provider first " - "with `hermes model`, then re-run this.") + _print_warning(" No authenticated providers found. Configure a provider first " + "with `hermes model`, then re-run this.") return provider_labels = [label for _slug, label, _models in format_aux_picker_entries( - providers, current_provider=current_provider, current_base_url=current_base_url)] - provider_labels.append("Cancel") - + providers, current_provider=current_provider, current_base_url=current_base_url)] + ["Cancel"] pidx = _prompt_choice(" Choose vision provider:", provider_labels, 0) if pidx >= len(providers): _print_info(" Cancelled") @@ -1019,8 +1014,7 @@ def _configure_vision_provider_model(config: dict, vision_cfg: dict) -> None: chosen = providers[pidx] slug = chosen.get("slug") models = list(chosen.get("models", [])) - model_choices = list(models) + ["Type a custom model id…"] - midx = _prompt_choice(f" Choose vision model for {chosen.get('name') or slug}:", model_choices, 0) + midx = _prompt_choice(f" Choose vision model for {chosen.get('name') or slug}:", models + ["Type a custom model id…"], 0) if midx < len(models): model = models[midx] else: