The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): group D layout — join lone closing-bracket lines (AST-neutral)
Tekniumc25960666dfc
diff --git a/hermes_cli/container_boot.py b/hermes_cli/container_boot.pyindex 3bf70a16b17..c50dc09bdf4 100644--- a/hermes_cli/container_boot.py+++ b/hermes_cli/container_boot.py@@ -43,8 +43,7 @@ class ReconcileAction:def _slot_action(- profile: str, profile_dir: Path, prior_state: str | None, start: bool,-) -> ReconcileAction:+ profile: str, profile_dir: Path, prior_state: str | None, start: bool) -> ReconcileAction:return ReconcileAction(profile=profile, prior_state=prior_state,action="started" if start else "registered",prior_exit=_read_prior_exit_label(profile_dir))@@ -52,8 +51,7 @@ def _slot_action(def reconcile_profile_gateways(*, hermes_home: Path, scandir: Path, dry_run: bool = False,- container_argv: Sequence[str] | None = None,-) -> list[ReconcileAction]:+ container_argv: Sequence[str] | None = None) -> list[ReconcileAction]:"""Recreate s6 service registrations for every persistent profile.Always registers a ``gateway-default`` slot for the root profile (the implicit profile at@@ -106,8 +104,7 @@ def reconcile_profile_gateways(def _maybe_migrate_legacy_gateway_run_state(- hermes_home: Path, *, container_argv: Sequence[str] | None, dry_run: bool-) -> str | None:+ hermes_home: Path, *, container_argv: Sequence[str] | None, dry_run: bool) -> str | None:"""Seed root gateway_state for pre-s6 `gateway run` containers (the tini image let users runthe gateway as the container command; post-s6 it would register down and never start)."""state_file = hermes_home / "gateway_state.json"@@ -237,8 +234,7 @@ def _register_service(scandir: Path, profile: str, *, start: bool) -> None:import shutilfrom hermes_cli.service_manager import (- S6ServiceManager, _seed_supervise_skeleton, validate_profile_name,- )+ S6ServiceManager, _seed_supervise_skeleton, validate_profile_name)validate_profile_name(profile)service_dir = scandir / f"gateway-{profile}"diff --git a/hermes_cli/copilot_auth.py b/hermes_cli/copilot_auth.pyindex ad7f134f1c9..b178bdc8356 100644--- a/hermes_cli/copilot_auth.py+++ b/hermes_cli/copilot_auth.py@@ -42,8 +42,7 @@ def validate_copilot_token(token: str) -> tuple[bool, str]:"Copilot API. Use one of:\n"" → `copilot login` or `hermes model` to authenticate via OAuth\n"" → A fine-grained PAT (github_pat_*) with Copilot Requests permission\n"- " → `gh auth login` with the default device code flow (produces gho_* tokens)"- )+ " → `gh auth login` with the default device code flow (produces gho_* tokens)")return True, "OK"@@ -84,8 +83,7 @@ def _gh_cli_candidates() -> list[str]:candidates: list[str] = [c for c in (shutil.which("gh"),) if c]candidates += [c for c in ("/opt/homebrew/bin/gh", "/usr/local/bin/gh", str(Path.home() / ".local/bin/gh"))- if c not in candidates and os.path.isfile(c) and os.access(c, os.X_OK)- ]+ if c not in candidates and os.path.isfile(c) and os.access(c, os.X_OK)]return candidates@@ -146,15 +144,13 @@ def _post_form(url: str, fields: dict, timeout: float) -> dict:req = urllib.request.Request(url, data=urllib.parse.urlencode(fields).encode(),headers={"Accept": "application/json", "User-Agent": "HermesAgent/1.0",- "Content-Type": "application/x-www-form-urlencoded"},- )+ "Content-Type": "application/x-www-form-urlencoded"})with urllib.request.urlopen(req, timeout=timeout) as resp:return json.loads(resp.read().decode())def copilot_device_code_login(- *, host: str = "github.com", timeout_seconds: float = 300,-) -> Optional[str]:+ *, host: str = "github.com", timeout_seconds: float = 300) -> Optional[str]:"""Run the GitHub OAuth device code flow for Copilot."""domain = host.rstrip("/")try:@@ -334,8 +330,7 @@ def _save_jwt_to_disk(fp: str, api_token: str, expires_at: float, base_url: Optinow = time.time()kept = {k: v for k, v in (store or {}).items()- if isinstance(v, dict) and float(v.get("expires_at", 0) or 0) > now- }+ if isinstance(v, dict) and float(v.get("expires_at", 0) or 0) > now}kept[fp] = {"api_token": api_token, "expires_at": expires_at, "base_url": base_url}_write_jwt_store(path, kept)@@ -417,8 +412,7 @@ def _cache_entry_fresh(cached) -> bool:def exchange_copilot_token(- raw_token: str, *, timeout: float = 10.0,-) -> tuple[str, float, Optional[str]]:+ raw_token: str, *, timeout: float = 10.0) -> tuple[str, float, Optional[str]]:"""Exchange a raw GitHub token for a Copilot API token → (token, expires_at, base_url).The token is a semicolon-separated string (not a JWT) used as a Bearer token. ``base_url``@@ -435,8 +429,7 @@ def exchange_copilot_token(def _exchange_copilot_token_locked(- raw_token: str, fp: str, *, timeout: float,-) -> tuple[str, float, Optional[str]]:+ raw_token: str, fp: str, *, timeout: float) -> tuple[str, float, Optional[str]]:# Re-check in-process under the lock (a queued-behind caller may have just exchanged), then# on-disk: a fresh process may hold a still-valid persisted JWT, avoiding a network# round-trip precisely when the network is most likely flaky.@@ -453,8 +446,7 @@ def _exchange_copilot_token_locked(req = urllib.request.Request(_TOKEN_EXCHANGE_URL, method="GET",headers={"Authorization": f"token {raw_token}", "User-Agent": _EXCHANGE_USER_AGENT,- "Accept": "application/json", "Editor-Version": _EDITOR_VERSION},- )+ "Accept": "application/json", "Editor-Version": _EDITOR_VERSION})data = _fetch_exchange_with_retry(req, timeout, fp)api_token = data.get("token", "")if not api_token:@@ -496,8 +488,7 @@ def get_copilot_api_token(raw_token: str) -> tuple[str, Optional[str]]:def copilot_request_headers(- *, is_agent_turn: bool = True, is_vision: bool = False,-) -> dict[str, str]:+ *, is_agent_turn: bool = True, is_vision: bool = False) -> dict[str, str]:"""Build the standard headers for Copilot API requests."""headers: dict[str, str] = {"Editor-Version": _EDITOR_VERSION, "User-Agent": "HermesAgent/1.0","Copilot-Integration-Id": "vscode-chat",diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex 8f79eb6f2af..ad21d2d6319 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -15,8 +15,7 @@ from hermes_cli.colors import Colors, color# Re-exported: ``tools/terminal_tool.py`` imports it from here to hard-block the same# gateway-lifecycle commands at execution time when ``_HERMES_GATEWAY=1``.from cron.lifecycle_guard import ( # noqa: F401- contains_gateway_lifecycle_command as _contains_gateway_lifecycle_command,-)+ contains_gateway_lifecycle_command as _contains_gateway_lifecycle_command)def _normalize_skills(single_skill=None, skills: Optional[Iterable[str]] = None) -> Optional[List[str]]:@@ -62,8 +61,7 @@ def _builtin_gateway_liveness() -> Optional[bool]:if is_gateway_runtime_lock_active():return Truefrom hermes_cli.gateway import (- find_gateway_pids, named_profile_served_by_running_multiplexer,- )+ find_gateway_pids, named_profile_served_by_running_multiplexer)# Satellite profile: no local gateway.pid, but the default multiplexer ticks its store.return bool(find_gateway_pids()) or named_profile_served_by_running_multiplexer()except Exception:@@ -196,8 +194,7 @@ def _job_rows(job: Dict[str, Any]) -> List[tuple[str, str]]:if job.get("last_status") else ""),("Dispatch", _dispatch_display(job.get("last_dispatch"))),("Execution", f"{latest_execution.get('status', '?')} {latest_execution.get('id', '?')}"- if latest_execution else ""),- ]+ if latest_execution else "")]return [("Name", job.get("name", "(unnamed)")),("Schedule", job.get("schedule_display", job.get("schedule", {}).get("value", "?"))),@@ -323,8 +320,7 @@ def _print_ticker_health(pids: list) -> None:"""from cron.jobs import (get_ticker_heartbeat_age, get_ticker_last_error, get_ticker_success_age,- TICKER_INTERVAL_SECONDS,- )+ TICKER_INTERVAL_SECONDS)from cron.scheduler import _is_fd_exhaustion_text as _cron_is_fd_exhaustion_textSTALE_AFTER = TICKER_INTERVAL_SECONDS * 3 + 20 # ~3 missed iterations + slack (200s @ 60s)hb_age = get_ticker_heartbeat_age()@@ -540,8 +536,7 @@ _JOB_DETAIL_LINES = (("monitor_url", " Monitor: {} (agent runs only on output change)"),("no_agent", " Mode: no-agent (script stdout delivered directly)"),("continuity", " Continuity: on (each run sees the previous run's output)"),- ("workdir", " Workdir: {}"),-)+ ("workdir", " Workdir: {}"))def _print_job_details(job_data: Dict[str, Any]) -> None:@@ -558,8 +553,7 @@ def cron_create(args):action="create", schedule=args.schedule, prompt=args.prompt,skill=getattr(args, "skill", None),skills=_normalize_skills(getattr(args, "skill", None), getattr(args, "skills", None)),- no_agent=getattr(args, "no_agent", False) or None, **_job_api_kwargs(args),- )+ no_agent=getattr(args, "no_agent", False) or None, **_job_api_kwargs(args))if not result.get("success"):print(color(f"Failed to create job: {result.get('error', 'unknown error')}", Colors.RED))return 1@@ -739,8 +733,7 @@ _CRON_SUBCOMMANDS = {"pause": lambda a: _job_action("pause", a.job_id, "Paused"),"resume": lambda a: cron_resume(a),"run": lambda a: _job_action("run", a.job_id, "Triggered"),- "remove": lambda a: _job_action("remove", a.job_id, "Removed"),-}+ "remove": lambda a: _job_action("remove", a.job_id, "Removed")}_CRON_SUBCOMMANDS["history"] = _CRON_SUBCOMMANDS["runs"]_CRON_SUBCOMMANDS["add"] = _CRON_SUBCOMMANDS["create"]_CRON_SUBCOMMANDS["rm"] = _CRON_SUBCOMMANDS["delete"] = _CRON_SUBCOMMANDS["remove"]diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.pyindex 24a3c015277..8c22a1e6a9a 100644--- a/hermes_cli/dashboard_procs.py+++ b/hermes_cli/dashboard_procs.py@@ -15,8 +15,7 @@ from pathlib import Path_DASHBOARD_PATTERNS = tuple(f"{launcher} {cmd}"for cmd in ("dashboard", "serve")- for launcher in ("hermes", "hermes_cli.main", "hermes_cli/main.py")-)+ for launcher in ("hermes", "hermes_cli.main", "hermes_cli/main.py"))_PS_RUN_KWARGS = dict(capture_output=True, text=True, encoding="utf-8", errors="replace")@@ -47,8 +46,7 @@ def _iter_process_table() -> list[tuple[int, str]]:from hermes_cli._subprocess_compat import bounded_probe_runresult = bounded_probe_run(["wmic", "process", "get", "ProcessId,CommandLine", "/FORMAT:LIST"],- timeout=10, errors="ignore",- )+ timeout=10, errors="ignore")if result is None or result.returncode != 0 or result.stdout is None:return rowscurrent_cmd = ""@@ -344,8 +342,7 @@ def _kill_stale_dashboard_processes(def _restart_killed_backends(killed: list[int], pid_service: dict[int, str | None], pid_cgroup: dict[int, str | None],- pid_cmdline: dict[int, list[str]], pid_home: dict[int, str | None],-) -> list[int]:+ pid_cmdline: dict[int, list[str]], pid_home: dict[int, str | None]) -> list[int]:"""Update path: restart systemd units, respawn manual argv (detached, headless, logged tologs/dashboard-restart.log; one per profile, no ``--port 0``). Returns PIDs not brought back."""unrecovered: list[int] = []@@ -387,8 +384,7 @@ def _norm_exe(path) -> str:def _detect_concurrent_hermes_instances(- scripts_dir: Path, *, exclude_pid: int | None = None-) -> list[tuple[int, str]]:+ scripts_dir: Path, *, exclude_pid: int | None = None) -> list[tuple[int, str]]:"""``(pid, name)`` of other live processes whose .exe is one of our entry-point shims.Windows blocks DELETE/REPLACE on a running .exe, so a Desktop-spawned ``hermes.EXE`` makes@@ -485,8 +481,7 @@ def _valid_lockfile_payload(parsed: object, ownership_id: str) -> bool:or parsed.get("protocolVersion") != _PROTOCOL_VERSIONor parsed.get("ownershipId") != ownership_idor not _is_hex(parsed.get("spawnNonce"), 16)- or not _is_hex(parsed.get("tokenFingerprint"), 32)- ):+ or not _is_hex(parsed.get("tokenFingerprint"), 32)):return Falsepid, port = parsed.get("pid"), parsed.get("port")if not (isinstance(pid, int) and 0 < pid <= 4194304 and isinstance(port, int)@@ -541,8 +536,7 @@ def _process_age_seconds(pid: int) -> float:def _reap_orphaned_desktop_local_serves(*, reason: str = "orphaned desktop-local hermes serve", signal_term=None, signal_kill=None,- sleep_fn=None, lock_owned_pids_fn=None, process_age_seconds_fn=None,-) -> dict[str, list]:+ sleep_fn=None, lock_owned_pids_fn=None, process_age_seconds_fn=None) -> dict[str, list]:"""Kill leftover Desktop-local ``hermes serve`` backends with no parent. Never raises.When Electron dies uncleanly its ``serve --host 127.0.0.1 --port 0`` children arediff --git a/hermes_cli/dashboard_register.py b/hermes_cli/dashboard_register.pyindex ea477960375..a6d2d1e248f 100644--- a/hermes_cli/dashboard_register.py+++ b/hermes_cli/dashboard_register.py@@ -26,8 +26,7 @@ _NAME_ADJECTIVES = ("hidden", "jolly", "keen", "lively", "lucid", "lunar", "mellow", "merry","mighty", "nimble", "noble", "polished", "quiet", "quirky", "rapid","serene", "sharp", "shiny", "silent", "snappy", "solar", "spry", "stellar",- "sunny", "swift", "tidy", "vivid", "vibrant", "witty", "zesty",-)+ "sunny", "swift", "tidy", "vivid", "vibrant", "witty", "zesty")_NAME_NOUNS = ("albatross", "antelope", "badger", "beacon", "comet", "condor", "cypress",@@ -35,8 +34,7 @@ _NAME_NOUNS = ("heron", "ibex", "jaguar", "kestrel", "lantern", "lynx", "meadow", "nebula","ocelot", "orchid", "otter", "panther", "petrel", "quasar", "raven", "reef","sparrow", "summit", "tundra", "vortex", "walrus", "willow", "yarrow",- "kepler", "tesla", "curie", "hopper", "turing", "lovelace",-)+ "kepler", "tesla", "curie", "hopper", "turing", "lovelace")def _generate_dashboard_name() -> str:@@ -59,8 +57,7 @@ def _resolve_portal_base_url(override: Optional[str] = None) -> str:def _register_self_hosted_client(*, access_token: str, portal_base_url: str, name: Optional[str], custom_redirect_uri: Optional[str],- existing_client_id: Optional[str] = None, timeout: float = 15.0,-) -> dict:+ existing_client_id: Optional[str] = None, timeout: float = 15.0) -> dict:"""POST to the portal's self-hosted-client endpoint and return the JSON body.``existing_client_id`` makes the portal update that record in place (idempotent re-runs;@@ -74,8 +71,7 @@ def _register_self_hosted_client(f"{portal_base_url.rstrip('/')}/api/oauth/self-hosted-client",data=json.dumps({k: v for k, v in fields if v}).encode("utf-8"), method="POST",headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json",- "Accept": "application/json"},- )+ "Accept": "application/json"})try:with urllib.request.urlopen(req, timeout=timeout) as resp:payload = json.loads(resp.read().decode())@@ -102,8 +98,7 @@ def _register_self_hosted_client(def _print_post_register_hint(*, client_id: str, portal_base_url: str, custom_redirect_uri: Optional[str],- wrote_portal_url: bool, public_url: str = "",-) -> None:+ wrote_portal_url: bool, public_url: str = "") -> None:"""Print the success summary + the gate-engagement caveat."""from hermes_cli.config import get_env_pathprint(f"\n Wrote to {get_env_path()}:\n HERMES_DASHBOARD_OAUTH_CLIENT_ID={client_id}")@@ -114,8 +109,7 @@ def _print_post_register_hint(print("\n Heads up — Nous login only *engages* on a non-loopback bind. A plain\n"" `hermes dashboard` (localhost) leaves the gate off and serves locally\n"- " without auth, which is fine for your own machine.\n"- )+ " without auth, which is fine for your own machine.\n")if custom_redirect_uri:try: # example host matches the one the user registeredhost = urlparse(custom_redirect_uri).hostname or "your-host"@@ -124,18 +118,15 @@ def _print_post_register_hint(print(" To require Nous login on your registered host, run the dashboard\n"f" bound publicly (it must be reachable at https://{host}) and log in\n"- " at its /login page."- )+ " at its /login page.")else:print(" To require Nous login (e.g. exposing on your LAN or a public host):\n"" hermes dashboard --host 0.0.0.0\n"- " …then log in at the dashboard's /login page."- )+ " …then log in at the dashboard's /login page.")print("\n If the dashboard is already running, restart it to pick up the new env.\n"- f" Manage or revoke this dashboard at {portal_base_url}/local-dashboards"- )+ f" Manage or revoke this dashboard at {portal_base_url}/local-dashboards")def _env_value(key: str) -> Optional[str]:@@ -202,8 +193,7 @@ def cmd_dashboard_register(args) -> None:try:result = _register_self_hosted_client(access_token=access_token, portal_base_url=portal_base_url, name=name,- custom_redirect_uri=custom_redirect_uri, existing_client_id=existing_client_id,- )+ custom_redirect_uri=custom_redirect_uri, existing_client_id=existing_client_id)except RuntimeError as exc:print(f"✗ Registration failed: {exc}")sys.exit(1)@@ -224,17 +214,14 @@ def cmd_dashboard_register(args) -> None:should_write_portal = (existing_portal != portal_base_urlif custom_portal_supplied- else not existing_portal and portal_base_url.rstrip("/") != _DEFAULT_PORTAL- )+ else not existing_portal and portal_base_url.rstrip("/") != _DEFAULT_PORTAL)wrote_portal_url = should_write_portal and _save_env_quietly("HERMES_DASHBOARD_PORTAL_URL", portal_base_url)# Public URL from --redirect-uri: written when supplied and different; never localhost-only.public_url = _public_url_from_redirect(custom_redirect_uri)wrote_public_url = bool(public_urland _env_value("HERMES_DASHBOARD_PUBLIC_URL") != public_url- and _save_env_quietly("HERMES_DASHBOARD_PUBLIC_URL", public_url)- )+ and _save_env_quietly("HERMES_DASHBOARD_PUBLIC_URL", public_url))_print_post_register_hint(client_id=client_id, portal_base_url=portal_base_url, custom_redirect_uri=custom_redirect_uri,- wrote_portal_url=wrote_portal_url, public_url=public_url if wrote_public_url else "",- )+ wrote_portal_url=wrote_portal_url, public_url=public_url if wrote_public_url else "")diff --git a/hermes_cli/debug.py b/hermes_cli/debug.pyindex df1fe193e6c..43ff19d3fe3 100644--- a/hermes_cli/debug.py+++ b/hermes_cli/debug.py@@ -23,13 +23,11 @@ logger = logging.getLogger(__name__)# Prepended to upload-bound content when redaction is enabled so paste reviewers know._REDACTION_BANNER = ("[hermes debug share: log content redacted at upload time. "- "run with --no-redact to disable]\n"-)+ "run with --no-redact to disable]\n")_EMAIL_ADDRESS_RE = re.compile(r"(?<![A-Za-z0-9._%+-])"r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"- r"(?![A-Za-z0-9._%+-])"-)+ r"(?![A-Za-z0-9._%+-])")_PASTE_RS_URL = "https://paste.rs/" # primary; dpaste.com is the fallback_DPASTE_COM_URL = "https://dpaste.com/api/"_USER_AGENT = "hermes-agent/debug-share"@@ -126,8 +124,7 @@ _GATEWAY_PRIVACY_NOTICE = ("(may contain conversation fragments) to a public paste service. ""Full logs are NOT included from the gateway — use `hermes debug share` ""from the CLI for full log uploads.\n"- "Pastes auto-delete after 6 hours."-)+ "Pastes auto-delete after 6 hours.")def _extract_paste_id(url: str) -> Optional[str]:@@ -192,8 +189,7 @@ def upload_to_pastebin(content: str, expiry_days: int = 7) -> str:errors: list[str] = []for service, upload in (("paste.rs", lambda: _upload_paste_rs(content)),- ("dpaste.com", lambda: _upload_dpaste_com(content, expiry_days=expiry_days)),- ):+ ("dpaste.com", lambda: _upload_dpaste_com(content, expiry_days=expiry_days))):try:return upload()except Exception as exc:@@ -222,9 +218,7 @@ _CLIENT_SIDE_LOGS = {"desktop": ("written by Hermes Desktop on the machine running the app, not by this ""backend. If the desktop connects to a remote/docker/SSH backend, collect "- "it on that client machine"- ),-}+ "it on that client machine")}def _missing_log_note(log_name: str) -> str:@@ -258,8 +252,7 @@ def _redact_log_text(text: str) -> str:def _read_tail_bytes(- log_path: Path, size: int, max_bytes: int, tail_lines: int,-) -> tuple[bytes, bool]:+ log_path: Path, size: int, max_bytes: int, tail_lines: int) -> tuple[bytes, bool]:"""Whole file, or (oversized) a backwards read holding ``max_bytes`` for the full upload ANDenough newlines for the summary tail from the same snapshot → (raw, truncated)."""with open(log_path, "rb") as f:@@ -331,13 +324,11 @@ def _tail_budget(name: str, log_lines: int) -> int:def _capture_default_log_snapshots(- log_lines: int, *, redact: bool = True,-) -> dict[str, LogSnapshot]:+ log_lines: int, *, redact: bool = True) -> dict[str, LogSnapshot]:"""Capture all logs used by debug-share exactly once."""return {name: _capture_log_snapshot(name, tail_lines=_tail_budget(name, log_lines), redact=redact)- for name in _REPORT_LOGS- }+ for name in _REPORT_LOGS}def _capture_dump() -> str:@@ -351,8 +342,7 @@ def _capture_dump() -> str:def collect_debug_report(*, log_lines: int = 200, dump_text: str = "",- log_snapshots: Optional[dict[str, LogSnapshot]] = None,-) -> str:+ log_snapshots: Optional[dict[str, LogSnapshot]] = None) -> str:"""Build the summary debug report (system dump + log tails) as upload-ready text.``dump_text`` is pre-captured dump output; when empty, ``hermes dump`` is run internally.@@ -420,8 +410,7 @@ class DebugShareResult:def build_debug_share(- *, log_lines: int = 200, expiry: int = 7, redact: bool = True,-) -> DebugShareResult:+ *, log_lines: int = 200, expiry: int = 7, redact: bool = True) -> DebugShareResult:"""Collect the debug report + full logs, upload each, return the URLs.Shared by ``hermes debug share`` and the dashboard ``POST /api/ops/debug-share``. Blocking