Skip to content

The agent that grows with you

refactor(web_server helpers): compact gateway/messaging/cron/oauth helpers and CLI utils (-21% LOC, zero behavior change)

Tekniumf0a451f1daf0
diff --git a/hermes_cli/web_server_cron.py b/hermes_cli/web_server_cron.py
index 2f61fbc44d8..f2dfd1ac1ac 100644
--- a/hermes_cli/web_server_cron.py
+++ b/hermes_cli/web_server_cron.py
@@ -1,10 +1,12 @@
-"""Dashboard cron helpers: per-profile scheduler I/O, job validation/normalisation, cron fire and gateway forwarding.
+"""Dashboard cron helpers: per-profile scheduler I/O, job validation/normalisation, cron fire and
+gateway forwarding.
-Split out of ``hermes_cli.web_server``; every externally used name is re-imported
-there, so ``web_server.<name>`` keeps resolving (and monkeypatching) as before.
-Helpers that tests patch on ``web_server`` are reached lazily through it.
+Split out of ``hermes_cli.web_server``; every externally used name is re-imported there, so
+``web_server.<name>`` keeps resolving (and monkeypatching). Helpers that tests patch on
+``web_server`` are reached lazily through it.
"""
+import contextlib
import logging
import inspect
import re
@@ -18,11 +20,6 @@ from hermes_cli.web_models import CronJobCreate
_log = logging.getLogger("hermes_cli.web_server")
-# ---------------------------------------------------------------------------
-# Cron job management endpoints
-# ---------------------------------------------------------------------------
-
-
def _cron_optional_text(value: Any, *, strip_trailing_slash: bool = False) -> Optional[str]:
if value is None:
return None
@@ -33,8 +30,6 @@ def _cron_optional_text(value: Any, *, strip_trailing_slash: bool = False) -> Op
def _cron_string_list(value: Any) -> Optional[List[str]]:
- if value is None:
- return None
if isinstance(value, str):
raw_items = re.split(r"[\n,]", value)
elif isinstance(value, (list, tuple)):
@@ -50,17 +45,13 @@ def _normalize_dashboard_cron_script(value: Any, profile_home: Path) -> Optional
text = _cron_optional_text(value)
if not text:
return None
-
scripts_root = (profile_home / "scripts").resolve()
raw_path = Path(text).expanduser()
candidate = raw_path.resolve() if raw_path.is_absolute() else (scripts_root / raw_path).resolve()
try:
relative = candidate.relative_to(scripts_root)
except ValueError as exc:
- raise HTTPException(
- status_code=400,
- detail=f"script must be inside {scripts_root}",
- ) from exc
+ raise HTTPException(status_code=400, detail=f"script must be inside {scripts_root}") from exc
if not candidate.exists():
raise HTTPException(status_code=400, detail=f"script does not exist: {candidate}")
if not candidate.is_file():
@@ -72,65 +63,36 @@ def _validate_dashboard_cron_effective_job(job: Dict[str, Any]) -> None:
prompt = _cron_optional_text(job.get("prompt"))
script = _cron_optional_text(job.get("script"))
skills = _cron_string_list(job.get("skills")) or _cron_string_list(job.get("skill"))
- no_agent = bool(job.get("no_agent"))
-
- if no_agent:
+ if job.get("no_agent"):
if not script:
- raise HTTPException(
- status_code=400,
- detail="no_agent=True requires a script",
- )
+ raise HTTPException(status_code=400, detail="no_agent=True requires a script")
return
-
if not (prompt or skills or script):
- raise HTTPException(
- status_code=400,
- detail="agent cron jobs require a prompt, skill, or script",
- )
+ raise HTTPException(status_code=400, detail="agent cron jobs require a prompt, skill, or script")
-def _validate_dashboard_cron_context_from(
- refs: Optional[List[str]],
- profile_name: str,
-) -> None:
+def _validate_dashboard_cron_context_from(refs: Optional[List[str]], profile_name: str) -> None:
from hermes_cli.web_server import _call_cron_for_profile
- if not refs:
- return
- for ref in refs:
- # "self" (the continuity toggle) resolves to the job's own id at run
- # time — it can't be validated against the store (create precedes the
- # job's existence).
+ for ref in refs or ():
+ # "self" (the continuity toggle) resolves to the job's own id at run time — it can't be
+ # validated against the store (create precedes the job's existence).
if isinstance(ref, str) and ref.strip().lower() == "self":
continue
if not _call_cron_for_profile(profile_name, "get_job", ref):
raise HTTPException(
status_code=400,
- detail=(
- f"context_from job '{ref}' not found in profile "
- f"'{profile_name}'"
- ),
- )
+ detail=f"context_from job '{ref}' not found in profile '{profile_name}'")
def _cron_profile_dicts() -> List[Dict[str, Any]]:
- """Return the minimal profile records needed by cron aggregation.
-
- The two callers only consume ``name``. ``list_profiles()`` also parses
- config/distribution metadata, probes gateway processes, and counts skills
- for every profile; polling cron jobs through that path creates avoidable
- GIL pressure on large profile pools.
- """
+ """Minimal profile records (callers only consume ``name``); avoids ``list_profiles()``,
+ whose config parsing, gateway probes and skill counts are GIL pressure on large pools."""
from hermes_cli.web_server import _fallback_profile_dicts
from hermes_cli import profiles as profiles_mod
try:
return [
- {
- "name": name,
- "path": str(home),
- "is_default": name == "default",
- }
- for name, home in profiles_mod.profiles_to_serve(multiplex=True)
- ]
+ {"name": name, "path": str(home), "is_default": name == "default"}
+ for name, home in profiles_mod.profiles_to_serve(multiplex=True)]
except Exception:
_log.exception("Failed to list profiles for cron dashboard; falling back to directory scan")
return _fallback_profile_dicts(profiles_mod)
@@ -139,17 +101,13 @@ def _cron_profile_dicts() -> List[Dict[str, Any]]:
def _cron_default_profile() -> str:
"""Profile to target when a cron request carries no explicit ``profile``.
- A desktop pool backend runs one process per profile (HERMES_HOME already
- scoped), but these cron endpoints deliberately route storage through the
- profiles tree via ``_cron_profile_home`` — so a hardcoded ``"default"``
- fallback would write a non-default profile's job into ``~/.hermes``.
- Resolve the process's own profile instead. ``custom`` (an unrecognized
- HERMES_HOME outside the profiles tree) has no profile-dir equivalent, so
- it keeps the legacy ``default`` fallback.
+ A desktop pool backend runs one process per profile, but these endpoints route storage through
+ the profiles tree via ``_cron_profile_home`` — a hardcoded "default" would write a non-default
+ profile's job into ~/.hermes. ``custom`` (HERMES_HOME outside the profiles tree) has no
+ profile-dir equivalent, so it keeps the legacy "default" fallback.
"""
try:
from hermes_cli.profiles import get_active_profile_name
-
name = get_active_profile_name()
except Exception:
return "default"
@@ -173,41 +131,42 @@ def _cron_profile_home(profile: Optional[str]) -> Tuple[str, Path]:
def _annotate_cron_job(job: Dict[str, Any], profile: str, home: Path) -> Dict[str, Any]:
- annotated = dict(job)
- annotated["profile"] = profile
- annotated["profile_name"] = profile
- annotated["hermes_home"] = str(home)
- annotated["is_default_profile"] = profile == "default"
- return annotated
+ return {
+ **job,
+ "profile": profile,
+ "profile_name": profile,
+ "hermes_home": str(home),
+ "is_default_profile": profile == "default"}
-def _call_cron_for_profile(target_profile: Optional[str], func_name: str, *args, **kwargs):
- """Run cron.jobs helpers against the selected profile's cron directory.
+def _cron_store_scope(home: Path):
+ """Point HERMES_HOME and the cron.jobs store at one profile's home for the block.
- The dashboard is a single process that can inspect many profiles. Route
- storage through cron.jobs' execution-context override so dashboard calls
- cannot retarget a concurrent desktop ticker's load/save transaction.
+ The dashboard is a single process inspecting many profiles; cron.jobs' execution-context
+ override keeps these calls from retargeting a concurrent desktop ticker's load/save.
"""
- from hermes_cli.web_server import _cron_profile_home
- profile_name, home = _cron_profile_home(target_profile)
from cron import jobs as cron_jobs
- from hermes_constants import (
- reset_hermes_home_override,
- set_hermes_home_override,
- )
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
token = set_hermes_home_override(str(home))
try:
with cron_jobs.use_cron_store(home):
- if func_name == "create_job":
- from cron.scheduler import create_job_with_scheduler_registration
-
- result = create_job_with_scheduler_registration(*args, **kwargs)
- else:
- result = getattr(cron_jobs, func_name)(*args, **kwargs)
+ yield cron_jobs
finally:
reset_hermes_home_override(token)
+
+def _call_cron_for_profile(target_profile: Optional[str], func_name: str, *args, **kwargs):
+ """Run a cron.jobs helper against the selected profile's cron directory."""
+ from hermes_cli.web_server import _cron_profile_home
+ profile_name, home = _cron_profile_home(target_profile)
+ with _cron_store_scope(home) as cron_jobs:
+ if func_name == "create_job":
+ from cron.scheduler import create_job_with_scheduler_registration
+ result = create_job_with_scheduler_registration(*args, **kwargs)
+ else:
+ result = getattr(cron_jobs, func_name)(*args, **kwargs)
if isinstance(result, list):
return [_annotate_cron_job(j, profile_name, home) for j in result]
if isinstance(result, dict):
@@ -218,64 +177,37 @@ def _call_cron_for_profile(target_profile: Optional[str], func_name: str, *args,
def _notify_cron_provider_for_profile(target_profile: Optional[str]) -> None:
"""Best-effort provider reconcile against one profile's job store.
- Fail-closed for external providers on a multi-profile dashboard: an
- external provider's ``reconcile`` converges its REMOTE registry toward
- one profile's jobs.json, and its orphan cleanup cancels every remote
- entry absent from that store. The NAS registry is not profile-scoped,
- so reconciling profile B would silently disarm profile A's one-shots.
- Until the provider contract carries a profile identity through
- arm/cancel/list, a multi-profile dashboard must not drive unscoped
- external reconciles at all — the affected profile simply re-arms on
- its next fire/start (idempotent via dedup_key). The built-in provider
- re-reads jobs.json each tick and stays a no-op here.
+ Fail-closed for external providers on a multi-profile dashboard: an external ``reconcile``
+ converges its REMOTE (non-profile-scoped) registry toward one profile's jobs.json and cancels
+ every remote entry absent from it, so reconciling profile B would disarm profile A's one-shots.
+ Until the provider contract carries a profile identity, skip unscoped external reconciles; the
+ affected profile re-arms on its next fire/start (idempotent via dedup_key). The built-in
+ provider re-reads jobs.json each tick and stays a no-op here.
"""
from hermes_cli.web_server import _cron_profile_dicts, _cron_profile_home
try:
_profile_name, home = _cron_profile_home(target_profile)
- from cron import jobs as cron_jobs
- from cron.scheduler_provider import (
- InProcessCronScheduler,
- resolve_cron_scheduler,
- )
- from hermes_constants import (
- reset_hermes_home_override,
- set_hermes_home_override,
- )
-
- token = set_hermes_home_override(str(home))
- try:
- with cron_jobs.use_cron_store(home):
- provider = resolve_cron_scheduler()
- if not isinstance(provider, InProcessCronScheduler):
- profile_names = [
- str(p.get("name") or "")
- for p in _cron_profile_dicts()
- ]
- if len([n for n in profile_names if n]) > 1:
- _log.warning(
- "Skipping cron provider reconcile for profile %s: "
- "external provider '%s' reconcile is not "
- "profile-scoped and would disarm other profiles' "
- "armed one-shots. The mutated profile re-arms "
- "idempotently on its next fire/start.",
- target_profile,
- provider.name,
- )
- return
- provider.on_jobs_changed()
- finally:
- reset_hermes_home_override(token)
+ from cron.scheduler_provider import InProcessCronScheduler, resolve_cron_scheduler
+ with _cron_store_scope(home):
+ provider = resolve_cron_scheduler()
+ if not isinstance(provider, InProcessCronScheduler):
+ profile_names = [str(p.get("name") or "") for p in _cron_profile_dicts()]
+ if len([n for n in profile_names if n]) > 1:
+ _log.warning(
+ "Skipping cron provider reconcile for profile %s: "
+ "external provider '%s' reconcile is not "
+ "profile-scoped and would disarm other profiles' "
+ "armed one-shots. The mutated profile re-arms "
+ "idempotently on its next fire/start.",
+ target_profile,
+ provider.name)
+ return
+ provider.on_jobs_changed()
except Exception:
- _log.debug(
- "Cron provider reconciliation failed for profile %s",
- target_profile,
- exc_info=True,
- )
+ _log.debug("Cron provider reconciliation failed for profile %s", target_profile, exc_info=True)
-def _mutate_cron_for_profile(
- target_profile: Optional[str], func_name: str, *args, **kwargs
-):
+def _mutate_cron_for_profile(target_profile: Optional[str], func_name: str, *args, **kwargs):
"""Apply a cron store mutation and reconcile its scheduler provider."""
from hermes_cli.web_server import _call_cron_for_profile, _notify_cron_provider_for_profile
result = _call_cron_for_profile(target_profile, func_name, *args, **kwargs)
@@ -308,14 +240,9 @@ async def _run_cron_dashboard_io(func, *args, **kwargs):
def _raise_if_cron_registration_error(e: Exception) -> None:
- """Re-raise a cron partial-failure (job saved, external scheduler
- registration failed) as HTTP 424 with the structured envelope.
-
- Shared by every dashboard cron-create surface so the contract can't
- drift between copies. The lazy import keeps cron out of module import.
- """
+ """Re-raise a cron partial failure (job saved, external scheduler registration failed) as
+ HTTP 424 with the structured envelope. Shared by every dashboard cron-create surface."""
from cron.scheduler import CronSchedulerRegistrationError
-
if isinstance(e, CronSchedulerRegistrationError):
raise HTTPException(status_code=424, detail=e.to_dict()) from e
@@ -329,12 +256,8 @@ def _create_cron_job_sync(body: CronJobCreate, profile: Optional[str] = None):
context_from = _cron_string_list(body.context_from)
_validate_dashboard_cron_context_from(context_from, profile_name)
no_agent = bool(body.no_agent)
- _validate_dashboard_cron_effective_job({
- "prompt": body.prompt,
- "skills": skills,
- "script": script,
- "no_agent": no_agent,
- })
+ _validate_dashboard_cron_effective_job(
+ {"prompt": body.prompt, "skills": skills, "script": script, "no_agent": no_agent})
return _mutate_cron_for_profile(
profile_name,
"create_job",
@@ -350,8 +273,7 @@ def _create_cron_job_sync(body: CronJobCreate, profile: Optional[str] = None):
context_from=context_from,
enabled_toolsets=_cron_string_list(body.enabled_toolsets),
workdir=_cron_optional_text(body.workdir),
- no_agent=no_agent,
- )
+ no_agent=no_agent)
except HTTPException:
raise
except Exception as e:
@@ -360,57 +282,29 @@ def _create_cron_job_sync(body: CronJobCreate, profile: Optional[str] = None):
raise HTTPException(status_code=400, detail=str(e))
-def _fire_cron_job_for_profile(
- profile: str,
- job_id: str,
- *,
- force: bool = False,
-) -> bool:
- """DEPRECATED for NAS webhook fires (superseded by gateway forwarding);
- retained for the dashboard trigger path — do not add new uses.
-
- Run ONE due cron job end-to-end for ``profile`` via the resolved
- scheduler provider's ``fire_due`` (store CAS claim + ``run_one_job``).
-
- Superseded by :func:`_forward_cron_fire_to_gateway`: cron fires must
- execute in the GATEWAY process (which owns the live platform adapters),
- not the dashboard. Executing here delivered through the standalone path
- only, which cannot serve relay-fronted logical platforms (their only
- sender is the live relay adapter — no native credential exists on the
- box) or E2EE rooms. Kept temporarily because external callers may still
- resolve it via the web_deps late-binding seam.
+def _fire_cron_job_for_profile(profile: str, job_id: str, *, force: bool = False) -> bool:
+ """Run ONE due cron job for ``profile`` via the scheduler provider's ``fire_due``.
+
+ DEPRECATED for NAS webhook fires — superseded by :func:`_forward_cron_fire_to_gateway`, since
+ fires must run in the GATEWAY process (it owns the live adapters; the standalone path here
+ cannot serve relay-fronted platforms or E2EE rooms). Retained for the dashboard trigger path
+ and external callers on the web_deps late-binding seam; do not add new uses.
"""
from hermes_cli.web_server import _cron_profile_home
_profile_name, home = _cron_profile_home(profile)
- from cron import jobs as cron_jobs
- from cron.scheduler_provider import (
- provider_supports_force_fire,
- resolve_cron_scheduler,
- )
- from hermes_constants import (
- reset_hermes_home_override,
- set_hermes_home_override,
- )
+ from cron.scheduler_provider import provider_supports_force_fire, resolve_cron_scheduler
- token = set_hermes_home_override(str(home))
- try:
- with cron_jobs.use_cron_store(home):
- provider = resolve_cron_scheduler()
- if force:
- if not provider_supports_force_fire(provider):
- raise HTTPException(
- status_code=409,
- detail=(
- f"Cron provider '{getattr(provider, 'name', 'custom')}' "
- "does not support atomic forced firing of paused jobs"
- ),
- )
- return bool(
- provider.fire_due(job_id, adapters=None, loop=None, force=True)
- )
- return bool(provider.fire_due(job_id, adapters=None, loop=None))
- finally:
- reset_hermes_home_override(token)
+ with _cron_store_scope(home):
+ provider = resolve_cron_scheduler()
+ if force:
+ if not provider_supports_force_fire(provider):
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ f"Cron provider '{getattr(provider, 'name', 'custom')}' "
+ "does not support atomic forced firing of paused jobs"))
+ return bool(provider.fire_due(job_id, adapters=None, loop=None, force=True))
+ return bool(provider.fire_due(job_id, adapters=None, loop=None))
def _profile_env_value(home: Path, key: str) -> str:
@@ -432,24 +326,16 @@ def _profile_env_value(home: Path, key: str) -> str:
def _gateway_fire_endpoint(profile: str, home: Path) -> str:
- """Resolve the loopback URL of the gateway api_server's cron-fire route.
-
- Port resolution mirrors gateway/config.py's api_server load order for the
- LISTENER-OWNER profile: ``platforms.api_server.extra.port`` in that
- profile's config.yaml, then ``API_SERVER_PORT`` (process env for the
- active profile, the profile's own .env otherwise), then the adapter
- default 8642. The bind host is the adapter's loopback default — the
- dashboard and gateway share a network namespace in every supported
- deployment (same host process tree, or the same container under s6).
-
- Multiplex mode (one gateway serving several profiles) exposes per-profile
- mirrors under ``/p/<profile>/…``, so a non-default profile routes through
- the default gateway's port with that prefix — only the DEFAULT profile's
- api_server is bound in that mode, so the port must be read from the
- default home, never the target profile's (a secondary's own
- ``API_SERVER_PORT`` is a port nothing listens on). Per-profile-gateway
- mode (each profile its own process/port) uses the bare path on the
- profile's own port.
+ """Loopback URL of the gateway api_server's cron-fire route.
+
+ Port resolution mirrors gateway/config.py's api_server load order for the LISTENER-OWNER
+ profile: ``platforms.api_server.extra.port`` in its config.yaml, then ``API_SERVER_PORT``
+ (process env for the active profile, the profile's own .env otherwise), then 8642. Loopback
+ is safe: dashboard and gateway share a network namespace in every supported deployment.
+
+ In multiplex mode only the DEFAULT profile's api_server is bound and exposes per-profile
+ mirrors under ``/p/<profile>/…``, so a non-default profile's port must be read from the
+ default home (a secondary's own API_SERVER_PORT is a port nothing listens on).
"""
from hermes_cli.web_server import _cron_default_profile, load_config
import os as _os
@@ -457,9 +343,7 @@ def _gateway_fire_endpoint(profile: str, home: Path) -> str:
multiplex = False
try:
from gateway.config import _env_multiplex_profiles_override
-
- cfg = load_config()
- multiplex = bool(cfg_get(cfg, "gateway", "multiplex_profiles", default=False))
+ multiplex = bool(cfg_get(load_config(), "gateway", "multiplex_profiles", default=False))
env_flag = _env_multiplex_profiles_override()
if env_flag is not None:
multiplex = env_flag
@@ -469,36 +353,24 @@ def _gateway_fire_endpoint(profile: str, home: Path) -> str:
listener_profile, listener_home = profile, home
if multiplex and profile != "default":
from hermes_constants import get_default_hermes_root
-
listener_profile, listener_home = "default", get_default_hermes_root()
_log.info(
"cron fire: multiplex gateway — resolving api_server port for %s "
"from the default profile's listener (%s)",
profile,
- listener_home,
- )
+ listener_home)
port = 0
try:
- # Profile-scoped read through the CANONICAL loader (managed-scope
- # overlay, ${ENV_VAR} expansion, profile pathing) — never a raw
- # yaml.safe_load of config.yaml (tests/hermes_cli/
- # test_config_read_guard.py). The HERMES_HOME override scopes
- # get_config_path() to the LISTENER-OWNER profile, same pattern the
- # deprecated _fire_cron_job_for_profile used for its store scope.
- from hermes_constants import (
- reset_hermes_home_override,
- set_hermes_home_override,
- )
-
+ # Profile-scoped read through the CANONICAL loader (managed-scope overlay, ${ENV_VAR}
+ # expansion) — never a raw yaml.safe_load (tests/hermes_cli/test_config_read_guard.py).
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
token = set_hermes_home_override(str(listener_home))
try:
profile_cfg = load_config()
finally:
reset_hermes_home_override(token)
- raw = cfg_get(
- profile_cfg, "platforms", "api_server", "extra", "port", default=None
- )
+ raw = cfg_get(profile_cfg, "platforms", "api_server", "extra", "port", default=None)
if raw:
port = int(raw)
except Exception:
@@ -507,42 +379,29 @@ def _gateway_fire_endpoint(profile: str, home: Path) -> str:
raw = (
_os.getenv("API_SERVER_PORT", "")
if listener_profile == _cron_default_profile()
- else _profile_env_value(listener_home, "API_SERVER_PORT")
- )
+ else _profile_env_value(listener_home, "API_SERVER_PORT"))
try:
port = int(raw) if raw else 0
except ValueError:
port = 0
- if not port:
- port = 8642
-
+ port = port or 8642
if multiplex and profile != "default":
return f"http://127.0.0.1:{port}/p/{profile}/api/cron/fire"
return f"http://127.0.0.1:{port}/api/cron/fire"
async def _forward_cron_fire_to_gateway(
- profile: str, job_id: str, authorization: str
-) -> Optional[Tuple[int, Dict[str, Any]]]:
- """Forward a Chronos fire callback to the gateway api_server on loopback.
-
- The dashboard is the hosted deployment's only public HTTP door (Fly proxy
- → internal_port 9119), but cron execution belongs to the GATEWAY process:
- it owns the live platform adapters, so delivery works for relay-fronted
- logical platforms and E2EE rooms — the standalone path the dashboard used
- to run cannot serve either. This forwards the fire byte-preserved (same
- job_id, same NAS bearer — the gateway re-verifies the JWT itself) and
- passes the gateway's response through.
-
- Returns ``(status_code, body)`` from the gateway, or ``None`` when the
- gateway is unreachable (not started yet after a scale-to-zero wake,
- restarting, or api_server disabled) — the caller maps that to 503 so NAS
- retries per the Chronos contract (non-2xx = retryable; the store CAS
- de-dupes the eventual double fire), UNLESS the profile's gateway was
- deliberately stopped (see :func:`_gateway_intentionally_stopped`), in
- which case the caller drops the fire with 200 — retrying into an
- operator-stopped gateway can never succeed and only burns scheduler
- retries (OOF-266).
+ profile: str, job_id: str, authorization: str) -> Optional[Tuple[int, Dict[str, Any]]]:
+ """Forward a Chronos fire callback byte-preserved to the gateway api_server on loopback.
+
+ The dashboard is the hosted deployment's only public HTTP door, but cron execution belongs to
+ the GATEWAY process (live adapters → relay-fronted platforms and E2EE rooms work). Same job_id
+ and NAS bearer; the gateway re-verifies the JWT itself.
+
+ Returns ``(status_code, body)``, or ``None`` when the gateway is unreachable (scale-to-zero
+ wake, restart, api_server disabled). The caller maps None to 503 so NAS retries (store CAS
+ de-dupes a double fire) — unless :func:`_gateway_intentionally_stopped`, in which case it
+ drops the fire with 200: retrying into an operator-stopped gateway can never succeed.
"""
from hermes_cli.web_server import _cron_profile_home
_profile_name, home = _cron_profile_home(profile)
@@ -551,16 +410,11 @@ async def _forward_cron_fire_to_gateway(
try:
async with httpx.AsyncClient(timeout=10.0) as client:
- resp = await client.post(
- url,
- json={"job_id": job_id},
- headers={"Authorization": authorization},
- )
+ resp = await client.post(url, json={"job_id": job_id}, headers={"Authorization": authorization})
except Exception as exc:
_log.warning(
"cron fire forward to %s failed (%s: %s); returning 503 for NAS retry",
- url, type(exc).__name__, exc,
- )
+ url, type(exc).__name__, exc)
return None
try:
body = resp.json()
@@ -574,24 +428,12 @@ async def _forward_cron_fire_to_gateway(
def _gateway_intentionally_stopped(profile: Optional[str]) -> bool:
"""True when the profile's gateway is stopped BY OPERATOR INTENT.
- Reads the durable ``desired_state`` field of the profile's
- ``gateway_state.json`` — written exclusively by the s6 lifecycle
- commands (``hermes gateway stop`` persists ``"stopped"``; start and
- restart persist ``"running"``, see service_manager's
- ``_write_gateway_desired_state``). This is the same operator-intent
- signal container-boot reconciliation trusts, and it is precisely NOT
- set to "stopped" during transient windows (crash loops, drains,
- scale-to-zero wakes, restarts) — so it cleanly splits "retry will
- eventually succeed" from "retry can never succeed".
-
- Deliberately does NOT fall back to the volatile ``gateway_state``
- runtime field: a legacy file without ``desired_state`` (or a gateway
- that crashed before persisting) must stay on the retryable-503 path.
- Failing open to "not intentionally stopped" is the safe direction —
- the worst case is retries against a dead gateway, which is exactly
- today's behavior.
-
- Exception-safe: any resolution or parse failure returns False.
+ Reads the durable ``desired_state`` of gateway_state.json, written only by the s6 lifecycle
+ commands (``gateway stop`` persists "stopped"; start/restart persist "running") and never
+ during transient windows (crash loops, drains, wakes) — so it splits "retry will eventually
+ succeed" from "retry can never succeed". Deliberately does NOT fall back to the volatile
+ ``gateway_state`` runtime field: a legacy/crashed file must stay on the retryable-503 path.
+ Any resolution or parse failure returns False (fail open toward retry).
"""
from hermes_cli.web_server import _cron_profile_home
import json as _json
@@ -602,8 +444,6 @@ def _gateway_intentionally_stopped(profile: Optional[str]) -> bool:
if not state_file.exists():
return False
data = _json.loads(state_file.read_text(encoding="utf-8"))
- if not isinstance(data, dict):
- return False
- return data.get("desired_state") == "stopped"
+ return isinstance(data, dict) and data.get("desired_state") == "stopped"
except Exception:
return False
diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.py
index af87beb40e6..2b79299b61b 100644
--- a/hermes_cli/web_server_gateway.py
+++ b/hermes_cli/web_server_gateway.py
@@ -1,8 +1,9 @@
-"""Gateway/process helpers for the dashboard: per-profile gateway topology (+cache), action subprocess spawning, gateway restart plumbing, system platform display.
+"""Gateway/process helpers for the dashboard: per-profile gateway topology (+cache), action
+subprocess spawning, gateway restart plumbing, system platform display.
-Split out of ``hermes_cli.web_server``; every externally used name is re-imported
-there, so ``web_server.<name>`` keeps resolving (and monkeypatching) as before.
-Helpers that tests patch on ``web_server`` are reached lazily through it.
+Split out of ``hermes_cli.web_server``; every externally used name is re-imported there, so
+``web_server.<name>`` keeps resolving (and monkeypatching). Helpers that tests patch on
+``web_server`` are reached lazily through it.
"""
import logging
@@ -23,62 +24,35 @@ from hermes_cli.config import get_hermes_home
_log = logging.getLogger("hermes_cli.web_server")
-# DEPRECATED (scheduled for removal): GATEWAY_HEALTH_URL / GATEWAY_HEALTH_TIMEOUT.
-# Cross-container / cross-host gateway liveness detection will be folded into a
-# first-class dashboard config key so it's no longer Docker-adjacent lore buried
-# in env vars. The env vars still work for now so existing Compose deployments
-# don't break. Do not add new callers — wire new uses through the planned
-# config surface.
-
-
def _probe_gateway_health() -> tuple[bool, dict | None]:
- """Probe the gateway via its HTTP health endpoint (cross-container).
-
- .. deprecated::
- Driven by the deprecated ``GATEWAY_HEALTH_URL`` /
- ``GATEWAY_HEALTH_TIMEOUT`` env vars. Scheduled for removal alongside
- a move to a first-class dashboard config key. See
- :data:`_GATEWAY_HEALTH_URL` for context.
-
- Uses ``/health/detailed`` first (returns full state), falling back to
- the simpler ``/health`` endpoint. Returns ``(is_alive, body_dict)``.
-
- Accepts any of these as ``GATEWAY_HEALTH_URL``:
- - ``http://gateway:8642`` (base URL — recommended)
- - ``http://gateway:8642/health`` (explicit health path)
- - ``http://gateway:8642/health/detailed`` (explicit detailed path)
+ """Probe the gateway's HTTP health endpoint (cross-container). Blocking — run in an executor.
- This is a **blocking** call — run via ``run_in_executor`` from async code.
+ DEPRECATED: driven by the ``GATEWAY_HEALTH_URL`` / ``GATEWAY_HEALTH_TIMEOUT`` env vars,
+ to be replaced by a dashboard config key; do not add callers. Accepts a base URL or an
+ explicit ``/health`` / ``/health/detailed`` path; tries ``/health/detailed`` first.
"""
from hermes_cli.web_server import _GATEWAY_HEALTH_TIMEOUT, _GATEWAY_HEALTH_URL
if not _GATEWAY_HEALTH_URL:
return False, None
-
- # Normalise to base URL so we always probe the right paths regardless of
- # whether the user included /health or /health/detailed in the env var.
base = _GATEWAY_HEALTH_URL.rstrip("/")
if base.endswith("/health/detailed"):
base = base[: -len("/health/detailed")]
elif base.endswith("/health"):
base = base[: -len("/health")]
-
for path in (f"{base}/health/detailed", f"{base}/health"):
try:
req = urllib.request.Request(path, method="GET")
with urllib.request.urlopen(req, timeout=_GATEWAY_HEALTH_TIMEOUT) as resp:
if resp.status == 200:
- body = json.loads(resp.read())
- return True, body
+ return True, json.loads(resp.read())
except Exception:
continue
return False, None
-# Host TCP ports each port-binding gateway platform listens on, as
-# ``platform-name -> (config port key, adapter default)``. Mirrors
-# ``PORT_BINDING_PLATFORM_VALUES`` in gateway/config.py and each adapter's
-# DEFAULT_PORT / DEFAULT_WEBHOOK_PORT constant. Used only for the dashboard's
-# gateway-topology readout — best-effort display data, not a bind source.
+# ``platform-name -> (config port key, adapter default)`` for port-binding gateway platforms.
+# Mirrors PORT_BINDING_PLATFORM_VALUES (gateway/config.py) and each adapter's DEFAULT_PORT /
+# DEFAULT_WEBHOOK_PORT. Display-only data for the topology readout, not a bind source.
_PORT_BINDING_PLATFORM_PORTS: Dict[str, Tuple[str, int]] = {
"webhook": ("port", 8644),
"api_server": ("port", 8642),
@@ -89,42 +63,34 @@ _PORT_BINDING_PLATFORM_PORTS: Dict[str, Tuple[str, int]] = {
"sms": ("webhook_port", 8080),
"whatsapp_cloud": ("webhook_port", 8090),
"line": ("port", 8646),
- "teams": ("port", 3978),
-}
+ "teams": ("port", 3978)}
# Platform states that mean the adapter is NOT serving its port right now.
_PLATFORM_DEAD_STATES = frozenset({"fatal", "disconnected", "stopped"})
def _profile_platform_ports(profile_home: Path, runtime: Optional[dict]) -> Dict[str, int]:
- """Best-effort map of ``platform -> host TCP port`` for one profile's gateway.
-
- Reads the platforms the running gateway reported in its
- ``gateway_state.json`` and resolves each port-binding platform's port from
- the profile's ``config.yaml`` (top-level ``platforms:`` wins over
- ``gateway.platforms:``, matching ``load_gateway_config`` precedence),
- falling back to the adapter default. Display-only: env-var port overrides
- (e.g. ``WEBHOOK_PORT`` in that profile's .env) are not resolved here.
+ """Best-effort ``platform -> host TCP port`` for one profile's live gateway.
+
+ Ports come from the profile's own config.yaml (``gateway.platforms`` then top-level
+ ``platforms`` — later wins, matching load_gateway_config precedence), falling back to the
+ adapter default. Env-var overrides (e.g. WEBHOOK_PORT in that profile's .env) are not resolved.
"""
platforms = (runtime or {}).get("platforms") or {}
active = [
name for name, state in platforms.items()
if name in _PORT_BINDING_PLATFORM_PORTS
and isinstance(state, dict)
- and state.get("state") not in _PLATFORM_DEAD_STATES
- ]
+ and state.get("state") not in _PLATFORM_DEAD_STATES]
if not active:
return {}
blocks: Dict[str, dict] = {}
try:
- # Multi-profile probe: load_config() targets the ACTIVE profile's
- # home, so read the probed profile's file via the raw primitive.
+ # load_config() targets the ACTIVE profile's home; read the probed profile's file raw.
from hermes_cli.config import read_user_config_raw
cfg = read_user_config_raw(profile_home / "config.yaml")
gateway_cfg = cfg.get("gateway") if isinstance(cfg.get("gateway"), dict) else {}
- # gateway.platforms first, top-level platforms second — later wins,
- # matching the precedence in gateway.config.load_gateway_config().
for src in ((gateway_cfg or {}).get("platforms"), cfg.get("platforms")):
if not isinstance(src, dict):
continue
@@ -147,97 +113,50 @@ def _profile_platform_ports(profile_home: Path, runtime: Optional[dict]) -> Dict
return ports
-def _profile_gateway_writer_identity(
- profile_home: Path, runtime: Optional[dict]
-) -> Optional[tuple]:
- """``(pid, start_time)`` identity of the profile's LIVE gateway, or None.
+def _profile_gateway_writer_identity(profile_home: Path, runtime: Optional[dict]) -> Optional[tuple]:
+ """``(pid, start_time)`` of the profile's LIVE gateway, or None.
- Reuses the validated-liveness helper — recorded PID checked against the
- live process table, the start-time PID-reuse fingerprint, and the
- profile's home — then reads the live process's fingerprint via the same
- ``_get_process_start_time`` that stamped it, so equality is exact (no
- unit or clock-source mismatch). None when the record doesn't belong to
- a live gateway; nothing in it is current by definition then.
+ Uses the same validated-liveness helper and the same ``_get_process_start_time`` that stamped
+ the record, so equality is exact (no unit/clock-source mismatch).
"""
try:
- from gateway.status import (
- _get_process_start_time,
- get_runtime_status_running_pid,
- )
-
+ from gateway.status import _get_process_start_time, get_runtime_status_running_pid
pid = get_runtime_status_running_pid(runtime, expected_home=profile_home)
if pid is None:
return None
start_time = _get_process_start_time(pid)
- if start_time is None:
- return None
- return (pid, start_time)
+ return None if start_time is None else (pid, start_time)
except Exception:
return None
-def _owned_profile_platforms(
- writer_identity: Optional[tuple], platforms: dict
-) -> dict:
- """Keep only platform entries the profile's CURRENT process wrote.
-
- Gateway startup deliberately preserves plain platform entries in
- ``gateway_state.json`` across restarts (the dashboard keeps showing
- last-known state while adapters reconnect), and the active-profile
- endpoint compensates by filtering them against the current
- configuration. The cross-profile aggregation has no equivalent config
- context (a profile's platform set depends on tokens in that profile's
- ``.env`` behind its secret scope), so it demands strict process
- ownership instead: ``write_runtime_status`` stamps every platform write
- with the writer's ``(pid, start_time)`` identity, and an entry is
- aggregatable only when that identity equals the profile's live gateway
- process — exact match, no clock heuristics, so an entry written moments
- before a fast restart can never masquerade as current. A fatal entry
- left behind by a platform the operator has since disabled/removed thus
- stops degrading fleet health as soon as that profile's gateway restarts
- (a config change requires that restart to take effect anyway). Fail
- closed: entries without a writer identity (legacy records) or records
- with no live process are excluded — aggregation is a supplement, and a
- false "degraded forever" is the worse failure mode.
+def _owned_profile_platforms(writer_identity: Optional[tuple], platforms: dict) -> dict:
+ """Keep only platform entries stamped by the profile's CURRENT gateway process.
+
+ Gateway startup preserves plain platform entries in gateway_state.json across restarts, so the
+ raw map can carry fatal state for platforms since disabled/removed. Cross-profile aggregation
+ has no config context to filter against, so it demands exact ``(pid, start_time)`` writer
+ identity instead. Fail closed: legacy entries without identity, or no live process, yield {} —
+ a false "degraded forever" is the worse failure mode.
"""
if writer_identity is None:
return {}
live_pid, live_start = writer_identity
- owned: Dict[str, dict] = {}
- for key, value in platforms.items():
- if not isinstance(value, dict):
- continue
- if (
- value.get("writer_pid") == live_pid
- and value.get("writer_start_time") == live_start
- ):
- owned[key] = value
- return owned
+ return {
+ key: value for key, value in platforms.items()
+ if isinstance(value, dict)
+ and value.get("writer_pid") == live_pid
+ and value.get("writer_start_time") == live_start}
def _collect_profile_gateway_topology() -> Dict[str, Any]:
"""Enumerate profiles and the gateways serving them for ``/api/status``.
- Returns ``{"profiles": [...], "gateway_mode": ..., "gateways": [...]}``:
-
- * ``profiles`` — every profile on the host (default + named), from
- ``profiles_to_serve(True)`` (the cheap enumeration chokepoint — no
- per-profile config reads or skill counts).
- * ``gateways`` — one entry per profile with a LIVE gateway process:
- ``{"profile", "ports", "served_profiles"?}``. Liveness reuses
- ``_check_gateway_running`` so this agrees with the profiles sidebar.
- * ``gateway_mode`` — ``"multiplex"`` when the default gateway serves
- multiple profiles (gateway.multiplex_profiles), ``"single"`` for one
- live gateway, ``"multiple"`` for independent per-profile gateways,
- ``"none"`` when nothing is running.
- * ``profile_platforms`` — ``{profile: platforms}`` runtime platform maps
- for each LIVE gateway, ownership-filtered to entries stamped by that
- profile's current process (stale preserved entries for since-removed
- platforms are excluded — see ``_owned_profile_platforms``). Internal
- aggregation input for ``/api/status`` (independent per-profile gateways
- write failures to their own ``gateway_state.json``, which the
- unparameterized endpoint would otherwise never see). Never exposed
- directly.
+ Returns ``profiles`` (all profile names via the cheap ``profiles_to_serve(True)`` chokepoint),
+ ``gateways`` (one ``{"profile", "ports", "served_profiles"?}`` per LIVE gateway; liveness via
+ ``_check_gateway_running`` so it agrees with the sidebar), ``gateway_mode``
+ (multiplex / single / multiple / none) and ``profile_platforms`` — ownership-filtered runtime
+ platform maps per live gateway, an internal aggregation input never exposed directly.
"""
from hermes_cli.web_server import _profile_gateway_writer_identity
try:
@@ -246,14 +165,8 @@ def _collect_profile_gateway_topology() -> Dict[str, Any]:
homes = profiles_to_serve(True)
except Exception:
_log.debug("profile/gateway topology enumeration failed", exc_info=True)
- return {
- "profiles": [],
- "gateway_mode": "unknown",
- "gateways": [],
- "profile_platforms": {},
- }
-
- profile_names = [name for name, _home in homes]
+ return {"profiles": [], "gateway_mode": "unknown", "gateways": [], "profile_platforms": {}}
+
gateways: List[Dict[str, Any]] = []
profile_platforms: Dict[str, dict] = {}
multiplex = False
@@ -272,53 +185,31 @@ def _collect_profile_gateway_topology() -> Dict[str, Any]:
multiplex = True
plats = (runtime or {}).get("platforms")
if isinstance(plats, dict) and plats:
- # Ownership filter: gateway startup preserves plain platform
- # entries across restarts, so the raw map can carry fatal state
- # for platforms the operator has since disabled/removed. Only
- # entries stamped with the profile's current live process's
- # writer identity are aggregation candidates (see
- # _owned_profile_platforms).
- owned = _owned_profile_platforms(
- _profile_gateway_writer_identity(home, runtime), plats
- )
+ owned = _owned_profile_platforms(_profile_gateway_writer_identity(home, runtime), plats)
if owned:
profile_platforms[name] = owned
- entry: Dict[str, Any] = {
- "profile": name,
- "ports": _profile_platform_ports(home, runtime),
- }
+ entry: Dict[str, Any] = {"profile": name, "ports": _profile_platform_ports(home, runtime)}
if served:
entry["served_profiles"] = served
gateways.append(entry)
if multiplex:
mode = "multiplex"
- elif len(gateways) > 1:
- mode = "multiple"
- elif len(gateways) == 1:
- mode = "single"
else:
- mode = "none"
-
+ mode = {0: "none", 1: "single"}.get(len(gateways), "multiple")
return {
- "profiles": profile_names,
+ "profiles": [name for name, _home in homes],
"gateway_mode": mode,
"gateways": gateways,
- "profile_platforms": profile_platforms,
- }
-
-
-# /api/status is polled ~1/s by the desktop app while it waits for the backend
-# (and again by the dashboard badge). Each uncached call above walks 7+ profile
-# homes (yaml.safe_load with the pure-Python loader + psutil process-table
-# probes + realpath walks) inside the default executor; concurrent polls pile
-# up and hold the GIL for 14-16s, starving the event loop — the desktop WS
-# never receives gateway.ready and boot fails ("event loop stalled ... GIL
-# pressure suspected"). Topology changes on gateway start/stop, so a short TTL
-# cache with a collapse lock keeps the scan to one per window. The cache also
-# remembers which collector produced the entry: tests monkeypatch
-# _collect_profile_gateway_topology per case, and the identity check keeps
-# them hermetic without needing a reset hook (a swapped collector is a miss).
+ "profile_platforms": profile_platforms}
+
+
+# /api/status is polled ~1/s by the desktop app while it waits for the backend. Each uncached
+# collect walks 7+ profile homes (pure-Python yaml + psutil + realpath) in the default executor;
+# concurrent polls pile up and hold the GIL for 14-16s, starving the loop so the desktop WS never
+# gets gateway.ready. A short TTL cache with a collapse lock keeps the scan to one per window.
+# The cache remembers which collector produced the entry: tests monkeypatch
+# _collect_profile_gateway_topology per case, and a swapped collector is a miss (no reset hook).
_TOPOLOGY_CACHE: Dict[str, Any] = {"ts": 0.0, "data": None, "fn": None}
_TOPOLOGY_CACHE_LOCK = threading.Lock()
_TOPOLOGY_CACHE_TTL = 10.0
@@ -328,8 +219,7 @@ def _topology_cache_get(fn: Any) -> Optional[Dict[str, Any]]:
if (
_TOPOLOGY_CACHE["data"] is not None
and _TOPOLOGY_CACHE["fn"] is fn
- and time.monotonic() - _TOPOLOGY_CACHE["ts"] < _TOPOLOGY_CACHE_TTL
- ):
+ and time.monotonic() - _TOPOLOGY_CACHE["ts"] < _TOPOLOGY_CACHE_TTL):
return _TOPOLOGY_CACHE["data"]
return None
@@ -345,24 +235,16 @@ def _collect_profile_gateway_topology_cached() -> Dict[str, Any]:
if cached is not None:
return cached
data = fn()
- _TOPOLOGY_CACHE["data"] = data
- _TOPOLOGY_CACHE["fn"] = fn
- _TOPOLOGY_CACHE["ts"] = time.monotonic()
+ _TOPOLOGY_CACHE.update(data=data, fn=fn, ts=time.monotonic())
return data
def _load_configured_gateway_platforms() -> set[str]:
- """Load connected platform names away from the asyncio event loop.
-
- The first ``load_gateway_config()`` call performs platform discovery and
- can take longer than Desktop's WebSocket connect timeout on Windows. This
- helper is synchronous by design; ``get_status`` runs it in Starlette's
- worker pool so a concurrent ``/api/ws`` handshake can still complete.
- """
+ """Connected platform names; synchronous by design — the first ``load_gateway_config()`` does
+ platform discovery and can outlast Desktop's WS connect timeout on Windows, so ``get_status``
+ runs this in Starlette's worker pool."""
from gateway.config import load_gateway_config
-
- gateway_config = load_gateway_config()
- return {platform.value for platform in gateway_config.get_connected_platforms()}
+ return {platform.value for platform in load_gateway_config().get_connected_platforms()}
_WINDOWS_11_MIN_BUILD = 22000
@@ -372,83 +254,47 @@ def _windows_build_number(version: str, platform_label: str) -> Optional[int]:
"""Extract the Windows NT build number from stdlib platform strings."""
for value in (version or "", platform_label or ""):
match = re.search(r"(?:^|[^\d])10\.0\.(\d{5,})(?:[^\d]|$)", value)
- if not match:
- continue
- try:
+ if match:
return int(match.group(1))
- except ValueError:
- continue
return None
-def _display_system_platform(
- *,
- system: str,
- release: str,
- version: str,
- platform_label: str,
-) -> Dict[str, str]:
- """Return host OS fields for display while preserving stdlib detail."""
+def _display_system_platform(*, system: str, release: str, version: str, platform_label: str) -> Dict[str, str]:
+ """Host OS fields for display; Windows 10 builds >= 22000 are relabelled Windows 11."""
if system == "Windows" and release == "10":
build = _windows_build_number(version, platform_label)
if build is not None and build >= _WINDOWS_11_MIN_BUILD:
- platform_label = re.sub(
- r"^Windows-10(?=-)",
- "Windows-11",
- platform_label,
- count=1,
- )
+ platform_label = re.sub(r"^Windows-10(?=-)", "Windows-11", platform_label, count=1)
release = "11"
-
- return {
- "os": system,
- "os_release": release,
- "os_version": version,
- "platform": platform_label,
- }
+ return {"os": system, "os_release": release, "os_version": version, "platform": platform_label}
# ---------------------------------------------------------------------------
-# Gateway + update actions (invoked from the Status page).
-#
-# Both commands are spawned as detached subprocesses so the HTTP request
-# returns immediately. stdin is closed (``DEVNULL``) so any stray ``input()``
-# calls fail fast with EOF rather than hanging forever. stdout/stderr are
-# streamed to a per-action log file under ``~/.hermes/logs/<action>.log`` so
-# the dashboard can tail them back to the user.
+# Gateway + update actions (invoked from the Status page). Spawned detached so the request
+# returns immediately; stdin is DEVNULL so stray input() fails fast; stdout/stderr stream to
+# ~/.hermes/logs/<action>.log which the dashboard tails.
# ---------------------------------------------------------------------------
_ACTION_LOG_DIR: Path = get_hermes_home() / "logs"
-# Short ``name`` (from the URL) → absolute log file path.
+# Short ``name`` (from the URL) → log file name under _ACTION_LOG_DIR.
_ACTION_LOG_FILES: Dict[str, str] = {
"gateway-restart": "gateway-restart.log",
"gateway-start": "gateway-start.log",
"gateway-stop": "gateway-stop.log",
"hermes-update": "hermes-update.log",
- "doctor": "action-doctor.log",
- "security-audit": "action-security-audit.log",
- "backup": "action-backup.log",
- "import": "action-import.log",
- "checkpoints-prune": "action-checkpoints-prune.log",
- "skills-install": "action-skills-install.log",
- "skills-uninstall": "action-skills-uninstall.log",
- "skills-update": "action-skills-update.log",
- "curator-run": "action-curator-run.log",
- "prompt-size": "action-prompt-size.log",
- "dump": "action-dump.log",
- "config-migrate": "action-config-migrate.log",
- "tools-post-setup": "action-tools-post-setup.log",
+ **{name: f"action-{name}.log" for name in (
+ "doctor", "security-audit", "backup", "import", "checkpoints-prune", "skills-install",
+ "skills-uninstall", "skills-update", "curator-run", "prompt-size", "dump", "config-migrate",
+ "tools-post-setup",
+ )},
}
-# ``name`` → most recently spawned Popen handle. Used so ``status`` can
-# report liveness and exit code without shelling out to ``ps``.
+# ``name`` → most recent Popen handle / argv / action id, so ``status`` needs no ``ps``.
_ACTION_PROCS: Dict[str, subprocess.Popen] = {}
_ACTION_COMMANDS: Dict[str, Tuple[str, ...]] = {}
_ACTION_IDS: Dict[str, str] = {}
-
-# ``name`` → completed synthetic action result for actions the server handled
-# without spawning a subprocess (for example, unsupported Docker updates).
+# ``name`` → synthetic result for actions handled without a subprocess (e.g. unsupported Docker updates).
_ACTION_RESULTS: Dict[str, Dict[str, Any]] = {}
@@ -462,31 +308,21 @@ def _terminate_desktop_managed_gateway() -> None:
if proc.poll() is None:
proc.terminate()
except OSError:
- # The child may have exited between poll() and terminate().
- pass
+ pass # exited between poll() and terminate()
def _dashboard_spawn_executable() -> str:
- """Interpreter for detached dashboard actions.
-
- Prefers the install's own venv interpreter over ``sys.executable`` when
- they differ. Under an SSH remote backend the web server is launched by
- running the **uv base interpreter** with the venv's site-packages
- injected into ``sys.path`` at startup (``-c "sys.path[:0]=[...];
- runpy.run_module('hermes_cli.main', ...)"``) — so ``sys.executable`` is
- the dependency-less base python and a detached action spawned from it
- dies on the first third-party import (``ModuleNotFoundError: yaml``),
- because the injected path is a startup artifact of the parent and is
- not inherited (#90026). The venv launcher resolves the same dependency
- set on its own.
-
- Falls back to ``sys.executable`` when no venv interpreter exists next
- to the install (in-process dev runs, exotic layouts). On Windows the
- spawn below carries ``windows_detach_flags()`` (CREATE_NO_WINDOW), so
- the console python owns a single hidden console that its own subprocess
- spawns inherit — the action stays invisible without resorting to
- console-less pythonw.exe, which would make every console-subsystem
- descendant flash its own conhost (#54220/#56747).
+ """Interpreter for detached dashboard actions: the install's venv python when it differs
+ from ``sys.executable``, else ``sys.executable``.
+
+ Under an SSH remote backend the server runs on the uv BASE interpreter with the venv's
+ site-packages injected into sys.path at startup, so ``sys.executable`` is dependency-less and
+ a detached child dies on its first third-party import; the venv launcher resolves the same
+ dependency set on its own. Paths are compared UNRESOLVED: the venv python is typically a
+ symlink to the base interpreter, so resolving would make them compare equal (exactly the
+ case this fixes), and pyvenv.cfg discovery keys off argv0's unresolved location. On Windows
+ the console python plus ``windows_detach_flags()`` keeps the action invisible without
+ pythonw.exe (which makes every console descendant flash its own conhost).
"""
from hermes_cli.web_server import PROJECT_ROOT
exe = Path(sys.executable)
@@ -494,21 +330,9 @@ def _dashboard_spawn_executable() -> str:
for rel in ("venv/bin/python", "venv/Scripts/python.exe"):
candidate = PROJECT_ROOT / rel
if candidate.is_file():
- # Same interpreter → keep sys.executable (preserves the
- # docstring's console-ownership behavior verbatim). Compare
- # UNRESOLVED normalized paths: a venv's bin/python is
- # typically a SYMLINK to the base interpreter, so resolving
- # both sides makes the venv python and the dependency-less
- # base compare equal — exactly the SSH-runtime case this
- # function exists to fix. The unresolved path IS the venv's
- # identity (pyvenv.cfg discovery keys off argv0's location).
if os.path.normcase(os.path.normpath(str(candidate))) == (
- os.path.normcase(os.path.normpath(str(exe)))
- ):
+ os.path.normcase(os.path.normpath(str(exe)))):
return sys.executable
- # Return the candidate UNRESOLVED for the same reason:
- # invoking the resolved target would bypass pyvenv.cfg and
- # run the bare base interpreter again.
return str(candidate)
except OSError:
pass
@@ -516,59 +340,35 @@ def _dashboard_spawn_executable() -> str:
def _spawn_hermes_action(
- subcommand: List[str],
- name: str,
- *,
- env_overrides: Optional[Dict[str, str]] = None,
+ subcommand: List[str], name: str, *, env_overrides: Optional[Dict[str, str]] = None
) -> subprocess.Popen:
- """Spawn ``hermes <subcommand>`` detached and record the Popen handle.
-
- Uses the running interpreter's ``hermes_cli.main`` module so the action
- inherits the same venv/PYTHONPATH the web server is using.
- """
+ """Spawn ``hermes <subcommand>`` detached (via ``hermes_cli.main``) and record the handle."""
from hermes_cli.web_server import (
- PROJECT_ROOT,
- _ACTION_COMMANDS,
- _ACTION_IDS,
- _ACTION_LOG_DIR,
- _ACTION_PROCS,
- _ACTION_RESULTS,
+ PROJECT_ROOT, _ACTION_COMMANDS, _ACTION_IDS, _ACTION_LOG_DIR, _ACTION_PROCS, _ACTION_RESULTS,
)
- log_file_name = _ACTION_LOG_FILES[name]
_ACTION_LOG_DIR.mkdir(parents=True, exist_ok=True)
- log_path = _ACTION_LOG_DIR / log_file_name
- log_file = open(log_path, "ab", buffering=0)
- log_file.write(
- f"\n=== {name} started {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n".encode()
- )
+ log_file = open(_ACTION_LOG_DIR / _ACTION_LOG_FILES[name], "ab", buffering=0)
+ log_file.write(f"\n=== {name} started {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n".encode())
cmd = [_dashboard_spawn_executable(), "-m", "hermes_cli.main", *subcommand]
-
- # The dashboard runs *inside* the gateway process, so os.environ carries
- # _HERMES_GATEWAY=1. Inheriting it makes a spawned `hermes gateway restart`
- # trip the in-process restart-loop guard and exit 1 — silently failing the
- # dashboard's auto-restart paths. The gateway's own restart watcher already
- # drops it (gateway/run.py); mirror that here (#52470).
+ # The dashboard runs inside the gateway process, so os.environ carries _HERMES_GATEWAY=1;
+ # inheriting it trips the child's in-process restart-loop guard (exit 1). Drop it, like
+ # the gateway's own restart watcher does.
action_env = {**os.environ, "HERMES_NONINTERACTIVE": "1"}
action_env.pop("_HERMES_GATEWAY", None)
-
popen_kwargs: Dict[str, Any] = {
"cwd": str(PROJECT_ROOT),
"stdin": subprocess.DEVNULL,
"stdout": log_file,
"stderr": subprocess.STDOUT,
- "env": {**action_env, **(env_overrides or {})},
- }
+ "env": {**action_env, **(env_overrides or {})}}
if sys.platform == "win32":
popen_kwargs["creationflags"] = windows_detach_flags()
else:
popen_kwargs["start_new_session"] = True
proc = subprocess.Popen(cmd, **popen_kwargs)
- # The child inherits its own duplicated fd for stdout/stderr, so the
- # parent's handle can be released immediately — otherwise we leak one
- # fd per spawned action.
- log_file.close()
+ log_file.close() # child holds its own dup'd fd; keeping ours leaks one per action
_ACTION_RESULTS.pop(name, None)
_ACTION_COMMANDS[name] = tuple(subcommand)
_ACTION_PROCS[name] = proc
@@ -586,12 +386,9 @@ def _gateway_subcommand(profile: Optional[str], verb: str) -> List[str]:
def _restart_gateway_after(profile: Optional[str], *, what: str, label: str) -> dict[str, Any]:
- """Best-effort gateway restart after a config change (webhooks, onboarding).
-
- The config save stays authoritative; a failed spawn is reported in the
- result (``restart_started: False`` + ``restart_error``) so the UI can fall
- back to its manual restart banner instead of failing the request.
- """
+ """Best-effort gateway restart after a config change. The save stays authoritative: a failed
+ spawn is reported (``restart_started: False`` + ``restart_error``) so the UI can fall back to
+ its manual restart banner instead of failing the request."""
from hermes_cli.web_server import _spawn_gateway_restart
try:
proc, reused = _spawn_gateway_restart(profile)
@@ -606,10 +403,8 @@ def _restart_gateway_after(profile: Optional[str], *, what: str, label: str) ->
def _split_text_for_speak_stream(text: str, cap: int) -> list:
"""Split *text* into provider-cap-sized pieces on sentence boundaries.
- Deliberately NOT unified with gateway.platforms.helpers'
- split_text_fence_aware: this splitter reflows whitespace (sentences are
- re-joined with single spaces) and has no fence/markdown semantics, so
- expressing it as knobs on the fence-aware core would change behavior.
+ Deliberately NOT unified with gateway.platforms.helpers' split_text_fence_aware: this
+ reflows whitespace (sentences re-joined with single spaces) and has no fence semantics.
"""
from tools.tts_streaming import SENTENCE_BOUNDARY_RE as _SENTENCE_BOUNDARY_RE
@@ -629,13 +424,9 @@ def _split_text_for_speak_stream(text: str, cap: int) -> list:
return pieces
-# Per-row fields that no session LIST consumer reads but that dominate the
-# payload. ``system_prompt`` is the fully rendered prompt — tens of KB per
-# row — and made a 21-row /api/sessions response 528KB (96% dead weight),
-# re-fetched by the desktop sidebar on every refresh. The desktop's
-# SessionInfo type doesn't declare either field and the web UI never touches
-# them; ``GET /api/sessions/{id}`` detail reads stay complete. List callers
-# that genuinely need the full rows can pass ``?full=1``.
+# Per-row fields no session LIST consumer reads but that dominate the payload (``system_prompt``
+# is the fully rendered prompt, tens of KB per row — 96% of a 528KB /api/sessions response).
+# Detail reads stay complete; list callers that need full rows pass ``?full=1``.
_SESSION_LIST_HEAVY_FIELDS = ("system_prompt", "model_config")
diff --git a/hermes_cli/web_server_messaging.py b/hermes_cli/web_server_messaging.py
index b898f3b21a1..98877da25ff 100644
--- a/hermes_cli/web_server_messaging.py
+++ b/hermes_cli/web_server_messaging.py
@@ -1,8 +1,9 @@
-"""Messaging-platform catalog and onboarding helpers: platform overrides/env discovery, WhatsApp and Telegram onboarding state.
+"""Messaging-platform catalog and onboarding helpers: platform overrides/env discovery, WhatsApp
+and Telegram onboarding state.
-Split out of ``hermes_cli.web_server``; every externally used name is re-imported
-there, so ``web_server.<name>`` keeps resolving (and monkeypatching) as before.
-Helpers that tests patch on ``web_server`` are reached lazily through it.
+Split out of ``hermes_cli.web_server``; every externally used name is re-imported there, so
+``web_server.<name>`` keeps resolving (and monkeypatching). Helpers that tests patch on
+``web_server`` are reached lazily through it.
"""
import logging
@@ -36,10 +37,7 @@ _PLATFORM_OVERRIDES: dict[str, dict[str, Any]] = {
"name": "Discord",
"description": "Connect Hermes to Discord DMs, channels, and threads.",
"docs_url": "https://discord.com/developers/applications",
- "env_vars": (
- "DISCORD_BOT_TOKEN",
- "DISCORD_ALLOWED_USERS",
- ),
+ "env_vars": ("DISCORD_BOT_TOKEN", "DISCORD_ALLOWED_USERS"),
"required_env": ("DISCORD_BOT_TOKEN",),
},
"slack": {
@@ -98,18 +96,8 @@ _PLATFORM_OVERRIDES: dict[str, dict[str, Any]] = {
"name": "Email",
"description": "Talk to Hermes through an IMAP/SMTP mailbox.",
"docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/",
- "env_vars": (
- "EMAIL_ADDRESS",
- "EMAIL_PASSWORD",
- "EMAIL_IMAP_HOST",
- "EMAIL_SMTP_HOST",
- ),
- "required_env": (
- "EMAIL_ADDRESS",
- "EMAIL_PASSWORD",
- "EMAIL_IMAP_HOST",
- "EMAIL_SMTP_HOST",
- ),
+ "env_vars": ("EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_IMAP_HOST", "EMAIL_SMTP_HOST"),
+ "required_env": ("EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_IMAP_HOST", "EMAIL_SMTP_HOST"),
},
"sms": {
"name": "SMS (Twilio)",
@@ -273,59 +261,31 @@ _PLATFORM_OVERRIDES: dict[str, dict[str, Any]] = {
# Display order: well-known platforms surface first; unknown plugins fall to
# the end alphabetically.
_PLATFORM_ORDER: tuple[str, ...] = (
- "telegram",
- "discord",
- "slack",
- "mattermost",
- "matrix",
- "whatsapp",
- "signal",
- "bluebubbles",
- "homeassistant",
- "email",
- "sms",
- "dingtalk",
- "feishu",
- "google_chat",
- "wecom",
- "wecom_callback",
- "weixin",
- "qqbot",
- "yuanbao",
- "api_server",
- "webhook",
+ "telegram", "discord", "slack", "mattermost", "matrix", "whatsapp", "signal", "bluebubbles",
+ "homeassistant", "email", "sms", "dingtalk", "feishu", "google_chat", "wecom", "wecom_callback",
+ "weixin", "qqbot", "yuanbao", "api_server", "webhook",
)
def _messaging_platform_catalog() -> tuple[dict[str, Any], ...]:
"""Build the messaging catalog from the gateway's Platform enum + plugin registry.
- Built-in platforms come from ``gateway.config.Platform`` (LOCAL is excluded).
- Plugin platforms come from ``gateway.platform_registry.plugin_entries()``,
- which lets newly installed adapters (e.g. IRC) appear without a code change
- here. Per-platform UI metadata (description, docs URL, env-var picks) lives
- in :data:`_PLATFORM_OVERRIDES`; anything not overridden gets reasonable
- defaults derived from the platform id and required_env.
+ Built-ins come from ``gateway.config.Platform`` (LOCAL excluded); plugin platforms from
+ ``platform_registry.plugin_entries()`` so new adapters appear without a code change here.
+ UI metadata lives in :data:`_PLATFORM_OVERRIDES`; the rest is derived from id/required_env.
"""
from gateway.config import Platform
- # Resolve plugin entries FIRST. Plugin platforms (irc, ntfy, photon, …)
- # leak into ``Platform.__members__`` as pseudo-members the moment any
- # earlier code path calls ``Platform("<plugin id>")`` — and iterating the
- # enum first would then claim them with no plugin metadata, rendering
- # nameless "Irc"/"Ntfy" cards with empty descriptions on the Channels
- # page while the real label/install-hint sat unused in the registry.
+ # Resolve plugin entries FIRST: plugin platforms leak into ``Platform.__members__`` as
+ # pseudo-members once anything calls ``Platform("<plugin id>")``, and iterating the enum
+ # first would claim them with no plugin metadata (nameless "Irc"/"Ntfy" cards).
plugin_map: dict[str, Any] = {}
try:
- # Plugin discovery only runs as a side effect of importing
- # model_tools; this server process doesn't do that, so trigger it
- # explicitly (idempotent) or plugin_entries() is empty here and
- # every plugin platform renders nameless.
+ # Plugin discovery normally runs as a side effect of importing model_tools, which this
+ # server process doesn't do — trigger it explicitly (idempotent).
from hermes_cli.plugins import discover_plugins
-
discover_plugins()
from gateway.platform_registry import platform_registry
-
for plugin_entry in platform_registry.plugin_entries():
plugin_map[plugin_entry.name] = plugin_entry
except Exception:
@@ -333,39 +293,21 @@ def _messaging_platform_catalog() -> tuple[dict[str, Any], ...]:
seen: set[str] = set()
entries: list[dict[str, Any]] = []
-
- for member in Platform.__members__.values():
- if member.value == "local":
- continue
- if member.value in seen:
- continue
- seen.add(member.value)
- entries.append(
- _build_catalog_entry(member.value, plugin_map.get(member.value))
- )
-
- for name, plugin_entry in plugin_map.items():
- if name in seen:
+ builtin = [m.value for m in Platform.__members__.values() if m.value != "local"]
+ for pid in builtin + list(plugin_map):
+ if pid in seen:
continue
- seen.add(name)
- entries.append(_build_catalog_entry(name, plugin_entry))
+ seen.add(pid)
+ entries.append(_build_catalog_entry(pid, plugin_map.get(pid)))
order = {pid: idx for idx, pid in enumerate(_PLATFORM_ORDER)}
- entries.sort(
- key=lambda e: (order.get(e["id"], len(_PLATFORM_ORDER)), e["name"].lower())
- )
+ entries.sort(key=lambda e: (order.get(e["id"], len(_PLATFORM_ORDER)), e["name"].lower()))
return tuple(entries)
def _channel_managed_env_keys() -> frozenset[str]:
- """Env-var keys owned by a Channels page platform card.
-
- The Channels page is the canonical surface for configuring messaging
- platform credentials (with connection status, test, enable toggle and
- gateway restart). The Keys/Env page consults this set to hide those vars
- so the same fields aren't duplicated in a plainer UI. Best-effort: if the
- gateway catalog can't be built, nothing is flagged and Keys shows it all.
- """
+ """Env-var keys owned by a Channels page platform card; the Keys/Env page hides them so the
+ same fields aren't duplicated. Best-effort: if the catalog can't be built, nothing is hidden."""
try:
keys: set[str] = set()
for entry in _messaging_platform_catalog():
@@ -380,99 +322,70 @@ def _channel_managed_env_keys() -> frozenset[str]:
# they use the ``messaging`` category in OPTIONAL_ENV_VARS. Platform-scoped vars
# (``DISCORD_*``, ``MATRIX_*``, …) are owned by the Messaging UI instead.
_MESSAGING_KEYS_PAGE_KEYS = frozenset({
- "GATEWAY_ALLOW_ALL_USERS",
- "GATEWAY_PROXY_KEY",
- "GATEWAY_PROXY_URL",
-})
+ "GATEWAY_ALLOW_ALL_USERS", "GATEWAY_PROXY_KEY", "GATEWAY_PROXY_URL"})
+
+
+_PLATFORM_ENV_PREFIX_ALIASES: dict[str, tuple[str, ...]] = {
+ "email": ("EMAIL_",),
+ "homeassistant": ("HASS_",),
+ "qqbot": ("QQ_", "QQBOT_"),
+ "sms": ("TWILIO_",),
+ "wecom": ("WECOM_BOT_", "WECOM_SECRET"),
+ "wecom_callback": ("WECOM_CALLBACK_",)}
def _platform_env_prefixes(platform_id: str) -> tuple[str, ...]:
"""Env-var prefixes owned by a messaging platform card."""
- aliases: dict[str, tuple[str, ...]] = {
- "email": ("EMAIL_",),
- "homeassistant": ("HASS_",),
- "qqbot": ("QQ_", "QQBOT_"),
- "sms": ("TWILIO_",),
- "wecom": ("WECOM_BOT_", "WECOM_SECRET"),
- "wecom_callback": ("WECOM_CALLBACK_",),
- }
- if platform_id in aliases:
- return aliases[platform_id]
- return (platform_id.upper().replace("-", "_") + "_",)
+ return _PLATFORM_ENV_PREFIX_ALIASES.get(platform_id, (platform_id.upper().replace("-", "_") + "_",))
def _discover_platform_env_vars(platform_id: str) -> tuple[str, ...]:
"""All messaging-category env vars for a platform (override + plugin + prefix)."""
prefixes = _platform_env_prefixes(platform_id)
- keys: list[str] = []
- for name, info in OPTIONAL_ENV_VARS.items():
- if info.get("category") != "messaging":
- continue
- if name in _MESSAGING_KEYS_PAGE_KEYS:
- continue
- if _is_setup_hidden_env(name):
- continue
- if not any(name.startswith(prefix) for prefix in prefixes):
- continue
- keys.append(name)
- return tuple(sorted(set(keys)))
-
+ return tuple(sorted({
+ name for name, info in OPTIONAL_ENV_VARS.items()
+ if info.get("category") == "messaging"
+ and name not in _MESSAGING_KEYS_PAGE_KEYS
+ and not _is_setup_hidden_env(name)
+ and any(name.startswith(prefix) for prefix in prefixes)}))
-def _merge_platform_env_vars(
- platform_id: str,
- override: dict[str, Any],
- plugin_entry: Any | None,
-) -> tuple[str, ...]:
- """Canonical env-var list for a messaging platform card.
- Required credentials always survive: a platform that genuinely needs one of
- the hidden-suffix vars to connect keeps it, since hiding a required field
- would make the platform unconfigurable.
- """
+def _merge_platform_env_vars(platform_id: str, override: dict[str, Any], plugin_entry: Any | None) -> tuple[str, ...]:
+ """Canonical env-var list for a platform card. Required credentials always survive: hiding a
+ required field would make the platform unconfigurable."""
discovered = _discover_platform_env_vars(platform_id)
if "env_vars" in override:
- explicit = tuple(
- key for key in override["env_vars"] if not _is_setup_hidden_env(key)
- )
+ explicit = tuple(key for key in override["env_vars"] if not _is_setup_hidden_env(key))
return tuple(dict.fromkeys((*explicit, *discovered)))
if plugin_entry is not None and plugin_entry.required_env:
return tuple(dict.fromkeys((*tuple(plugin_entry.required_env), *discovered)))
return discovered
-def _build_catalog_entry(
- platform_id: str, plugin_entry: Any | None = None
-) -> dict[str, Any]:
+def _build_catalog_entry(platform_id: str, plugin_entry: Any | None = None) -> dict[str, Any]:
override = _PLATFORM_OVERRIDES.get(platform_id, {})
-
- env_vars = _merge_platform_env_vars(platform_id, override, plugin_entry)
-
if "required_env" in override:
required_env = tuple(override["required_env"])
elif plugin_entry is not None:
required_env = tuple(plugin_entry.required_env or ())
else:
required_env = ()
-
if override.get("name"):
name = override["name"]
elif plugin_entry is not None and plugin_entry.label:
name = plugin_entry.label
else:
name = platform_id.replace("_", " ").title()
-
description = override.get("description")
if not description and plugin_entry is not None:
description = plugin_entry.install_hint or ""
-
return {
"id": platform_id,
"name": name,
"description": description or "",
"docs_url": override.get("docs_url", ""),
- "env_vars": env_vars,
- "required_env": required_env,
- }
+ "env_vars": _merge_platform_env_vars(platform_id, override, plugin_entry),
+ "required_env": required_env}
def _write_platform_enabled(platform_id: str, enabled: bool) -> None:
@@ -516,8 +429,7 @@ def _whatsapp_onboarding_payload(pairing_id: str, record: _WhatsAppOnboardingSes
"account_id": record.account_id,
"account_name": record.account_name,
"account_phone": record.account_phone,
- "error": record.error,
- }
+ "error": record.error}
def _restart_gateway_after_whatsapp_onboarding(profile: Optional[str] = None) -> dict[str, Any]:
@@ -544,11 +456,7 @@ _telegram_onboarding_lock = threading.RLock()
def _telegram_onboarding_base_url() -> str:
- return (
- os.getenv("TELEGRAM_ONBOARDING_URL", _TELEGRAM_ONBOARDING_DEFAULT_URL)
- .strip()
- .rstrip("/")
- )
+ return os.getenv("TELEGRAM_ONBOARDING_URL", _TELEGRAM_ONBOARDING_DEFAULT_URL).strip().rstrip("/")
def _telegram_onboarding_error_message(error: str, fallback: str) -> str:
@@ -562,19 +470,16 @@ def _telegram_onboarding_error_message(error: str, fallback: str) -> str:
}.get(error, fallback)
+_TELEGRAM_UNAVAILABLE = "Telegram setup service is unavailable. Try again shortly."
+_TELEGRAM_INVALID = "Telegram setup service returned an invalid response."
+
+
def _telegram_onboarding_request_sync(
- method: str,
- path: str,
- *,
- body: dict[str, Any] | None = None,
- bearer_token: str | None = None,
+ method: str, path: str, *, body: dict[str, Any] | None = None, bearer_token: str | None = None
) -> dict[str, Any]:
import httpx
- headers = {
- "Accept": "application/json",
- "User-Agent": _TELEGRAM_ONBOARDING_USER_AGENT,
- }
+ headers = {"Accept": "application/json", "User-Agent": _TELEGRAM_ONBOARDING_USER_AGENT}
request_kwargs: dict[str, Any] = {}
if body is not None:
headers["Content-Type"] = "application/json"
@@ -585,12 +490,7 @@ def _telegram_onboarding_request_sync(
url = f"{_telegram_onboarding_base_url()}{path}"
try:
with httpx.Client(timeout=httpx.Timeout(10.0)) as client:
- response = client.request(
- method,
- url,
- headers=headers,
- **request_kwargs,
- )
+ response = client.request(method, url, headers=headers, **request_kwargs)
response.raise_for_status()
except httpx.HTTPStatusError as exc:
try:
@@ -598,35 +498,19 @@ def _telegram_onboarding_request_sync(
except Exception:
parsed = {}
error = str(parsed.get("error") or parsed.get("status") or "")
- detail = _telegram_onboarding_error_message(
- error,
- "Telegram setup service returned an error.",
- )
- status_code = 404 if exc.response.status_code == 404 else 502
+ detail = _telegram_onboarding_error_message(error, "Telegram setup service returned an error.")
if error in {"expired", "claimed"}:
status_code = 410
+ else:
+ status_code = 404 if exc.response.status_code == 404 else 502
raise HTTPException(status_code=status_code, detail=detail) from exc
- except httpx.RequestError as exc:
- raise HTTPException(
- status_code=502,
- detail="Telegram setup service is unavailable. Try again shortly.",
- ) from exc
except Exception as exc:
- raise HTTPException(
- status_code=502,
- detail="Telegram setup service is unavailable. Try again shortly.",
- ) from exc
+ raise HTTPException(status_code=502, detail=_TELEGRAM_UNAVAILABLE) from exc
try:
parsed = response.json()
except Exception as exc:
- raise HTTPException(
- status_code=502,
- detail="Telegram setup service returned an invalid response.",
- ) from exc
+ raise HTTPException(status_code=502, detail=_TELEGRAM_INVALID) from exc
if not isinstance(parsed, dict):
- raise HTTPException(
- status_code=502,
- detail="Telegram setup service returned an invalid response.",
- )
+ raise HTTPException(status_code=502, detail=_TELEGRAM_INVALID)
return parsed
diff --git a/hermes_cli/web_server_oauth.py b/hermes_cli/web_server_oauth.py
index 223671be714..23be1b9661b 100644
--- a/hermes_cli/web_server_oauth.py
+++ b/hermes_cli/web_server_oauth.py
@@ -1,8 +1,9 @@
-"""Dashboard OAuth/login-status helpers: provider catalog, per-provider device pollers, Anthropic/Copilot/Claude-Code status probes.
+"""Dashboard OAuth/login-status helpers: provider catalog, per-provider device pollers,
+Anthropic/Copilot/Claude-Code status probes.
-Split out of ``hermes_cli.web_server``; every externally used name is re-imported
-there, so ``web_server.<name>`` keeps resolving (and monkeypatching) as before.
-Helpers that tests patch on ``web_server`` are reached lazily through it.
+Split out of ``hermes_cli.web_server``; every externally used name is re-imported there, so
+``web_server.<name>`` keeps resolving (and monkeypatching). Helpers that tests patch on
+``web_server`` are reached lazily through it.
"""
import logging
@@ -17,151 +18,86 @@ from typing import Any, Dict, Optional
_log = logging.getLogger("hermes_cli.web_server")
-# ---------------------------------------------------------------------------
-# OAuth provider endpoints — status + disconnect (Phase 1)
-# ---------------------------------------------------------------------------
-#
-# Phase 1 surfaces *which OAuth providers exist* and whether each is
-# connected, plus a disconnect button. Anthropic subscription OAuth is
-# deliberately delegated away from the dashboard: its card is external and
-# points to the supported terminal path. Phase 2 adds in-browser device-code
-# flows for providers that support them. For unconnected providers we return
-# the canonical ``hermes auth add <provider>`` command so the dashboard can
-# surface a one-click copy.
+_LOGGED_OUT: Dict[str, Any] = {"logged_in": False, "source": None}
def _truncate_token(value: Optional[str], visible: int = 6) -> str:
- """Return ``...XXXXXX`` (last N chars) for safe display in the UI.
-
- We never expose more than the trailing ``visible`` characters of an
- OAuth access token. JWT prefixes (the part before the first dot) are
- stripped first when present so the visible suffix is always part of
- the signing region rather than a meaningless header chunk.
-
- Returns the Entra-ID placeholder when handed a callable (Azure Foundry
- bearer provider) — the callable is NEVER invoked here.
- """
+ """``…XXXXXX`` (last N chars) for UI display. JWTs show only the tail of the signature
+ segment. A callable (Azure Foundry Entra-ID bearer provider) is NEVER invoked — it yields
+ the ``<entra-id-bearer>`` placeholder."""
if not value:
return ""
if callable(value) and not isinstance(value, str):
- # Entra ID bearer provider — never reveal a minted token in the UI.
return "<entra-id-bearer>"
s = str(value)
- if "." in s and s.count(".") >= 2:
- # Looks like a JWT — show the trailing piece of the signature only.
+ if s.count(".") >= 2:
s = s.rsplit(".", 1)[-1]
- if len(s) <= visible:
- return s
- return f"…{s[-visible:]}"
+ return s if len(s) <= visible else f"…{s[-visible:]}"
+
+
+def _token_status(source: str, source_label: str, creds: Dict[str, Any]) -> Dict[str, Any]:
+ return {
+ "logged_in": True,
+ "source": source,
+ "source_label": source_label,
+ "token_preview": _truncate_token(creds.get("accessToken")),
+ "expires_at": creds.get("expiresAt"),
+ "has_refresh_token": bool(creds.get("refreshToken"))}
def _anthropic_oauth_status() -> Dict[str, Any]:
- """Status for the "Anthropic API Key" catalog entry.
-
- Two sources, in priority order:
- 1. ``~/.hermes/.anthropic_oauth.json`` — Hermes-managed terminal PKCE
- credentials (the dashboard no longer has a Connect button for this)
- 2. ``ANTHROPIC_API_KEY`` → ``ANTHROPIC_TOKEN`` → ``CLAUDE_CODE_OAUTH_TOKEN``
- env vars (registry order) — from ``.env``, the shell, or an external
- secret source like Bitwarden (whose keys are injected into the process
- env during ``load_hermes_dotenv()``, so the same check covers them)
-
- Claude Code's ``~/.claude/.credentials.json`` is deliberately NOT read
- here — it has its own dedicated catalog entry (``claude-code`` →
- ``_claude_code_only_status``). Reporting it under the API-key entry
- double-counts the token and shadows a real ANTHROPIC_API_KEY.
+ """Status for the "Anthropic API Key" card: Hermes-managed PKCE file first, then the
+ registry-ordered env vars (process env — where Bitwarden-sourced secrets land — then .env).
+
+ Claude Code's ``~/.claude/.credentials.json`` is deliberately NOT read here; it has its own
+ ``claude-code`` entry, and counting it here would shadow a real ANTHROPIC_API_KEY.
"""
try:
- from agent.anthropic_adapter import (
- read_hermes_oauth_credentials,
- _get_hermes_oauth_file,
- )
- except ImportError:
- read_hermes_oauth_credentials = None # type: ignore
- _get_hermes_oauth_file = None # type: ignore
-
- hermes_creds = None
- if read_hermes_oauth_credentials:
- try:
- hermes_creds = read_hermes_oauth_credentials()
- except Exception:
- hermes_creds = None
+ from agent.anthropic_adapter import read_hermes_oauth_credentials, _get_hermes_oauth_file
+ hermes_creds = read_hermes_oauth_credentials()
+ except Exception:
+ hermes_creds = None
if hermes_creds and hermes_creds.get("accessToken"):
- return {
- "logged_in": True,
- "source": "hermes_pkce",
- "source_label": f"Hermes PKCE ({_get_hermes_oauth_file() if _get_hermes_oauth_file else None})",
- "token_preview": _truncate_token(hermes_creds.get("accessToken")),
- "expires_at": hermes_creds.get("expiresAt"),
- "has_refresh_token": bool(hermes_creds.get("refreshToken")),
- }
-
- # Env-var / secret-source path. ``get_env_value`` checks the process
- # environment first (where Bitwarden-sourced secrets land) then .env.
+ return _token_status("hermes_pkce", f"Hermes PKCE ({_get_hermes_oauth_file()})", hermes_creds)
+
env_var_order: tuple = ("ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN")
try:
from hermes_cli.auth import PROVIDER_REGISTRY
env_var_order = PROVIDER_REGISTRY["anthropic"].api_key_env_vars
except (ImportError, KeyError):
pass
- try:
- from hermes_cli.config import get_env_value
- except ImportError:
- get_env_value = None # type: ignore
- try:
- from hermes_cli.env_loader import format_secret_source_suffix
- except ImportError:
- format_secret_source_suffix = None # type: ignore
+ from hermes_cli.config import get_env_value
+ from hermes_cli.env_loader import format_secret_source_suffix
for var in env_var_order:
- value = (get_env_value(var) if get_env_value else None) or os.getenv(var)
- if not value:
- continue
- suffix = format_secret_source_suffix(var) if format_secret_source_suffix else ""
- return {
- "logged_in": True,
- "source": "env_var",
- "source_label": f"{var}{suffix}",
- "token_preview": _truncate_token(value),
- "expires_at": None,
- "has_refresh_token": False,
- }
- return {"logged_in": False, "source": None}
+ value = get_env_value(var) or os.getenv(var)
+ if value:
+ return {
+ "logged_in": True,
+ "source": "env_var",
+ "source_label": f"{var}{format_secret_source_suffix(var)}",
+ "token_preview": _truncate_token(value),
+ "expires_at": None,
+ "has_refresh_token": False}
+ return dict(_LOGGED_OUT)
def _claude_code_only_status() -> Dict[str, Any]:
- """Surface Claude Code CLI credentials as their own provider entry.
-
- Independent of the Anthropic entry above so users can see whether their
- Claude Code subscription tokens are actively flowing into Hermes even
- when they also have a separate Hermes-managed PKCE login.
- """
+ """Claude Code CLI credentials as their own entry, independent of the Anthropic card."""
try:
from agent.anthropic_adapter import read_claude_code_credentials
creds = read_claude_code_credentials()
except Exception:
creds = None
if creds and creds.get("accessToken"):
- return {
- "logged_in": True,
- "source": "claude_code_cli",
- "source_label": "~/.claude/.credentials.json",
- "token_preview": _truncate_token(creds.get("accessToken")),
- "expires_at": creds.get("expiresAt"),
- "has_refresh_token": bool(creds.get("refreshToken")),
- }
- return {"logged_in": False, "source": None}
+ return _token_status("claude_code_cli", "~/.claude/.credentials.json", creds)
+ return dict(_LOGGED_OUT)
def _copilot_acp_status() -> Dict[str, Any]:
- """Status for copilot-acp — credentials are owned by the Copilot CLI.
-
- ``logged_in`` is claimed only on positive evidence (a supported env token
- or a known on-disk GitHub Copilot credential store, via
- ``auth.get_external_process_provider_status``). The Copilot CLI may also
- hold its session in an OS keychain Hermes can't read, so the unverified
- state is presented as "managed by the Copilot CLI" — never as signed out.
- """
+ """Status for copilot-acp. ``logged_in`` only on positive evidence (env token or known on-disk
+ store); the CLI may hold its session in an OS keychain Hermes can't read, so the unverified
+ state reads "managed by the Copilot CLI" — never signed out."""
try:
from hermes_cli.auth import get_external_process_provider_status
status = get_external_process_provider_status("copilot-acp") or {}
@@ -183,20 +119,12 @@ def _copilot_acp_status() -> Dict[str, Any]:
"token_preview": None,
"expires_at": None,
"has_refresh_token": False,
- "configured": configured,
- }
+ "configured": configured}
def _external_process_cli_command(provider_id: str, default: str) -> str:
- """Render an external-process provider's sign-in command with the CLI the
- user actually has configured.
-
- The static catalog assumes the default executable name; users who point
- Hermes at a custom binary (``HERMES_COPILOT_ACP_COMMAND`` /
- ``COPILOT_CLI_PATH``) would otherwise be told to run a command that isn't
- the one Hermes spawns. Non-external-process providers get ``default`` back
- untouched.
- """
+ """Render an external-process provider's sign-in command with the CLI actually configured
+ (``HERMES_COPILOT_ACP_COMMAND`` / ``COPILOT_CLI_PATH``); others get ``default`` untouched."""
try:
from hermes_cli.auth import PROVIDER_REGISTRY, get_external_process_provider_status
pconfig = PROVIDER_REGISTRY.get(provider_id)
@@ -213,106 +141,43 @@ def _external_process_cli_command(provider_id: str, default: str) -> str:
return default
-# Explicit, hand-tuned OAuth/account provider cards. These carry the bits that
-# can't be derived from the unified provider catalog: the OAuth ``flow`` shape,
-# the per-provider ``status_fn``, the ``cli_command`` fallback, and curated
-# display order. They are the OVERRIDE BASE for ``_build_oauth_catalog()``,
-# which unions them with every accounts-tab provider in ``provider_catalog()``
-# so newly-added OAuth/external providers appear automatically (no hand edit).
-# This tuple also still includes two entries that are NOT catalog providers but
-# must show on the Accounts tab: the Anthropic credential-status card and the
-# synthetic ``claude-code`` subscription row.
-# ``flow`` describes the account-management shape so the UI can pick the right
-# behavior: ``device_code`` = show code + verification URL + poll, and
-# ``external`` = read-only/delegated to a terminal or third-party CLI.
+# Hand-tuned OAuth/account cards: the bits not derivable from the unified provider catalog
+# (``flow``, ``status_fn``, ``cli_command``, display order). OVERRIDE BASE for
+# ``_build_oauth_catalog()``, which unions them with every accounts-tab provider so new
+# providers appear automatically. Also carries two non-catalog rows the Accounts tab needs:
+# the Anthropic credential-status card and the synthetic ``claude-code`` row.
+# ``flow``: ``device_code`` = show code + URL + poll; ``external`` = delegated to a terminal/CLI.
_OAUTH_PROVIDER_CATALOG: tuple[Dict[str, Any], ...] = (
- {
- "id": "nous",
- "name": "Nous Portal",
- "flow": "device_code",
- "cli_command": "hermes auth add nous",
- "docs_url": "https://portal.nousresearch.com",
- "status_fn": None, # dispatched via auth.get_nous_auth_status
- },
- {
- "id": "openai-codex",
- "name": "ChatGPT or Codex Subscription",
- "flow": "device_code",
- "cli_command": "hermes auth add openai-codex",
- "docs_url": "https://platform.openai.com/docs",
- "status_fn": None, # dispatched via auth.get_codex_auth_status
- },
- {
- "id": "qwen-oauth",
- "name": "Qwen (via Qwen CLI)",
- "flow": "external",
- "cli_command": "hermes auth add qwen-oauth",
- "docs_url": "https://github.com/QwenLM/qwen-code",
- "status_fn": None, # dispatched via auth.get_qwen_auth_status
- },
- {
- "id": "minimax-oauth",
- "name": "MiniMax (OAuth)",
- # MiniMax's flow is structurally device-code (verification URI +
- # user code, backend polls the token endpoint) with a PKCE
- # extension for code-binding. The dashboard renders the same UX
- # as Nous's device-code flow; the PKCE bit is a security
- # extension that doesn't change the operator experience.
- "flow": "device_code",
- "cli_command": "hermes auth add minimax-oauth",
- "docs_url": "https://www.minimax.io",
- "status_fn": None, # dispatched via auth.get_minimax_oauth_auth_status
- },
- {
- "id": "xai-oauth",
- "name": "xAI Grok OAuth (SuperGrok / Premium+)",
- # Device code is the default because it works in remote shells,
- # containers, and desktop installs without requiring a reachable
- # 127.0.0.1 callback.
- "flow": "device_code",
- "cli_command": "hermes auth add xai-oauth",
- "docs_url": "https://hermes-agent.nousresearch.com/docs/guides/xai-grok-oauth",
- "status_fn": None, # dispatched via auth.get_xai_oauth_auth_status
- },
- {
- "id": "copilot-acp",
- "name": "GitHub Copilot (ACP)",
- "flow": "external",
- # `copilot login` is the CLI's non-interactive device-code login
- # subcommand; the previous `copilot /login` form is not a valid
- # invocation (slash-commands only exist inside an interactive
- # session, reachable as `copilot -i /login`).
- "cli_command": "copilot login",
- "docs_url": "https://docs.github.com/en/copilot",
- "status_fn": _copilot_acp_status,
- },
- # ── Anthropic / Claude entries sit at the bottom.
- #
- # This card is deliberately flow == "external" (no in-dashboard "Connect"
- # button walking the user through claude.ai/oauth/authorize from the web
- # server). Hermes previously reimplemented that subscription-OAuth PKCE
- # dance itself for the dashboard (issues #87887/#87888); that surface was
- # removed because it lets an unattended, scriptable HTTP endpoint mint
- # Claude Pro/Max subscription tokens outside Anthropic's own client,
- # which sits on the wrong side of Anthropic's usage policies for OAuth
- # credentials. Login still works via the terminal (`hermes auth add
- # anthropic`, unaffected by this change) or a plain API key below.
- {
- "id": "anthropic",
- "name": "Anthropic API Key",
- "flow": "external",
- "cli_command": "hermes auth add anthropic",
- "docs_url": "https://docs.claude.com/en/api/getting-started",
- "status_fn": _anthropic_oauth_status,
- },
- {
- "id": "claude-code",
- "name": "Anthropic OAuth: Required Extra Usage Credits to Use Subscription",
- "flow": "external",
- "cli_command": "claude setup-token",
- "docs_url": "https://docs.claude.com/en/docs/claude-code",
- "status_fn": _claude_code_only_status,
- },
+ # status_fn None → dispatched via auth.get_<provider>_auth_status.
+ {"id": "nous", "name": "Nous Portal", "flow": "device_code", "cli_command": "hermes auth add nous",
+ "docs_url": "https://portal.nousresearch.com", "status_fn": None},
+ {"id": "openai-codex", "name": "ChatGPT or Codex Subscription", "flow": "device_code",
+ "cli_command": "hermes auth add openai-codex", "docs_url": "https://platform.openai.com/docs",
+ "status_fn": None},
+ {"id": "qwen-oauth", "name": "Qwen (via Qwen CLI)", "flow": "external",
+ "cli_command": "hermes auth add qwen-oauth", "docs_url": "https://github.com/QwenLM/qwen-code",
+ "status_fn": None},
+ # Structurally device-code (verification URI + user code + token polling) with a PKCE
+ # code-binding extension that doesn't change the operator UX.
+ {"id": "minimax-oauth", "name": "MiniMax (OAuth)", "flow": "device_code",
+ "cli_command": "hermes auth add minimax-oauth", "docs_url": "https://www.minimax.io", "status_fn": None},
+ # Device code works in remote shells/containers without a reachable 127.0.0.1 callback.
+ {"id": "xai-oauth", "name": "xAI Grok OAuth (SuperGrok / Premium+)", "flow": "device_code",
+ "cli_command": "hermes auth add xai-oauth",
+ "docs_url": "https://hermes-agent.nousresearch.com/docs/guides/xai-grok-oauth", "status_fn": None},
+ # `copilot login` is the non-interactive subcommand; `copilot /login` is not valid
+ # (slash-commands only exist inside an interactive session).
+ {"id": "copilot-acp", "name": "GitHub Copilot (ACP)", "flow": "external", "cli_command": "copilot login",
+ "docs_url": "https://docs.github.com/en/copilot", "status_fn": _copilot_acp_status},
+ # Anthropic / Claude entries sit at the bottom. Deliberately flow == "external": an
+ # in-dashboard Connect button would let a scriptable HTTP endpoint mint Claude Pro/Max
+ # subscription tokens outside Anthropic's own client, against its OAuth usage policies.
+ # Login works via the terminal (`hermes auth add anthropic`) or a plain API key.
+ {"id": "anthropic", "name": "Anthropic API Key", "flow": "external", "cli_command": "hermes auth add anthropic",
+ "docs_url": "https://docs.claude.com/en/api/getting-started", "status_fn": _anthropic_oauth_status},
+ {"id": "claude-code", "name": "Anthropic OAuth: Required Extra Usage Credits to Use Subscription",
+ "flow": "external", "cli_command": "claude setup-token",
+ "docs_url": "https://docs.claude.com/en/docs/claude-code", "status_fn": _claude_code_only_status},
)
_oauth_sessions: Dict[str, Dict[str, Any]] = {}
_oauth_sessions_lock = threading.Lock()
@@ -325,10 +190,7 @@ def _oauth_profile_name(profile: Optional[str]) -> Optional[str]:
return requested
-def _oauth_session_profile(
- session_id: str,
- fallback: Optional[str] = None,
-) -> Optional[str]:
+def _oauth_session_profile(session_id: str, fallback: Optional[str] = None) -> Optional[str]:
"""Return the profile that owns an OAuth session, if one was provided."""
with _oauth_sessions_lock:
sess = _oauth_sessions.get(session_id)
@@ -337,13 +199,9 @@ def _oauth_session_profile(
def _oauth_poller(label: str):
- """Wrap a background device-code poller body ``fn(session_id, sess)``.
-
- Looks up the session (a vanished session is a no-op), marks it
- ``approved`` when the body returns, and on any exception records
- ``error`` + ``error_message`` on the session instead of raising — the
- thread has no caller to report to; the dashboard reads the status.
- """
+ """Wrap a device-code poller body ``fn(session_id, sess)``: vanished session is a no-op,
+ success marks ``approved``, any exception records ``error`` + ``error_message`` on the
+ session instead of raising (the thread has no caller; the dashboard reads the status)."""
def deco(fn):
@functools.wraps(fn)
def poller(session_id: str) -> None:
@@ -369,11 +227,7 @@ def _oauth_poller(label: str):
def _nous_poller(session_id: str, sess: Dict[str, Any]) -> None:
"""Background poller that drives a Nous device-code flow to completion."""
from hermes_cli.web_server import _profile_scope
- from hermes_cli.auth import (
- _poll_for_token,
- refresh_nous_oauth_from_state,
- )
- from datetime import datetime, timezone
+ from hermes_cli.auth import _poll_for_token, persist_nous_credentials, refresh_nous_oauth_from_state
import httpx
portal_base_url = sess["portal_base_url"]
client_id = sess["client_id"]
@@ -388,8 +242,7 @@ def _nous_poller(session_id: str, sess: Dict[str, Any]) -> None:
client_id=client_id,
device_code=device_code,
expires_in=expires_in,
- poll_interval=interval,
- )
+ poll_interval=interval)
# Same post-processing as _nous_device_code_login (validate/refresh JWT)
now = datetime.now(timezone.utc)
token_ttl = int(token_data.get("expires_in") or 0)
@@ -404,41 +257,26 @@ def _nous_poller(session_id: str, sess: Dict[str, Any]) -> None:
"obtained_at": now.isoformat(),
"expires_at": (
datetime.fromtimestamp(now.timestamp() + token_ttl, tz=timezone.utc).isoformat()
- if token_ttl else None
- ),
- "expires_in": token_ttl,
- }
+ if token_ttl else None),
+ "expires_in": token_ttl}
with _profile_scope(_oauth_session_profile(session_id)):
- full_state = refresh_nous_oauth_from_state(
- auth_state,
- timeout_seconds=15.0,
- force_refresh=False,
- )
- from hermes_cli.auth import persist_nous_credentials
+ full_state = refresh_nous_oauth_from_state(auth_state, timeout_seconds=15.0, force_refresh=False)
persist_nous_credentials(full_state)
@_oauth_poller("minimax")
def _minimax_poller(session_id: str, sess: Dict[str, Any]) -> None:
- """Background poller that drives a MiniMax OAuth flow to completion.
-
- Mirrors `_nous_poller` but calls the MiniMax-specific token endpoint,
- which uses a PKCE-style ``code_verifier`` + ``user_code`` rather than
- the ``device_code`` field used by Nous. On success, builds the same
- auth_state dict that ``_minimax_oauth_login`` (the CLI flow) builds
- and persists via ``_minimax_save_auth_state`` — so the dashboard
- path leaves the system in the same state as
- ``hermes auth add minimax-oauth``.
- """
+ """MiniMax poller: PKCE-style ``code_verifier`` + ``user_code`` instead of Nous's
+ ``device_code``. Builds the same auth_state as the CLI's ``_minimax_oauth_login`` and persists
+ via ``_minimax_save_auth_state`` so the system ends up as after ``hermes auth add minimax-oauth``.
+ Region is fixed to "global" here; cn-region operators use the CLI's ``--region cn``."""
from hermes_cli.web_server import _profile_scope
from hermes_cli.auth import (
_minimax_poll_token,
_minimax_resolve_token_expiry_unix,
_minimax_save_auth_state,
MINIMAX_OAUTH_GLOBAL_INFERENCE,
- MINIMAX_OAUTH_SCOPE,
- )
- from datetime import datetime, timezone
+ MINIMAX_OAUTH_SCOPE)
import httpx
portal_base_url = sess["portal_base_url"]
client_id = sess["client_id"]
@@ -447,9 +285,7 @@ def _minimax_poller(session_id: str, sess: Dict[str, Any]) -> None:
interval_ms = sess.get("interval_ms")
expired_in_raw = sess["expired_in_raw"]
with httpx.Client(
- timeout=httpx.Timeout(15.0),
- headers={"Accept": "application/json"},
- follow_redirects=True,
+ timeout=httpx.Timeout(15.0), headers={"Accept": "application/json"}, follow_redirects=True
) as client:
token_data = _minimax_poll_token(
client=client,
@@ -458,17 +294,10 @@ def _minimax_poller(session_id: str, sess: Dict[str, Any]) -> None:
user_code=user_code,
code_verifier=code_verifier,
expired_in=expired_in_raw,
- interval_ms=interval_ms,
- )
- # Build the auth_state dict in the same shape as the CLI flow's
- # `_minimax_oauth_login` so `_minimax_save_auth_state` writes
- # the canonical record. Region is fixed to "global" for the
- # dashboard path; cn-region operators can still use the CLI
- # flow which supports `--region cn`.
+ interval_ms=interval_ms)
now = datetime.now(timezone.utc)
expires_at_ts = _minimax_resolve_token_expiry_unix(
- int(token_data["expired_in"]), now=now,
- )
+ int(token_data["expired_in"]), now=now)
expires_in_s = max(0, int(expires_at_ts - now.timestamp()))
auth_state = {
"provider": "minimax-oauth",
@@ -483,10 +312,8 @@ def _minimax_poller(session_id: str, sess: Dict[str, Any]) -> None:
"resource_url": token_data.get("resource_url"),
"obtained_at": now.isoformat(),
"expires_at": datetime.fromtimestamp(
- expires_at_ts, tz=timezone.utc
- ).isoformat(),
- "expires_in": expires_in_s,
- }
+ expires_at_ts, tz=timezone.utc).isoformat(),
+ "expires_in": expires_in_s}
with _profile_scope(_oauth_session_profile(session_id)):
_minimax_save_auth_state(auth_state)
@@ -501,51 +328,39 @@ def _xai_device_poller(session_id: str, sess: Dict[str, Any]) -> None:
_xai_oauth_discovery,
_xai_oauth_poll_device_token,
mark_provider_active_if_unset,
- unsuppress_credential_source,
- )
+ unsuppress_credential_source)
device_code = sess["device_code"]
interval = int(sess["interval"])
expires_in = max(60, int(sess["expires_at"] - time.time()))
discovery = _xai_oauth_discovery(20.0)
with httpx.Client(
- timeout=httpx.Timeout(20.0),
- headers={"Accept": "application/json"},
+ timeout=httpx.Timeout(20.0), headers={"Accept": "application/json"}
) as client:
token_data = _xai_oauth_poll_device_token(
client,
token_endpoint=discovery["token_endpoint"],
device_code=device_code,
expires_in=expires_in,
- poll_interval=interval,
- )
+ poll_interval=interval)
tokens = {
"access_token": str(token_data.get("access_token", "") or "").strip(),
"refresh_token": str(token_data.get("refresh_token", "") or "").strip(),
"id_token": str(token_data.get("id_token", "") or "").strip(),
"expires_in": token_data.get("expires_in"),
- "token_type": str(token_data.get("token_type") or "Bearer").strip() or "Bearer",
- }
+ "token_type": str(token_data.get("token_type") or "Bearer").strip() or "Bearer"}
with _profile_scope(_oauth_session_profile(session_id)):
+ # set_active=False: persist without hijacking an existing active chat provider.
_save_xai_oauth_tokens(
tokens,
discovery=discovery,
last_refresh=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
auth_mode="oauth_device_code",
- # Persist credentials without hijacking an existing active
- # chat provider.
- set_active=False,
- )
- # Mirror `hermes auth add xai-oauth`: first credential may become
- # active when none is set yet; never overwrite an existing choice.
+ set_active=False)
+ # Mirror `hermes auth add xai-oauth`: first credential may become active; never overwrite.
mark_provider_active_if_unset("xai-oauth")
- # The singleton write above is the single source of truth: the
- # credential-pool load seeds it as the canonical ``device_code``
- # entry. Do NOT also insert a parallel ``manual:dashboard_*`` pool
- # entry — that duplicates the single-use refresh token across two
- # entries and triggers rotation churn / ``refresh_token_reused``.
- # An interactive dashboard login is also an explicit re-enable
- # signal, so clear any ``device_code`` suppression left by a
- # prior ``hermes auth remove xai-oauth`` (mirrors auth_add_command
- # and the ``hermes model`` re-login path in _login_xai_oauth).
+ # The singleton write is the source of truth (the pool load seeds it as the canonical
+ # ``device_code`` entry). Do NOT add a parallel ``manual:dashboard_*`` pool entry — it
+ # duplicates the single-use refresh token and triggers ``refresh_token_reused`` churn.
+ # An interactive login is an explicit re-enable, so clear any prior suppression.
unsuppress_credential_source("xai-oauth", "device_code")
diff --git a/hermes_cli/webhook.py b/hermes_cli/webhook.py
index 191a773d001..ef145554c96 100644
--- a/hermes_cli/webhook.py
+++ b/hermes_cli/webhook.py
@@ -44,16 +44,9 @@ def _load_subscriptions() -> Dict[str, dict]:
def _save_subscriptions(subs: Dict[str, dict]) -> None:
path = _subscriptions_path()
path.parent.mkdir(parents=True, exist_ok=True)
- # webhook_subscriptions.json contains per-route HMAC secrets — write
- # via tempfile + chmod 0o600 before the atomic rename so a permissive
- # umask cannot leave the secrets readable to other local users in the
- # window between create and rename.
- fd, tmp_name = tempfile.mkstemp(
- prefix=f".{path.name}.",
- suffix=".tmp",
- dir=path.parent,
- text=True,
- )
+ # The file holds per-route HMAC secrets: chmod 0o600 the temp file BEFORE the atomic rename so
+ # a permissive umask can't expose them in the create→rename window.
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent, text=True)
tmp_path = Path(tmp_name)
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
@@ -62,8 +55,7 @@ def _save_subscriptions(subs: Dict[str, dict]) -> None:
os.fsync(fh.fileno())
os.chmod(tmp_path, _SUBSCRIPTIONS_FILE_MODE)
atomic_replace(tmp_path, path)
- # Re-assert after rename in case the destination existed with a
- # broader mode and atomic_replace preserved it.
+ # Re-assert: the destination may have existed with a broader mode that the replace kept.
os.chmod(path, _SUBSCRIPTIONS_FILE_MODE)
except Exception:
try:
@@ -122,26 +114,16 @@ def _setup_hint() -> str:
"""
-def _require_webhook_enabled() -> bool:
- """Check webhook is enabled. Print setup guide and return False if not."""
- if _is_webhook_enabled():
- return True
- print(_setup_hint())
- return False
-
-
def webhook_command(args):
"""Entry point for 'hermes webhook' subcommand."""
sub = getattr(args, "webhook_action", None)
-
if not sub:
print("Usage: hermes webhook {subscribe|list|remove|test}")
print("Run 'hermes webhook --help' for details.")
return
-
- if not _require_webhook_enabled():
+ if not _is_webhook_enabled():
+ print(_setup_hint())
return
-
handler = _ACTIONS.get(sub)
if handler is not None:
handler(args)
@@ -155,10 +137,8 @@ def _cmd_subscribe(args):
subs = _load_subscriptions()
is_update = name in subs
-
secret = args.secret or secrets.token_urlsafe(32)
events = [e.strip() for e in args.events.split(",")] if args.events else []
-
route = {
"description": args.description or f"Agent-created subscription: {name}",
"events": events,
@@ -166,33 +146,25 @@ def _cmd_subscribe(args):
"prompt": args.prompt or "",
"skills": [s.strip() for s in args.skills.split(",")] if args.skills else [],
"deliver": args.deliver or "log",
- "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
- }
+ "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
if getattr(args, "deliver_only", False):
if route["deliver"] == "log":
print(
"Error: --deliver-only requires --deliver to be a real target "
- "(telegram, discord, slack, github_comment, etc.) — not 'log'."
- )
+ "(telegram, discord, slack, github_comment, etc.) — not 'log'.")
return
route["deliver_only"] = True
-
script = (getattr(args, "script", "") or "").strip()
if script:
route["script"] = script
-
if args.deliver_chat_id:
route["deliver_extra"] = {"chat_id": args.deliver_chat_id}
-
subs[name] = route
_save_subscriptions(subs)
- base_url = _get_webhook_base_url()
- status = "Updated" if is_update else "Created"
-
- print(f"\n {status} webhook subscription: {name}")
- print(f" URL: {base_url}/webhooks/{name}")
+ print(f"\n {'Updated' if is_update else 'Created'} webhook subscription: {name}")
+ print(f" URL: {_get_webhook_base_url()}/webhooks/{name}")
print(f" Secret: {secret}")
print(f" Events: {', '.join(events) or '(all)'}")
print(f" Deliver: {route['deliver']}")
@@ -238,12 +210,10 @@ def _cmd_list(args):
def _cmd_remove(args):
name = args.name.strip().lower()
subs = _load_subscriptions()
-
if name not in subs:
print(f" No subscription named '{name}'.")
print(" Note: Static routes from config.yaml cannot be removed here.")
return
-
del subs[name]
_save_subscriptions(subs)
print(f" Removed webhook subscription: {name}")
@@ -253,30 +223,20 @@ def _cmd_test(args):
"""Send a test POST to a webhook route."""
name = args.name.strip().lower()
subs = _load_subscriptions()
-
if name not in subs:
print(f" No subscription named '{name}'.")
return
-
secret = subs[name].get("secret", "")
- base_url = _get_webhook_base_url()
- url = f"{base_url}/webhooks/{name}"
-
+ url = f"{_get_webhook_base_url()}/webhooks/{name}"
payload = args.payload or '{"test": true, "event_type": "test", "message": "Hello from hermes webhook test"}'
sig = "sha256=" + hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
-
print(f" Sending test POST to {url}")
try:
req = urllib.request.Request(
url,
data=payload.encode(),
- headers={
- "Content-Type": "application/json",
- "X-Hub-Signature-256": sig,
- "X-GitHub-Event": "test",
- },
- method="POST",
- )
+ headers={"Content-Type": "application/json", "X-Hub-Signature-256": sig, "X-GitHub-Event": "test"},
+ method="POST")
with urllib.request.urlopen(req, timeout=10) as resp:
body = resp.read().decode()
print(f" Response ({resp.status}): {body}")
@@ -289,5 +249,4 @@ _ACTIONS = {
"subscribe": _cmd_subscribe, "add": _cmd_subscribe,
"list": _cmd_list, "ls": _cmd_list,
"remove": _cmd_remove, "rm": _cmd_remove,
- "test": _cmd_test,
-}
+ "test": _cmd_test}
diff --git a/hermes_cli/win_pty_bridge.py b/hermes_cli/win_pty_bridge.py
index 04998df266c..c8282f81a77 100644
--- a/hermes_cli/win_pty_bridge.py
+++ b/hermes_cli/win_pty_bridge.py
@@ -17,9 +17,7 @@ except ImportError: # pragma: no cover - non-Windows or pywinpty missing
__all__ = ["WinPtyBridge", "PtyUnavailableError"]
-# Same clamp ceiling as the POSIX bridge: a broken winsize probe must never
-# reach the resize call. ConPTY tolerates large values better than ioctl,
-# but we keep parity to avoid layout surprises.
+# Same clamp ceiling as the POSIX bridge so a broken winsize probe never reaches the resize call.
_MIN_DIMENSION = 1
_MAX_COLS = 2000
_MAX_ROWS = 1000
@@ -30,11 +28,7 @@ def _clamp(value: int, maximum: int) -> int:
n = int(value)
except (TypeError, ValueError, OverflowError):
return _MIN_DIMENSION
- if n < _MIN_DIMENSION:
- return _MIN_DIMENSION
- if n > maximum:
- return maximum
- return n
+ return max(_MIN_DIMENSION, min(n, maximum))
class PtyUnavailableError(RuntimeError):
@@ -42,55 +36,34 @@ class PtyUnavailableError(RuntimeError):
class WinPtyBridge:
- """pywinpty-backed bridge with the same interface as ``PtyBridge``.
-
- ``web_server`` calls :meth:`read` inside ``run_in_executor``, so a blocking/polling read here
- never stalls the event loop. ConPTY exposes no selectable fd, so we poll with a short sleep
- instead of ``select``.
- """
+ """pywinpty-backed bridge with the same interface as ``PtyBridge``. ``read`` runs inside
+ ``run_in_executor``; ConPTY has no selectable fd, so it polls with a short sleep."""
def __init__(self, proc: "PtyProcess") -> None: # type: ignore[name-defined]
self._proc = proc
self._closed = False
- # -- lifecycle --------------------------------------------------------
-
@classmethod
def is_available(cls) -> bool:
return bool(_PTY_AVAILABLE)
@classmethod
def spawn(
- cls,
- argv: Sequence[str],
- *,
- cwd: Optional[str] = None,
- env: Optional[dict] = None,
- cols: int = 80,
- rows: int = 24,
- ) -> "WinPtyBridge":
+ cls, argv: Sequence[str], *, cwd: Optional[str] = None, env: Optional[dict] = None,
+ cols: int = 80, rows: int = 24) -> "WinPtyBridge":
if not _PTY_AVAILABLE:
if PtyProcess is None:
- raise PtyUnavailableError(
- "pywinpty is not installed. Install with: pip install pywinpty"
- )
+ raise PtyUnavailableError("pywinpty is not installed. Install with: pip install pywinpty")
raise PtyUnavailableError("ConPTY is unavailable on this platform.")
# See pty_bridge.py: exact-preservation factory for the env=None fallback.
from tools.environments.local import build_subprocess_env
spawn_env = (
build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
- if env is None else dict(env)
- )
+ if env is None else dict(env))
if not spawn_env.get("TERM"):
spawn_env["TERM"] = "xterm-256color"
# pywinpty mirrors ptyprocess: dimensions=(rows, cols).
- # This call shape is the one already used in tools/process_registry.py.
- proc = PtyProcess.spawn( # type: ignore[union-attr]
- list(argv),
- cwd=cwd,
- env=spawn_env,
- dimensions=(rows, cols),
- )
+ proc = PtyProcess.spawn(list(argv), cwd=cwd, env=spawn_env, dimensions=(rows, cols)) # type: ignore[union-attr]
return cls(proc)
@property
@@ -105,37 +78,29 @@ class WinPtyBridge:
except Exception:
return False
- # -- I/O --------------------------------------------------------------
-
def read(self, timeout: float = 0.2) -> Optional[bytes]:
"""Up to 64 KiB of child output."""
if self._closed:
return None
try:
data = self._proc.read(65536) # pywinpty returns str
- except EOFError:
- return None
except Exception:
return None
if not data:
- # No fd to select on; poll politely so the executor thread
- # doesn't pin a core while the TUI is idle.
+ # No fd to select on; sleep so the executor thread doesn't pin a core while idle.
time.sleep(min(timeout, 0.02))
return b""
if isinstance(data, bytes):
return data
- # NOTE: pywinpty decodes internally, so a multibyte UTF-8 sequence
- # can in theory split across reads. xterm.js tolerates the rare
- # replacement char; this is the one fidelity tradeoff vs the POSIX
- # raw-fd path.
+ # pywinpty decodes internally, so a multibyte UTF-8 sequence can split across reads;
+ # xterm.js tolerates the rare replacement char (the one fidelity tradeoff vs POSIX).
return data.encode("utf-8", errors="replace")
def write(self, data: bytes) -> None:
if self._closed or not data:
return
try:
- # The dashboard sends raw keystroke bytes; pywinpty.write wants text.
- self._proc.write(data.decode("utf-8", errors="replace"))
+ self._proc.write(data.decode("utf-8", errors="replace")) # pywinpty wants text
except Exception:
return
@@ -149,8 +114,6 @@ class WinPtyBridge:
except Exception:
pass
- # -- teardown ---------------------------------------------------------
-
def close(self) -> None:
if self._closed:
return
diff --git a/hermes_cli/windows_ssh_runtime.py b/hermes_cli/windows_ssh_runtime.py
index e031274583a..f48bfb7ebff 100644
--- a/hermes_cli/windows_ssh_runtime.py
+++ b/hermes_cli/windows_ssh_runtime.py
@@ -8,6 +8,7 @@ import re
import subprocess
import sys
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
from hermes_constants import get_default_hermes_root
@@ -23,7 +24,9 @@ _MOVE_REPLACE_EXISTING = 0x00000001
_MOVE_WRITE_THROUGH = 0x00000008
-def _win32() -> tuple[Any, ...]:
+def _win32() -> Any:
+ """Namespace of the pywin32 modules (ntsecuritycon, pywintypes, win32api, win32con, win32file,
+ win32security); import is deferred so the module imports on non-Windows hosts."""
if sys.platform != "win32":
raise RuntimeError("Windows SSH runtime is only available on Windows")
import ntsecuritycon
@@ -31,28 +34,29 @@ def _win32() -> tuple[Any, ...]:
import win32api
import win32con
import win32file
- import win32process
import win32security
- return ntsecuritycon, pywintypes, win32api, win32con, win32file, win32process, win32security
+ return SimpleNamespace(ntsecuritycon=ntsecuritycon, pywintypes=pywintypes, win32api=win32api,
+ win32con=win32con, win32file=win32file, win32security=win32security)
-def _ownership(value: str) -> str:
- if not _HEX32.fullmatch(value or ""):
- raise ValueError("invalid ownership ID")
+def _check(pattern: re.Pattern, value: str, message: str) -> str:
+ if not pattern.fullmatch(value or ""):
+ raise ValueError(message)
return value
+def _ownership(value: str) -> str:
+ return _check(_HEX32, value, "invalid ownership ID")
+
+
def _nonce(value: str) -> str:
- if not _HEX16.fullmatch(value or ""):
- raise ValueError("invalid spawn nonce")
- return value
+ return _check(_HEX16, value, "invalid spawn nonce")
def _root() -> Path:
- # The helper uploads the token before the child applies `--profile`, while
- # read_token() runs after profile activation. Anchor both processes to the
- # machine root so a named profile cannot move the reader away from the
- # helper's token, including custom HERMES_HOME layouts.
+ # The helper uploads the token before the child applies `--profile`; read_token() runs after
+ # profile activation. Anchor both to the machine root so a named profile (or custom
+ # HERMES_HOME) cannot move the reader away from the helper's token.
return get_default_hermes_root() / "desktop-ssh"
@@ -73,17 +77,22 @@ def _lock_path(ownership_id: str) -> Path:
def _current_sid():
- _, _, win32api, win32con, _, _, win32security = _win32()
- token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
- return win32security.GetTokenInformation(token, win32security.TokenUser)[0]
+ w = _win32()
+ token = w.win32security.OpenProcessToken(w.win32api.GetCurrentProcess(), w.win32con.TOKEN_QUERY)
+ return w.win32security.GetTokenInformation(token, w.win32security.TokenUser)[0]
def _system_sid():
- return _win32()[6].ConvertStringSidToSid("S-1-5-18")
+ return _win32().win32security.ConvertStringSidToSid("S-1-5-18")
+
+
+def _sid_str(sid) -> str:
+ return _win32().win32security.ConvertSidToStringSid(sid)
def _security_attributes():
- ntsecuritycon, _, _, _, _, _, win32security = _win32()
+ w = _win32()
+ ntsecuritycon, win32security = w.ntsecuritycon, w.win32security
owner = _current_sid()
acl = win32security.ACL()
for sid in (owner, _system_sid()):
@@ -99,41 +108,32 @@ def _security_attributes():
def _allowed_sids():
- win32security = _win32()[6]
- return {win32security.ConvertSidToStringSid(_current_sid()),
- win32security.ConvertSidToStringSid(_system_sid())}
+ return {_sid_str(_current_sid()), _sid_str(_system_sid())}
def _verify_security(handle) -> None:
- _, _, _, _, _, _, win32security = _win32()
+ win32security = _win32().win32security
info = win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
descriptor = win32security.GetSecurityInfo(handle, win32security.SE_FILE_OBJECT, info)
- owner = descriptor.GetSecurityDescriptorOwner()
- owner_value = win32security.ConvertSidToStringSid(owner)
- if owner_value not in _allowed_sids():
+ allowed = _allowed_sids()
+ if _sid_str(descriptor.GetSecurityDescriptorOwner()) not in allowed:
raise OSError("Windows SSH runtime object has the wrong owner")
dacl = descriptor.GetSecurityDescriptorDacl()
if dacl is None:
raise OSError("Windows SSH runtime object has a null DACL")
- allowed = _allowed_sids()
allow_types = {
win32security.ACCESS_ALLOWED_ACE_TYPE,
win32security.ACCESS_ALLOWED_OBJECT_ACE_TYPE,
getattr(win32security, "ACCESS_ALLOWED_CALLBACK_ACE_TYPE", 9),
- getattr(win32security, "ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE", 11),
- }
+ getattr(win32security, "ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE", 11)}
for index in range(dacl.GetAceCount()):
ace = dacl.GetAce(index)
- ace_type = ace[0][0]
- mask = ace[1]
- sid = ace[-1]
- if ace_type in allow_types and mask:
- if win32security.ConvertSidToStringSid(sid) not in allowed:
- raise OSError("Windows SSH runtime object has a permissive DACL")
+ if ace[0][0] in allow_types and ace[1] and _sid_str(ace[-1]) not in allowed:
+ raise OSError("Windows SSH runtime object has a permissive DACL")
def _open(path: Path, access: int, creation: int, flags: int, share: int = 0):
- _, _, _, _, win32file, _, _ = _win32()
+ win32file = _win32().win32file
handle = win32file.CreateFile(str(path), access, share, _security_attributes(), creation, flags, None)
try:
actual = win32file.GetFinalPathNameByHandle(handle, 0)
@@ -152,10 +152,41 @@ def _open(path: Path, access: int, creation: int, flags: int, share: int = 0):
raise
+def _read_shared(path: Path, limit: int, share: int) -> bytes | None:
+ """Open ``path`` read-only with ``share`` and read up to ``limit`` bytes; None when missing."""
+ w = _win32()
+ pywintypes, win32con, win32file = w.pywintypes, w.win32con, w.win32file
+ try:
+ handle = _open(path, win32con.GENERIC_READ | win32con.READ_CONTROL, win32con.OPEN_EXISTING,
+ win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT, share)
+ except pywintypes.error as exc:
+ if exc.winerror in (2, 3):
+ return None
+ raise
+ try:
+ return win32file.ReadFile(handle, limit)[1]
+ finally:
+ win32file.CloseHandle(handle)
+
+
+def _write_new(path: Path, data: bytes, share: int = 0) -> None:
+ """Create ``path`` (CREATE_NEW), write ``data`` and flush."""
+ w = _win32()
+ win32con, win32file = w.win32con, w.win32file
+ handle = _open(path, win32con.GENERIC_WRITE | win32con.READ_CONTROL, win32con.CREATE_NEW,
+ win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT, share)
+ try:
+ win32file.WriteFile(handle, data)
+ win32file.FlushFileBuffers(handle)
+ finally:
+ win32file.CloseHandle(handle)
+
+
def _ensure_directory(path: Path) -> None:
- _, pywintypes, _, win32con, win32file, _, _ = _win32()
- if path.parent != path:
- _ensure_directory(path.parent) if path.parent not in (Path(path.anchor), path) and not path.parent.exists() else None
+ w = _win32()
+ pywintypes, win32con, win32file = w.pywintypes, w.win32con, w.win32file
+ if path.parent not in (Path(path.anchor), path) and not path.parent.exists():
+ _ensure_directory(path.parent)
if not path.exists():
try:
win32file.CreateDirectory(str(path), _security_attributes())
@@ -177,19 +208,12 @@ def _ensure_scope(ownership_id: str) -> Path:
def upload_token(ownership_id: str, spawn_nonce: str, token: bytes) -> dict[str, Any]:
- _, _, _, win32con, win32file, _, _ = _win32()
if len(token) != 64 or not _HEX64.fullmatch(token.decode("ascii", errors="ignore")):
raise ValueError("invalid session token")
_ensure_scope(ownership_id)
path = _token_path(ownership_id, spawn_nonce)
try:
- handle = _open(path, win32con.GENERIC_WRITE | win32con.READ_CONTROL, win32con.CREATE_NEW,
- win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT)
- try:
- win32file.WriteFile(handle, token)
- win32file.FlushFileBuffers(handle)
- finally:
- win32file.CloseHandle(handle)
+ _write_new(path, token)
except BaseException:
path.unlink(missing_ok=True)
raise
@@ -197,7 +221,8 @@ def upload_token(ownership_id: str, spawn_nonce: str, token: bytes) -> dict[str,
def read_token(path_value: str) -> str:
- _, _, _, win32con, win32file, _, _ = _win32()
+ w = _win32()
+ win32con, win32file = w.win32con, w.win32file
path = Path(path_value)
root = _root()
try:
@@ -233,22 +258,10 @@ def _read_json_stdin() -> dict[str, Any]:
def read_lock(ownership_id: str) -> dict[str, Any] | None:
- _, pywintypes, _, win32con, win32file, _, _ = _win32()
+ win32con = _win32().win32con
_ensure_scope(ownership_id)
- path = _lock_path(ownership_id)
- try:
- handle = _open(path, win32con.GENERIC_READ | win32con.READ_CONTROL, win32con.OPEN_EXISTING,
- win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT,
- win32con.FILE_SHARE_READ)
- except pywintypes.error as exc:
- if exc.winerror in (2, 3):
- return None
- raise
- try:
- _, data = win32file.ReadFile(handle, _MAX_JSON + 1)
- finally:
- win32file.CloseHandle(handle)
- if len(data) > _MAX_JSON:
+ data = _read_shared(_lock_path(ownership_id), _MAX_JSON + 1, win32con.FILE_SHARE_READ)
+ if data is None or len(data) > _MAX_JSON:
return None
try:
parsed = json.loads(data)
@@ -258,25 +271,20 @@ def read_lock(ownership_id: str) -> dict[str, Any] | None:
def write_lock(ownership_id: str, payload: dict[str, Any]) -> None:
- _, _, _, win32con, win32file, _, _ = _win32()
+ win32file = _win32().win32file
directory = _ensure_scope(ownership_id)
data = json.dumps(payload, separators=(",", ":")).encode()
if len(data) > _MAX_JSON:
raise ValueError("lock payload is too large")
temporary = directory / f".{os.urandom(8).hex()}.lock.tmp"
- handle = _open(temporary, win32con.GENERIC_WRITE | win32con.READ_CONTROL, win32con.CREATE_NEW,
- win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT)
- try:
- win32file.WriteFile(handle, data)
- win32file.FlushFileBuffers(handle)
- finally:
- win32file.CloseHandle(handle)
+ _write_new(temporary, data)
win32file.MoveFileEx(str(temporary), str(_lock_path(ownership_id)),
_MOVE_REPLACE_EXISTING | _MOVE_WRITE_THROUGH)
def remove_artifact(path: Path) -> bool:
- _, pywintypes, _, win32con, win32file, _, _ = _win32()
+ w = _win32()
+ pywintypes, win32con, win32file = w.pywintypes, w.win32con, w.win32file
try:
handle = _open(path, win32con.DELETE | win32con.READ_CONTROL, win32con.OPEN_EXISTING,
win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT | _DELETE_ON_CLOSE)
@@ -293,9 +301,6 @@ def process_state(pid: int, creation_time_ns: int, hermes_path: str, spawn_nonce
_nonce(spawn_nonce)
try:
process = psutil.Process(pid)
- except psutil.NoSuchProcess as exc:
- return {"alive": False, "owned": False, "indeterminate": False, "reason": type(exc).__name__}
- try:
actual_creation = int(process.create_time() * 1_000_000_000)
argv = process.cmdline()
except psutil.NoSuchProcess as exc:
@@ -309,16 +314,13 @@ def process_state(pid: int, creation_time_ns: int, hermes_path: str, spawn_nonce
return {"alive": True, "owned": False, "indeterminate": True, "reason": "argv-unavailable"}
expected = os.path.normcase(os.path.abspath(hermes_path))
arg0 = os.path.normcase(os.path.abspath(argv[0]))
- # argv[0] is either the hermes exe directly, or (normal case) the base Python
- # interpreter -- its exact path varies by venv/uv layout, so match on "a python
- # running our module". We launch via `-c` bootstrap, so it shows as
- # `-c <bootstrap that runs hermes_cli.main>`; also accept a plain `-m` launch.
- # Identity is anchored by the unforgeable creation-time + secret owner-nonce below.
+ # argv[0] is the hermes exe or (normally) the base Python, whose path varies by venv/uv
+ # layout — so match "a python running our module" (`-c` bootstrap or plain `-m`). Identity
+ # is anchored by the unforgeable creation-time + secret owner-nonce below.
is_python = os.path.basename(arg0).startswith("python")
launches_module = (
argv[1:3] == ["-m", "hermes_cli.main"]
- or (len(argv) > 2 and argv[1] == "-c" and "hermes_cli.main" in argv[2])
- )
+ or (len(argv) > 2 and argv[1] == "-c" and "hermes_cli.main" in argv[2]))
executable_match = arg0 == expected or (is_python and launches_module)
try:
serve = argv.index("serve")
@@ -349,22 +351,18 @@ def terminate_owned(pid: int, creation_time_ns: int, hermes_path: str, spawn_non
def _resolve_direct_interpreter(python_entry: str) -> tuple[str, list[str]]:
- """Resolve the venv launcher to the base interpreter it would exec, plus the
- sys.path to reproduce. On Windows a venv Scripts\\python.exe is a launcher stub
- that spawns the real interpreter as a CHILD (two PIDs); spawning the base
- interpreter directly with the launcher's sys.path injected yields ONE process
- that both owns the port and is the process we lock.
-
- Also resolves hermes_cli's own location and prepends its parent, because the
- launcher finds the module via cwd / an editable-install path hook that a bare
- PYTHONPATH does not reproduce."""
+ """Resolve the venv launcher to (base interpreter, sys.path to reproduce).
+
+ On Windows a venv Scripts\\python.exe is a stub that spawns the real interpreter as a CHILD
+ (two PIDs); spawning the base interpreter with the launcher's sys.path injected yields ONE
+ process that both owns the port and is the one we lock. hermes_cli's parent is prepended
+ because the launcher finds it via cwd / an editable-install hook a bare PYTHONPATH lacks."""
query = (
"import sys,json,os,importlib.util as u;"
"s=u.find_spec('hermes_cli');"
"root=os.path.dirname(os.path.dirname(s.origin)) if s and s.origin else '';"
"print(json.dumps({'base':getattr(sys,'_base_executable','') or sys.executable,"
- "'path':[p for p in sys.path if p],'root':root}))"
- )
+ "'path':[p for p in sys.path if p],'root':root}))")
out = subprocess.run([python_entry, "-c", query], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30)
if out.returncode != 0:
raise ValueError("could not resolve the base Python interpreter")
@@ -372,16 +370,13 @@ def _resolve_direct_interpreter(python_entry: str) -> tuple[str, list[str]]:
base = info["base"]
if not base or not os.path.isfile(base):
raise ValueError("base Python interpreter was not found")
- # drop editable-install finder markers ('__editable__.*.finder.__path_hook__')
- # that PYTHONPATH cannot reproduce; keep only real filesystem entries.
+ # keep only real filesystem entries (drops '__editable__.*' finder markers)
py_path = [p for p in info.get("path", []) if os.path.exists(p)]
- # the hermes_cli package parent must be explicit -- the launcher resolves it via
- # cwd or an editable path hook, neither of which survives a bare PYTHONPATH spawn.
root = info.get("root") or ""
- if root and os.path.isdir(root) and root not in py_path:
- py_path.insert(0, root)
if not root or not os.path.isdir(root):
raise ValueError("could not locate the hermes_cli package")
+ if root not in py_path:
+ py_path.insert(0, root)
return base, py_path
@@ -402,27 +397,23 @@ def spawn_backend(payload: dict[str, Any]) -> dict[str, Any]:
if not os.path.isfile(python_entry):
raise ValueError("Hermes Python runtime was not found")
base_python, sys_path = _resolve_direct_interpreter(python_entry)
- # Seed sys.path IN-PROCESS via a -c bootstrap rather than exporting PYTHONPATH:
- # PYTHONPATH would be inherited by every subprocess the running backend spawns
- # (terminal tool, user scripts), shadowing their imports. This keeps the path
- # scoped to the backend process alone.
+ # Seed sys.path IN-PROCESS via -c rather than PYTHONPATH, which every subprocess the backend
+ # spawns (terminal tool, user scripts) would inherit, shadowing their imports.
bootstrap = (
"import sys,runpy;"
f"sys.path[:0]={sys_path!r};"
- "runpy.run_module('hermes_cli.main',run_name='__main__',alter_sys=True)"
- )
+ "runpy.run_module('hermes_cli.main',run_name='__main__',alter_sys=True)")
args = [base_python, "-c", bootstrap]
if profile:
args.extend(["--profile", profile])
args.extend(["serve", "--isolated", "--host", "127.0.0.1", "--port", "0",
"--ssh-session-token-file", token_path, "--ssh-owner-nonce", spawn_nonce])
- # VIRTUAL_ENV preserves venv identity; PYTHONPATH is deliberately NOT set (see above).
env = dict(os.environ)
env["VIRTUAL_ENV"] = os.path.dirname(venv_dir)
env.pop("PYTHONPATH", None)
_ensure_scope(ownership_id)
creationflags = 0x00000008 | 0x00000200 | 0x01000000
- _, _, _, win32con, win32file, _, _ = _win32()
+ win32con = _win32().win32con
log_handle = _open(log_path, win32con.GENERIC_WRITE | win32con.READ_CONTROL,
win32con.CREATE_NEW, win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE)
@@ -446,54 +437,50 @@ def inspect_hermes(hermes_path: str) -> dict[str, Any]:
return {
"path": path,
"version": (version.stdout + version.stderr).splitlines()[0] if version.returncode == 0 else "",
- "supported": "--ssh-session-token-file" in help_text and "--ssh-owner-nonce" in help_text,
- }
+ "supported": "--ssh-session-token-file" in help_text and "--ssh-owner-nonce" in help_text}
+
+
+def _probe(*_: str) -> dict[str, Any]:
+ import platform
+ return {"os": "Windows", "arch": platform.machine(), "hermesHome": str(get_default_hermes_root()), "python": sys.executable}
+
+
+def _read_log(ownership_id: str, spawn_nonce: str) -> dict[str, Any]:
+ win32con = _win32().win32con
+ data = _read_shared(_log_path(ownership_id, spawn_nonce), _MAX_LOG,
+ win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE)
+ return {"content": "" if data is None else data.decode(errors="replace")}
+
+
+def _write_lock_op(ownership_id: str) -> dict[str, Any]:
+ write_lock(ownership_id, _read_json_stdin())
+ return {"ok": True}
+
+
+# operation -> (argument count or None for "any", handler(*args)).
+_OPERATIONS: dict[str, tuple[int | None, Any]] = {
+ "probe": (None, _probe),
+ "upload-token": (2, lambda o, n: upload_token(o, n, sys.stdin.buffer.read(65))),
+ "read-lock": (1, read_lock),
+ "write-lock": (1, _write_lock_op),
+ "remove-lock": (1, lambda o: {"removed": remove_artifact(_lock_path(o))}),
+ "remove-token": (2, lambda o, n: {"removed": remove_artifact(_token_path(o, n))}),
+ "read-log": (2, _read_log),
+ "remove-log": (2, lambda o, n: {"removed": remove_artifact(_log_path(o, n))}),
+ "spawn": (None, lambda *_: spawn_backend(_read_json_stdin())),
+ "inspect": (1, inspect_hermes),
+ "process-state": (4, lambda p, c, h, n: process_state(int(p), int(c), h, n)),
+ "terminate": (4, lambda p, c, h, n: {"terminated": terminate_owned(int(p), int(c), h, n)})}
def dispatch(argv: list[str]) -> Any:
if not argv:
raise ValueError("missing operation")
- operation = argv[0]
- if operation == "probe":
- import platform
- return {"os": "Windows", "arch": platform.machine(), "hermesHome": str(get_default_hermes_root()), "python": sys.executable}
- if operation == "upload-token" and len(argv) == 3:
- return upload_token(argv[1], argv[2], sys.stdin.buffer.read(65))
- if operation == "read-lock" and len(argv) == 2:
- return read_lock(argv[1])
- if operation == "write-lock" and len(argv) == 2:
- write_lock(argv[1], _read_json_stdin()); return {"ok": True}
- if operation == "remove-lock" and len(argv) == 2:
- return {"removed": remove_artifact(_lock_path(argv[1]))}
- if operation == "remove-token" and len(argv) == 3:
- return {"removed": remove_artifact(_token_path(argv[1], argv[2]))}
- if operation == "read-log" and len(argv) == 3:
- path = _log_path(argv[1], argv[2])
- _, pywintypes, _, win32con, win32file, _, _ = _win32()
- try:
- handle = _open(path, win32con.GENERIC_READ | win32con.READ_CONTROL,
- win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT,
- win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE)
- except pywintypes.error as exc:
- if exc.winerror in (2, 3):
- return {"content": ""}
- raise
- try:
- _, data = win32file.ReadFile(handle, _MAX_LOG)
- finally:
- win32file.CloseHandle(handle)
- return {"content": data.decode(errors="replace")}
- if operation == "remove-log" and len(argv) == 3:
- return {"removed": remove_artifact(_log_path(argv[1], argv[2]))}
- if operation == "spawn":
- return spawn_backend(_read_json_stdin())
- if operation == "inspect" and len(argv) == 2:
- return inspect_hermes(argv[1])
- if operation == "process-state" and len(argv) == 5:
- return process_state(int(argv[1]), int(argv[2]), argv[3], argv[4])
- if operation == "terminate" and len(argv) == 5:
- return {"terminated": terminate_owned(int(argv[1]), int(argv[2]), argv[3], argv[4])}
- raise ValueError("invalid operation")
+ operation, args = argv[0], argv[1:]
+ entry = _OPERATIONS.get(operation)
+ if entry is None or (entry[0] is not None and len(args) != entry[0]):
+ raise ValueError("invalid operation")
+ return entry[1](*args)
def main() -> None:
diff --git a/hermes_cli/worktree_cmd.py b/hermes_cli/worktree_cmd.py
index 55e269dc110..93a166a138e 100644
--- a/hermes_cli/worktree_cmd.py
+++ b/hermes_cli/worktree_cmd.py
@@ -1,21 +1,11 @@
-"""``hermes worktree`` — audit and reclaim accumulated git worktrees/branches.
-
-hermes worktree list # audit: verdict + reason per tree hermes worktree prune # reap safe trees +
-merged branches hermes worktree prune --dry-run # show the plan, change nothing hermes worktree
-prune --trees-only / --branches-only
-"""
+"""``hermes worktree`` — audit (``list``) and reclaim (``prune [--dry-run] [--trees-only |
+--branches-only]``) accumulated git worktrees/branches."""
from __future__ import annotations
from typing import Optional
-def _repo_root() -> Optional[str]:
- import cli as _cli
-
- return _cli._git_repo_root()
-
-
def _fmt_size(size_mb: Optional[int]) -> str:
if size_mb is None:
return "?"
@@ -34,8 +24,7 @@ def _list(worktree_gc, repo_root: str, args) -> int:
print(f"{r.name[:32]:32} {r.age_days:>5.1f}d {_fmt_size(r.size_mb):>6} {r.verdict:13} {r.reason}")
print(
f"\n{len(records)} tree(s), {_fmt_size(total_mb)} total — "
- f"{_fmt_size(reapable_mb)} reclaimable now via `hermes worktree prune`."
- )
+ f"{_fmt_size(reapable_mb)} reclaimable now via `hermes worktree prune`.")
deletable = [b for b in worktree_gc.audit_branches(repo_root) if b.verdict == "delete"]
if deletable:
print(f"{len(deletable)} local branch(es) fully merged/patch-equivalent upstream would also be deleted.")
@@ -72,7 +61,10 @@ _ACTIONS = {"list": _list, "prune": _prune}
def cmd_worktree(args) -> int:
from hermes_cli import worktree_gc
- repo_root = getattr(args, "repo", None) or _repo_root()
+ repo_root = getattr(args, "repo", None)
+ if not repo_root:
+ import cli as _cli
+ repo_root = _cli._git_repo_root()
if not repo_root:
print("Not inside a git repository (or pass --repo <path>).")
return 1
diff --git a/hermes_cli/worktree_gc.py b/hermes_cli/worktree_gc.py
index c2b4e21e4f9..fec55f6f0c2 100644
--- a/hermes_cli/worktree_gc.py
+++ b/hermes_cli/worktree_gc.py
@@ -1,15 +1,13 @@
"""On-demand worktree + branch reclaim (``hermes worktree`` / ``/worktree prune``).
-The startup pruner in ``cli._prune_stale_worktrees`` is deliberately conservative and silent: it
-runs before the banner on every ``hermes -w`` launch, so it only reaps clean, fully-merged scratch
-trees past an age tier and preserves everything else.
-
-- **Preserved trees** whose only "dirt" is untracked scratch (PR body drafts, logs) on an otherwise
-merged branch — preserved forever by the dirty guard.
+The startup pruner (``cli._prune_stale_worktrees``) is conservative and silent — clean, fully
+merged scratch past an age tier only. This module also reclaims trees whose only "dirt" is
+untracked scratch (archived first) and branches whose content is on upstream.
"""
from __future__ import annotations
+import contextlib
import logging
import os
import re
@@ -52,44 +50,33 @@ class BranchRecord:
reason: str
-def _git(args: list, cwd: str, timeout: int = 15) -> subprocess.CompletedProcess:
- """Run git, translating timeouts into a nonzero returncode.
+def _run(cmd: list, timeout: int, cwd: Optional[str] = None) -> subprocess.CompletedProcess:
+ return subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=timeout, cwd=cwd)
+
- Every verdict in this module fails safe toward "keep" on a nonzero returncode, so a hung/slow
- git call (large repos make ``git cherry`` genuinely slow) must degrade to keep — never crash the
- whole audit (live-verified failure on a 746MB .git: TimeoutExpired escaped and aborted the
- branch audit mid-list).
- """
+def _git(args: list, cwd: str, timeout: int = 15) -> subprocess.CompletedProcess:
+ """Run git, translating timeouts into returncode 124. Every verdict fails safe toward "keep"
+ on nonzero, so a slow ``git cherry`` on a huge repo degrades to keep instead of aborting the
+ audit mid-list."""
try:
- return subprocess.run(
- ["git", *args],
- capture_output=True, text=True, encoding="utf-8",
- errors="replace", timeout=timeout, cwd=cwd,
- )
+ return _run(["git", *args], timeout, cwd)
except subprocess.TimeoutExpired:
- return subprocess.CompletedProcess(
- args=["git", *args], returncode=124,
- stdout="", stderr=f"timeout after {timeout}s",
- )
+ return subprocess.CompletedProcess(args=["git", *args], returncode=124, stdout="",
+ stderr=f"timeout after {timeout}s")
def _tree_size_mb(path: Path, timeout: int = 30) -> Optional[int]:
"""Cheap directory size via ``du -sm`` — best-effort, None on failure."""
try:
- result = subprocess.run(
- ["du", "-sm", str(path)], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout
- )
+ result = _run(["du", "-sm", str(path)], timeout)
return int(result.stdout.split()[0]) if result.returncode == 0 and result.stdout.strip() else None
except Exception:
return None
def _dirty_split(path: str) -> tuple[bool, List[str]]:
- """Return (has_tracked_modifications, untracked_paths).
-
- ``git status --porcelain`` counts untracked scratch the same as real edits, but the reclaim
- policy treats them differently (tracked = real work, untracked = archivable scratch).
- """
+ """(has_tracked_modifications, untracked_paths) — tracked = real work, untracked = archivable."""
try:
result = _git(["status", "--porcelain"], cwd=path, timeout=10)
if result.returncode != 0:
@@ -102,11 +89,7 @@ def _dirty_split(path: str) -> tuple[bool, List[str]]:
def _archive_untracked(tree: Path, untracked: List[str]) -> Optional[Path]:
- """Copy untracked files out of a doomed tree. Returns the archive dir.
-
- Never destroys: on any copy failure the caller must treat the tree as keep. Costs almost nothing
- and removes the "did I just delete something?" question.
- """
+ """Copy untracked files out of a doomed tree; None on any failure (caller must then keep)."""
stamp = time.strftime("%Y%m%d-%H%M%S")
dest = Path.home() / ".hermes" / "archive" / "worktree-prune" / f"{tree.name}-{stamp}"
try:
@@ -138,12 +121,10 @@ def _classify_tree(_cli, repo_root: str, entry: Path, merge_cache, remote_heads)
return "keep", "uncommitted tracked changes (real work)", []
archive_note = f"{len(untracked)} untracked file(s) will be archived"
if _cli._worktree_has_unpushed_commits(path, timeout=5) and not _cli._worktree_commits_all_merged_upstream(
- path, timeout=30, cache=merge_cache, max_ahead=_MAX_CHERRY_AHEAD
- ):
- # Pushed-branch tier: single-branch fetch refspecs (the managed-install default) leave
- # pushed PR branches with no refs/remotes/* entry, so `git log HEAD --not --remotes`
- # reads them as unpushed forever. A local head that EXACTLY matches the remote branch
- # has nothing origin lacks — the checkout is redundant; only the branch ref stays.
+ path, timeout=30, cache=merge_cache, max_ahead=_MAX_CHERRY_AHEAD):
+ # Pushed-branch tier: single-branch fetch refspecs (managed-install default) leave pushed
+ # PR branches with no refs/remotes/* entry, so `git log HEAD --not --remotes` reads them
+ # as unpushed forever. A head EXACTLY matching the remote branch has nothing origin lacks.
if not _cli._worktree_branch_pushed_exact(path, remote_heads, timeout=10):
return "keep", "unpushed commits not found upstream", []
if untracked:
@@ -167,9 +148,7 @@ def audit_worktrees(repo_root: str, *, with_sizes: bool = True) -> List[TreeReco
merge_cache = _cli._load_worktree_merge_cache()
cache_size_before = len(merge_cache)
-
- # One ls-remote resolves "is this branch pushed as-is?" for the whole
- # sweep. None (offline) degrades every pushed-tier verdict to keep.
+ # One ls-remote for the whole sweep; None (offline) degrades pushed-tier verdicts to keep.
remote_heads = _cli._fetch_remote_branch_heads(repo_root)
now = time.time()
@@ -185,13 +164,11 @@ def audit_worktrees(repo_root: str, *, with_sizes: bool = True) -> List[TreeReco
branch = _git(["branch", "--show-current"], cwd=str(entry), timeout=5).stdout.strip()
except Exception:
branch = ""
-
verdict, reason, untracked = _classify_tree(_cli, repo_root, entry, merge_cache, remote_heads)
records.append(TreeRecord(
name=entry.name, path=str(entry), branch=branch,
age_days=age_days, size_mb=_tree_size_mb(entry) if with_sizes else None,
- verdict=verdict, reason=reason, untracked=untracked,
- ))
+ verdict=verdict, reason=reason, untracked=untracked))
if len(merge_cache) != cache_size_before:
_cli._save_worktree_merge_cache(merge_cache)
@@ -202,17 +179,10 @@ _REAP_VERDICTS = {"reap", "reap-archive", "reap-keep-branch"}
def reclaim_worktrees(
- repo_root: str,
- *,
- dry_run: bool = False,
- records: Optional[List[TreeRecord]] = None,
+ repo_root: str, *, dry_run: bool = False, records: Optional[List[TreeRecord]] = None
) -> List[str]:
- """Remove every reap-verdict tree from a frozen audit list.
-
- Operates ONLY on the provided (or freshly computed) audit records — never re-globs inside the
- destructive loop, so trees created by concurrent sessions after the audit are out of scope by
- construction.
- """
+ """Remove every reap-verdict tree from a frozen audit list — never re-globs inside the
+ destructive loop, so trees created by concurrent sessions after the audit are out of scope."""
if records is None:
records = audit_worktrees(repo_root, with_sizes=False)
actions: List[str] = []
@@ -232,11 +202,8 @@ def reclaim_worktrees(
actions.append(f"archived {len(record.untracked)} untracked file(s) → {archive}")
# Dead-pid locks must be unlocked or `remove --force` refuses.
- try:
+ with contextlib.suppress(Exception):
_git(["worktree", "unlock", record.path], cwd=repo_root, timeout=10)
- except Exception:
- pass
-
try:
remove_result = _git(["worktree", "remove", record.path, "--force"], cwd=repo_root, timeout=30)
if remove_result.returncode != 0:
@@ -252,20 +219,14 @@ def reclaim_worktrees(
actions.append(f"failed to remove {record.name}: {exc}")
if not dry_run:
- try:
+ with contextlib.suppress(Exception):
_git(["worktree", "prune"], cwd=repo_root, timeout=15)
- except Exception:
- pass
return actions
def audit_branches(repo_root: str) -> List[BranchRecord]:
- """Classify local branches: deletable when their content is on upstream and not checked out.
-
- "On upstream" means fully merged OR every commit patch-equivalent via ``git cherry``. Applies
- to EVERY local branch, not just the startup pass's prefix list, because the gate is content
- reachability rather than name. Checked-out, protected, and unique-commit branches are kept.
- """
+ """Classify EVERY local branch: deletable when fully merged OR every commit is patch-equivalent
+ upstream (``git cherry``) and not checked out. The gate is content reachability, not name."""
import cli as _cli
if _cli._repo_is_shallow(repo_root):
@@ -277,8 +238,7 @@ def audit_branches(repo_root: str) -> List[BranchRecord]:
upstream = next(
(c for c in ("origin/HEAD", "origin/main", "origin/master")
if _git(["rev-parse", "--verify", "--quiet", c], cwd=repo_root, timeout=5).returncode == 0),
- None,
- )
+ None)
if upstream is None:
return []
@@ -290,8 +250,7 @@ def audit_branches(repo_root: str) -> List[BranchRecord]:
wt = _git(["worktree", "list", "--porcelain"], cwd=repo_root, timeout=10)
active = {
line.removeprefix("branch refs/heads/").strip()
- for line in wt.stdout.splitlines() if line.startswith("branch refs/heads/")
- }
+ for line in wt.stdout.splitlines() if line.startswith("branch refs/heads/")}
merged = set(_lines(_git(["branch", "--merged", upstream, "--format=%(refname:short)"], cwd=repo_root, timeout=15)))
def _classify_branch(branch: str) -> BranchRecord:
@@ -299,9 +258,8 @@ def audit_branches(repo_root: str) -> List[BranchRecord]:
return BranchRecord(branch, "keep", "protected or checked out")
if branch in merged:
return BranchRecord(branch, "delete", "fully merged into " + upstream)
- # Rebase merges rewrite SHAs, so --merged misses them; cherry
- # patch-equivalence catches the dominant leak. Bounded: a branch
- # far ahead is a stale-base lane, keep it.
+ # Rebase merges rewrite SHAs, so --merged misses them; cherry patch-equivalence catches
+ # the dominant leak. Bounded: a branch far ahead is a stale-base lane, keep it.
ahead = _git(["rev-list", "--count", f"{upstream}..{branch}"], cwd=repo_root, timeout=10)
try:
ahead_count = int(ahead.stdout.strip() or "0")
@@ -320,17 +278,13 @@ def audit_branches(repo_root: str) -> List[BranchRecord]:
unique = sum(1 for ln in lines if ln.startswith("+"))
return BranchRecord(branch, "keep", f"{unique} unique commit(s) not upstream")
- # Read-only classification — parallel, like the tree audit (a busy
- # multi-agent box carries hundreds of local branches; serial cherry
- # probes at ~0.2-1s each make the audit minutes long).
+ # Read-only, so parallel: hundreds of local branches × ~0.2-1s cherry probes would be minutes.
import concurrent.futures
workers = max(1, min(8, (os.cpu_count() or 4), len(branches)))
if workers > 1:
try:
- with concurrent.futures.ThreadPoolExecutor(
- max_workers=workers, thread_name_prefix="hermes-branch-gc"
- ) as pool:
+ with concurrent.futures.ThreadPoolExecutor(max_workers=workers, thread_name_prefix="hermes-branch-gc") as pool:
return list(pool.map(_classify_branch, branches))
except Exception:
pass
@@ -338,10 +292,7 @@ def audit_branches(repo_root: str) -> List[BranchRecord]:
def reclaim_branches(
- repo_root: str,
- *,
- dry_run: bool = False,
- records: Optional[List[BranchRecord]] = None,
+ repo_root: str, *, dry_run: bool = False, records: Optional[List[BranchRecord]] = None
) -> List[str]:
"""Delete every delete-verdict branch from a frozen audit list."""
if records is None:
@@ -356,14 +307,12 @@ def reclaim_branches(
result = _git(["branch", "-D", record.name], cwd=repo_root, timeout=10)
actions.append(
f"deleted branch {record.name}" if result.returncode == 0
- else f"failed to delete {record.name}: {result.stderr.strip()}"
- )
+ else f"failed to delete {record.name}: {result.stderr.strip()}")
return actions
def worktrees_summary(repo_root: str) -> tuple[int, Optional[int]]:
- """(tree_count, total_size_mb) for the escalation notice. Size is
- best-effort with a hard timeout so the startup path never stalls."""
+ """(tree_count, total_size_mb) for the escalation notice; size is best-effort with a timeout."""
worktrees_dir = Path(repo_root) / ".worktrees"
if not worktrees_dir.exists():
return 0, None
diff --git a/hermes_cli/write_approval_commands.py b/hermes_cli/write_approval_commands.py
index 8fa473359d6..150b72dfd17 100644
--- a/hermes_cli/write_approval_commands.py
+++ b/hermes_cli/write_approval_commands.py
@@ -14,10 +14,6 @@ def _fmt_state(subsystem: str) -> str:
return f"{subsystem}.write_approval = {'on' if on else 'off'}"
-# ---------------------------------------------------------------------------
-# Formatting helpers
-# ---------------------------------------------------------------------------
-
def _fmt_pending_list(subsystem: str) -> str:
records = wa.list_pending(subsystem)
if not records:
@@ -34,17 +30,8 @@ def _fmt_pending_list(subsystem: str) -> str:
return "\n".join(lines)
-# ---------------------------------------------------------------------------
-# Subcommand dispatch
-# ---------------------------------------------------------------------------
-
def handle_pending_subcommand(
- subsystem: str,
- args: List[str],
- *,
- memory_store=None,
- set_mode_fn=None,
-) -> Optional[str]:
+ subsystem: str, args: List[str], *, memory_store=None, set_mode_fn=None) -> Optional[str]:
"""Dispatch a /memory or /skills write-approval subcommand.
``memory_store`` applies approved memory writes (CLI passes its live store; gateway a freshly
@@ -53,12 +40,8 @@ def handle_pending_subcommand(
other handling (e.g. /skills search).
"""
if not args:
- # Bare /memory or /skills with no sub → show pending + gate state.
return f"{_fmt_state(subsystem)}\n\n" + _fmt_pending_list(subsystem)
-
- sub = args[0].lower()
- rest = args[1:]
-
+ sub, rest = args[0].lower(), args[1:]
if sub == "pending":
return _fmt_pending_list(subsystem)
if sub in {"approve", "apply"}:
@@ -80,11 +63,9 @@ def _approve(subsystem: str, rest: List[str], memory_store) -> str:
if not rest:
return _usage(subsystem)
target = rest[0]
-
records = wa.list_pending(subsystem)
if not records:
return f"No pending {subsystem} writes."
-
if target.lower() == "all":
targets = list(records)
else:
@@ -143,9 +124,12 @@ def _diff(rest: List[str]) -> str:
rec = wa.get_pending(wa.SKILLS, rest[0])
if not rec:
return f"No pending skill write with id '{rest[0]}'."
- diff = wa.skill_pending_diff(rec)
- header = f"# Pending skill write {rec['id']}: {rec.get('summary', '')}\n"
- return header + "\n" + diff
+ return f"# Pending skill write {rec['id']}: {rec.get('summary', '')}\n\n" + wa.skill_pending_diff(rec)
+
+
+_APPROVAL_VALUES = {
+ **dict.fromkeys(("on", "true", "yes", "1", "enable", "enabled"), True),
+ **dict.fromkeys(("off", "false", "no", "0", "disable", "disabled"), False)}
def _set_approval(subsystem: str, rest: List[str], set_mode_fn) -> str:
@@ -154,10 +138,7 @@ def _set_approval(subsystem: str, rest: List[str], set_mode_fn) -> str:
return (f"{_fmt_state(subsystem)}\n"
f"Set with: /{subsystem} approval <on|off>")
arg = rest[0].strip().lower()
- enabled = {
- **dict.fromkeys(("on", "true", "yes", "1", "enable", "enabled"), True),
- **dict.fromkeys(("off", "false", "no", "0", "disable", "disabled"), False),
- }.get(arg)
+ enabled = _APPROVAL_VALUES.get(arg)
if enabled is None:
return f"Invalid value '{arg}'. Use: on or off."
if set_mode_fn is None:
diff --git a/hermes_cli/xai_retirement.py b/hermes_cli/xai_retirement.py
index e6670c16142..c3b608b6915 100644
--- a/hermes_cli/xai_retirement.py
+++ b/hermes_cli/xai_retirement.py
@@ -1,7 +1,11 @@
-"""Detect xAI models retired on May 15, 2026."""
+"""Detect xAI models retired on May 15, 2026 and migrate config.yaml references."""
from __future__ import annotations
+import datetime as _dt
+import io
+import shutil
from dataclasses import dataclass
+from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -9,10 +13,8 @@ MIGRATION_GUIDE_URL = "https://docs.x.ai/developers/migration/may-15-retirement"
RETIREMENT_DATE = "May 15, 2026"
-# Official mapping per xAI migration guide.
-# Some entries set ``reasoning_effort`` because non-reasoning variants don't
-# have a one-to-one replacement: ``grok-4.3`` reasons by default, so emulating
-# ``*-non-reasoning`` behavior on it requires ``reasoning_effort="none"``.
+# Official mapping per xAI migration guide. ``grok-4.3`` reasons by default, so ``*-non-reasoning``
+# variants need ``reasoning_effort="none"`` to emulate their behavior.
_RETIRED_MODELS: Dict[str, Dict[str, Optional[str]]] = {
"grok-4-0709": {"replacement": "grok-4.3", "reasoning_effort": None, "note": None},
"grok-4-fast-reasoning": {"replacement": "grok-4.3", "reasoning_effort": None, "note": None},
@@ -31,9 +33,9 @@ class RetirementIssue:
config_path: str # e.g. "principal.model" or "auxiliary.vision.model"
current_model: str # exact value found in config (preserves casing/prefix)
- replacement: str # recommended xAI replacement
- reasoning_effort: Optional[str] = None # set if non-reasoning variant migration
- note: Optional[str] = None # disambiguation note when applicable
+ replacement: str
+ reasoning_effort: Optional[str] = None # set for non-reasoning variant migration
+ note: Optional[str] = None
def _normalize(model_id: str) -> str:
@@ -41,15 +43,12 @@ def _normalize(model_id: str) -> str:
m = model_id.strip().lower()
for prefix in ("x-ai/", "xai/"):
if m.startswith(prefix):
- m = m[len(prefix):]
- break
+ return m[len(prefix):]
return m
def _looks_like_xai(model_id: Optional[str]) -> bool:
- if not isinstance(model_id, str) or not model_id.strip():
- return False
- return _normalize(model_id).startswith("grok-")
+ return isinstance(model_id, str) and _normalize(model_id).startswith("grok-")
def find_retired_xai_refs(config: Dict[str, Any]) -> List[RetirementIssue]:
@@ -59,21 +58,18 @@ def find_retired_xai_refs(config: Dict[str, Any]) -> List[RetirementIssue]:
aux slots), ``delegation.model``, ``tts.xai.model``, ``plugins.image_gen.xai.model``.
"""
issues: List[RetirementIssue] = []
+ if not isinstance(config, dict):
+ return issues
def _check(path: str, model: Any) -> None:
- if not _looks_like_xai(model):
- return
- norm = _normalize(model)
- entry = _RETIRED_MODELS.get(norm)
- if entry is None:
- return
- issues.append(RetirementIssue(
- config_path=path,
- current_model=model,
- replacement=entry["replacement"],
- reasoning_effort=entry.get("reasoning_effort"),
- note=entry.get("note"),
- ))
+ entry = _RETIRED_MODELS.get(_normalize(model)) if _looks_like_xai(model) else None
+ if entry is not None:
+ issues.append(RetirementIssue(
+ config_path=path,
+ current_model=model,
+ replacement=entry["replacement"],
+ reasoning_effort=entry.get("reasoning_effort"),
+ note=entry.get("note")))
def _section(*keys: str) -> Optional[Dict[str, Any]]:
node: Any = config
@@ -83,32 +79,23 @@ def find_retired_xai_refs(config: Dict[str, Any]) -> List[RetirementIssue]:
node = node.get(key)
return node if isinstance(node, dict) else None
- if not isinstance(config, dict):
- return issues
-
- principal = _section("principal")
- if principal is not None:
- _check("principal.model", principal.get("model"))
-
- aux = _section("auxiliary")
- if aux is not None:
- for slot_name, slot_cfg in aux.items():
- if isinstance(slot_cfg, dict):
- _check(f"auxiliary.{slot_name}.model", slot_cfg.get("model"))
-
- for path in (("delegation",), ("tts", "xai"), ("plugins", "image_gen", "xai")):
+ def _check_section(*path: str) -> None:
section = _section(*path)
if section is not None:
_check(".".join(path) + ".model", section.get("model"))
+ _check_section("principal")
+ for slot_name, slot_cfg in (_section("auxiliary") or {}).items():
+ if isinstance(slot_cfg, dict):
+ _check(f"auxiliary.{slot_name}.model", slot_cfg.get("model"))
+ for path in (("delegation",), ("tts", "xai"), ("plugins", "image_gen", "xai")):
+ _check_section(*path)
return issues
def format_issue(issue: RetirementIssue) -> str:
"""One-line human-readable rendering of a retirement issue."""
- parts = [
- f"{issue.config_path}: {issue.current_model!r} → use {issue.replacement!r}"
- ]
+ parts = [f"{issue.config_path}: {issue.current_model!r} → use {issue.replacement!r}"]
if issue.reasoning_effort:
parts.append(f'(set reasoning_effort: "{issue.reasoning_effort}")')
if issue.note:
@@ -116,16 +103,6 @@ def format_issue(issue: RetirementIssue) -> str:
return " ".join(parts)
-# ---------------------------------------------------------------------------
-# Apply migration to config.yaml (round-trip preserves comments/order/types)
-# ---------------------------------------------------------------------------
-
-import datetime as _dt
-import io
-from pathlib import Path
-import shutil
-
-
@dataclass(frozen=True)
class ApplyResult:
"""Outcome of an apply_migration call."""
@@ -150,27 +127,17 @@ def _walk_to_parent(yaml_doc: Any, dotted_path: str) -> "tuple[Any, str]":
def apply_migration(
- config_path: Path,
- issues: List[RetirementIssue],
- backup: bool = True,
-) -> ApplyResult:
- """Rewrite ``config_path`` in-place so each issue is resolved.
-
- Uses ``ruamel.yaml`` round-trip mode so comments, key order, indentation, and type literals
- (booleans, ints) are preserved.
+ config_path: Path, issues: List[RetirementIssue], backup: bool = True) -> ApplyResult:
+ """Rewrite ``config_path`` in place (ruamel round-trip: comments, order, type literals kept).
- A backup copy is written to ``<config_path>.bak-pre-migrate-xai-YYYYMMDD-HHMMSS`` before
- rewriting, unless ``backup=False``.
+ Unless ``backup=False`` a copy goes to ``<config_path>.bak-pre-migrate-xai-YYYYMMDD-HHMMSS``.
"""
from ruamel.yaml import YAML # local import — avoid hard dep at module load
config_path = Path(config_path)
if not config_path.exists():
raise FileNotFoundError(config_path)
- unchanged = ApplyResult(
- file_path=config_path, backup_path=None, issues_resolved=[], config_changed=False
- )
-
+ unchanged = ApplyResult(file_path=config_path, backup_path=None, issues_resolved=[], config_changed=False)
if not issues:
return unchanged
@@ -178,7 +145,6 @@ def apply_migration(
yaml.preserve_quotes = True
with config_path.open("r", encoding="utf-8") as fh:
doc = yaml.load(fh)
-
if doc is None:
return unchanged
@@ -187,50 +153,30 @@ def apply_migration(
try:
parent, leaf = _walk_to_parent(doc, issue.config_path)
except KeyError:
- # Slot vanished between scan and apply — skip silently
- continue
+ continue # slot vanished between scan and apply
parent[leaf] = issue.replacement
if issue.reasoning_effort:
parent["reasoning_effort"] = issue.reasoning_effort
resolved.append(issue)
-
if not resolved:
return unchanged
backup_path: Optional[Path] = None
if backup:
ts = _dt.datetime.now().strftime("%Y%m%d-%H%M%S")
- backup_path = config_path.with_name(
- f"{config_path.name}.bak-pre-migrate-xai-{ts}"
- )
+ backup_path = config_path.with_name(f"{config_path.name}.bak-pre-migrate-xai-{ts}")
shutil.copy2(config_path, backup_path)
from hermes_cli.config import require_readable_config_before_write
from utils import atomic_write_text
require_readable_config_before_write(config_path)
-
- # Serialize with the round-trip dumper first, then hand the finished text
- # to the shared atomic writer (temp file + fsync + atomic replace).
- # ``open(config_path, "w")`` truncates before the dump runs, so a crash or
- # SIGINT mid-write leaves config.yaml empty or half-written -- and
- # ``--no-backup`` is a documented flag, so on that path the truncated file
- # is the only copy left. The load half above returns early when ``doc is
- # None``, so the next `hermes migrate xai` reports nothing to migrate
- # rather than surfacing the damage. atomic_replace also keeps a symlinked
- # config.yaml (dotfiles repo / managed deployment) intact (GitHub #16743).
+ # Dump to a buffer, then atomic-write: ``open(path, "w")`` truncates before the dump runs, so a
+ # crash mid-write would leave config.yaml empty (and with ``--no-backup`` that is the only
+ # copy; the ``doc is None`` early return would then hide the damage). atomic_replace also keeps
+ # a symlinked config.yaml intact. preserve_mode keeps permission bits AND owner (managed NixOS
+ # 0640 / container installs; a root-run migration must not flip ownership).
buf = io.StringIO()
yaml.dump(doc, buf)
-
- # preserve_mode carries the existing permission bits AND owner across the
- # replace: _secure_file deliberately leaves config.yaml alone under managed
- # (NixOS 0640) and container installs, and a root-run migration on a
- # user-owned volume must not flip ownership to root.
atomic_write_text(config_path, buf.getvalue(), preserve_mode=True)
-
- return ApplyResult(
- file_path=config_path,
- backup_path=backup_path,
- issues_resolved=resolved,
- config_changed=True,
- )
+ return ApplyResult(file_path=config_path, backup_path=backup_path, issues_resolved=resolved, config_changed=True)