| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126 |
- """Dashboard/serve support: managed-service restart (systemd/respawn), status/listening probes, SSH session token file, named-profile routing, web-dist resolution, update stdio hangup protection.
- Split out of ``hermes_cli/main.py``. Names that still live in main (``PROJECT_ROOT``, ...)
- are imported lazily inside the functions that use them (avoids an import cycle).
- """
- import contextlib
- import os
- import re
- import shlex
- import subprocess
- import sys
- import time
- from pathlib import Path
- from typing import NoReturn
- from hermes_cli.cli_output import line_input
- from hermes_cli.process_identity import is_desktop_owned_backend as _is_desktop_owned_backend
- _PRE_BUILD_HINT = " Pre-build first: npm install --workspace web && npm run build -w web"
- def _find_stale_dashboard_pids(*, exclude_pids: set[int] | None = None,
- scope_home: str | None = None) -> list[int]:
- """PIDs of running ``dashboard``/``serve`` backends the caller may stop.
- *scope_home*: keep only backends whose resolved Hermes home (see
- ``_hermes_home_for_pid``) is this home; unreadable ownership is spared, never guessed.
- ``--stop`` and the post-update cleanup pass their own home so another install's or
- profile's backend on the same machine is never a target (#113978).
- """
- from hermes_cli.dashboard_procs import (
- _caller_ancestor_pids,
- _is_caller_wrapper_shell,
- _pids_owned_by_hermes_home,
- _scan_dashboard_processes,
- )
- pids = [pid for pid, _cmd in _scan_dashboard_processes(exclude_pids=exclude_pids)]
- # The scan also selects the caller's own wrapper shell (``bash -c 'hermes dashboard --stop'``);
- # killing it takes down the invoking terminal.
- ancestors = _caller_ancestor_pids()
- pids = [pid for pid in pids if not _is_caller_wrapper_shell(pid, ancestors)]
- return _pids_owned_by_hermes_home(pids, scope_home) if scope_home else pids
- def _parse_dashboard_runtime(command: str) -> tuple[str, str, int] | None:
- """Best-effort parse of a dashboard/server cmdline into mode, host, and port.
- The mode is the canonical holder subcommand, never an argv substring: this gates the launchd
- backend inventory (a kill + kickstart path) and ``--status`` (#121156).
- """
- from hermes_cli.update_cmd_windows import _hermes_holder_subcommand
- mode = _hermes_holder_subcommand(command)
- if mode not in ("dashboard", "serve"):
- return None
- port = 9119
- host = "127.0.0.1"
- port_match = re.search(r"(?:^|\s)--port(?:=|\s+)(\d+)", command)
- if port_match:
- try:
- port = int(port_match.group(1))
- except ValueError:
- return None
- host_match = re.search(r"(?:^|\s)--host(?:=|\s+)(\"[^\"]+\"|'[^']+'|\S+)", command)
- if host_match:
- host = host_match.group(1).strip("\"'") or "127.0.0.1"
- return mode, host, port
- def _dashboard_probe_host(host: str | None) -> str:
- """Map wildcard binds to a loopback address suitable for local probing."""
- normalized = (host or "127.0.0.1").strip().strip("[]")
- if normalized in {"", "0.0.0.0", "::"}:
- return "127.0.0.1"
- return normalized
- _DASHBOARD_SYSTEMD_UNIT = "hermes-dashboard.service"
- _SYSTEMCTL_ERRORS = (FileNotFoundError, subprocess.TimeoutExpired, OSError)
- def _run_probe(cmd: list[str], *, timeout: int) -> subprocess.CompletedProcess:
- """Captured, text-decoded ``subprocess.run`` for short local probes (systemctl, ps)."""
- return subprocess.run(
- cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, check=False)
- def _restart_managed_dashboard_service(reason: str, unit: str = _DASHBOARD_SYSTEMD_UNIT) -> bool:
- """Restart a systemd-managed dashboard instead of raw-killing its PID.
- True when a unit was found and handled (success or printed failure) — which
- deliberately stops the caller's ``os.kill`` fallback: systemd treats a direct
- SIGTERM as a clean stop, so ``Restart=on-failure`` won't bring it back.
- """
- if sys.platform == "win32":
- return False
- def _systemctl(*args: str, timeout: int = 10) -> subprocess.CompletedProcess:
- return _run_probe(["systemctl", *args], timeout=timeout)
- # User manager first (Hermes installs Linux services in the user scope by
- # default), system manager only when the unit isn't there. Keep the selected
- # scope for ALL probes and the restart — a user unit must never be restarted
- # through the system manager (or raw-killed).
- scope: tuple[str, ...] | None = None
- for candidate in (("--user",), ()):
- try:
- result = _systemctl(*candidate, "list-unit-files", unit, "--no-legend", "--no-pager")
- except _SYSTEMCTL_ERRORS:
- continue
- if result.returncode != 0:
- continue
- unit_rows = (result.stdout or "").splitlines()
- if any(row.split()[0:1] == [unit] for row in unit_rows if row.split()):
- scope = candidate
- break
- if scope is None:
- return False
- try:
- active = _systemctl(*scope, "is-active", unit)
- enabled = _systemctl(*scope, "is-enabled", unit)
- except _SYSTEMCTL_ERRORS:
- return False
- active_state = (active.stdout or "").strip()
- enabled_state = (enabled.stdout or "").strip()
- if active_state != "active" and enabled_state not in {
- "enabled", "enabled-runtime", "linked", "linked-runtime", "static", "generated",
- }:
- return False
- print(f"\n⟲ Restarting managed dashboard service ({reason})")
- scope_label = "systemctl --user" if scope else "sudo systemctl"
- commands = [("systemctl", *scope, "restart", unit)]
- if not scope:
- # System units may require privilege escalation; user units must use
- # the user manager directly and never prompt for sudo.
- commands.append(("sudo", "-n", "systemctl", "restart", unit))
- errors: list[str] = []
- for command in commands:
- try:
- result = _run_probe(list(command), timeout=60)
- except _SYSTEMCTL_ERRORS as e:
- errors.append(f"{' '.join(command)}: {e}")
- continue
- if result.returncode == 0:
- print(f" ✓ restarted {unit}")
- return True
- errors.append(f"{' '.join(command)}: {(result.stderr or result.stdout or '').strip()}")
- print(f" ✗ failed to restart {unit}")
- for err in errors:
- if err.strip():
- print(f" {err}")
- print(
- " Dashboard is managed by systemd; not raw-killing its PID because "
- "systemd would treat that as a clean stop."
- )
- print(f" Restart manually: {scope_label} restart {unit}")
- return True
- def _pid_unified_cgroup_entries(pid: int):
- """Yield the ``0::<path>`` cgroup paths from ``/proc/<pid>/cgroup``; nothing when unreadable."""
- try:
- cgroup_path = Path(f"/proc/{pid}/cgroup")
- if not cgroup_path.is_file():
- return
- text = cgroup_path.read_text(encoding="utf-8-sig", errors="replace")
- except (OSError, PermissionError):
- return
- for line in text.splitlines():
- parts = line.strip().split("::", 1)
- if len(parts) == 2:
- yield parts[1]
- def _get_systemd_service_for_pid(pid: int) -> str | None:
- """The systemd service unit that supervises *pid* (``hermes-serve.service``), or None.
- A ``.service`` cgroup alone only says where the process was started: a dashboard launched by
- hand from a shell that itself runs under some unit (a CI runner agent, ``cron.service``, a
- tmux or IDE user service, the gateway's own terminal tool) sits in THAT unit's cgroup. The
- unit owns the backend only when its live ``MainPID`` is this PID; otherwise restarting it
- restarts an unrelated service and leaves the dashboard down. None when the PID isn't part of
- a service, ownership can't be proved, the file is unreadable, or off Linux.
- """
- for cg_path in _pid_unified_cgroup_entries(pid):
- if cg_path.endswith(".service"):
- svc_name = cg_path.rsplit("/", 1)[-1]
- if svc_name and _unit_main_pid_is(svc_name, cg_path, pid):
- return svc_name
- return None
- def _unit_main_pid_is(svc_name: str, cgroup_path: str, pid: int) -> bool:
- """True when *svc_name*'s live ``MainPID`` is *pid* (read-only ``systemctl show``)."""
- scope = _extract_scope_from_cgroup(cgroup_path)
- scopes = {"user": [["--user"]], "system": [[]]}.get(scope or "", [[], ["--user"]])
- for scope_args in scopes:
- try:
- result = _run_probe(
- ["systemctl", *scope_args, "show", svc_name, "--property=MainPID", "--value"], timeout=10)
- except _SYSTEMCTL_ERRORS:
- continue
- if result.returncode == 0 and (result.stdout or "").strip() == str(pid):
- return True
- return False
- def _extract_scope_from_cgroup(cgroup_entry: str) -> str | None:
- """``user`` / ``system`` from a cgroup path (``/user.slice/…`` vs ``/system.slice/…``), else None."""
- if "/system.slice/" in cgroup_entry:
- return "system"
- if "/user.slice/" in cgroup_entry:
- return "user"
- return None
- def _get_pid_cgroup_path(pid: int) -> str | None:
- """The unified (``0::``) cgroup path from ``/proc/<pid>/cgroup``, or None."""
- return next(_pid_unified_cgroup_entries(pid), None)
- def _systemd_owner_for_pid(pid: int) -> tuple[str, str | None] | None:
- """``(unit, scope)`` of the systemd unit whose live ``MainPID`` is *pid*; ``None`` when no unit
- provably owns it (see :func:`_get_systemd_service_for_pid`). Scope is ``user``/``system`` or
- ``None`` when the cgroup path does not say."""
- unit = _get_systemd_service_for_pid(pid)
- if unit is None:
- return None
- return unit, _extract_scope_from_cgroup(_get_pid_cgroup_path(pid) or "")
- def _systemd_restart_commands(unit: str, scope: str | None) -> list[str]:
- """The command(s) that restart *unit* in its scope; both forms when the scope is unknown."""
- user_cmd, system_cmd = f"systemctl --user restart {unit}", f"sudo systemctl restart {unit}"
- return {"user": [user_cmd], "system": [system_cmd]}.get(scope or "", [user_cmd, system_cmd])
- def _format_restart_commands(commands: list[str]) -> str:
- """Join restart commands as a user-facing hint: each backticked, separated by " or "."""
- return " or ".join(f"`{c}`" for c in commands)
- def _try_restart_systemd_service(svc_name: str, cgroup_path: str | None = None) -> bool:
- """Restart *svc_name* via systemctl (``--user`` for user-scope units). True on success.
- Unknown scope tries system first, then user.
- """
- scope = _extract_scope_from_cgroup(cgroup_path) if cgroup_path else None
- system_cmd = ["systemctl", "restart", svc_name]
- user_cmd = ["systemctl", "--user", "restart", svc_name]
- candidates = {"user": [user_cmd], "system": [system_cmd]}.get(scope, [system_cmd, user_cmd])
- for cmd in candidates:
- try:
- if _run_probe(cmd, timeout=15).returncode == 0:
- return True
- except _SYSTEMCTL_ERRORS:
- continue
- return False
- # launchd plist directories that can supervise a ``hermes dashboard`` / ``hermes serve`` backend on
- # macOS, with the launchctl domain their jobs load into (LaunchAgents: ``gui/<uid>`` or ``user/<uid>``,
- # probed per label like the gateway helpers; LaunchDaemons: ``system``). Both LaunchAgents dirs are
- # per-user domains, so they share the ``agent`` kind.
- def _launchd_plist_dirs() -> list[tuple[str, Path]]:
- return [
- ("agent", Path.home() / "Library" / "LaunchAgents"),
- ("agent", Path("/Library/LaunchAgents")),
- ("daemon", Path("/Library/LaunchDaemons")),
- ]
- def _loaded_launchd_backend_jobs(
- plist_dirs: list[tuple[str, Path]] | None = None,
- ) -> list[tuple[str, str, list[str], int | None]]:
- """``(domain, label, program_arguments, live_pid)`` for every LOADED launchd job whose
- ``ProgramArguments`` is a ``hermes dashboard`` / ``hermes serve`` backend. macOS only (empty
- elsewhere). Reads the plists (unreadable/malformed ones are skipped) and asks ``launchctl print``
- per candidate label — a job that is not loaded in any domain is not returned, so an operator's
- stale plist never claims a process."""
- if sys.platform != "darwin":
- return []
- import plistlib
- from xml.parsers.expat import ExpatError
- from hermes_cli.gateway import _launchd_print_service_pid
- uid = os.getuid() # windows-footgun: ok — darwin-only branch
- jobs: list[tuple[str, str, list[str], int | None]] = []
- for kind, plist_dir in (plist_dirs if plist_dirs is not None else _launchd_plist_dirs()):
- try:
- plists = sorted(plist_dir.glob("*.plist"))
- except OSError:
- continue
- for plist_path in plists:
- try:
- with open(plist_path, "rb") as f:
- data = plistlib.load(f)
- # ExpatError is NOT a ValueError: plistlib propagates it unwrapped for
- # XML that is not well-formed (e.g. a hand-edited plist with a raw
- # `&` in `ProgramArguments`), and one such operator file must skip —
- # not abort — the whole post-pull cleanup scan.
- except (OSError, ValueError, plistlib.InvalidFileException, ExpatError):
- continue
- if not isinstance(data, dict):
- continue
- label = str(data.get("Label") or "").strip()
- args = data.get("ProgramArguments")
- if not label or not isinstance(args, list) or not args:
- continue
- argv = [str(a) for a in args]
- if _parse_dashboard_runtime(shlex.join(argv)) is None:
- continue
- domains = ("system",) if kind == "daemon" else (f"gui/{uid}", f"user/{uid}")
- for domain in domains:
- try:
- loaded, live_pid = _launchd_print_service_pid(domain, label)
- except _SYSTEMCTL_ERRORS:
- loaded, live_pid = False, None
- if loaded:
- jobs.append((domain, label, argv, live_pid))
- break
- return jobs
- def _launchd_job_owning_backend(
- pid: int, cmdline: list[str] | None, jobs: list[tuple[str, str, list[str], int | None]],
- ancestors: list[int] | tuple[int, ...] = (),
- ) -> tuple[str, str, int | None] | None:
- """``(domain, label, live_pid)`` of the loaded launchd job that owns *pid*: launchd reports *pid*
- (or one of its *ancestors* — a plist may wrap the backend in ``/bin/sh -c …`` without ``exec``)
- as the job's live process, OR the process runs the job's ``ProgramArguments`` — a detached copy
- of a supervised backend (an earlier respawn) holds the port the job needs, and respawning it again
- would only re-create that conflict. ``--no-open`` is ignored on both sides: the respawn path adds
- it, so an earlier respawn's argv is the plist's plus that flag. None when no loaded job claims
- the process."""
- def _norm(argv: list[str]) -> list[str]:
- return [a for a in argv if a != "--no-open"]
- for domain, label, argv, live_pid in jobs:
- if live_pid is not None and (live_pid == pid or live_pid in ancestors):
- return (domain, label, live_pid)
- if cmdline is not None and _norm(list(cmdline)) == _norm(argv):
- return (domain, label, live_pid)
- return None
- def _restart_launchd_job(domain: str, label: str, old_pid: int | None, *, timeout: float = 15.0) -> bool:
- """Bring a launchd-supervised backend back after its process was stopped: ``launchctl kickstart
- <domain>/<label>`` (no ``-k`` — a KeepAlive job may already have respawned it, and a kill would
- take that fresh process down), then require launchd to report a live PID other than *old_pid*
- within *timeout*. A kickstart that returns 0 only means "restart requested"; a job that is loaded
- but never comes back on a fresh PID is a failure the operator must hear about."""
- from hermes_cli.gateway import _wait_for_launchd_service_pid
- try:
- if _run_probe(["launchctl", "kickstart", f"{domain}/{label}"], timeout=30).returncode != 0:
- return False
- return _wait_for_launchd_service_pid(label, old_pid=old_pid, timeout=timeout, domain=domain)
- except _SYSTEMCTL_ERRORS:
- return False
- def _dashboard_cmdline_for_pid(pid: int) -> list[str] | None:
- """Exact argv of a running process: ``/proc/<pid>/cmdline`` (Linux), ``ps -o command=`` + shlex
- (macOS), None on Windows (no graceful taskkill window; Desktop manages its backend)."""
- if sys.platform == "win32":
- return None
- try:
- cmdline_path = f"/proc/{pid}/cmdline"
- if os.path.exists(cmdline_path):
- with open(cmdline_path, "rb") as f:
- raw = f.read()
- argv = [part.decode("utf-8", errors="replace") for part in raw.split(b"\x00") if part]
- return argv or None
- result = _run_probe(["ps", "-p", str(pid), "-o", "command="], timeout=10)
- if result.returncode != 0:
- return None
- command = (result.stdout or "").strip()
- if not command:
- return None
- try:
- argv = shlex.split(command)
- except ValueError:
- argv = command.split()
- return argv or None
- except (OSError, ValueError, subprocess.TimeoutExpired):
- return None
- _RESPAWN_LIVENESS_GRACE_SECONDS = 1.0
- def _respawnable_command_for_current_install(argv: list[str]) -> list[str]:
- """Rebuild a captured ``[<interpreter>, <hermes launcher>, ...]`` argv on this install's launcher.
- A pre-PM-takeover install left ``~/.local/bin/hermes`` as a symlink to a Python console
- script, so the kernel recorded a manual backend as ``[<old venv python>, <launcher>, dashboard,
- ...]``. The takeover then rewrote that launcher into a POSIX shell shim, and replaying the
- captured argv verbatim asks the old interpreter to parse a shell script (#124778). This
- checkout's own ``hermes`` entry script stays Python, so it and every other shape replay unchanged.
- """
- root = Path(__file__).resolve().parents[1]
- if (len(argv) > 2 and os.path.basename(argv[0]).startswith("python")
- and os.path.basename(argv[1]) == "hermes" and Path(argv[1]) != root / "hermes"):
- from hermes_cli._launchers import runtime_command
- return runtime_command(root, argv[2:])
- return list(argv)
- def _respawn_dashboard_processes(commands: list[list[str]]) -> list[list[str]]:
- """Respawn manually-started dashboards after ``hermes update``, detached, logging to
- ``logs/dashboard-restart.log``; returns the argvs that failed to spawn. Callers pre-filter via
- ``_filter_dashboard_respawn_candidates`` (no Desktop ``--port 0`` backends, capped per profile).
- See #78821.
- """
- from hermes_constants import get_hermes_home
- respawned: list[list[str]] = []
- spawned: list[tuple[list[str], list[str], subprocess.Popen]] = []
- failed: list[tuple[list[str], list[str], str]] = []
- log_path = get_hermes_home() / "logs" / "dashboard-restart.log"
- with contextlib.suppress(OSError):
- log_path.parent.mkdir(parents=True, exist_ok=True)
- for original in commands:
- command = _respawnable_command_for_current_install(original)
- # Keep restarted dashboards headless; reopening a browser after a
- # background update is noisy and fails in SSH/headless sessions.
- if "dashboard" in command and "--no-open" not in command:
- command = [*command, "--no-open"]
- try:
- with open(log_path, "ab") as log_f:
- proc = subprocess.Popen(
- command, stdin=subprocess.DEVNULL, stdout=log_f, stderr=subprocess.STDOUT,
- # detached-spawn: ok — dashboard service launch, meant to outlive the CLI that starts it
- start_new_session=True, close_fds=True)
- spawned.append((original, command, proc))
- except (OSError, ValueError) as exc:
- failed.append((original, command, str(exc)))
- # A respawned backend is a resident server: one that exits within the grace
- # window died at startup (SyntaxError on a stale argv, port already bound,
- # ...) and must surface as a failure, not as ``✓ restarted`` (#124778).
- if spawned:
- time.sleep(_RESPAWN_LIVENESS_GRACE_SECONDS)
- for original, command, proc in spawned:
- if proc.poll() is None:
- respawned.append(command)
- else:
- failed.append((original, command, f"child exited during the first "
- f"{_RESPAWN_LIVENESS_GRACE_SECONDS:.0f}s (code {proc.returncode})"))
- for command in respawned:
- print(f" ✓ restarted: {shlex.join(command)}")
- for _, command, err_msg in failed:
- print(f" ✗ failed to restart ({shlex.join(command)}): {err_msg}")
- # The caller's argv, not the spawned one: callers match it against the stopped PID's
- # captured cmdline to book the runtime as not brought back (#109290).
- return [original for original, _, _ in failed]
- class _UpdateOutputStream:
- """stdout/stderr wrapper for ``hermes update``: mirrors to ``logs/update.log`` and, once the
- terminal vanishes (BrokenPipe/OSError/ValueError), drops screen output instead of the update."""
- _BROKEN = (BrokenPipeError, OSError, ValueError)
- def __init__(self, original, log_file):
- self._original = original
- self._log = log_file
- self._original_broken = False
- def write(self, data):
- # Mirror to the log file first — it's the most reliable destination.
- if self._log is not None:
- with contextlib.suppress(Exception):
- self._log.write(data)
- if not self._original_broken:
- try:
- return self._original.write(data)
- except self._BROKEN:
- self._original_broken = True # terminal vanished; keep updating
- return len(data) if isinstance(data, (str, bytes)) else 0
- def flush(self):
- if self._log is not None:
- with contextlib.suppress(Exception):
- self._log.flush()
- if self._original_broken:
- return
- try:
- self._original.flush()
- except self._BROKEN:
- self._original_broken = True
- def isatty(self):
- if self._original_broken:
- return False
- try:
- return self._original.isatty()
- except Exception:
- return False
- def fileno(self):
- # Defer to the underlying stream; callers handle failures as when unwrapped.
- return self._original.fileno()
- def __getattr__(self, name):
- return getattr(self._original, name)
- def _install_hangup_protection(gateway_mode: bool = False):
- """Protect ``cmd_update`` from SIGHUP (→ SIG_IGN, inherited by pip/git children) and broken pipes
- (stdio wrapped in ``_UpdateOutputStream``). SIGINT/SIGTERM are left alone — legitimate cancels.
- Gateway updates are already detached, but still need the log mirror for the
- Desktop progress watchdog. Returns state for ``_finalize_update_output``."""
- state = {
- "prev_stdout": sys.stdout, "prev_stderr": sys.stderr, "log_file": None, "installed": False}
- import signal as _signal
- if not gateway_mode and hasattr(_signal, "SIGHUP"):
- # Non-main thread: update still runs, just without hangup protection.
- with contextlib.suppress(ValueError, OSError):
- _signal.signal(_signal.SIGHUP, _signal.SIG_IGN)
- # Any failure here is non-fatal; we just skip the wrap.
- try:
- # Late-bound import so tests can monkeypatch it to simulate setup failure. The ROOT
- # home, never a sticky profile's: the update mutates the shared checkout, and the
- # Desktop and the hand-off scripts read <root>/logs/update.log.
- from hermes_constants import get_default_hermes_root as _get_root_home
- logs_dir = _get_root_home() / "logs"
- logs_dir.mkdir(parents=True, exist_ok=True)
- log_file = open(logs_dir / "update.log", "a", buffering=1, encoding="utf-8")
- import datetime as _dt
- stage = "continued on the pulled code" if os.environ.get("HERMES_UPDATE_POST_SWAP") == "1" else "started"
- log_file.write(f"\n=== hermes update {stage} {_dt.datetime.now().isoformat(timespec='seconds')} ===\n")
- state["log_file"] = log_file
- sys.stdout = _UpdateOutputStream(state["prev_stdout"], log_file)
- sys.stderr = _UpdateOutputStream(state["prev_stderr"], log_file)
- state["installed"] = True
- except Exception:
- state["log_file"] = None
- return state
- def _finalize_update_output(state):
- """Restore stdio and close the update.log handle opened by ``_install_hangup_protection``."""
- if not state:
- return
- if state.get("installed"):
- with contextlib.suppress(Exception):
- sys.stdout = state.get("prev_stdout", sys.stdout)
- with contextlib.suppress(Exception):
- sys.stderr = state.get("prev_stderr", sys.stderr)
- log_file = state.get("log_file")
- if log_file is not None:
- with contextlib.suppress(Exception):
- log_file.flush()
- log_file.close()
- def _report_dashboard_status() -> int:
- """Print live listening dashboard/serve processes and return the count.
- Serve-mode backends are INCLUDED: ``--stop`` kills them, so hiding them from
- ``--status`` let an operator kill what they couldn't see.
- Ledger-registered serves (profiled launches the argv scan can't match) surface via the spawn-ledger
- augmentation in _scan_dashboard_processes, and the ledger's recorded bind replaces the argv port so
- ``--port 0`` backends are probed on the port the OS actually gave them. See #81564.
- """
- from hermes_cli.dashboard_procs import _ledger_serve_binds, _scan_dashboard_processes
- from gateway.status import _pid_exists
- binds = _ledger_serve_binds()
- live: list[tuple[int, str, str]] = []
- for pid, command in _scan_dashboard_processes():
- runtime = _parse_dashboard_runtime(command)
- if runtime is None:
- continue
- mode, host, port = runtime
- if pid in binds:
- ledger_host, port = binds[pid]
- host = ledger_host or host
- if port <= 0 or not _pid_exists(pid) or not _dashboard_listening(host, port):
- continue
- live.append((pid, command, mode))
- if not live:
- print("No hermes dashboard or serve processes running.")
- return 0
- print(f"{len(live)} hermes dashboard/serve process(es) running:")
- for pid, command, mode in live:
- print(f" PID {pid} [{mode}]: {command}")
- return len(live)
- def _dashboard_listening(host: str, port: int) -> bool:
- """True when something accepts TCP connections at host:port (even a 401 proves a dashboard is up)."""
- import socket
- try:
- with socket.create_connection((_dashboard_probe_host(host), port), timeout=1.5):
- return True
- except OSError:
- return False
- def _cancel(message: str = " Cancelled.") -> NoReturn:
- print(message)
- sys.exit(1)
- def _maybe_setup_dashboard_auth_interactively(args) -> None:
- """Offer to configure dashboard auth when the gate engages and no provider exists.
- ``start_server`` fails closed for a non-loopback bind / ``dashboard.public_url``
- without a ``DashboardAuthProvider``; prompt an interactive operator first.
- No-op (fail-closed backstop stays) when the gate doesn't engage, a provider
- exists, or stdin/stdout isn't a TTY.
- """
- host = getattr(args, "host", "127.0.0.1") or "127.0.0.1"
- try:
- from hermes_cli.web_server import should_require_dashboard_auth
- if not should_require_dashboard_auth(host):
- return
- except Exception:
- return # if we can't tell, defer to start_server's own gate
- try:
- from hermes_cli.dashboard_auth import list_providers
- if list_providers():
- return
- except Exception:
- return
- if not (sys.stdin.isatty() and sys.stdout.isatty()):
- return
- print(f"\n⚠ Dashboard authentication is required for this configuration ({host}).")
- print(
- " Non-loopback binds and configured external dashboard.public_url "
- "values require authentication (--insecure does not bypass this)."
- )
- print()
- print(" How do you want to authenticate the dashboard?")
- print(" [1] Username & password (quickest; for a trusted LAN / VPN)")
- print(" [2] OAuth via Nous Portal (run `hermes dashboard register`)\n [3] Cancel\n")
- try:
- choice = input(" Choice [1]: ").strip() or "1"
- except (EOFError, KeyboardInterrupt):
- _cancel("\n Cancelled.")
- if choice == "2":
- print()
- print(
- " Run this on the host where the dashboard lives, then start "
- "the dashboard again:\n"
- " hermes dashboard register\n"
- " It provisions a Nous Portal OAuth client and writes "
- "HERMES_DASHBOARD_OAUTH_CLIENT_ID into ~/.hermes/.env for you.\n"
- " Docs: https://hermes-agent.nousresearch.com/docs/"
- "user-guide/features/web-dashboard#authentication-gated-mode"
- )
- sys.exit(0)
- if choice != "1":
- _cancel()
- import getpass
- import secrets
- print()
- try:
- username = line_input(" Username [admin]: ").strip() or "admin"
- password = getpass.getpass(" Password: ")
- confirm = getpass.getpass(" Confirm password: ")
- except (EOFError, KeyboardInterrupt):
- _cancel("\n Cancelled.")
- if not password:
- _cancel(" ✗ Empty password — aborting.")
- if password != confirm:
- _cancel(" ✗ Passwords don't match — aborting.")
- try:
- from plugins.dashboard_auth.basic import hash_password
- except Exception as exc:
- _cancel(f" ✗ Could not load the password provider: {exc}")
- password_hash = hash_password(password)
- # A stable token-signing secret so sessions survive a dashboard restart.
- secret = secrets.token_urlsafe(32)
- try:
- from hermes_cli.config import load_config, save_config
- from hermes_cli.plugins_cmd import ensure_basic_auth_plugin_enabled_in_config
- cfg = load_config()
- basic = cfg.setdefault("dashboard", {}).setdefault("basic_auth", {})
- basic["username"] = username
- basic["password_hash"] = password_hash
- basic["password"] = "" # never persist plaintext
- if not str(basic.get("secret", "") or "").strip():
- basic["secret"] = secret
- # The bundled basic provider is a backend plugin that honours
- # plugins.disabled; unblock it so discover_plugins below registers it,
- # and tell an operator who deliberately disabled it.
- if ensure_basic_auth_plugin_enabled_in_config(cfg):
- print(" ✓ Re-enabled the bundled 'basic' auth plugin (was in plugins.disabled)")
- save_config(cfg)
- except Exception as exc:
- _cancel(f" ✗ Failed to write config.yaml: {exc}")
- # Re-run plugin discovery so the provider registers before start_server's gate.
- try:
- from hermes_cli.plugins import discover_plugins
- discover_plugins(force=True)
- except Exception as exc:
- print(f" ⚠ Plugin re-discovery failed ({exc}); the gate may still "
- "fail closed. Set the password again or restart the dashboard.")
- print()
- print(f" ✓ Username/password auth configured (user: {username}).")
- print(" Saved to config.yaml under dashboard.basic_auth.")
- print(" Sign in at the dashboard with these credentials.\n")
- def _read_ssh_session_token_file(path: str) -> str:
- """Read and unlink a Desktop SSH token from its private runtime directory."""
- if sys.platform == "win32":
- from hermes_cli.windows_ssh_runtime import read_token
- return read_token(path)
- import stat as _stat
- if not os.path.isabs(path):
- raise SystemExit("--ssh-session-token-file must be absolute")
- # The Desktop client writes the token under the account's $HOME/.hermes/
- # desktop-ssh, independent of HERMES_HOME and the active profile. Anchor
- # validation there, NOT get_hermes_home(): a non-default profile or a Docker
- # /opt/data root re-homes get_hermes_home() and would reject every token.
- # See #69551.
- token_root = Path.home() / ".hermes" / "desktop-ssh"
- try:
- relative = Path(path).relative_to(token_root)
- except ValueError as exc:
- raise SystemExit("--ssh-session-token-file must be under the desktop-ssh directory") from exc
- if len(relative.parts) != 2 or not re.fullmatch(r"[0-9a-f]{32}", relative.parts[0]):
- raise SystemExit("--ssh-session-token-file has an invalid runtime path")
- if not re.fullmatch(r"[0-9a-f]{16}\.token", relative.parts[1]):
- raise SystemExit("--ssh-session-token-file has an invalid filename")
- directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
- file_flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
- uid = os.getuid() if hasattr(os, "getuid") else None
- def _check_dir(fd: int, what: str) -> None:
- st = os.fstat(fd)
- if not _stat.S_ISDIR(st.st_mode):
- raise SystemExit(f"--ssh-session-token-file has an unsafe {what}")
- if uid is not None and st.st_uid != uid:
- raise SystemExit(f"--ssh-session-token-file {what} has the wrong owner")
- if what == "parent directory" and (st.st_mode & 0o777) != 0o700:
- raise SystemExit("--ssh-session-token-file parent has unsafe permissions")
- root_fd = -1
- directory_fd = -1
- file_fd = -1
- try:
- try:
- root_fd = os.open(token_root, directory_flags)
- _check_dir(root_fd, "runtime root")
- directory_fd = os.open(relative.parts[0], directory_flags, dir_fd=root_fd)
- _check_dir(directory_fd, "parent directory")
- file_fd = os.open(relative.parts[1], file_flags, dir_fd=directory_fd)
- except SystemExit:
- raise
- except OSError as exc:
- if exc.errno == getattr(__import__("errno"), "ELOOP", -1):
- raise SystemExit("--ssh-session-token-file is a symlink") from exc
- raise SystemExit("--ssh-session-token-file is not accessible") from exc
- file_stat = os.fstat(file_fd)
- if not _stat.S_ISREG(file_stat.st_mode):
- raise SystemExit("--ssh-session-token-file is not a regular file")
- if file_stat.st_size != 64:
- raise SystemExit("--ssh-session-token-file contains an invalid token")
- if uid is not None and file_stat.st_uid != uid:
- raise SystemExit("--ssh-session-token-file has the wrong owner")
- if uid is not None and (file_stat.st_mode & 0o777) & ~0o600:
- raise SystemExit("--ssh-session-token-file has unsafe permissions")
- with os.fdopen(file_fd, "r", encoding="utf-8-sig") as token_stream:
- file_fd = -1
- token = token_stream.read(65)
- if not re.fullmatch(r"[0-9a-f]{64}", token):
- raise SystemExit("--ssh-session-token-file contains an invalid token")
- return token
- finally:
- if file_fd >= 0:
- os.close(file_fd)
- if directory_fd >= 0:
- with contextlib.suppress(OSError):
- os.unlink(relative.parts[1], dir_fd=directory_fd)
- os.close(directory_fd)
- if root_fd >= 0:
- os.close(root_fd)
- def _is_electron_packaged_web_dist(path: str) -> bool:
- """True when *path* is an Electron-packaged renderer dist (``app.asar[.unpacked]/dist``).
- A standalone ``hermes dashboard`` inheriting that ``HERMES_WEB_DIST`` would
- serve the desktop frontend in the browser ("Desktop IPC bridge is unavailable").
- """
- if not path:
- return False
- return "app.asar" in path.replace("\\", "/")
- def _host_backend_attachment():
- """Live host serve/dashboard record to attach to, or ``None``.
- Record-based discovery replaces the old bare-TCP probe: "something accepts a connection on
- this port" proved nothing about WHO answers (a foreign service, or a recycled PID's new
- owner). The record carries ``(pid, createTime)`` so liveness is proved against the same
- incarnation, and its token fingerprint must still match the 0600 token file the owner wrote.
- The record only nominates a CANDIDATE; :func:`_attach_to_host_backend` makes it prove itself.
- """
- try:
- from gateway import host_rendezvous as hr
- record = hr.read_record(hr.ROLE_SERVE)
- if record is None or not record.port:
- return None
- return record if hr.record_token_is_consistent(record) else None
- except Exception:
- return None
- def _explicit_endpoint_flags(argv=None) -> set:
- """Which of ``--host``/``--port`` the operator actually typed.
- argparse defaults are indistinguishable from a typed value in ``args``, and the difference is
- load-bearing: an unset ``--port`` may attach to whatever port the host owner bound, but a
- typed ``--port 8899`` or ``--host 0.0.0.0`` (LAN access) must never be silently answered with
- a loopback attach on some other port.
- """
- typed = set()
- for token in (sys.argv[1:] if argv is None else argv):
- name = str(token).split("=", 1)[0]
- if name in ("--host", "--port"):
- typed.add(name[2:])
- return typed
- def _endpoint_conflict(args, record, typed: set) -> str:
- """Why an explicitly requested endpoint cannot be served by ``record`` ('' when it can)."""
- if "port" in typed:
- wanted_port = getattr(args, "port", None)
- # ``--port 0`` is "any free port", not a demand for a specific one.
- if isinstance(wanted_port, int) and wanted_port > 0 and wanted_port != record.port:
- return f"--port {wanted_port} (the host owner is on port {record.port})"
- if "host" in typed:
- wanted_host = str(getattr(args, "host", "") or "")
- owner_host = record.host or "127.0.0.1"
- loopback = {"127.0.0.1", "localhost", "::1"}
- wildcard = {"0.0.0.0", "::", "*"}
- # A wildcard owner already answers on loopback; anything else must match exactly.
- reachable = wanted_host == owner_host or (owner_host in wildcard and wanted_host in loopback)
- if not reachable:
- return f"--host {wanted_host} (the host owner is bound to {owner_host})"
- return ""
- def _attach_to_host_backend(args, headless_backend: bool) -> None:
- """Multiplex-only: a second `hermes serve`/`dashboard` attaches to the host backend.
- Exactly ONE backend runs per host and multiplexes every profile, so a second invocation —
- for ANY profile, the default included — reports the live one and exits 0 instead of binding
- a second port. ``--isolated`` opts out (Desktop's SSH backend proves ownership with it) and
- Desktop pool backends (HERMES_DESKTOP=1) keep their own lifecycle.
- Exit 0 means "the host backend answered and serves what you asked for", and nothing else:
- * the owner must ANSWER on its recorded port and identify itself (a record alone cannot see a
- graceful-shutdown window or a foreign listener that inherited the port) — a supervisor or
- `hermes update` relaunch landing in that window would otherwise exit 0 with NOTHING
- listening, reporting success for a dead service;
- * an explicitly typed ``--port``/``--host`` the owner cannot serve is a REFUSAL naming the
- owner, never a silent redirect. It exits 78 (EX_CONFIG), the deliberate-refusal code
- ``RestartPreventExitStatus=78`` parks on: exit 1 under ``Restart=always`` was an infinite
- restart loop with nothing listening on the ingress port (#119824);
- * a `hermes dashboard` user is never handed a headless backend's URL (no SPA behind it).
- Returns normally — leaving the caller to BIND — when no owner answers.
- """
- if getattr(args, "isolated", False) or _is_desktop_owned_backend():
- return
- record = _host_backend_attachment()
- if record is None:
- return
- from gateway import host_rendezvous as hr
- from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE
- identity = hr.probe_owner(record)
- if identity is None:
- # Unprovable liveness (no psutil), a closed port, a foreign listener: all mean "no owner
- # answered". Fall through to the bind — never exit 0 on an attach that did not happen.
- return
- typed = _explicit_endpoint_flags()
- conflict = _endpoint_conflict(args, record, typed)
- if conflict:
- print(f"Refusing to start: this host is already served by {hr.describe(record)}.")
- print(f" You asked for {conflict}.")
- print(" Stop that backend, or drop the flag to use the running one.")
- sys.exit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
- if not headless_backend and not identity.get("servesSpa"):
- print(f"Refusing to start: this host is already served by {hr.describe(record)}, "
- "which is a headless `hermes serve` backend with no dashboard UI.")
- print(" Stop it and run `hermes dashboard`, or use --isolated for a dedicated server.")
- sys.exit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
- try:
- from hermes_cli.profiles import get_active_profile_name
- profile = get_active_profile_name()
- except Exception:
- profile = "default"
- wanted = getattr(args, "open_profile", "") or profile
- from hermes_cli.url_utils import format_url_host
- url = f"http://{format_url_host(hr.dial_host(record))}:{record.port}/?profile={wanted}"
- kind = "backend" if headless_backend else "dashboard"
- print(f"Hermes {kind} already running on this host: PID {record.pid}, port {record.port}.")
- print(f" Managing profile '{wanted}': {url}")
- if not headless_backend and not args.no_open:
- with contextlib.suppress(Exception):
- import webbrowser
- webbrowser.open(url)
- sys.exit(0)
- 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=`` scoping
- makes one server per profile pure fragmentation).
- No-record fallback to :func:`_attach_to_host_backend`, which already attached (and exited)
- when the host publishes a live rendezvous record: re-exec pinned to ``-p default`` (so
- ``_apply_profile_override`` can't re-route via the sticky active_profile file). ``--isolated``
- opts out; Desktop pool backends (HERMES_DESKTOP=1) stay per-profile. Returns normally when no
- routing applies.
- """
- try:
- from hermes_cli.profiles import get_active_profile_name
- _launch_profile = get_active_profile_name()
- except Exception:
- _launch_profile = "default"
- if (
- _launch_profile in ("default", "custom")
- or getattr(args, "isolated", False)
- or getattr(args, "open_profile", "")
- or _is_desktop_owned_backend()
- ):
- return
- print(
- f"Routing to the machine dashboard (profile '{_launch_profile}' "
- f"preselected). Use --isolated for a dedicated per-profile server."
- )
- reexec_argv = [
- sys.executable, "-m", "hermes_cli.main",
- "-p", "default",
- # Preserve the lean serve path so a named-profile `serve` doesn't
- # silently rebuild the UI as `dashboard`.
- "serve" if _headless_backend else "dashboard",
- "--port", str(args.port),
- "--host", args.host,
- "--open-profile", _launch_profile]
- 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.
- env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
- # Pin the child to the machine ROOT, resolved explicitly rather than by
- # dropping HERMES_HOME: in the Docker layout the root is /opt/data, and an
- # unset HERMES_HOME would fall back to $HOME/.hermes = /opt/data/.hermes — an
- # empty auto-seeded home with only the default profile and no install stamp.
- # get_default_hermes_root() strips a trailing profiles/<name> for both layouts.
- try:
- from hermes_constants import get_default_hermes_root
- env["HERMES_HOME"] = str(get_default_hermes_root())
- except Exception:
- env.pop("HERMES_HOME", None) # prior behaviour rather than blocking the reroute
- # On Windows os.execvpe() spawns via CreateProcess then exits, which under
- # Python 3.14+ can crash with STATUS_ACCESS_VIOLATION; use Popen + exit.
- if sys.platform == "win32":
- proc = subprocess.Popen(reexec_argv, env=env)
- sys.exit(proc.wait())
- else:
- from hermes_cli.cpu_profile import write_cpu_profile
- write_cpu_profile() # exec skips atexit
- os.execvpe(sys.executable, reexec_argv, env)
- def _resolve_dashboard_web_dist(args, _headless_backend: bool) -> None:
- """Build or validate the web UI dist before the server imports.
- ``serve`` sets HERMES_SERVE_HEADLESS so mount_spa() stays off. Otherwise build
- unless HERMES_WEB_DIST / --skip-build promise a dist — then verify index.html
- (else the server serves 404s). --skip-build on the default location gets ONE
- recovery build; a caller-managed HERMES_WEB_DIST can't be populated.
- """
- from hermes_cli.main import PROJECT_ROOT
- from hermes_cli.main_web_build import _build_web_ui
- skip_build = getattr(args, "skip_build", False)
- if _headless_backend:
- os.environ["HERMES_SERVE_HEADLESS"] = "1" # set before web_server import
- elif "HERMES_WEB_DIST" not in os.environ and not skip_build:
- if not _build_web_ui(PROJECT_ROOT / "web", fatal=True):
- sys.exit(1)
- elif skip_build:
- _dist_root = (
- # --build-mode skip trusts the caller to have pre-built the web UI. Verify the dist actually
- # exists; otherwise the server will start and serve 404s with no obvious cause (issue #23817).
- Path(os.environ["HERMES_WEB_DIST"])
- if "HERMES_WEB_DIST" in os.environ
- else PROJECT_ROOT / "hermes_cli" / "web_dist"
- )
- if not (_dist_root / "index.html").exists():
- # Only the default dist location is recoverable (desktop launches with
- # --build-mode skip after a wipe of web_dist); a custom HERMES_WEB_DIST
- # is a caller-managed directory the build cannot populate.
- # The caller promised a pre-built dist but there isn't one. Instead of hard-failing (issue
- # #59288 — desktop launches with --build-mode skip after a wipe of web_dist), warn and attempt
- # ONE recovery build through the normal build path.
- _recoverable = "HERMES_WEB_DIST" not in os.environ
- if _recoverable:
- print(f"⚠ --skip-build was passed but no web dist found at: {_dist_root}")
- print(" Attempting one recovery build of the web UI...")
- _build_web_ui(PROJECT_ROOT / "web", fatal=True)
- if not (_dist_root / "index.html").exists():
- print(f"✗ --skip-build was passed but no web dist found at: {_dist_root}")
- if _recoverable:
- print(" The recovery build did not produce a usable dist.")
- print(_PRE_BUILD_HINT)
- print(" Or drop --skip-build to build automatically.")
- sys.exit(1)
- print(" ✓ Recovery build produced a web dist")
- print(f"→ Skipping web UI build (--skip-build); using dist at {_dist_root}")
- else:
- # HERMES_WEB_DIST without --skip-build: the env var points at a
- # caller-managed dist, so validate it like the --skip-build branch.
- # HERMES_WEB_DIST is set without --skip-build: the build is skipped (the env var points at a
- # caller-managed dist), so validate it the same way the --skip-build branch does — otherwise the
- # server starts and serves 404s with no obvious cause (same failure mode as #23817, via the env-var
- # path).
- _dist_root = Path(os.environ["HERMES_WEB_DIST"]).expanduser()
- if not (_dist_root / "index.html").exists():
- print(f"✗ HERMES_WEB_DIST is set but no web dist found at: {_dist_root}")
- print(_PRE_BUILD_HINT)
- print(" Or unset HERMES_WEB_DIST to build and use the default web UI dist.")
- sys.exit(1)
- # web_server reads HERMES_WEB_DIST raw at import (no expanduser), so a
- # validated "~/dist" would otherwise pass here and still 404 there.
- os.environ["HERMES_WEB_DIST"] = str(_dist_root)
- print(f"→ Using web dist from HERMES_WEB_DIST: {_dist_root}")
- def _dashboard_validate_serve_args(args, headless_backend, token_file):
- """Headless-serve argument checks -> ssh_owner_nonce (or None)."""
- # `hermes serve` is headless/non-interactive: fail closed on a corrupt
- # config.yaml instead of silently starting on defaults where provider
- # auto-detection can adopt unnamed .env credentials (issue #81952).
- # Same policy + escape hatch as _guard_noninteractive_user_config.
- if headless_backend:
- from hermes_cli.config import (
- InvalidUserConfigError,
- require_parseable_user_config,
- )
- try:
- require_parseable_user_config(
- ignore_user_config=bool(getattr(args, "ignore_user_config", False))
- )
- except InvalidUserConfigError as exc:
- print(f"Error: {exc}", file=sys.stderr)
- raise SystemExit(2) from exc
- ssh_owner_nonce = getattr(args, "ssh_owner_nonce", None)
- if ssh_owner_nonce and not re.fullmatch(r"[0-9a-f]{16}", ssh_owner_nonce):
- raise SystemExit("--ssh-owner-nonce must be 16 lowercase hex characters")
- if token_file and not headless_backend:
- raise SystemExit("--ssh-session-token-file is only valid with hermes serve")
- return ssh_owner_nonce
|