Skip to content

The agent that grows with you

refactor(web-profiles/status): fold db-open into read helper, data-drive sidebar slices, compact docstrings

Tekniumba1df7dab113
diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.py
index 375c64c36b1..df5ccc48bdd 100644
--- a/hermes_cli/web_routers/profiles.py
+++ b/hermes_cli/web_routers/profiles.py
@@ -36,10 +36,9 @@ from hermes_cli.web_server_profiles import _hermes_home_scope
# Same logger the handlers used before extraction (identical logger object).
_log = logging.getLogger("hermes_cli.web_server")
-# Per-profile session reads report failures in the response's ``errors`` array, which the
-# desktop sidebar does not surface — an empty sidebar can look healthy while nothing logs.
-# Warn once per (profile, message) per process so a persistent failure is loud in
-# errors.log without turning every sidebar poll into log spam.
+# Per-profile session reads report failures only in the response's ``errors`` array, which
+# the desktop sidebar does not surface. Warn once per (profile, message) per process so a
+# persistent failure is loud in errors.log without turning every sidebar poll into spam.
_profile_read_warned: set = set()
@@ -76,11 +75,9 @@ _normalize_main_model_assignment = late("_normalize_main_model_assignment")
def _profile_to_dict(info) -> Dict[str, Any]:
attr = functools.partial(getattr, info)
return {
- "name": attr("name", ""),
- "path": str(attr("path", "")),
+ "name": attr("name", ""), "path": str(attr("path", "")),
"is_default": bool(attr("is_default", False)),
- "model": attr("model", None),
- "provider": attr("provider", None),
+ "model": attr("model", None), "provider": attr("provider", None),
"has_env": bool(attr("has_env", False)),
"skill_count": int(attr("skill_count", 0) or 0),
"gateway_running": bool(attr("gateway_running", False)),
@@ -100,11 +97,9 @@ def _profile_setup_command(name: str) -> str:
def _write_profile_model(profile_dir: Path, provider: str, model: str) -> None:
- """Write the main model assignment into ``profile_dir``'s config.yaml (HERMES_HOME-scoped,
- so it lands in the target profile rather than the dashboard's active one). Clears stale
- ``base_url`` / ``context_length`` the same way ``POST /api/model/set`` does."""
+ """Write the main model assignment into ``profile_dir``'s config.yaml (HERMES_HOME-scoped);
+ clears stale ``base_url`` / ``context_length`` like ``POST /api/model/set`` does."""
from hermes_cli.web_server import load_config, save_config
-
with _hermes_home_scope(profile_dir):
provider, model = _normalize_main_model_assignment(provider, model)
cfg = load_config()
@@ -113,17 +108,12 @@ def _write_profile_model(profile_dir: Path, provider: str, model: str) -> None:
def _disable_unselected_skills(profile_dir: Path, keep: List[str]) -> int:
- """Disable every installed skill in ``profile_dir`` not in ``keep``; returns how many
- were newly disabled.
-
- Profiles manage activation via a *disabled* list (everything installed is active by
- default). The builder's skill step has "replace" semantics: the user picks exactly which
- seeded skills stay active. Hub skills are installed separately via subprocess and are
- active on install.
- """
+ """Disable every installed skill in ``profile_dir`` not in ``keep``; returns how many were
+ newly disabled. Profiles manage activation via a *disabled* list (everything installed is
+ active by default); the builder's skill step has "replace" semantics. Hub skills are
+ installed separately via subprocess and are active on install."""
from hermes_cli.web_server import load_config
from hermes_cli.skills_config import get_disabled_skills, save_disabled_skills
-
keep_set = {s.strip() for s in keep if s and s.strip()}
with _hermes_home_scope(profile_dir):
skills_root = profile_dir / "skills"
@@ -148,9 +138,8 @@ _MISSING = object()
@contextlib.contextmanager
def _profile_errors(log_msg: str, *args, not_found=(FileNotFoundError,),
bad_request=(ValueError,)):
- """Map hermes_cli.profiles exceptions to HTTP: ``not_found`` -> 404,
- ``bad_request`` -> 400 (checked in that order), anything else is logged
- with ``log_msg`` and becomes a 500. ``HTTPException`` passes through."""
+ """Map hermes_cli.profiles exceptions to HTTP: ``not_found`` -> 404, ``bad_request`` -> 400
+ (in that order), anything else is logged with ``log_msg`` -> 500. HTTPException passes."""
try:
yield
except HTTPException:
@@ -164,9 +153,17 @@ def _profile_errors(log_msg: str, *args, not_found=(FileNotFoundError,),
raise HTTPException(status_code=500, detail=str(e))
+async def _read_off_loop(read, label: str, errors):
+ """``read()`` on a worker thread; ``errors`` become ``500 "Could not read <label>: e"``."""
+ try:
+ return await run_in_threadpool(read)
+ except errors as e:
+ raise HTTPException(status_code=500, detail=f"Could not read {label}: {e}")
+
+
def _best_effort(log_msg: str, *args, fn, default=None):
- """Run ``fn()``; on failure log ``log_msg`` with traceback and return
- ``default`` (the parent operation already succeeded, so never 500)."""
+ """Run ``fn()``; on failure log ``log_msg`` with traceback and return ``default`` (the
+ parent operation already succeeded, so never 500)."""
try:
return fn()
except Exception:
@@ -175,13 +172,10 @@ def _best_effort(log_msg: str, *args, fn, default=None):
def _profile_targets(log_label: str, *, lightweight: bool) -> List[Tuple[str, Path]]:
- """(name, home) for every profile, falling back to ``default`` alone.
-
- ``lightweight`` uses ``profiles_to_serve`` (name/path only) instead of
- ``list_profiles``, which parses config/meta and probes gateways/skills
- per profile — too heavy for every sidebar refresh."""
+ """(name, home) for every profile, falling back to ``default`` alone. ``lightweight``
+ uses ``profiles_to_serve`` (name/path only) instead of ``list_profiles``, which parses
+ config/meta and probes gateways/skills per profile — too heavy per sidebar refresh."""
from hermes_cli import profiles as profiles_mod
-
try:
if lightweight:
targets = list(profiles_mod.profiles_to_serve(multiplex=True))
@@ -196,8 +190,8 @@ def _profile_targets(log_label: str, *, lightweight: bool) -> List[Tuple[str, Pa
def _tag_rows(rows: List[Dict[str, Any]], name: str, now: float) -> List[Dict[str, Any]]:
- """Stamp session rows with their owning profile and the 300s active
- heuristic; SQLite stores flags as 0/1 and the sidebar needs booleans."""
+ """Stamp session rows with their owning profile and the 300s active heuristic; SQLite
+ stores flags as 0/1 and the sidebar needs booleans."""
for s in rows:
s["profile"] = name
s["is_default_profile"] = name == "default"
@@ -210,9 +204,8 @@ def _tag_rows(rows: List[Dict[str, Any]], name: str, now: float) -> List[Dict[st
def _pinned_window(rows: List[Dict[str, Any]], offset: int, cap: int) -> List[Dict[str, Any]]:
- """``rows[offset:offset+cap]`` plus every pinned row past it. The
- per-profile queries deliberately back-fill pinned rows past their LIMIT,
- so truncating on recency alone would drop exactly what they fetched."""
+ """``rows[offset:offset+cap]`` plus every pinned row past it: the per-profile queries
+ back-fill pinned rows past their LIMIT, so truncating on recency alone would drop them."""
window = rows[offset:offset + cap]
if len(rows) > offset + cap:
seen = {id(s) for s in window}
@@ -224,35 +217,21 @@ def _recency(s: Dict[str, Any]) -> Any:
return s.get("last_active") or s.get("started_at") or 0
-def _open_profile_db(name: str, home, errors: Optional[List[Dict[str, str]]]):
- """Read-only SessionDB for a profile's state.db, or None when the file is
- missing or the open fails (failure recorded in ``errors`` when given).
+def _read_profile_db(name: str, home, errors: Optional[List[Dict[str, str]]],
+ fn: Callable[[Any], Any]) -> Any:
+ """``fn(db)`` against the profile's read-only state.db; None when the file is missing,
+ the open fails or ``fn`` raises (warned once, recorded in ``errors`` when given).
- Read-only on the healthy path: this runs on every sidebar refresh, so it
- must not routinely DDL/write-lock another profile's live DB. The helper's
- stale-schema probe performs a ONE-TIME writable open when the store
- predates a schema addition — read-only opens skip column reconciliation
- and would otherwise fail here on every refresh."""
+ Read-only on the healthy path: this runs on every sidebar refresh, so it must not
+ routinely DDL/write-lock another profile's live DB. The open helper's stale-schema probe
+ performs a ONE-TIME writable open when the store predates a schema addition — read-only
+ opens skip column reconciliation and would otherwise fail here on every refresh."""
db_path = Path(home) / "state.db"
if not db_path.exists():
return None
+ db = None
try:
- return _open_session_db_at_path(db_path, read_only=True)
- except Exception as exc:
- _warn_profile_read_error(name, exc)
- if errors is not None:
- errors.append({"profile": name, "error": str(exc)})
- return None
-
-
-def _read_profile_db(name: str, home, errors: Optional[List[Dict[str, str]]],
- fn: Callable[[Any], Any]) -> Any:
- """``fn(db)`` against the profile's read-only DB, or None when it can't be opened or
- ``fn`` raises (warned once, recorded in ``errors`` when given). Always closes the DB."""
- db = _open_profile_db(name, home, errors)
- if db is None:
- return None
- try:
+ db = _open_session_db_at_path(db_path, read_only=True)
return fn(db)
except Exception as exc:
_warn_profile_read_error(name, exc)
@@ -260,12 +239,12 @@ def _read_profile_db(name: str, home, errors: Optional[List[Dict[str, str]]],
errors.append({"profile": name, "error": str(exc)})
return None
finally:
- db.close()
+ if db is not None:
+ db.close()
-# Bounded cache lifetime for the expensive sidebar scan. Short enough that the UI never shows
-# meaningfully stale data, long enough to coalesce the desktop's reconnect/focus/change poll
-# bursts into one scan.
+# Sidebar scan cache TTL: short enough that the UI never shows meaningfully stale data, long
+# enough to coalesce the desktop's reconnect/focus/change poll bursts into one scan.
_SIDEBAR_CACHE_TTL_SECONDS = 5.0
_SIDEBAR_CACHE_MAX_ENTRIES = 32
_SIDEBAR_PROFILE_CACHE_MAX_ENTRIES = 256
@@ -319,12 +298,10 @@ def _sidebar_profile_cache_clear():
def _sidebar_singleflight_cache(func):
"""Coalesce concurrent sidebar scans and briefly reuse their response.
- Every uncached refresh opens every profile database and runs several session queries
- per profile. Desktop reconnect/focus/change bursts overlap identical scans in AnyIO
- worker threads, amplifying YAML/SQLite work and starving the uvicorn loop for the GIL.
- The short TTL bounds UI staleness; the single-flight lock guarantees one expensive scan
- at a time. Cached values are copied on store and hit so FastAPI serialization or a
- caller cannot mutate shared state.
+ Every uncached refresh opens every profile database; desktop poll bursts overlap identical
+ scans in AnyIO worker threads, starving the uvicorn loop for the GIL. The TTL bounds UI
+ staleness; the single-flight lock guarantees one expensive scan at a time. Cached values
+ are copied on store and hit so serialization or a caller cannot mutate shared state.
"""
signature = inspect.signature(func)
cache = OrderedDict()
@@ -341,14 +318,11 @@ def _sidebar_singleflight_cache(func):
now = time.monotonic()
with cache_lock:
item = cache.get(key)
- if item is None:
- return miss
- expires_at, value = item
- if now >= expires_at:
+ if item is None or now >= item[0]:
cache.pop(key, None)
return miss
cache.move_to_end(key)
- return copy.deepcopy(value)
+ return copy.deepcopy(item[1])
@functools.wraps(func)
def wrapped(*args, **kwargs):
@@ -399,27 +373,16 @@ def _csv_list(value: Optional[str]) -> List[str]:
@sessions_router.get("/api/profiles/sessions")
def get_profiles_sessions(
- # ``le=500`` caps the per-request page size — this endpoint fans out across EVERY
- # profile's state.db, so an unbounded limit multiplies the damage. 500 (not 100) because
- # real desktop callers use limit=200 and the electron remote-merge over-fetches
- # ``limit + offset``.
- limit: int = Query(20, ge=0, le=500),
- offset: int = Query(0, ge=0),
- min_messages: int = 0,
- archived: str = "exclude",
- order: str = "recent",
- profile: str = "all",
- source: str = None,
- sources: str = None,
- exclude_sources: str = None,
- full: bool = False):
- """Unified, read-only session list aggregated across ALL profiles.
-
- Process-light: opens each profile's ``state.db`` directly from disk — it does NOT spawn
- a dashboard backend per profile. Each row is tagged with its owning ``profile`` so the
- desktop renders one list and only spins up a backend when the user interacts. Rows omit
- ``system_prompt`` / ``model_config`` unless ``full=1`` — same projection as ``/api/sessions``.
- """
+ # ``le=500`` caps the page size — this endpoint fans out across EVERY profile's state.db.
+ # 500 (not 100) because desktop callers use limit=200 and the electron remote-merge
+ # over-fetches ``limit + offset``.
+ limit: int = Query(20, ge=0, le=500), offset: int = Query(0, ge=0), min_messages: int = 0,
+ archived: str = "exclude", order: str = "recent", profile: str = "all",
+ source: str = None, sources: str = None, exclude_sources: str = None, full: bool = False):
+ """Unified, read-only session list aggregated across ALL profiles: opens each profile's
+ ``state.db`` directly (no dashboard backend per profile) and tags rows with their owning
+ ``profile``. Rows omit ``system_prompt`` / ``model_config`` unless ``full=1`` — same
+ projection as ``/api/sessions``."""
if archived not in ("exclude", "only", "include"):
raise HTTPException(status_code=400, detail="archived must be one of: exclude, only, include")
if order not in ("created", "recent"):
@@ -431,8 +394,7 @@ def get_profiles_sessions(
targets = _profile_targets("GET /api/profiles/sessions", lightweight=True)
# Source scoping (see /api/sessions): recents pass exclude_sources=cron, the cron-jobs
- # section passes source=cron — two independent lists so newest cron sessions can't
- # starve the recents page.
+ # section source=cron — two independent lists so cron sessions can't starve recents.
filters = dict(
source=source or None, sources=_csv_list(sources) or None,
exclude_sources=_csv_list(exclude_sources) or None, min_message_count=max(0, min_messages),
@@ -469,53 +431,45 @@ def get_profiles_sessions(
def get_profiles_sessions_sidebar(
recents_profile: str = "all", recents_limit: int = 20, recents_exclude: str = None,
cron_limit: int = 50, messaging_limit: int = 100, messaging_exclude: str = None):
- """Batched sidebar session slices — one profile-DB open per refresh.
-
- The desktop sidebar needs three source-scoped windows per refresh: recents (local
- chats), cron sessions, and messaging-platform sessions. Served as three
- ``/api/profiles/sessions`` calls they reopened every profile's DB three times; this
- opens each once. Same row projection and 300s active heuristic as the per-slice endpoint.
+ """Batched sidebar session slices (recents / cron / messaging) — one profile-DB open per
+ refresh instead of three ``/api/profiles/sessions`` calls. Same row projection and 300s
+ active heuristic as the per-slice endpoint; all slices use ``min_messages=1`` /
+ ``archived=exclude`` / recency order.
``recents_profile`` scopes the WHOLE payload, not just recents — the sidebar has one
scope, so a concrete profile must never show another profile's Telegram threads or
- cronjobs; ``all`` asks for everything. The caller passes the source taxonomy
- (``recents_exclude`` / ``messaging_exclude`` CSV, ``source=cron`` is implicit). All
- slices use ``min_messages=1`` / ``archived=exclude`` / recency order.
+ cronjobs; ``all`` asks for everything.
"""
targets = _profile_targets("GET /api/profiles/sessions/sidebar", lightweight=True)
recents_scope = (recents_profile or "all").strip() or "all"
recents_exclude_list = [s for s in (recents_exclude or "").split(",") if s.strip()]
messaging_exclude_list = [s for s in (messaging_exclude or "").split(",") if s.strip()]
-
- recents_cap = min(max(recents_limit, 1), 500)
- cron_cap = min(max(cron_limit, 1), 500)
- messaging_cap = min(max(messaging_limit, 1), 500)
-
- recents_rows: List[Dict[str, Any]] = []
- cron_rows: List[Dict[str, Any]] = []
- messaging_rows: List[Dict[str, Any]] = []
+ # (source, exclude) per slice; ``source=cron`` is the implicit cron taxonomy.
+ slice_scope = {"recents": (None, recents_exclude_list), "cron": ("cron", None),
+ "messaging": (None, messaging_exclude_list)}
+ cap = {"recents": min(max(recents_limit, 1), 500), "cron": min(max(cron_limit, 1), 500),
+ "messaging": min(max(messaging_limit, 1), 500)}
+ rows: Dict[str, List[Dict[str, Any]]] = {k: [] for k in slice_scope}
recents_truncated: Dict[str, bool] = {}
profile_totals: Dict[str, Dict[str, float]] = {}
errors: List[Dict[str, str]] = []
now = time.time()
- def _slice(db, *, source=None, exclude=None, cap):
+ def _slice(db, key):
+ source, exclude = slice_scope[key]
# include_pinned: a pinned conversation must reach the sidebar even when it has aged
# past the window, or its Pinned row renders empty.
return db.list_sessions_rich(
- source=source, exclude_sources=exclude or None, limit=cap, offset=0,
+ source=source, exclude_sources=exclude or None, limit=cap[key], offset=0,
min_message_count=1, include_archived=False, archived_only=False,
order_by_last_active=True, compact_rows=True, include_pinned=True)
def _build_slices(db, cache_key):
- slices = {
- "recents": _slice(db, exclude=recents_exclude_list, cap=recents_cap),
- # Aggregated in SQL rather than over the recents window: the window is a page,
- # and a total that shrank when you scrolled would be worse than no total at all.
- "usage": db.usage_totals(),
- "cron": _slice(db, source="cron", cap=cron_cap),
- "messaging": _slice(db, exclude=messaging_exclude_list, cap=messaging_cap)}
+ # ``usage`` is aggregated in SQL rather than over the recents window: the window is a
+ # page, and a total that shrank when you scrolled would be worse than no total at all.
+ slices = {"recents": _slice(db, "recents"), "usage": db.usage_totals(),
+ "cron": _slice(db, "cron"), "messaging": _slice(db, "messaging")}
_sidebar_profile_cache_put(cache_key, slices)
return slices
@@ -525,8 +479,8 @@ def get_profiles_sessions_sidebar(
db_path = Path(home) / "state.db"
if not db_path.exists():
continue
- profile_cache_key = (str(db_path), _sidebar_db_fingerprint(db_path), recents_cap,
- tuple(recents_exclude_list), cron_cap, messaging_cap,
+ profile_cache_key = (str(db_path), _sidebar_db_fingerprint(db_path), cap["recents"],
+ tuple(recents_exclude_list), cap["cron"], cap["messaging"],
tuple(messaging_exclude_list))
slices = _sidebar_profile_cache_get(profile_cache_key)
if slices is None:
@@ -534,39 +488,33 @@ def get_profiles_sessions_sidebar(
lambda db: _build_slices(db, profile_cache_key))
if slices is None:
continue
-
- profile_rows = slices["recents"]
# A full window means more rows remain on disk — all "load more" needs, at no cost
# beyond the rows already read. Discount pinned back-fills: they arrive past the
# LIMIT and would fake a full page on a short list.
- unpinned_count = sum(1 for s in profile_rows if not s.get("pinned"))
- recents_truncated[name] = unpinned_count >= recents_cap
- recents_rows.extend(_tag_rows(profile_rows, name, now))
+ unpinned_count = sum(1 for s in slices["recents"] if not s.get("pinned"))
+ recents_truncated[name] = unpinned_count >= cap["recents"]
profile_totals[name] = slices["usage"]
- cron_rows.extend(_tag_rows(slices["cron"], name, now))
- messaging_rows.extend(_tag_rows(slices["messaging"], name, now))
+ for key in slice_scope:
+ rows[key].extend(_tag_rows(slices[key], name, now))
- def _window(rows: List[Dict[str, Any]], cap: int) -> List[Dict[str, Any]]:
- rows.sort(key=_recency, reverse=True)
- win = _pinned_window(rows, 0, cap)
+ def _window(key: str) -> List[Dict[str, Any]]:
+ rows[key].sort(key=_recency, reverse=True)
+ win = _pinned_window(rows[key], 0, cap[key])
_strip_session_list_rows(win)
return win
return {
- "recents": {"sessions": _window(recents_rows, recents_cap),
- "profiles_truncated": recents_truncated, "profiles_usage": profile_totals},
- "cron": {"sessions": _window(cron_rows, cron_cap)},
- "messaging": {"sessions": _window(messaging_rows, messaging_cap), "total": len(messaging_rows)},
+ "recents": {"sessions": _window("recents"), "profiles_truncated": recents_truncated,
+ "profiles_usage": profile_totals},
+ "cron": {"sessions": _window("cron")},
+ "messaging": {"sessions": _window("messaging"), "total": len(rows["messaging"])},
"errors": errors}
def _merge_by_id(into: Dict[str, Dict[str, Any]], entries: List[Dict[str, Any]], child_key: str) -> None:
- """Fold ``entries`` into ``into`` by id, recursing through one child list.
-
- Repos merge their lanes, lanes merge their sessions. Counts add up and the newest
- activity wins; everything else is first-writer, since the entries describe the same
- path either way.
- """
+ """Fold ``entries`` into ``into`` by id, recursing through one child list (repos merge
+ their lanes, lanes merge their sessions). Counts add up; everything else is
+ first-writer, since the entries describe the same path either way."""
for entry in entries:
existing = into.get(entry["id"])
if existing is None:
@@ -585,14 +533,10 @@ def _merge_by_id(into: Dict[str, Dict[str, Any]], entries: List[Dict[str, Any]],
def _merge_profile_tree(
merged: Dict[str, Dict[str, Any]], projects: List[Dict[str, Any]], profile: str,
preview_limit: int) -> None:
- """Fold one profile's projects into the shared tree, keyed by folder.
-
- The same checkout in two profiles is one group, as is ``__no_project__`` (every profile
- has one, which would otherwise put a "Home" on screen per profile). Keying on the path
- also folds a declared project (``p_<hash>``) with the auto entry another profile grows
- for the same folder. Sessions carry the owning profile — the row badge and profile
- filter read that; a group header never claims a single owner.
- """
+ """Fold one profile's projects into the shared tree, keyed by folder: the same checkout
+ in two profiles is one group, as is ``__no_project__`` (else one "Home" per profile), and
+ a declared project (``p_<hash>``) folds with another profile's auto entry for the same
+ folder. Sessions carry the owning profile; a group header never claims a single owner."""
for project in projects:
lane_sessions = (s for r in project.get("repos") or []
for lane in r.get("groups") or []
@@ -628,19 +572,14 @@ def _merge_profile_tree(
def get_profiles_projects_tree(preview_limit: int = 3, session_limit: int = 2000):
"""Project tree for every profile at once, for the all-profiles sidebar.
- ``projects.tree`` over JSON-RPC answers for the backend's own profile only. This runs
- the same authoritative builder once per profile against that profile's ``state.db``,
- scoping its other inputs (projects.db, repo-scan policy, HERMES_HOME junk filters)
- through the context-local home override. Projects merge across profiles so a group
- stands for a checkout rather than a checkout-and-owner.
-
- Discovery is off: a repo with zero sessions is the same repo in every profile (the disk
- scan would multiply empty lanes by the profile count), and it is the one part of the
- builder that writes (policy reconciliation), which this read-only fan-out must not do
- to a profile the user isn't driving.
+ ``projects.tree`` over JSON-RPC answers for the backend's own profile only; this runs the
+ same builder once per profile against its ``state.db``, scoping the other inputs
+ (projects.db, repo-scan policy, junk filters) through the home override. Discovery is
+ off: a repo with zero sessions is the same repo in every profile (the disk scan would
+ multiply empty lanes by the profile count), and discovery is the one part of the builder
+ that writes (policy reconciliation), which a read-only fan-out must not do.
"""
from tui_gateway import server as gateway_server
-
merged: Dict[str, Dict[str, Any]] = {}
scoped_session_ids: List[str] = []
errors: List[Dict[str, str]] = []
@@ -662,9 +601,8 @@ def get_profiles_projects_tree(preview_limit: int = 3, session_limit: int = 2000
"active_id": None, "scoped_session_ids": scoped_session_ids, "errors": errors}
-# `gh pr create` prints the PR url and nothing else, so a tool result whose whole output IS
-# a PR url means this session opened that PR. Anything looser — a url inside prose, a
-# `gh pr view` payload, an issue link — is a session TALKING about a PR, not the same claim.
+# `gh pr create` prints the PR url and nothing else, so a tool result whose whole output IS a
+# PR url means this session opened that PR; a url inside prose is a session TALKING about one.
_PR_URL_RE = re.compile(r"^https://github\.com/[\w.-]+/[\w.-]+/pull/(\d+)/?$")
@@ -682,14 +620,10 @@ def _pr_url_from_tool_output(content: str) -> Optional[Tuple[int, str]]:
@sessions_router.post("/api/profiles/sessions/pull-requests")
def post_profiles_sessions_pull_requests(body: SessionPrScanBody):
- """The PR each of these sessions opened, recovered from its own transcript.
-
- A session records the branch it started on, but one that starts in the main checkout
- and works in a worktree has no branch of its own, so its PR is invisible to that join.
- The evidence is in the conversation: ``gh pr create`` ran and its output is a bare PR
- url (see ``_pr_url_from_tool_output``). Read-only across every profile; the caller asks
- once per session and remembers the answer.
- """
+ """The PR each of these sessions opened, recovered from its own transcript: a session
+ that starts in the main checkout and works in a worktree has no branch of its own, so
+ its PR is invisible to the branch join — but ``gh pr create`` ran in the conversation
+ (see ``_pr_url_from_tool_output``). Read-only across every profile."""
wanted = list(dict.fromkeys(s for s in (body.ids or []) if s))[:2000]
if not wanted:
return {"pull_requests": {}, "scanned": []}
@@ -700,15 +634,13 @@ def post_profiles_sessions_pull_requests(body: SessionPrScanBody):
for pr in db.find_pr_url_messages(wanted):
parsed = _pr_url_from_tool_output(pr["content"])
if parsed:
- # Ordered oldest-first, so a later `gh pr create` in the same conversation
- # wins — the replacement PR is the one the session ended on.
+ # Oldest-first, so a later `gh pr create` (the replacement PR) wins.
found[pr["session_id"]] = {"number": parsed[0], "url": parsed[1]}
for name, home in _profile_targets("POST /api/profiles/sessions/pull-requests", lightweight=False):
_read_profile_db(name, home, None, _read)
- # Every id we looked at, so the caller can remember "asked, nothing there" and never
- # scan this session again.
+ # ``scanned``: every id looked at, so the caller can remember "nothing there".
return {"pull_requests": found, "scanned": wanted}
@@ -728,12 +660,10 @@ async def create_profile_endpoint(body: ProfileCreate):
from hermes_cli import profiles as profiles_mod
explicit_source = (body.clone_from or "").strip()
if explicit_source:
- # Duplicating a specific profile: clone its config/skills/SOUL (or full state when
- # clone_all) from the named source rather than "default".
+ # Clone config/skills/SOUL (or full state when clone_all) from the named source.
clone, clone_from, clone_config = True, explicit_source, not body.clone_all
elif body.clone_all:
- # Historical dashboard clone-all behavior: a full-copy request with no explicit
- # dropdown source copies from default.
+ # Historical dashboard behavior: clone-all with no explicit source copies default.
clone, clone_from, clone_config = True, "default", False
else:
clone = body.clone_from_default
@@ -744,19 +674,16 @@ async def create_profile_endpoint(body: ProfileCreate):
path = profiles_mod.create_profile(
name=body.name, clone_from=clone_from, clone_all=body.clone_all,
clone_config=clone_config, no_skills=body.no_skills, description=body.description)
- # Match the CLI's profile-create flow: fresh named profiles get the bundled skills.
- # Cloning already copied the source's skills (incl. user-installed); no_skills wrote
- # the opt-out marker so seeding no-ops.
+ # Match the CLI flow: fresh named profiles get the bundled skills (cloning already
+ # copied the source's; no_skills wrote the opt-out marker so seeding no-ops) and a
+ # ~/.local/bin wrapper when the alias is safe.
if not clone:
profiles_mod.seed_profile_skills(path, quiet=True)
-
- # Match the CLI: named profiles get a ~/.local/bin wrapper when the alias is safe.
if not profiles_mod.check_alias_collision(body.name):
profiles_mod.create_wrapper_script(body.name)
# Everything below is best-effort: the profile already exists, so a hiccup must not 500
- # the whole create — the user can fix it from the relevant dashboard page or
- # `<profile> setup` afterward.
+ # the whole create — the user can fix it from the dashboard or `<profile> setup`.
provider = (body.provider or "").strip()
model = (body.model or "").strip()
model_set = bool(provider and model) and _best_effort(
@@ -766,16 +693,14 @@ async def create_profile_endpoint(body: ProfileCreate):
"Writing MCP servers for new profile %s failed", body.name,
fn=lambda: _write_profile_mcp_servers(path, body.mcp_servers), default=0
) if body.mcp_servers else 0
- # "keep" skill selection has replace semantics: disable every seeded skill not in the
- # list. Skipped when empty (legacy: keep the bundle).
+ # "keep" has replace semantics; skipped when empty (legacy: keep the bundle).
skills_disabled = _best_effort(
"Applying skill selection for new profile %s failed", body.name,
fn=lambda: _disable_unselected_skills(path, body.keep_skills), default=0
) if body.keep_skills else 0
- # Skills-hub installs are spawned async, scoped to the new profile via `-p <name>` (a
- # fresh subprocess re-binds skills_hub.SKILLS_DIR to the profile's HERMES_HOME at
- # import). PIDs go back for the UI to poll.
+ # Hub installs spawn async, scoped via `-p <name>` (a fresh subprocess re-binds
+ # skills_hub.SKILLS_DIR at import). PIDs go back for the UI to poll.
def _spawn_install(ident: str):
return _spawn_hermes_action(["-p", body.name, "skills", "install", ident, "--yes"],
_hub_action_name("install", ident)).pid
@@ -794,13 +719,11 @@ async def create_profile_endpoint(body: ProfileCreate):
@router.get("/api/profiles/active")
async def get_active_profile_endpoint():
"""``active`` is the sticky default written by ``hermes profile use`` (what new CLI
- invocations pick up); ``current`` is the profile this running dashboard/gateway is
- scoped to (derived from HERMES_HOME)."""
+ invocations pick up); ``current`` is the profile this running dashboard is scoped to."""
from hermes_cli import profiles as profiles_mod
def _run():
- # Both reads touch the filesystem; batched into one hop so the sidebar's polling
- # costs a single executor round-trip, not two.
+ # Both reads touch the filesystem; one hop so sidebar polling costs one round-trip.
def _or_default(fn):
try:
return fn() or "default"
@@ -814,13 +737,11 @@ async def get_active_profile_endpoint():
@router.post("/api/profiles/active")
async def set_active_profile_endpoint(body: ProfileActiveUpdate):
- """Set the sticky active profile (mirrors ``hermes profile use``). Does not retarget the
- already-running dashboard — it changes which profile subsequent CLI commands and
- gateways use."""
+ """Set the sticky active profile (mirrors ``hermes profile use``); does not retarget the
+ running dashboard, only subsequent CLI commands and gateways."""
from hermes_cli import profiles as profiles_mod
with _profile_errors("POST /api/profiles/active failed"):
- # set_active_profile() stats the target, creates the state directory and writes
- # active_profile through a temp file + replace.
+ # Stats the target, creates the state directory, writes via temp file + replace.
await run_in_threadpool(profiles_mod.set_active_profile, body.name)
return {"ok": True, "active": profiles_mod.normalize_profile_name(body.name)}
@@ -830,8 +751,8 @@ async def get_profile_setup_command(name: str):
return {"command": _profile_setup_command(name)}
-# (executable, flag) — a flag of None means the emulator takes one quoted `sh -lc '…'` string
-# after -e; "" means the argv follows the executable directly (kitty).
+# (executable, flag): None = takes one quoted `sh -lc '…'` string after -e; "" = argv follows
+# the executable directly (kitty).
_LINUX_TERMINALS = (
("x-terminal-emulator", "-e"), ("gnome-terminal", "--"), ("konsole", "-e"),
("xfce4-terminal", None), ("mate-terminal", None), ("lxterminal", None),
@@ -873,13 +794,11 @@ async def rename_profile_endpoint(name: str, body: ProfileRename):
from hermes_cli import profiles as profiles_mod
with _profile_errors("PATCH /api/profiles/%s failed", name,
bad_request=(ValueError, FileExistsError)):
- # rename_profile() stops a running gateway through the same 10-second poll that
- # delete does, then renames the directory, rewrites the Honcho host blocks and
- # regenerates the wrapper script.
+ # Stops a running gateway (10 s poll), renames the directory, rewrites the Honcho
+ # host blocks and regenerates the wrapper script.
path = await run_in_threadpool(profiles_mod.rename_profile, name, body.new_name)
# For the default profile the rename lands as a presentation-only display_name; the
- # canonical id ("default") is unchanged and always returned so callers keying on `name`
- # stay correct.
+ # canonical id ("default") is always returned so callers keying on `name` stay correct.
try:
is_default = profiles_mod.normalize_profile_name(name) == "default"
except ValueError:
@@ -895,9 +814,8 @@ async def delete_profile_endpoint(name: str):
always skips the CLI's interactive prompt."""
from hermes_cli import profiles as profiles_mod
with _profile_errors("DELETE /api/profiles/%s failed", name):
- # delete_profile() polls a running gateway's PID for up to 10 s, then rmtree()s the
- # directory; on the loop that parks every request past the desktop's 10 s
- # WebSocket ready-probe.
+ # Polls a running gateway's PID for up to 10 s, then rmtree()s the directory; on the
+ # loop that parks every request past the desktop's 10 s WebSocket ready-probe.
path = await run_in_threadpool(profiles_mod.delete_profile, name, yes=True)
return {"ok": True, "path": str(path)}
@@ -907,16 +825,12 @@ async def get_profile_soul(name: str):
soul_path = _resolve_profile_dir(name) / "SOUL.md"
def _run():
- # Probe and read in the same hop: two round-trips would also widen the window
- # between the existence check and the read.
+ # Probe and read in one hop (two round-trips would widen the check/read window).
if not soul_path.exists():
return _MISSING
return soul_path.read_text(encoding="utf-8")
- try:
- content = await run_in_threadpool(_run)
- except OSError as e:
- raise HTTPException(status_code=500, detail=f"Could not read SOUL.md: {e}")
+ content = await _read_off_loop(_run, "SOUL.md", OSError)
if content is _MISSING:
return {"content": "", "exists": False}
return {"content": content, "exists": True}
@@ -928,20 +842,15 @@ async def update_profile_soul(name: str, body: ProfileSoulUpdate):
def _run():
from utils import atomic_write_text
-
- # PUT replaces the whole persona document. A bare write_text() truncates SOUL.md
- # before the new body lands, and the paired GET reports an unreadable file as
- # ``{"content": "", "exists": False}`` — so an interrupted save reads as "never set"
- # and the editor's next Save persists that empty document over it.
- #
- # preserve_mode keeps an existing file's mode/owner across the replace. create_mode
- # 0o644 covers the first save: named profiles seed SOUL.md at the umask default
- # (profiles chmods only .env to 0600) and SOUL.md is not a secret.
+ # Atomic: a bare write_text() truncates SOUL.md before the new body lands, and the
+ # paired GET reports an unreadable file as "never set" — so an interrupted save would
+ # make the editor's next Save persist an empty document. preserve_mode keeps an
+ # existing file's mode/owner; create_mode=0o644 covers the first save (profiles
+ # chmods only .env to 0600 and SOUL.md is not a secret).
atomic_write_text(soul_path, body.content, preserve_mode=True, create_mode=0o644)
try:
- # atomic_write_text() writes a temp file, fsyncs and replaces — blocking for as long
- # as the filesystem takes to commit.
+ # Temp file + fsync + replace blocks for as long as the filesystem takes to commit.
await run_in_threadpool(_run)
except OSError as e:
_log.exception("PUT /api/profiles/%s/soul failed", name)
@@ -951,15 +860,13 @@ async def update_profile_soul(name: str, body: ProfileSoulUpdate):
@router.put("/api/profiles/{name}/description")
async def update_profile_description_endpoint(name: str, body: ProfileDescriptionUpdate):
- """Set or clear a profile's role description (kanban routing signal). Non-empty stores
- it as user-authored (``description_auto: false``) so the auto-describer won't overwrite
- it on a sweep."""
+ """Set or clear a profile's role description (kanban routing signal), stored as
+ user-authored (``description_auto: false``) so the auto-describer won't overwrite it."""
from hermes_cli import profiles as profiles_mod
profile_dir = _resolve_profile_dir(name)
text = (body.description or "").strip()
with _profile_errors("PUT /api/profiles/%s/description failed", name,
not_found=(), bad_request=()):
- # write_profile_meta() reads profile.yaml, merges and rewrites it.
await run_in_threadpool(
profiles_mod.write_profile_meta, profile_dir, description=text, description_auto=False)
return {"ok": True, "description": text, "description_auto": False}
@@ -967,9 +874,8 @@ async def update_profile_description_endpoint(name: str, body: ProfileDescriptio
@router.put("/api/profiles/{name}/model")
async def update_profile_model_endpoint(name: str, body: ProfileModelUpdate):
- """Set the main model (``model.default`` + ``model.provider``) for a specific profile's
- config.yaml without touching the dashboard's own active profile. Mirrors
- ``POST /api/model/set`` (main scope) via the HERMES_HOME override."""
+ """Set the main model for a specific profile's config.yaml without touching the
+ dashboard's own profile — ``POST /api/model/set`` (main scope) via the HERMES_HOME override."""
profile_dir = _resolve_profile_dir(name)
provider = (body.provider or "").strip()
model = (body.model or "").strip()
@@ -983,12 +889,10 @@ async def update_profile_model_endpoint(name: str, body: ProfileModelUpdate):
@router.post("/api/profiles/{name}/describe-auto")
async def describe_profile_auto_endpoint(name: str, body: ProfileDescribeAuto):
- """Auto-generate a profile's description via the auxiliary LLM
- (``auxiliary.profile_describer``); mirrors ``hermes profile describe <name> --auto``.
- A failed generation (no aux client, LLM error, …) is ``ok: false`` with a reason rather
- than an HTTP error so the UI can surface it inline and let the operator retry."""
- # Resolution stays on the loop: a name check plus one stat, and it owns the 400/404
- # mapping that the 500 fallback below would flatten.
+ """Auto-generate a profile's description via the auxiliary LLM (mirrors ``hermes profile
+ describe <name> --auto``). A failed generation is ``ok: false`` with a reason rather than
+ an HTTP error so the UI can surface it inline and let the operator retry."""
+ # Resolution stays on the loop: it owns the 400/404 mapping the 500 fallback would flatten.
_resolve_profile_dir(name)
def _run():
@@ -997,22 +901,18 @@ async def describe_profile_auto_endpoint(name: str, body: ProfileDescribeAuto):
with _profile_errors("POST /api/profiles/%s/describe-auto failed", name,
not_found=(), bad_request=()):
- # describe_profile() is a synchronous LLM round-trip with a 60 s ceiling; held on
- # the loop it stalls every other dashboard request.
+ # A synchronous LLM round-trip with a 60 s ceiling; on the loop it stalls everything.
outcome = await run_in_threadpool(_run)
return {
"ok": bool(outcome.ok),
"reason": outcome.reason,
"description": outcome.description,
- # Only a successful generation is an auto-authored description. A failed sweep
- # leaves any existing description untouched, so don't claim it's auto-generated.
+ # A failed sweep leaves any existing description untouched: not auto-authored.
"description_auto": bool(outcome.ok)}
-# ── Export / Import ──────────────────────────────────────────────────────────
-# Profile sharing for the desktop: wraps hermes_cli.profiles.export_profile / import_profile
-# (the machinery behind `hermes profile export|import`). Paths are exchanged, not bytes —
-# the desktop's local and pooled backends share the filesystem with the native dialogs.
+# ── Export / Import ── wraps hermes_cli.profiles.export_profile / import_profile. Paths are
+# exchanged, not bytes — the desktop backends share the filesystem with the native dialogs.
def _read_desktop_overlay(profile_dir: Path) -> Any:
@@ -1024,7 +924,6 @@ def _read_desktop_overlay(profile_dir: Path) -> Any:
@router.post("/api/profiles/{name}/export")
async def export_profile_endpoint(name: str, body: ProfileExport):
from hermes_cli import profiles as profiles_mod
-
output = (body.output or "").strip()
if not output:
try:
@@ -1043,7 +942,6 @@ async def export_profile_endpoint(name: str, body: ProfileExport):
@router.post("/api/profiles/import")
async def import_profile_endpoint(body: ProfileImport):
from hermes_cli import profiles as profiles_mod
-
archive = (body.archive or "").strip()
if not archive:
raise HTTPException(status_code=400, detail="archive path is required")
@@ -1061,8 +959,7 @@ async def import_profile_endpoint(body: ProfileImport):
profiles_mod.create_wrapper_script(imported)
_best_effort("Creating wrapper for imported profile %s failed", imported, fn=_wrapper)
- # Surface the bundled desktop appearance overlay (if the archive carried one) so the
- # desktop can apply theme/interface prefs without another round-trip.
+ # Bundled desktop appearance overlay, so the desktop needn't make another round-trip.
desktop_overlay = None
if (profile_dir / "desktop.json").is_file():
desktop_overlay = _best_effort(
@@ -1078,16 +975,12 @@ async def get_profile_desktop_overlay(name: str):
profile_dir = _resolve_profile_dir(name)
def _run():
- # Probe and read in one hop; _MISSING (not None) because desktop.json may
- # legitimately hold the document ``null``.
+ # Probe and read in one hop; _MISSING because desktop.json may hold ``null``.
if not (profile_dir / "desktop.json").is_file():
return _MISSING
return _read_desktop_overlay(profile_dir)
- try:
- overlay = await run_in_threadpool(_run)
- except Exception as e:
- raise HTTPException(status_code=500, detail=f"Could not read desktop.json: {e}")
+ overlay = await _read_off_loop(_run, "desktop.json", Exception)
if overlay is _MISSING:
return {"exists": False, "desktop": None}
return {"exists": True, "desktop": overlay}
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index 3fd15f45e52..87034770722 100644
--- a/hermes_cli/web_routers/status.py
+++ b/hermes_cli/web_routers/status.py
@@ -62,20 +62,16 @@ def _count_status_active_sessions() -> int:
"""Best-effort status garnish. Opens read-only (via the shared stale-schema heal) so
/api/status never routinely writes to state.db while another Hermes process uses it."""
from hermes_state import _default_db_path
-
# The heal helper bootstraps a missing store; this garnish must not — on a fresh install
# /api/status polls would otherwise create state.db before the user's first session.
if not Path(_default_db_path()).exists():
return 0
-
db = _open_session_db_for_profile(None, read_only=True)
try:
sessions = db.list_sessions_rich(limit=50, compact_rows=True)
now = time.time()
- return sum(
- 1 for s in sessions
- if s.get("ended_at") is None
- and (now - s.get("last_active", s.get("started_at", 0))) < 300)
+ return sum(1 for s in sessions if s.get("ended_at") is None
+ and (now - s.get("last_active", s.get("started_at", 0))) < 300)
finally:
db.close()
@@ -86,9 +82,8 @@ async def _status_active_sessions() -> int:
run_in_threadpool(_count_status_active_sessions),
timeout=_STATUS_ACTIVE_SESSIONS_TIMEOUT)
except asyncio.TimeoutError:
- _log.debug(
- "/api/status active session count exceeded %.2fs; returning 0",
- _STATUS_ACTIVE_SESSIONS_TIMEOUT)
+ _log.debug("/api/status active session count exceeded %.2fs; returning 0",
+ _STATUS_ACTIVE_SESSIONS_TIMEOUT)
except Exception as exc:
_log.debug("/api/status active session count unavailable: %s", exc)
return 0
@@ -128,14 +123,11 @@ def _is_profile_platform_status_key(key: object) -> bool:
def _status_platform_key_allowed(key: object, configured: "set[str] | None") -> bool:
- """Whether a runtime-status platform key may appear publicly.
-
- Namespaced ``<profile>:<platform>`` keys are validated against the key grammar
- *unconditionally* — the config-set load failing must not fail open into projecting
- arbitrary colon-containing keys from a process-local JSON file onto the public
- endpoint. Plain platform keys keep the long-standing behavior: checked against the
- configured set when it loaded, passed through when it did not.
- """
+ """Whether a runtime-status platform key may appear publicly: namespaced
+ ``<profile>:<platform>`` keys are validated against the grammar *unconditionally* (a
+ failed config-set load must not fail open into projecting arbitrary keys from a
+ process-local JSON file); plain keys are checked against the configured set when it
+ loaded, passed through when it did not."""
if not isinstance(key, str):
return False
if ":" in key:
@@ -157,15 +149,11 @@ def _public_platform_entry(value: Any) -> Any:
def _merge_profile_gateway_platforms(gateway_platforms: dict, profile_platforms: dict) -> dict:
- """Merge independent per-profile gateway platform states.
-
- Hosts running separate gateway services per profile (``gateway_mode == "multiple"``)
- persist each profile's platform failures in that profile's own ``gateway_state.json``.
- The unparameterized ``/api/status`` — the machine-level probe NAS health monitoring
- reads — only read the active profile's file, so those failures were invisible to fleet
- health. Fold them in under the validated ``<profile>:<platform>`` grammar. The active
- profile's own map is skipped (already present) and existing keys are never overwritten.
- """
+ """Merge independent per-profile gateway platform states: hosts running separate gateway
+ services per profile (``gateway_mode == "multiple"``) persist each profile's platform
+ failures in its own ``gateway_state.json``, invisible to the machine-level probe NAS
+ reads unless folded in under the validated ``<profile>:<platform>`` grammar. The active
+ profile's own map is skipped (already present); existing keys are never overwritten."""
try:
from hermes_cli.profiles import get_active_profile_name
active = get_active_profile_name()
@@ -194,10 +182,8 @@ def _bounded_health_probe():
try:
return future.result(timeout=_GATEWAY_HEALTH_ROUTE_TIMEOUT)
except concurrent.futures.TimeoutError:
- _log.warning(
- "/api/status gateway health probe exceeded %.2fs; "
- "using local status",
- _GATEWAY_HEALTH_ROUTE_TIMEOUT)
+ _log.warning("/api/status gateway health probe exceeded %.2fs; using local status",
+ _GATEWAY_HEALTH_ROUTE_TIMEOUT)
return False, None
except Exception:
return False, None
@@ -205,18 +191,12 @@ def _bounded_health_probe():
def _project_gateway_platforms(gateway_platforms: dict, configured: "set[str] | None",
gateway_running: bool, gateway_state) -> dict:
- """Public projection of a runtime's platform map.
-
- Colon-containing keys are validated against the narrow grammar UNCONDITIONALLY — a
- failed config load must not fail open into projecting arbitrary keys from a
- process-local JSON file onto this public endpoint (the config set belongs to the
- active/default profile, so suffix-checking secondary-profile keys against it would
- incorrectly hide them). A cleanly stopped gateway's platform states are stale noise
- and are cleared so a dead process can't report "connected"; a startup_failed
- gateway's FATAL entries are the diagnosis (per-profile credential collisions, auth
- failures) that the single exit_reason string can't express, so they are kept —
- upstream writer-identity/freshness filtering already dropped other processes' entries.
- """
+ """Public projection of a runtime's platform map (see ``_status_platform_key_allowed``
+ for the key rules). A cleanly stopped gateway's platform states are stale noise and are
+ cleared so a dead process can't report "connected"; a startup_failed gateway's FATAL
+ entries are the diagnosis (credential collisions, auth failures) that the single
+ exit_reason string can't express, so they are kept — upstream writer-identity/freshness
+ filtering already dropped other processes' entries."""
platforms = {
key: _public_platform_entry(value)
for key, value in gateway_platforms.items()
@@ -230,17 +210,15 @@ def _project_gateway_platforms(gateway_platforms: dict, configured: "set[str] |
async def _resolve_gateway_status(profile_dir: Optional[Path], health_url) -> Dict[str, Any]:
- """Liveness + runtime-state readout: gateway_running/pid/state/platforms/exit_reason/
- updated_at plus the raw ``runtime`` document used downstream.
-
- Liveness is delegated to the single shared ladder in gateway.status so this endpoint
- and /api/messaging/platforms can never disagree about whether the gateway is up. With
- ``?profile=<name>`` PID/state reads are scoped to that profile's directory — gateway
- identity files live in the per-profile home, not the process-level HERMES_HOME; plain
- /api/status keeps the exact zero-arg call so its behavior (and cache signature) is
+ """Liveness + runtime-state readout (running/pid/state/platforms/exit_reason/updated_at
+ plus the raw ``runtime`` document).
+
+ Liveness is delegated to the shared ladder in gateway.status so this endpoint and
+ /api/messaging/platforms can never disagree. With ``?profile=<name>`` PID/state reads are
+ scoped to that profile's directory (gateway identity files live in the per-profile
+ home); plain /api/status keeps the exact zero-arg call so its cache signature is
unchanged. The module-level probe references are handed to the resolver so the
- long-standing ``monkeypatch.setattr(web_server, "get_running_pid_cached", ...)`` seam
- still intercepts them.
+ ``monkeypatch.setattr(web_server, "get_running_pid_cached", ...)`` seam still intercepts.
"""
local_runtime = (read_runtime_status(path=profile_dir / "gateway_state.json")
if profile_dir else read_runtime_status())
@@ -294,17 +272,12 @@ async def _resolve_gateway_status(profile_dir: Optional[Path], health_url) -> Di
def _auth_gate_status() -> Dict[str, Any]:
- """Dashboard auth gate readout: whether the gate is engaged, which providers are
- registered, and the RFC 8252 native-app capability advertisement (``auth_flows``).
-
- The desktop reads ``auth_flows`` to decide whether it can use the system-browser +
- loopback + PKCE flow or must fall back to the embedded-webview cookie flow. "cookie" is
- always available in gated mode; "native_pkce" is present when at least one interactive
- session provider is registered (OAuth providers broker the IDP round trip, password
- providers complete at /login in the system browser where OS password managers can
- autofill). Token-only credentials (e.g. drain) don't count. Absent field / missing
- "native_pkce" ⇒ older gateway ⇒ desktop falls back automatically.
- """
+ """Dashboard auth gate readout: gate engaged, registered providers, and the RFC 8252
+ native-app capability advertisement ``auth_flows`` the desktop reads to pick the
+ system-browser + loopback + PKCE flow over the embedded-webview cookie flow. "cookie" is
+ always available in gated mode; "native_pkce" when at least one interactive session
+ provider is registered (token-only credentials such as drain don't count). Missing
+ "native_pkce" ⇒ older gateway ⇒ desktop falls back automatically."""
auth_required = bool(getattr(app.state, "auth_required", False))
auth_providers: list[str] = []
auth_flows: list[str] = []
@@ -324,11 +297,10 @@ def _auth_gate_status() -> Dict[str, Any]:
def _nous_session_validity() -> str:
- """Nous bootstrap-session validity for the NAS health sweep. A hosted agent whose Nous
- auth dies terminally (invalid_grant / quarantine) looks HEALTHY to every liveness probe
- yet every inference turn fails; this is the ONLY signal that surfaces it, determinable
- with no working token (local auth-store state). NAS re-mints the bootstrap session when
- it reads "terminal". Best-effort: never let auth classification break the probe."""
+ """Nous bootstrap-session validity for the NAS health sweep: a hosted agent whose Nous
+ auth dies terminally looks HEALTHY to every liveness probe yet every inference turn
+ fails, and this is the ONLY signal that surfaces it (local auth-store state, no token
+ needed). Best-effort: never let auth classification break the probe."""
try:
from hermes_cli.auth import get_nous_session_validity
return get_nous_session_validity()
@@ -337,12 +309,10 @@ def _nous_session_validity() -> str:
async def _component_health(gateway: Dict[str, Any]) -> Dict[str, Any]:
- """Component-level health rollup: counts and status enums only — this payload is
- public (PUBLIC_API_PATHS), so no messages, paths, or other detail that could carry
- secrets. The storage probe reuses the gateway readiness state_db check (read-only,
- 1s-bounded) in an executor so a wedged DB can't stall the event loop."""
+ """Component-level health rollup: counts and status enums only (public payload — no
+ messages, paths or other detail that could carry secrets). The storage probe reuses the
+ gateway readiness state_db check (read-only, 1s-bounded) off-loop."""
from hermes_cli.web_server import DASHBOARD_HEALTH
-
gateway_running, gateway_state = gateway["gateway_running"], gateway["gateway_state"]
gateway_platforms = gateway["gateway_platforms"]
components: Dict[str, Any] = {
@@ -352,7 +322,6 @@ async def _component_health(gateway: Dict[str, Any]) -> Dict[str, Any]:
"dashboard": DASHBOARD_HEALTH.snapshot()}
try:
from gateway.readiness import _probe_state_db
-
storage_check = await run_in_threadpool(_probe_state_db, get_hermes_home())
components["storage"] = {"status": storage_check.get("status", "degraded")}
except Exception:
@@ -370,14 +339,10 @@ async def _component_health(gateway: Dict[str, Any]) -> Dict[str, Any]:
async def _advisory_pressure(status: Dict[str, Any], home: Path) -> None:
- """Memory / disk pressure rollups + deferred FTS rebuild progress.
-
- Coarse MB numbers/enums/booleans only — this endpoint is public, same disclosure class
- as nous_session_valid. Deliberately NOT folded into components/overall: pressure is
- advisory (toast material), not a liveness verdict, and flipping ``overall`` on it would
- page NAS's availability sweep for a condition the valve is already handling. The FTS
- probe (schema v23) lets the desktop render "search index rebuilding: N%"; absent when
- no rebuild is pending. All read-only, never raise.
+ """Memory / disk pressure rollups + deferred FTS rebuild progress (coarse numbers/enums
+ only; public payload). Deliberately NOT folded into components/overall: pressure is
+ advisory, not a liveness verdict, and flipping ``overall`` on it would page NAS's
+ availability sweep for a condition the valve is already handling. Read-only, never raise.
"""
for key, mod_name, fn_name in (("memory", "gateway.memory_status", "collect_memory_status"),
("disk", "gateway.disk_status", "collect_disk_status")):
@@ -390,7 +355,6 @@ async def _advisory_pressure(status: Dict[str, Any], home: Path) -> None:
try:
from hermes_state import SessionDB as _SDB
from hermes_constants import get_hermes_home as _ghh
-
_db_path = _ghh() / "state.db"
if _db_path.exists():
_sdb = _SDB(db_path=_db_path, read_only=True)
@@ -409,11 +373,9 @@ async def get_status(profile: Optional[str] = None):
"""Public machine-level liveness probe (``PUBLIC_API_PATHS``): version, gateway state,
active session count and the auth-gate shape — no bodies, no session content, no secrets.
- Plain /api/status stays the machine-level probe; the dashboard adds ``?profile=`` when
- its management switcher targets another profile so its gateway badge follows. That uses
- the config-only (contextvar) scope, NOT _profile_scope: this handler awaits the remote
- health probe, and _profile_scope swaps process-global skills-module attributes that a
- concurrent request would cross-restore across that await.
+ ``?profile=`` (dashboard management switcher) uses the config-only contextvar scope, NOT
+ _profile_scope: this handler awaits the remote health probe, and _profile_scope swaps
+ process-global skills-module attributes a concurrent request would cross-restore.
"""
from hermes_cli.web_server import _GATEWAY_HEALTH_URL
status_scope = None
@@ -429,11 +391,9 @@ async def get_status(profile: Optional[str] = None):
gateway = await _resolve_gateway_status(profile_dir, _GATEWAY_HEALTH_URL)
gateway_running, gateway_state = gateway["gateway_running"], gateway["gateway_state"]
- # Topology (cached, TTL 10s) is fetched before the platform rollup because plain
- # /api/status is the machine-level probe NAS reads: hosts with per-profile gateway
- # services persist each profile's platform failures in its own gateway_state.json,
- # folded in here under the validated ``<profile>:<platform>`` grammar. A
- # ``?profile=`` request targets one profile's view and is left unmerged.
+ # Topology (cached, TTL 10s) is fetched before the platform rollup so per-profile
+ # gateway failures fold into the machine-level view (see
+ # _merge_profile_gateway_platforms); a ``?profile=`` request is left unmerged.
topology = await run_in_threadpool(_collect_profile_gateway_topology_cached)
if not requested_profile:
gateway["gateway_platforms"] = _merge_profile_gateway_platforms(
@@ -441,15 +401,12 @@ async def get_status(profile: Optional[str] = None):
active_sessions = await _status_active_sessions()
- # Busy/drainable readout (NAS lifecycle-safety gate). active_agents is the in-flight
- # gateway-turn count persisted at every turn boundary; busy/drainable derive from it
- # + liveness via the shared contract in gateway.status. Liveness keys off
- # gateway_running (live PID/health probe), NEVER gateway_updated_at — a healthy idle
- # gateway never advances that.
+ # Busy/drainable (NAS lifecycle-safety gate) derive from the persisted in-flight turn
+ # count + liveness via gateway.status. Liveness keys off gateway_running, NEVER
+ # gateway_updated_at — a healthy idle gateway never advances that.
active_agents = parse_active_agents((gateway["runtime"] or {}).get("active_agents", 0))
- # Drain timeout offloaded to a thread: on a cold Windows install the first import of
- # hermes_cli.gateway blocks the loop for 15-30s (.pyc compilation + Defender scans),
- # exceeding the desktop handshake's 15s socket timeout.
+ # Off-loop: on a cold Windows install the first import of hermes_cli.gateway blocks
+ # 15-30s (.pyc compilation + Defender), exceeding the desktop handshake's 15s timeout.
restart_drain_timeout = await run_in_threadpool(_resolve_restart_drain_timeout)
auth = _auth_gate_status()
@@ -475,9 +432,8 @@ async def get_status(profile: Optional[str] = None):
**auth,
"nous_session_valid": _nous_session_validity()}
- # Stable per-install identity. First call may touch disk, so keep it off the loop;
- # afterwards it is a process-global cache hit. Omitted (not null) when unpersistable
- # so older-client behavior and the no-identity fallback stay identical.
+ # Stable per-install identity (first call may touch disk). Omitted (not null) when
+ # unpersistable so older-client behavior and the no-identity fallback stay identical.
install_id = await run_in_threadpool(get_install_id)
if install_id:
status["install_id"] = install_id
@@ -488,17 +444,15 @@ async def get_status(profile: Optional[str] = None):
else "degraded")
await _advisory_pressure(status, profile_dir if profile_dir else get_hermes_home())
- # Split by sensitivity: profile NAMES and ``gateway_mode`` are low-sensitivity
- # PRODUCT surface — Hermes Cloud renders the profile list in the Portal over a gated
- # bind, so they must survive the auth gate. Per-gateway ``gateways[]`` carries host
- # ports (deployment recon) and stays gated with the host paths / PID below.
+ # Profile NAMES and ``gateway_mode`` are low-sensitivity product surface (Hermes Cloud
+ # renders the profile list over a gated bind) so they survive the auth gate; the
+ # per-gateway ``gateways[]`` carries host ports and stays gated below.
status["profiles"] = topology["profiles"]
status["gateway_mode"] = topology["gateway_mode"]
- # Absolute host paths, the gateway PID, the internal health URL and per-gateway ports
- # are deployment recon a liveness probe never needs; on a network-exposed (gated)
- # bind *any* unauthenticated caller reaches this endpoint. Surface them only on a
- # loopback / ``--insecure`` bind — the same split ``should_require_auth`` draws.
+ # Host paths, gateway PID, internal health URL and per-gateway ports are deployment
+ # recon a liveness probe never needs, and on a gated bind *any* unauthenticated caller
+ # reaches this endpoint — surface them only on a loopback / ``--insecure`` bind.
if not auth["auth_required"]:
status.update({
"hermes_home": str(get_hermes_home()),
@@ -516,9 +470,8 @@ async def get_status(profile: Optional[str] = None):
@router.get("/api/system/stats")
async def get_system_stats():
- """Host + process system stats for the System page: OS / Python / host identity from
- stdlib; CPU / memory / disk / uptime from psutil when available. Read-only and
- non-sensitive (no env values, no paths beyond the hermes home root)."""
+ """Host + process system stats for the System page (stdlib identity; psutil CPU/memory/
+ disk/uptime when available). Non-sensitive: no env values, no paths beyond hermes home."""
import platform as _platform
info: Dict[str, Any] = {
@@ -532,12 +485,6 @@ async def get_system_stats():
"hermes_version": __version__,
"cpu_count": os.cpu_count()}
- def _optional(fill):
- try:
- fill()
- except Exception:
- pass
-
def _disk():
du = psutil.disk_usage(str(get_hermes_home()))
info["disk"] = {"total": du.total, "used": du.used, "free": du.free, "percent": du.percent}
@@ -557,15 +504,17 @@ async def get_system_stats():
"create_time": int(proc.create_time()),
"num_threads": proc.num_threads()}
- # psutil enriches the picture when present; everything below is optional.
+ # psutil enriches the picture when present; every probe below is optional.
try:
import psutil # type: ignore
-
vm = psutil.virtual_memory()
info["memory"] = {"total": vm.total, "available": vm.available, "used": vm.used,
"percent": vm.percent}
for fill in (_disk, _cpu, _uptime, _process):
- _optional(fill)
+ try:
+ fill()
+ except Exception:
+ pass
info["psutil"] = True
except Exception:
info["psutil"] = False
@@ -578,10 +527,7 @@ async def get_system_stats():
return info
-# ---------------------------------------------------------------------------
-# Curator endpoints — background skill-maintenance (archive stale, prune, pin) status +
-# the pause/resume/run-now controls `hermes curator` exposes.
-# ---------------------------------------------------------------------------
+# Curator — background skill-maintenance status + the pause/resume/run-now controls.
@router.get("/api/curator")
@@ -599,15 +545,13 @@ async def get_curator_status():
"paused": _safe_call(curator, "is_paused", False),
"interval_hours": _safe_call(curator, "get_interval_hours", None),
"last_run_at": state.get("last_run_at"),
- "min_idle_hours": _safe_call(curator, "get_min_idle_hours", None),
- "stale_after_days": _safe_call(curator, "get_stale_after_days", None),
- "archive_after_days": _safe_call(curator, "get_archive_after_days", None)}
+ **{key: _safe_call(curator, f"get_{key}", None)
+ for key in ("min_idle_hours", "stale_after_days", "archive_after_days")}}
@router.put("/api/curator/paused")
async def set_curator_paused(body: CuratorPause):
from agent import curator
-
curator.set_paused(bool(body.paused))
return {"ok": True, "paused": bool(body.paused)}
@@ -629,9 +573,7 @@ async def run_curator():
@router.get("/api/learning/graph")
async def get_learning_graph(profile: Optional[str] = None):
- """Learning graph payload for the desktop panel: profile-scoped view of learned,
- non-base skills plus memory chunks, with links from skill relations and memory-skill
- overlap."""
+ """Learning graph for the desktop panel: profile-scoped learned skills + memory chunks."""
def _run():
from agent.learning_graph import build_learning_graph
return build_learning_graph()
@@ -685,9 +627,7 @@ def _safe_call(mod, fn_name: str, default):
return default
-# ---------------------------------------------------------------------------
-# Portal endpoint — Nous Portal auth + Tool Gateway routing status (read-only).
-# ---------------------------------------------------------------------------
+# Portal — Nous Portal auth + Tool Gateway routing status (read-only).
@router.get("/api/portal")
@@ -710,9 +650,7 @@ def _get_portal_status_sync():
auth: Dict[str, Any] = {}
try:
from hermes_cli.auth import get_nous_auth_status_local
-
- # Read-only dashboard endpoint: refresh-free snapshot so polling never performs an
- # OAuth refresh or burns a refresh token.
+ # Refresh-free snapshot so polling never performs an OAuth refresh.
auth = get_nous_auth_status_local() or {}
except Exception:
auth = {}
@@ -720,7 +658,6 @@ def _get_portal_status_sync():
features = []
try:
from hermes_cli.nous_subscription import get_nous_subscription_features
-
feats = get_nous_subscription_features(cfg)
if feats is not None:
features = [{"label": getattr(feat, "label", ""), "state": _feature_state(feat)}
@@ -738,10 +675,7 @@ def _get_portal_status_sync():
"features": features}
-# ---------------------------------------------------------------------------
-# Diagnostics: prompt-size, support dump, debug upload, config migrate. All produce text
-# output, so they spawn background actions tailed via /api/actions/<name>/status.
-# ---------------------------------------------------------------------------
+# Diagnostics: text-output actions spawned in the background, tailed via /api/actions/<name>.
@router.post("/api/ops/prompt-size")
@@ -761,15 +695,10 @@ async def run_config_migrate():
@router.post("/api/ops/debug-share")
async def run_debug_share_endpoint(body: DebugShareRequest | None = None):
- """Upload a redacted debug report + full logs and return the paste URLs.
-
- Unlike the other diagnostics actions this is *synchronous*: the point of ``debug share``
- is the set of shareable URLs it produces, so the upload runs in a worker thread and the
- structured ``{urls, failures, redacted, ...}`` payload is returned directly for the
- dashboard to render as copyable links. Pastes auto-delete after 6 hours (share core).
- """
+ """Upload a redacted debug report + full logs and return the paste URLs. Synchronous,
+ unlike the other diagnostics actions: the point is the shareable URLs, returned as a
+ structured payload the dashboard renders as copyable links."""
from hermes_cli.debug import build_debug_share
-
req = body or DebugShareRequest()
try:
result = await asyncio.to_thread(
@@ -789,17 +718,11 @@ async def run_debug_share_endpoint(body: DebugShareRequest | None = None):
"auto_delete_seconds": result.auto_delete_seconds}
-# ---------------------------------------------------------------------------
-# Log viewer endpoint
-# ---------------------------------------------------------------------------
-
-
@logs_router.get("/api/logs")
async def get_logs(
file: str = "agent", lines: int = 100, level: Optional[str] = None,
component: Optional[str] = None, search: Optional[str] = None):
from hermes_cli.logs import _read_tail, LOG_FILES
-
log_name = LOG_FILES.get(file)
if not log_name:
raise HTTPException(status_code=400, detail=f"Unknown log file: {file}")
@@ -811,11 +734,10 @@ async def get_logs(
from hermes_logging import COMPONENT_PREFIXES
except ImportError:
COMPONENT_PREFIXES = {}
-
- # Normalize "ALL" / "all" / empty → no filter. _matches_filters treats an empty tuple as
- # "must match a prefix" (startswith(()) is always False), so passing () instead of None
- # silently drops every line.
+ # "ALL"/"all"/empty → no filter (None, not (): _matches_filters treats an empty tuple as
+ # "must match a prefix", which silently drops every line).
min_level = level if level and level.upper() != "ALL" else None
+ comp_prefixes = None
if component and component.lower() != "all":
comp_prefixes = COMPONENT_PREFIXES.get(component)
if comp_prefixes is None:
@@ -823,12 +745,9 @@ async def get_logs(
status_code=400,
detail=f"Unknown component: {component}. "
f"Available: {', '.join(sorted(COMPONENT_PREFIXES))}")
- else:
- comp_prefixes = None
-
- has_filters = bool(min_level or comp_prefixes or search)
result = _read_tail(
- log_path, min(lines, 500) if not search else 2000, has_filters=has_filters,
+ log_path, min(lines, 500) if not search else 2000,
+ has_filters=bool(min_level or comp_prefixes or search),
min_level=min_level, component_prefixes=comp_prefixes)
# _read_tail doesn't support free-text search, so post-filter (case-insensitive
# substring) here and trim to the requested line count afterward.
diff --git a/hermes_cli/web_server_profiles.py b/hermes_cli/web_server_profiles.py
index 4337feb50b1..b80cb4dcb72 100644
--- a/hermes_cli/web_server_profiles.py
+++ b/hermes_cli/web_server_profiles.py
@@ -43,7 +43,6 @@ def _hermes_home_scope(path) -> Any:
"""Scope ``load_config``/``save_config`` (anything resolving ``get_hermes_home()`` at call
time) to ``path`` for the block via the context-local HERMES_HOME override."""
from hermes_constants import set_hermes_home_override, reset_hermes_home_override
-
token = set_hermes_home_override(str(path))
try:
yield
@@ -64,15 +63,11 @@ def _is_other_profile(profile: Optional[str]) -> bool:
def _approval_mode_of(config: Dict[str, Any]) -> str:
- """Normalize approvals.mode from an in-memory config document.
-
- Both sides of the broadcast comparison use in-memory documents: re-reading through
- the config cache after a save can serve the pre-save document when the replacement
- file collides on the (mtime_ns, size) cache key, suppressing the broadcast exactly
- when the mode changed. Absent block/key normalizes to the approval gate's default.
- """
+ """Normalize approvals.mode from an in-memory config document. Both sides of the
+ broadcast comparison use in-memory documents: re-reading through the config cache after
+ a save can serve the pre-save document when the replacement file collides on the
+ (mtime_ns, size) cache key, suppressing the broadcast exactly when the mode changed."""
from tools.approval import _normalize_approval_mode
-
approvals = config.get("approvals")
default_mode = (DEFAULT_CONFIG.get("approvals") or {}).get("mode", "manual")
mode = approvals.get("mode", default_mode) if isinstance(approvals, dict) else default_mode
@@ -174,7 +169,6 @@ def _write_profile_mcp_servers(profile_dir: Path, servers: List["MCPServerCreate
"""
from hermes_cli.web_server import load_config, save_config
from hermes_cli.mcp_config import _save_bearer_auth_token
-
written = 0
with _hermes_home_scope(profile_dir):
cfg = load_config()
@@ -199,12 +193,9 @@ def _write_profile_mcp_servers(profile_dir: Path, servers: List["MCPServerCreate
return written
-# ---------------------------------------------------------------------------
# Skills & Tools endpoints accept an optional ``profile`` query param so the dashboard can
-# manage ANY profile's skills/toolsets, not just the one the dashboard process runs under
-# ("Set as active" only flips the sticky active_profile file for FUTURE invocations, which
-# misled users into thinking toggles landed in the activated profile).
-# ---------------------------------------------------------------------------
+# manage ANY profile's skills/toolsets ("Set as active" only flips the sticky active_profile
+# file for FUTURE invocations, which misled users into thinking toggles landed there).
_SKILLS_PROFILE_LOCK = threading.RLock()
@@ -215,22 +206,17 @@ def _profile_scope(profile: Optional[str]):
"""Scope config + skill-directory resolution to ``profile`` for one request.
Two seams: (1) ``load_config``/``save_config`` resolve ``get_hermes_home()`` at call
- time, so the contextvar override (``_config_profile_scope``) reaches them; (2)
- ``tools.skills_tool`` / ``tools.skill_manager_tool`` bind ``SKILLS_DIR`` at import
- time, so both are retargeted under a lock and restored immediately after (like
- ``_call_cron_for_profile`` does for cron). ``tools.skills_sync`` needs no retargeting —
- its lookups resolve at call time through the same override.
-
- For the dashboard's own profile (None/""/"current") config resolution is untouched, but
- the skill-module globals are still retargeted to the *current* ``get_hermes_home()`` so
- writes land in the live home even when the import-time binding is stale (process
- imported the modules before a HERMES_HOME override, or under test isolation).
- Yields the profile dir for a named profile, None for the current one.
+ time, so the contextvar override reaches them; (2) ``tools.skills_tool`` /
+ ``tools.skill_manager_tool`` bind ``SKILLS_DIR`` at import time, so both are retargeted
+ under a lock and restored after. For the dashboard's own profile config resolution is
+ untouched, but the skill-module globals are still retargeted to the *current*
+ ``get_hermes_home()`` so writes land in the live home even when the import-time binding
+ is stale (test isolation, late HERMES_HOME override). Yields the profile dir for a named
+ profile, None for the current one.
"""
from hermes_constants import get_hermes_home
from tools import skills_tool as _skills_tool
from tools import skill_manager_tool as _skill_mgr
-
with _config_profile_scope(profile) as scoped:
profile_dir = get_hermes_home() if scoped is None else scoped
modules = (_skills_tool, _skill_mgr)
@@ -247,14 +233,10 @@ def _profile_scope(profile: Optional[str]):
@contextmanager
def _config_profile_scope(profile: Optional[str]):
- """Await-safe, config-only profile scope for handlers that ``await``.
-
- Touches ONLY the task-local ``set_hermes_home_override`` contextvar — never the
- process-global ``skills_tool``/``skill_manager`` attributes ``_profile_scope`` swaps:
- holding those across an ``await`` lets a concurrent skills request restore THIS
- request's dir on its ``finally``. Enough for endpoints that resolve ``get_hermes_home()``
- at call time (config, env, gateway status). None/""/"current" = no override.
- """
+ """Await-safe, config-only profile scope: touches ONLY the task-local HERMES_HOME
+ contextvar, never the process-global skills-module attributes ``_profile_scope`` swaps
+ (holding those across an ``await`` lets a concurrent request restore THIS request's dir
+ on its ``finally``). None/""/"current" = no override."""
from hermes_cli.web_server import _resolve_profile_dir
if _is_current_profile(profile):
yield None
@@ -264,12 +246,8 @@ def _config_profile_scope(profile: Optional[str]):
yield profile_dir
-# ---------------------------------------------------------------------------
-# Terminal execution backend picker — GUI counterpart of terminal.backend. Each row carries a
-# fast, defensive health probe so the Capabilities panel renders Ready / Needs setup instead
-# of a bare enum. Probes must never raise — a probe failure renders as a status, not a 500.
-# Keep in sync with tools/terminal_tool.py::_create_environment and the terminal.backend enum.
-# ---------------------------------------------------------------------------
+# Terminal backend picker rows — GUI counterpart of terminal.backend. Keep in sync with
+# tools/terminal_tool.py::_create_environment and the terminal.backend enum.
_TERMINAL_BACKENDS: List[Dict[str, str]] = [
dict(zip(("name", "label", "description"), row)) for row in (
@@ -288,13 +266,11 @@ def _plugin_terminal_backend_rows() -> List[Dict[str, str]]:
rows: List[Dict[str, str]] = []
try:
from hermes_cli.plugins import discover_plugins
-
discover_plugins() # idempotent — plugin state may not be loaded yet
except Exception:
pass
try:
from agent.terminal_env_registry import list_providers
-
for provider in list_providers():
try:
rows.append({"name": provider.name.strip().lower(), "label": provider.display_name,
@@ -306,10 +282,7 @@ def _plugin_terminal_backend_rows() -> List[Dict[str, str]]:
return rows
-# ---------------------------------------------------------------------------
-# Token / cost analytics endpoint
-# ---------------------------------------------------------------------------
-
+# Token / cost analytics helpers.
_AUX_COUNTERS = ("input_tokens", "output_tokens", "estimated_cost", "api_calls")
@@ -347,12 +320,9 @@ def _aux_usage_rows(db, cutoff: float) -> List[Dict[str, Any]]:
def _merge_aux_into_by_model(
by_model: List[Dict[str, Any]], aux_rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """Fold aux usage rows into the sessions-derived per-model list.
-
- Aux usage lives only in session_model_usage (never in the sessions counters), so
- adding it here cannot double-count. Models that ONLY appear via aux calls (e.g. a
- dedicated vision model) get their own entry.
- """
+ """Fold aux usage rows into the sessions-derived per-model list. Aux usage lives only in
+ session_model_usage (never in the sessions counters), so this cannot double-count;
+ models that ONLY appear via aux calls (e.g. a vision model) get their own entry."""
if not aux_rows:
return by_model
merged: Dict[str, Dict[str, Any]] = {row.get("model") or "unknown": row for row in by_model}
@@ -383,12 +353,9 @@ def _aux_task_summary(aux_rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
def _profile_cli_args(profile: Optional[str]) -> List[str]:
- """``["-p", <name>]`` for a validated non-default profile, else ``[]``.
-
- Hub install/uninstall/update run in a fresh ``hermes`` subprocess whose
- ``_apply_profile_override()`` reads ``-p`` from argv — the only mechanism that reaches
- import-time-bound globals like ``skills_hub.SKILLS_DIR``.
- """
+ """``["-p", <name>]`` for a validated non-default profile, else ``[]``. Hub actions run in
+ a fresh ``hermes`` subprocess whose ``_apply_profile_override()`` reads ``-p`` from argv —
+ the only mechanism that reaches import-time-bound globals like ``skills_hub.SKILLS_DIR``."""
requested = (profile or "").strip()
if not requested or requested.lower() in {"current", "default"}:
return []
@@ -398,12 +365,9 @@ def _profile_cli_args(profile: Optional[str]) -> List[str]:
def _hub_action_name(verb: str, key: str) -> str:
- """Unique per-skill hub action name (+ registered log file).
-
- ``_spawn_hermes_action`` tracks one process/log per name, so a shared
- "skills-install" would make concurrent row-level actions overwrite each other's
- status/log while the UI polls per identifier. Slug (readable) + hash (collision-proof).
- """
+ """Unique per-skill hub action name (+ registered log file): ``_spawn_hermes_action``
+ tracks one process/log per name, so a shared "skills-install" would make concurrent
+ row-level actions overwrite each other. Slug (readable) + hash (collision-proof)."""
slug = re.sub(r"[^a-z0-9]+", "-", key.lower()).strip("-")[:48] or "skill"
digest = hashlib.sha1(key.encode()).hexdigest()[:8]
name = f"skills-{verb}-{slug}-{digest}"
@@ -412,13 +376,11 @@ def _hub_action_name(verb: str, key: str) -> str:
def _installed_hub_identifiers(profile: Optional[str] = None) -> dict:
- """identifier -> installed lock entry for hub-installed skills, so the UI can mark
- search results already installed. Scoped to ``profile``'s skills/.hub/lock.json when
- given (HubLockFile takes an explicit path, sidestepping the import-time LOCK_FILE
- binding). Best-effort: {} when the lock file can't be read."""
+ """identifier -> installed lock entry for hub-installed skills (UI marks installed search
+ results). Scoped to ``profile``'s skills/.hub/lock.json when given — HubLockFile takes an
+ explicit path, sidestepping the import-time LOCK_FILE binding. {} when unreadable."""
try:
from tools.skills_hub import HubLockFile
-
if _is_current_profile(profile):
lock = HubLockFile()
else: