The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): table-drive env/argv flag assembly, collapse cache-dir + launch-option ladders
Teknium19c3f9f37f92
diff --git a/hermes_cli/main_dashboard.py b/hermes_cli/main_dashboard.pyindex 78dba581f4f..c36cec43aa8 100644--- a/hermes_cli/main_dashboard.py+++ b/hermes_cli/main_dashboard.py@@ -632,7 +632,8 @@ def _is_electron_packaged_web_dist(path: str) -> bool:return "app.asar" in path.replace("\\", "/")-def _route_named_profile_dashboard(args, _headless_backend: bool, _ssh_owner_nonce: str, _token_file: str) -> None:+def _route_named_profile_dashboard(+ args, _headless_backend: bool, _ssh_owner_nonce: str, _token_file: str) -> None:"""Route a named-profile launch to the single MACHINE dashboard (per-request ``?profile=`` scopingmakes one server per profile pure fragmentation).@@ -681,16 +682,14 @@ def _route_named_profile_dashboard(args, _headless_backend: bool, _ssh_owner_non"--port", str(args.port),"--host", args.host,"--open-profile", _launch_profile]- if _ssh_owner_nonce:- reexec_argv.extend(["--ssh-owner-nonce", _ssh_owner_nonce])- if _token_file:- reexec_argv.extend(["--ssh-session-token-file", _token_file])- if args.no_open:- reexec_argv.append("--no-open")- if getattr(args, "insecure", False):- reexec_argv.append("--insecure")- if getattr(args, "skip_build", False):- reexec_argv.append("--skip-build")+ for enabled, extra in (+ (_ssh_owner_nonce, ["--ssh-owner-nonce", _ssh_owner_nonce]),+ (_token_file, ["--ssh-session-token-file", _token_file]),+ (args.no_open, ["--no-open"]),+ (getattr(args, "insecure", False), ["--insecure"]),+ (getattr(args, "skip_build", False), ["--skip-build"])):+ if enabled:+ reexec_argv.extend(extra)from tools.environments.local import build_subprocess_env# HERMES_HOME is pinned to the machine root below — the factory must not# re-inject a profile home.diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.pyindex 441c8af2a7e..f820cc5b70b 100644--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@ -23,7 +23,8 @@ import time as _time_modfrom pathlib import Pathfrom typing import Optionalfrom hermes_cli.main_tui_launch import _npm_lifecycle_env-from hermes_cli.main_web_build import _hash_source_tree, _nixos_build_env, _stamp_is_current, _write_build_stamp+from hermes_cli.main_web_build import (+ _hash_source_tree, _nixos_build_env, _stamp_is_current, _write_build_stamp)# Log-record parity with the origin module.logger = logging.getLogger("hermes_cli.main")@@ -233,12 +234,17 @@ _PE_MACHINE_TO_NAME = {_PE_MACHINE_ARM64: "ARM64", _PE_MACHINE_AMD64: "AMD64", __MACHINE_ATTRIBUTE_USER_ENABLED = 0x00000001+def _kernel32():+ import ctypes+ return ctypes.WinDLL("kernel32", use_last_error=True)++def _windows_native_machine_from_iswow64() -> Optional[str]:"""IsWow64Process2's OS-native machine, or None. HANDLE types are bound explicitly: ctypes'default ``c_int`` truncates the ``(HANDLE)-1`` pseudo-handle → ``ERROR_INVALID_HANDLE`` on Win64."""import ctypesfrom ctypes import wintypes- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32 = _kernel32()kernel32.GetCurrentProcess.restype = wintypes.HANDLEkernel32.GetCurrentProcess.argtypes = []kernel32.IsWow64Process2.argtypes = [@@ -258,7 +264,7 @@ def _windows_user_runnable_pe_machines() -> Optional[set]:AMD64-on-ARM64 emulation); None when unavailable (pre-Win11 22000) so callers fall back."""import ctypesfrom ctypes import wintypes- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32 = _kernel32()kernel32.GetMachineTypeAttributes.argtypes = [wintypes.USHORT, ctypes.POINTER(ctypes.c_int)]kernel32.GetMachineTypeAttributes.restype = ctypes.c_long@@ -446,24 +452,18 @@ def _electron_download_cache_dirs() -> list[Path]:first): ``unpack-electron`` extracts from a zip here, NOT node_modules, so a corrupt zip poisonsthe build."""home = Path.home()- candidates: list[Path] = []override = os.environ.get("electron_config_cache") or os.environ.get("ELECTRON_CACHE")- if override:- candidates.append(Path(override))+ candidates: list[Optional[str | Path]] = [override]if sys.platform == "darwin":candidates.append(home / "Library" / "Caches" / "electron")elif sys.platform == "win32":local = os.environ.get("LOCALAPPDATA")- if local:- candidates.append(Path(local) / "electron" / "Cache")- candidates.append(home / "AppData" / "Local" / "electron" / "Cache")+ candidates += [Path(local) / "electron" / "Cache" if local else None,+ home / "AppData" / "Local" / "electron" / "Cache"]else:xdg = os.environ.get("XDG_CACHE_HOME")- if xdg:- candidates.append(Path(xdg) / "electron")- candidates.append(home / ".cache" / "electron")-- return list(dict.fromkeys(c.expanduser() for c in candidates))+ candidates += [Path(xdg) / "electron" if xdg else None, home / ".cache" / "electron"]+ return list(dict.fromkeys(Path(c).expanduser() for c in candidates if c))def _purge_electron_build_cache(desktop_dir: Path, release_dir: Optional[Path] = None) -> list[Path]:@@ -1118,6 +1118,8 @@ def _desktop_linux_needs_disable_setuid_sandbox(packaged_executable: Path) -> bo_LINUX_PASSWORD_STORES = frozenset({"gnome-libsecret", "kwallet", "kwallet5", "kwallet6", "basic"})+_GPU_FLAG_WORDS = {**dict.fromkeys(("1", "true", "yes", "on"), "1"), **dict.fromkeys(("0", "false", "no", "off"), "0")}+def _detect_linux_password_store() -> str | None:"""Chromium password-store backend for this Linux session (KDE env → GNOME Keyring socket → D-Bus@@ -1165,23 +1167,18 @@ def _desktop_launch_options() -> tuple[list[str], str, str, str]:elif isinstance(raw_flags, (list, tuple)):flags = [str(f) for f in raw_flags if str(f).strip()]+ def _choice(key: str, allowed) -> str:+ raw = desktop_cfg.get(key, "auto")+ low = raw.strip().lower() if isinstance(raw, str) else ""+ return low if low in allowed else "auto"+raw_gpu = desktop_cfg.get("disable_gpu", "auto")if isinstance(raw_gpu, bool):disable_gpu = "1" if raw_gpu else "0"elif isinstance(raw_gpu, str):- low = raw_gpu.strip().lower()- if low in ("1", "true", "yes", "on"):- disable_gpu = "1"- elif low in ("0", "false", "no", "off"):- disable_gpu = "0"-- raw_store = desktop_cfg.get("password_store", "auto")- if isinstance(raw_store, str) and raw_store.strip().lower() in _LINUX_PASSWORD_STORES:- password_store = raw_store.strip().lower()-- raw_ozone = desktop_cfg.get("ozone_platform_hint", "auto")- if isinstance(raw_ozone, str) and raw_ozone.strip().lower() in ("auto", "x11", "wayland"):- ozone_hint = raw_ozone.strip().lower()+ disable_gpu = _GPU_FLAG_WORDS.get(raw_gpu.strip().lower(), "auto")+ password_store = _choice("password_store", _LINUX_PASSWORD_STORES)+ ozone_hint = _choice("ozone_platform_hint", ("auto", "x11", "wayland"))return flags, disable_gpu, password_store, ozone_hint@@ -1361,16 +1358,14 @@ def _desktop_launch_env(args: argparse.Namespace) -> tuple[dict, list[str]]:from hermes_constants import with_hermes_node_path# with_hermes_node_path() copies os.environ when called with no arg.env = with_hermes_node_path()- if getattr(args, "fake_boot", False):- env["HERMES_DESKTOP_BOOT_FAKE"] = "1"- if getattr(args, "ignore_existing", False):- env["HERMES_DESKTOP_IGNORE_EXISTING"] = "1"+ for attr, key in (+ ("fake_boot", "HERMES_DESKTOP_BOOT_FAKE"), ("ignore_existing", "HERMES_DESKTOP_IGNORE_EXISTING")):+ if getattr(args, attr, False):+ env[key] = "1"if getattr(args, "hermes_root", None):env["HERMES_DESKTOP_HERMES_ROOT"] = str(Path(args.hermes_root).expanduser().resolve())- if getattr(args, "cwd", None):- env["HERMES_DESKTOP_CWD"] = str(Path(args.cwd).expanduser().resolve())- else:- env["HERMES_DESKTOP_CWD"] = os.getcwd()+ cwd = getattr(args, "cwd", None)+ env["HERMES_DESKTOP_CWD"] = str(Path(cwd).expanduser().resolve()) if cwd else os.getcwd()config_electron_flags, config_disable_gpu, config_password_store, config_ozone_hint = (_desktop_launch_options())diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.pyindex 94476eb6ddf..d85b635f071 100644--- a/hermes_cli/main_tui_launch.py+++ b/hermes_cli/main_tui_launch.py@@ -111,7 +111,8 @@ def _child_workspace_dirs(dir: Path):yield child-def _termux_workspace_install_context(dir: Path, *, include_child_workspaces: bool = False) -> tuple[Path, tuple[str, ...]]:+def _termux_workspace_install_context(+ dir: Path, *, include_child_workspaces: bool = False) -> tuple[Path, tuple[str, ...]]:"""Return Termux-only ``(cwd, npm_args)`` for installing deps for *dir* only."""ws_root = _workspace_root(dir)if ws_root == dir:@@ -341,14 +342,9 @@ def _ensure_tui_node() -> None:returnparts = os.environ.get("PATH", "").split(os.pathsep)- extras: list[Path] = []-resolved = (result.stdout or "").strip()- if resolved:- extras.append(Path(resolved).resolve().parent)-- extras.extend([Path(hermes_home) / "node" / "bin", Path.home() / ".local" / "bin"])-+ extras = [Path(resolved).resolve().parent] if resolved else []+ extras += [Path(hermes_home) / "node" / "bin", Path.home() / ".local" / "bin"]for extra in extras:s = str(extra)if extra.is_dir() and s not in parts:@@ -676,7 +672,8 @@ def _setup_tui_worktree() -> dict:# multi-agent box; on a thread so it can't block launch.import threading as _threading- _threading.Thread(target=_maintain_pack_health, args=(repo,), name="pack-maintenance", daemon=True).start()+ _threading.Thread(+ target=_maintain_pack_health, args=(repo,), name="pack-maintenance", daemon=True).start()wt_info = _setup_worktree()except Exception as exc:print(f"✗ Failed to create TUI worktree: {exc}", file=sys.stderr)@@ -705,7 +702,8 @@ def _launch_tui(apply_terminal_config_to_env(env=env)except Exception:logger.debug("Failed to apply terminal config bridge for TUI launch", exc_info=True)- active_session_fd, active_session_file = tempfile.mkstemp(prefix="hermes-tui-active-session-", suffix=".json")+ active_session_fd, active_session_file = tempfile.mkstemp(+ prefix="hermes-tui-active-session-", suffix=".json")os.close(active_session_fd)env["HERMES_TUI_ACTIVE_SESSION_FILE"] = active_session_fileenv.setdefault("NODE_ENV", "development" if tui_dev else "production")@@ -718,20 +716,15 @@ def _launch_tui(_apply_tui_python_env(env)- if model:- env["HERMES_MODEL"] = model- env["HERMES_INFERENCE_MODEL"] = model- if provider:- env["HERMES_TUI_PROVIDER"] = provider- env["HERMES_INFERENCE_PROVIDER"] = provider- tui_toolsets = _normalize_tui_toolsets(toolsets)- if tui_toolsets:- env["HERMES_TUI_TOOLSETS"] = ",".join(tui_toolsets)+ skills_value = ""if skills:- value = ",".join(_split_comma_items(skills)) if isinstance(skills, (list, tuple)) else str(skills).strip()- if value:- env["HERMES_TUI_SKILLS"] = value+ skills_value = (+ ",".join(_split_comma_items(skills)) if isinstance(skills, (list, tuple)) else str(skills).strip())for key, value in (+ ("HERMES_MODEL", model), ("HERMES_INFERENCE_MODEL", model),+ ("HERMES_TUI_PROVIDER", provider), ("HERMES_INFERENCE_PROVIDER", provider),+ ("HERMES_TUI_TOOLSETS", ",".join(_normalize_tui_toolsets(toolsets))),+ ("HERMES_TUI_SKILLS", skills_value),("HERMES_TUI_QUERY", query), ("HERMES_TUI_IMAGE", image),("HERMES_TUI_CHECKPOINTS", "1" if checkpoints else None),("HERMES_TUI_PASS_SESSION_ID", "1" if pass_session_id else None),diff --git a/hermes_cli/main_web_build.py b/hermes_cli/main_web_build.pyindex 1b99040dddc..bf083a51e9b 100644--- a/hermes_cli/main_web_build.py+++ b/hermes_cli/main_web_build.py@@ -171,10 +171,7 @@ def _web_ui_build_needed(web_dir: Path) -> bool:"""project_root = _web_project_root(web_dir)dist_dir = _web_dist_dir(web_dir)- sentinel = dist_dir / ".vite" / "manifest.json"- if not sentinel.exists():- sentinel = dist_dir / "index.html"- if not sentinel.exists():+ if not any(p.exists() for p in (dist_dir / ".vite" / "manifest.json", dist_dir / "index.html")):return Truereturn not _stamp_is_current(_web_ui_stamp_path(), lambda: _compute_web_ui_content_hash(project_root, web_dir))