"""Profiles dashboard routes. Two routers because route order matters: ``sessions_router`` (/api/profiles/sessions*, projects/tree, pull-requests) was registered long before the generic ``/api/profiles/{name}`` routes on ``router``; the original global registration order is preserved rather than relying on Starlette's literal-before-param matching. Shared helpers are reached via the late-binding seam in :mod:`hermes_cli.web_deps` so a test's ``monkeypatch.setattr(, "_helper", ...)`` keeps working. """ import asyncio import contextlib import copy import functools from hermes_cli.web_read_coalescing import coalesced_read import inspect import json import logging import re import subprocess import sys import threading import time from collections import OrderedDict from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple from fastapi import APIRouter, HTTPException, Query from hermes_cli.session_listing import subagent_listing_scope from hermes_cli.web_deps import late from hermes_cli.config import get_process_hermes_home from hermes_cli.profiles import ProfileIdentitySettlementPending from hermes_cli.web_server_config import ( _apply_main_model_assignment, _normalize_main_model_assignment, _validated_main_model_selection, ) from hermes_cli.web_server_gateway import _strip_session_list_rows from hermes_cli.web_routers._common import _CONFIG_MUTATION_LOCK from hermes_cli.web_server_profiles import ( _fallback_profile_dicts, _hub_action_name, _write_profile_mcp_servers, ) from hermes_cli.web_server_sessions import _open_session_db_at_path from hermes_state_health import STORAGE_CORRUPT, note_storage_error, storage_state from starlette.concurrency import run_in_threadpool from hermes_cli.web_models import ( ProfileCreate, ProfileActiveUpdate, ProfileExport, ProfileImport, ProfileRename, ProfileSoulUpdate, ProfileDescriptionUpdate, ProfileModelUpdate, ProfileDescribeAuto, SessionPrScanBody) from hermes_cli.web_server_profiles import _config_profile_scope, _hermes_home_scope # Same logger the handlers used before extraction (identical logger object). _log = logging.getLogger("hermes_cli.web_server") # A per-profile read failure is not an empty session list. The sidebar slice for # that profile is a failed load (``failed`` + ``retry``) so Desktop can offer Retry # instead of "No sessions yet". A successful read of zero rows still returns # ``sessions: []``. 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() def _warn_profile_read_error(profile: str, exc: Exception) -> None: key = (profile, str(exc)) if key in _profile_read_warned: return _profile_read_warned.add(key) _log.warning("profile session read failed for %r (reported only in the response " "errors array): %s", profile, exc) sessions_router = APIRouter() router = APIRouter() # Late-bound web_server helpers (resolved at call time; cycle-safe, monkeypatch-transparent). _cron_profile_home = late("_cron_profile_home", "hermes_cli.web_server_cron") _resolve_profile_dir = late("_resolve_profile_dir", "hermes_cli.web_server_profiles") _spawn_hermes_action = late("_spawn_hermes_action", "hermes_cli.web_server_gateway") # --------------------------------------------------------------------------- # Profile management endpoints (minimal — list/create/rename/delete + SOUL.md) # --------------------------------------------------------------------------- def _profile_to_dict(info) -> dict[str, Any]: attr = functools.partial(getattr, info) return { "name": attr("name", ""), "path": str(attr("path", "")), "is_default": bool(attr("is_default", False)), "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)), "description": attr("description", "") or "", "description_auto": bool(attr("description_auto", False)), "display_name": attr("display_name", "") or "", "bot_title": attr("bot_title", "") or "", "distribution_name": attr("distribution_name", None), "distribution_version": attr("distribution_version", None), "distribution_source": attr("distribution_source", None), "has_alias": attr("alias_path", None) is not None} def _profile_setup_command(name: str) -> str: """Return the shell command used to configure a profile in the CLI.""" _resolve_profile_dir(name) return "hermes setup" if name == "default" else f"{name} setup" def _scope_profile_name(path: Path) -> Optional[str]: """Map a profile directory onto the query name ``_config_profile_scope`` expects: None for the process home (current-profile semantics: launch secret scope, no home override), ``"default"`` for the default root (its basename -- ``.hermes`` or a custom root -- is not a profile name; launched from ``profiles/`` the root is a *different* profile), the directory name for ``profiles/``.""" from hermes_constants import get_default_hermes_root resolved = path.resolve() if resolved == get_process_hermes_home().resolve(): return None if resolved == get_default_hermes_root().resolve(): return "default" return path.name def _write_profile_model(profile_dir: Path, provider: str, model: str, validate_in: Optional[Path] = None, base_url: str = "") -> None: """Write the main model assignment into ``profile_dir``'s config.yaml (HERMES_HOME-scoped) through the same validated /model shape as ``POST /api/model/set``. ``validate_in`` is the home whose ``providers:``/``.env``/catalog vouch for the pick (default: ``profile_dir`` itself). Profile-create passes the dashboard's own home: the picker that offered the model read THAT catalog, and a just-created profile has no credentials yet, so validating in the empty profile rejected every non-env provider (anthropic, ollama, custom). Both spans enter ``_config_profile_scope`` (home + secret scope), matching ``/api/model/set``: once the dashboard has served a secondary profile, ``switch_model``'s ``key_env`` probe goes through ``get_secret``, which fails closed without a scope and reports the provider as unconnected (UnscopedSecretError class, #114676). ``base_url`` is the endpoint a bare ``custom``/``local`` pick binds to (a fresh profile's config names none); other providers ignore it.""" from hermes_cli.config import load_config, save_config from hermes_cli.config_backend import refusing_locked_omissions with _config_profile_scope(_scope_profile_name(validate_in or profile_dir)): provider, model = _normalize_main_model_assignment(provider, model) result = _validated_main_model_selection(load_config(), provider, model, base_url) with _config_profile_scope(_scope_profile_name(profile_dir)), _CONFIG_MUTATION_LOCK: # RMW span cfg = load_config() cfg["model"] = _apply_main_model_assignment(cfg.get("model", {}), result) with refusing_locked_omissions("model"): save_config(cfg) 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. Hub skills are installed separately via subprocess and are active on install.""" from hermes_cli.config 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), _CONFIG_MUTATION_LOCK: # RMW span skills_root = profile_dir / "skills" installed = ([md.parent.name for md in skills_root.rglob("SKILL.md")] if skills_root.is_dir() else []) cfg = load_config() disabled = get_disabled_skills(cfg) newly = 0 for name in installed: if name not in keep_set and name not in disabled: disabled.add(name) newly += 1 if newly: save_disabled_skills(cfg, disabled) return newly # Returned by the offloaded file readers below to mean "the file is not there", which a plain # ``None`` cannot express: ``desktop.json`` may legitimately hold the document ``null``. _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 (in that order), anything else is logged with ``log_msg`` -> 500. HTTPException passes, and so does ``ProfileIdentitySettlementPending`` — a typed partial success the calling endpoint (the delete route) owns; it must not flatten into the generic 500.""" try: yield except HTTPException: raise except not_found as e: raise HTTPException(status_code=404, detail=str(e)) except bad_request as e: raise HTTPException(status_code=400, detail=str(e)) except ProfileIdentitySettlementPending: raise except Exception as e: _log.exception(log_msg, *args) 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