The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): AST-neutral string-literal joins and import-blank squeeze in update_cmd*/uninstall
Tekniuma8e8db4fc5b0
diff --git a/hermes_cli/uninstall.py b/hermes_cli/uninstall.pyindex c0330cadfc4..faf0ebd7f89 100644--- a/hermes_cli/uninstall.py+++ b/hermes_cli/uninstall.py@@ -105,7 +105,6 @@ def remove_path_from_shell_configs():new_content = _strip_hermes_path_lines(content)if new_content != content:from utils import atomic_write_text-# This is the user's own shell rc, not a Hermes-owned file, and nothing here backs# it up. A bare write_text() truncates it before the new content lands, so a crash# or SIGINT mid-write leaves an empty/truncated ~/.zshrc -- and the enclosing@@ -387,7 +386,6 @@ def remove_windows_bin_launchers(*, windows: bool | None = None) -> list[Path]:# startup heal stage into this dir.from hermes_cli._install_repair import _WINDOWS_BIN_LAUNCHERSfrom hermes_constants import get_default_hermes_root-bin_dir = get_default_hermes_root() / "bin"except Exception as e:log_warn(f"Could not locate the managed binary dir: {e}")@@ -449,8 +447,7 @@ def _uninstall_profile(profile) -> None:try:subprocess.run(hermes_invocation + ["gateway", subcmd], capture_output=True, text=True,- encoding='utf-8', errors='replace', timeout=60, check=False,- )+ encoding='utf-8', errors='replace', timeout=60, check=False)except subprocess.TimeoutExpired:log_warn(f" Gateway {subcmd} timed out for '{name}'")except Exception as e:@@ -628,8 +625,7 @@ def run_uninstall(args):_perform_uninstall(project_root=project_root, hermes_home=hermes_home, full_uninstall=full_uninstall,- remove_profiles=remove_profiles, named_profiles=named_profiles,- )+ remove_profiles=remove_profiles, named_profiles=named_profiles)def _print_uninstall_dry_run(*, project_root: Path, hermes_home: Path, full_uninstall: bool) -> None:@@ -788,15 +784,13 @@ def _perform_uninstall(_REINSTALL_HINT = {True: " iex (irm https://hermes-agent.nousresearch.com/install.ps1)",- False: " curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",-}+ False: " curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash"}# windows -> [(line, color or None)]_RELOAD_HINT = {True: [("Open a new terminal (PowerShell / Windows Terminal) to pick up", Colors.YELLOW),("the updated User PATH and environment variables.", Colors.YELLOW)],False: [("Reload your shell to complete the process:", Colors.YELLOW),- (" source ~/.bashrc # or ~/.zshrc", None)],-}+ (" source ~/.bashrc # or ~/.zshrc", None)]}class _UninstallArgs:@@ -817,12 +811,10 @@ def main(argv=None) -> int:from the venv."""import argparse-parser = argparse.ArgumentParser(prog="python -m hermes_cli.uninstall")parser.add_argument("--mode", choices=["gui", "lite", "full"], required=True,- help="gui = Chat GUI only; lite = GUI + agent, keep data; full = everything",- )+ help="gui = Chat GUI only; lite = GUI + agent, keep data; full = everything")args = _UninstallArgs(mode=parser.parse_args(argv).mode)(run_gui_uninstall if args.gui else run_uninstall)(args)return 0diff --git a/hermes_cli/update_abort_recovery.py b/hermes_cli/update_abort_recovery.pyindex 782537a720e..cf035495384 100644--- a/hermes_cli/update_abort_recovery.py+++ b/hermes_cli/update_abort_recovery.py@@ -59,7 +59,6 @@ def _surviving_pre_update_serve_runtimes(plan) -> list[dict]:return []try:from hermes_cli.process_identity import ledger_entries-live: dict[int, float | None] = {entry["pid"]: _numeric(entry.get("create_time"))for entry in ledger_entries()@@ -123,7 +122,6 @@ def _recover_gateway_restart_after_abort(Only profiles classified as supervisor-owned by the pre-update inventory are handed off."""from hermes_cli.update_cmd import _gateway_recovery_partition-candidates, skipped = _gateway_recovery_partition(plan, skip_profiles=skip_profiles)profiles = sorted(candidates)recover_serve = _serve_unit_recovery_available()diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 6f3ffd41743..17bde3c9981 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -120,14 +120,12 @@ logger = logging.getLogger(__name__)def _m():"""Lazy ``hermes_cli.main`` handle: keeps main-side test patches effective, import one-way."""from hermes_cli import main-return maindef _updates_config() -> dict:"""The ``updates:`` config section (``{}`` when absent/malformed); may raise on config errors."""from hermes_cli.config import load_config-section = (load_config() or {}).get("updates", {})return section if isinstance(section, dict) else {}@@ -147,15 +145,13 @@ def _no_prompt_git_kwargs() -> dict:_UPDATE_CRITICAL_FILES = ("hermes_cli/main.py", "hermes_cli/config.py", "hermes_cli/__init__.py","hermes_cli/web_server.py", "cli.py", "run_agent.py", "model_tools.py", "toolsets.py",- "hermes_constants.py",-)+ "hermes_constants.py")def _record_update_step(step: str, ok: bool, detail: str = "") -> None:"""Best-effort ``update_receipt.record_step``; the receipt must never break an update."""with suppress(Exception):from hermes_cli.update_receipt import record_step-record_step(step, ok, detail)@@ -165,8 +161,7 @@ def _git_run(git_cmd, args, cwd=None, *, check=False, network=False):return subprocess.run(git_cmd + args, cwd=_m().PROJECT_ROOT if cwd is None else cwd, capture_output=True,text=True, encoding="utf-8", errors="replace", check=check,- **(_no_prompt_git_kwargs() if network else {}),- )+ **(_no_prompt_git_kwargs() if network else {}))def _capture_head_sha(git_cmd, cwd) -> str | None:@@ -183,7 +178,6 @@ def _validate_python_files_syntax("""Compile *relpaths* under *root* without writing bytecode into the tree."""import py_compileimport tempfile-root = Path(root)with tempfile.TemporaryDirectory(prefix="hermes-syntax-check-") as tmpdir:for relpath in relpaths:@@ -216,7 +210,6 @@ def _gateway_prompt(prompt_text: str, default: str = "", timeout: float = 300.0)import json as _jsonimport uuid as _uuidfrom hermes_constants import get_hermes_home # noqa: F811 (deliberate: constants variant)-home = get_hermes_home()prompt_path = home / ".update_prompt.json"response_path = home / ".update_response"@@ -393,20 +386,17 @@ def _format_concurrent_instances_message(""," Close Hermes Desktop, exit any open `hermes` REPLs, and"," stop the gateway (`hermes gateway stop`) before retrying.",- "",- ]+ ""]if matches:pid_args = " ".join(f"/PID {pid}" for pid, _ in matches)lines += [" If you've already closed everything and these PIDs are"," stale, terminate them directly, then retry the update:",f" taskkill {pid_args} /F",- "",- ]+ ""]lines += [" Override with `hermes update --force` if you've already",- " confirmed those processes will not write to the venv.",- ]+ " confirmed those processes will not write to the venv."]return "\n".join(lines)@@ -429,7 +419,6 @@ def _classify_concurrent_instance(pid: int) -> str:return "unknown"from hermes_cli._scan_venv_blockers import _is_pausable_gateway # noqa: PLC0415-return "gateway" if _is_pausable_gateway(" ".join(cmdline_list or [])) else "non-gateway"@@ -459,8 +448,7 @@ def _run_logged_subprocess(cmd, *, cwd=None, env=None):``CompletedProcess`` so the caller can surface the output on failure."""result = subprocess.run(cmd, cwd=cwd, env=env, check=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,- text=True, encoding="utf-8", errors="replace",- )+ text=True, encoding="utf-8", errors="replace")_log_only_write(result.stdout or "")return result@@ -491,7 +479,6 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):# Interrupted fetches leave .git/*.lock behind ("File exists" forever); self-heal first.from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs-cleared = clear_stale_git_locks(_m().PROJECT_ROOT)for lock_path in cleared:print(f" (removed stale git lock: {lock_path})")@@ -540,7 +527,6 @@ def _cmd_update_check(branch: str = "main", *, branch_explicit: bool = False):print("✓ Already up to date.")returnfrom hermes_cli.banner import _github_compare_behind-# counted == 0 means local-ahead, not behind; None means the API could not count._print_update_check_result(_github_compare_behind(head_sha, target_sha), compare_branch)return@@ -560,7 +546,6 @@ def _print_update_check_result(behind: int | None, compare_branch: str) -> None:else:print(f"⚕ Update available (behind {compare_branch}).")from hermes_cli.config import recommended_update_command-print(f" Run '{recommended_update_command()}' to install.")@@ -580,7 +565,6 @@ def _repair_current_checkout(# "No new commits" != safe interpreter: uv can keep the same CPython patch while# python-build-standalone refreshes the embedded SQLite; keep the boundary hook here too.from hermes_cli.managed_uv import ensure_uv, update_managed_uv-runtime_repairs = []update_managed_uv(repair_observer=runtime_repairs.append)ensure_uv(repair_observer=runtime_repairs.append)@@ -604,7 +588,6 @@ def _repair_current_checkout(_m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)_write_update_incomplete_marker()from hermes_cli.managed_uv import ensure_uv-repair_uv = ensure_uv()# Venv gone entirely (repair interrupted after the old one was moved aside): recreate.venv_python_missing = not (@@ -615,7 +598,6 @@ def _repair_current_checkout(if repair_uv:# Isolated from third-party UV env vars, like the other dependency syncs.from hermes_cli.managed_uv import managed_python_env-repair_prefix, repair_env = [repair_uv, "pip"], managed_python_env()repair_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")else:@@ -698,7 +680,6 @@ def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha) -> None:has_common_ancestor = merge_base_result.returncode == 0 and merge_base_result.stdout.strip()if not has_common_ancestor and pre_pull_sha:from datetime import datetime as _dt, timezone-# SHA suffix so two updates in the same second get distinct refs.rescue_ref = (f"refs/hermes-update-backups/orphan-{branch}-"@@ -936,7 +917,6 @@ def _prepare_checkout_for_update(_git_run(git_cmd, ["rev-parse", "--is-shallow-repository"]).stdout.strip() == "true")if commit_count > 0 and apply_is_shallow:from hermes_cli.banner import _github_compare_behind-head_sha = _git_run(git_cmd, ["rev-parse", "HEAD"]).stdout.strip()target_sha = _git_run(git_cmd, ["rev-parse", f"origin/{branch}"]).stdout.strip()counted = _github_compare_behind(head_sha, target_sha)@@ -961,8 +941,7 @@ def _prepare_checkout_for_update(return _CheckoutPlan(auto_stash_ref=auto_stash_ref, commit_count=commit_count, in_place_update=in_place_update,parked_branch_switched=parked_branch_switched, prompt_for_restore=prompt_for_restore,- switch_block_reason=switch_block_reason, upstream_checked=upstream_checked,- )+ switch_block_reason=switch_block_reason, upstream_checked=upstream_checked)@dataclass@@ -1012,8 +991,7 @@ def _resolve_update_options(args, gateway_mode: bool) -> _UpdateOptions:active_lazy_features=active_lazy_features,active_tool_dependencies=active_tool_dependencies, pre_update_version=pre_update_version,gw_input_fn=gw_input_fn, assume_yes=assume_yes, keep_stash=keep_stash,- switch_branch=switch_branch, discard_local_changes=discard_local_changes,- )+ switch_branch=switch_branch, discard_local_changes=discard_local_changes)def _begin_update_receipt_and_plan(args):@@ -1023,7 +1001,6 @@ def _begin_update_receipt_and_plan(args):# Structured receipt: record what this run discovers/does/skips so silent failures are diagnosable.with _best_effort('Update receipt unavailable: %s'):from hermes_cli.update_receipt import begin_update_receipt-begin_update_receipt()# Plan phase: snapshot runtimes/supervisors/version (read-only; probe failure records@@ -1148,8 +1125,7 @@ def _handle_update_called_process_error(if _called_process_error_is_python_dep_install(e):print(" The git update already finished. Re-downloading the source "- "ZIP cannot fix a dependency install error and would overwrite "- "local files.")+ "ZIP cannot fix a dependency install error and would overwrite local files.")if _m()._is_windows():print(" Retry through the venv interpreter:")print(@@ -1157,7 +1133,6 @@ def _handle_update_called_process_error('"from hermes_cli.main import main; main()" update --yes')with suppress(Exception):from hermes_cli.update_receipt import finalize_update_receipt-finalize_update_receipt("failed")sys.exit(1)@@ -1217,7 +1192,6 @@ def _finish_already_up_to_date(_write_gateway_update_exit_code(False)with _best_effort('Update receipt finalize (current checkout) failed: %s'):from hermes_cli.update_receipt import finalize_update_receipt-finalize_update_receipt("partial")sys.exit(1)@@ -1246,7 +1220,6 @@ def _cmd_update_impl(args, gateway_mode: bool):_windows_gateway_resume = _m()._pause_windows_gateways_for_update()if _windows_gateway_resume:import atexit as _atexit-_atexit.register(_m()._resume_windows_gateways_after_update, _windows_gateway_resume)# Any venv python still running (typically the Desktop `hermes serve` backend) keeps .pyd@@ -1282,7 +1255,6 @@ def _cmd_update_impl(args, gateway_mode: bool):# Self-heal abandoned .git/*.lock files (crashed fetch) or the fetch fails "File exists".from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packs-cleared = clear_stale_git_locks(_m().PROJECT_ROOT)if cleared:print(" (removed stale git lock(s): %s)" % ", ".join(cleared))@@ -1317,8 +1289,7 @@ def _cmd_update_impl(args, gateway_mode: bool):had_desktop_app_before_update=had_desktop_app_before_update,active_lazy_features=active_lazy_features,active_tool_dependencies=active_tool_dependencies,- _windows_gateway_resume=_windows_gateway_resume,- )+ _windows_gateway_resume=_windows_gateway_resume)returnif commit_count > 0:@@ -1356,8 +1327,7 @@ def _cmd_update_impl(args, gateway_mode: bool):_sync_python_dependencies_after_pull(git_cmd, branch, pre_pull_sha, active_lazy_features=active_lazy_features,active_tool_dependencies=active_tool_dependencies,- _windows_gateway_resume=_windows_gateway_resume,- )+ _windows_gateway_resume=_windows_gateway_resume)node_failures = _update_node_dependencies()_m()._build_web_ui(_m().PROJECT_ROOT / "web")@@ -1386,8 +1356,7 @@ def _cmd_update_impl(args, gateway_mode: bool):_verify_fleet_after_update(_restart, _pre_update_plan=_pre_update_plan,_windows_gateway_resume=_windows_gateway_resume, node_failures=node_failures,- update_complete=update_complete,- )+ update_complete=update_complete)except _shim_quarantine_error_type() as e:# Strict quarantine refused BEFORE any installer ran — defer via marker, exit 2, no ZIP.diff --git a/hermes_cli/update_cmd_config.py b/hermes_cli/update_cmd_config.pyindex ab27f88ac2c..cead271daec 100644--- a/hermes_cli/update_cmd_config.py+++ b/hermes_cli/update_cmd_config.py@@ -24,7 +24,6 @@ def _reload_config_modules() -> None:cleanup sees symbols the update added instead of dying with ImportError."""import importlib-importlib.invalidate_caches()for mod_name in ("hermes_cli.config_defaults",@@ -45,7 +44,6 @@ def _run_config_check_fresh() -> tuple:from hermes_cli.update_cmd import _reload_config_modules_reload_config_modules()from hermes_cli.config import check_config_version-return check_config_version()@@ -54,7 +52,6 @@ def _run_migrate_config_fresh(*, interactive: bool = False, quiet: bool = False)from hermes_cli.update_cmd import _reload_config_modules_reload_config_modules()from hermes_cli.config import migrate_config-return migrate_config(interactive=interactive, quiet=quiet)@@ -75,7 +72,6 @@ def _migrate_sibling_profile_configs() -> list[tuple[str, int, int]]:from hermes_constants import (get_process_hermes_home, reset_hermes_home_override, set_hermes_home_override)from hermes_cli.profiles import _get_profiles_root, _PROFILE_ID_RE-active_home = get_process_hermes_home()root = _get_profiles_root()if not root.is_dir():@@ -113,7 +109,6 @@ def _restore_snapshot_safety_nets(pre_update_snapshot_id) -> None:# restore from the pre-update snapshot if jobs went missing.try:from hermes_cli.backup import restore_cron_jobs_if_emptied-cron_restore = restore_cron_jobs_if_emptied(pre_update_snapshot_id)if cron_restore:print()@@ -129,7 +124,6 @@ def _restore_snapshot_safety_nets(pre_update_snapshot_id) -> None:# moa:; restore only those protected keys from the same pre-update snapshot.try:from hermes_cli.backup import restore_config_model_settings_if_rewritten-cfg_restore = restore_config_model_settings_if_rewritten(pre_update_snapshot_id)if cfg_restore:print()@@ -144,7 +138,6 @@ def _restore_snapshot_safety_nets(pre_update_snapshot_id) -> None:# Same cron-jobs safety net per sibling profile against ITS OWN pre-update snapshot.with _best_effort('Sibling cron auto-restore check failed: %s'):from hermes_cli.backup import restore_cron_jobs_all_profiles-for _restored in restore_cron_jobs_all_profiles(_LAST_SIBLING_SNAPSHOTS):print()@@ -157,7 +150,6 @@ def _restore_snapshot_safety_nets(pre_update_snapshot_id) -> None:# Same config model-settings safety net for sibling profiles.with _best_effort('Sibling config auto-restore check failed: %s'):from hermes_cli.backup import restore_config_model_settings_all_profiles-for _cfg_restored in restore_config_model_settings_all_profiles(_LAST_SIBLING_SNAPSHOTS):print()diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex eef2c4232d2..6f1b82e0b44 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -67,7 +67,6 @@ def _critical_module_import_failures(from hermes_constants import FIRST_PARTY_MODULE_ROOTSimport secrets-marker = f"__HERMES_IMPORT_HEALTH_{secrets.token_hex(16)}__"probe = ("import importlib, json, sys\n"@@ -103,8 +102,7 @@ def _critical_module_import_failures(interpreter = str(venv_python)result = subprocess.run([interpreter, "-c", probe], cwd=str(root), capture_output=True, text=True,- encoding="utf-8", errors="replace", timeout=120,- )+ encoding="utf-8", errors="replace", timeout=120)except subprocess.TimeoutExpired:return _probe_failure("TimeoutExpired", "timed out before reporting import health")except (OSError, subprocess.SubprocessError):@@ -197,7 +195,6 @@ def _capture_active_lazy_features() -> list[str]:"""Snapshot active lazy backends before a managed runtime is replaced."""try:from tools import lazy_deps-return lazy_deps.active_features()except Exception as exc:logger.debug("Could not snapshot active lazy features: %s", exc)@@ -208,7 +205,6 @@ def _capture_active_tool_dependencies() -> list[str]:"""Snapshot Python dependencies installed explicitly through ``hermes tools``."""try:from hermes_cli import tools_config-return tools_config.active_restorable_python_tool_dependencies()except Exception as exc:logger.debug("Could not snapshot active Hermes Tools dependencies: %s", exc)@@ -376,7 +372,6 @@ def _refresh_active_memory_provider_dependencies() -> None:"""try:from hermes_cli.config import load_config-cfg = load_config()except Exception as exc:logger.debug("Memory provider refresh skipped (config load failed): %s", exc)@@ -423,7 +418,6 @@ def _install_psutil_android_compat(import tempfileimport urllib.requestfrom hermes_cli.psutil_android import PSUTIL_URL, prepare_patched_psutil_sdist-with tempfile.TemporaryDirectory() as tmp:tmp_path = Path(tmp)archive = tmp_path / "psutil.tar.gz"@@ -439,7 +433,6 @@ def _ensure_uv_for_termux(pip_cmd: list[str]) -> str | None:PATH uv; else wheel-only ``pip install uv`` so the Rust crate is never source-built."""from hermes_cli.update_cmd import _mfrom hermes_cli.managed_uv import resolve_uv-existing = resolve_uv()if existing:return existing@@ -596,7 +589,6 @@ def _update_node_dependencies() -> list[str]:# Only a Windows npm reachable from WSL: flag loudly — skipping silently leaves# deps stale, running it would corrupt the tree.from hermes_constants import is_wsl-path_npm = shutil.which("npm")if is_wsl() and path_npm and _m()._is_windows_npm_path(path_npm):print("→ Updating Node.js dependencies...")@@ -609,7 +601,6 @@ def _update_node_dependencies() -> list[str]:return []from hermes_constants import get_default_hermes_root-# node_modules is shared by every profile on this checkout: one per-checkout cache.shared_hermes_root = get_default_hermes_root()@@ -644,7 +635,6 @@ def _update_node_dependencies() -> list[str]:"--include-workspace-root"]from hermes_constants import with_hermes_node_path-nixos_env = with_hermes_node_path(_m()._nixos_build_env())# capture_output=False is deliberate: postinstall scripts print download progress and@@ -694,8 +684,7 @@ def _venv_core_imports_healthy() -> tuple[bool, str]:try:result = subprocess.run([str(venv_python), "-c", check], capture_output=True, text=True, encoding="utf-8",- errors="replace", timeout=60, cwd=_m().PROJECT_ROOT,- )+ errors="replace", timeout=60, cwd=_m().PROJECT_ROOT)except Exception as exc:logger.debug("venv health probe failed to run: %s", exc)return True, ""@@ -730,7 +719,6 @@ def _dependency_sync_would_rewrite(dist_name: str) -> bool | None:from hermes_cli.update_cmd import _mtry:from importlib import metadata as _ilmd-installed = _ilmd.version(dist_name)except Exception:return True # not installed → the sync will definitely install it@@ -740,7 +728,6 @@ def _dependency_sync_would_rewrite(dist_name: str) -> bool | None:from packaging.requirements import Requirementfrom packaging.utils import canonicalize_namefrom packaging.version import Version-pyproject = _m().PROJECT_ROOT / "pyproject.toml"data = tomllib.loads(pyproject.read_text(encoding="utf-8"))project = data.get("project") or {}@@ -864,7 +851,6 @@ def _rebuild_desktop_after_update(# rebuild window), then surface the tail. Put Hermes-managed Node on PATH: the desktop# updater chain loses shell PATH customizations, so a bare-PATH child hits `node: not found`.from hermes_constants import with_hermes_node_path-build_env = with_hermes_node_path()build_result = _m()._run_logged_subprocess(desktop_build_cmd, cwd=_m().PROJECT_ROOT, env=build_env)@@ -877,7 +863,6 @@ def _rebuild_desktop_after_update(if tail:print(tail)from hermes_constants import display_hermes_home as _dhh-print(f" Full build log: {_dhh()}/logs/update.log")return Falseprint(" ✓ Desktop app up to date")@@ -1008,7 +993,6 @@ def _sync_python_dependencies_after_pull(else:print("→ Updating Python dependencies...")from hermes_cli.managed_uv import ensure_uv, update_managed_uv-# `uv self update` if we already have a managed uv.update_managed_uv()@@ -1023,7 +1007,6 @@ def _sync_python_dependencies_after_pull(if uv_bin:# managed_python_env() isolation so a third-party UV_PYTHON_INSTALL_DIR can't hijack uv.from hermes_cli.managed_uv import managed_python_env-install_prefix, lazy_env = [uv_bin, "pip"], managed_python_env()lazy_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")termux_note = " → Termux detected: using uv + curated termux-all optional profile..."