The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(web): hoist stdlib imports in extracted routers; drop unused web_server imports
Tekniumba91166b1c71
diff --git a/hermes_cli/web_routers/actions.py b/hermes_cli/web_routers/actions.pyindex 3c8db84b076..41d61e4d26e 100644--- a/hermes_cli/web_routers/actions.py+++ b/hermes_cli/web_routers/actions.py@@ -5,6 +5,9 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o"""import logging+import asyncio+import secrets+import subprocessfrom fastapi import APIRouterfrom fastapi import HTTPException, Requestfrom hermes_cli import __version__@@ -117,7 +120,6 @@ async def update_hermes():_dashboard_local_update_managed_externally,_record_completed_action,_spawn_hermes_action,- secrets,)if _dashboard_local_update_managed_externally():message = (@@ -207,7 +209,7 @@ def _recent_upstream_commits(n: int = 20) -> List[Dict[str, Any]]:Best-effort: returns [] if not a git checkout, origin/main is unreachable,or git is unavailable. Never raises into the request path."""- from hermes_cli.web_server import PROJECT_ROOT, subprocess+ from hermes_cli.web_server import PROJECT_ROOTtry:out = subprocess.run([@@ -279,7 +281,6 @@ async def check_hermes_update(force: bool = False):from hermes_cli.web_server import (PROJECT_ROOT,_dashboard_local_update_managed_externally,- asyncio,detect_install_method,get_hermes_home,)diff --git a/hermes_cli/web_routers/analytics.py b/hermes_cli/web_routers/analytics.pyindex 4b35b528dd0..c42c1e0be2a 100644--- a/hermes_cli/web_routers/analytics.py+++ b/hermes_cli/web_routers/analytics.py@@ -5,6 +5,8 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o"""import yaml+import asyncio+import timefrom fastapi import APIRouterfrom fastapi import HTTPException, Queryfrom hermes_cli.config import get_config_path, read_raw_config@@ -40,7 +42,7 @@ async def get_config_raw(profile: Optional[str] = None):``config_path`` is machine-global and always reports the dashboardprocess's own profile, which is wrong under the global profile switcher."""- from hermes_cli.web_server import _profile_scope, asyncio+ from hermes_cli.web_server import _profile_scopedef _run():with _profile_scope(profile):path = get_config_path()@@ -58,7 +60,6 @@ async def update_config_raw(body: RawConfigUpdate, profile: Optional[str] = None_broadcast_gateway_session_info,_is_other_profile,_profile_scope,- asyncio,save_config,)def _run():@@ -88,7 +89,6 @@ def _get_usage_analytics(days: int = 30, profile: Optional[str] = None):_aux_usage_rows,_merge_aux_into_by_model,_open_session_db_for_profile,- time,)from agent.insights import InsightsEngine@@ -170,7 +170,6 @@ async def get_usage_analytics(values would force expensive full-history SQL and InsightsEngine work, orproduce empty/inverted time windows. The UI only offers 7/30/90-daypresets."""- from hermes_cli.web_server import asyncioreturn await asyncio.to_thread(_get_usage_analytics, days, profile)@@ -180,7 +179,7 @@ def _get_models_analytics(days: int = 30, profile: Optional[str] = None):Returns token/cost/session breakdown per model plus capability metadatafrom models.dev (context window, vision, tools, reasoning, etc.)."""- from hermes_cli.web_server import _aux_usage_rows, _open_session_db_for_profile, time+ from hermes_cli.web_server import _aux_usage_rows, _open_session_db_for_profiledb = _open_session_db_for_profile(profile, read_only=True)try:cutoff = time.time() - (days * 86400)@@ -358,5 +357,4 @@ async def get_models_analytics():# ``days`` clamped to 1-365 (idea from #74778) — see get_usage_analytics."""Return model analytics without blocking the serving event loop."""- from hermes_cli.web_server import asyncioreturn await asyncio.to_thread(_get_models_analytics, days, profile)diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.pyindex 5ffcb844e49..a8ceb521342 100644--- a/hermes_cli/web_routers/audio.py+++ b/hermes_cli/web_routers/audio.py@@ -11,6 +11,11 @@ import loggingimport queueimport tempfileimport threading+import asyncio+import json+import os+import urllib.parse+import urllib.requestfrom fastapi import APIRouterfrom fastapi import HTTPException, WebSocket, WebSocketDisconnectfrom hermes_cli.web_models import AudioTranscriptionRequest, TTSSpeakRequest, TTSLeaseRequest@@ -28,8 +33,6 @@ async def transcribe_audio_upload(_MAX_TRANSCRIPTION_UPLOAD_BYTES,_audio_extension_for_mime,_config_profile_scope,- asyncio,- os,)data_url = (payload.data_url or "").strip()if not data_url.startswith("data:") or "," not in data_url:@@ -137,7 +140,7 @@ async def get_client_voice_config(profile: Optional[str] = None):response are held in client memory only, never persisted client-side.Gate: ``voice.client_direct`` in config.yaml (default true)."""- from hermes_cli.web_server import _config_profile_scope, asyncio+ from hermes_cli.web_server import _config_profile_scopefrom tools.voice_client_config import resolve_client_voice_configdef _resolve_scoped():@@ -172,15 +175,7 @@ async def get_elevenlabs_voices(profile: Optional[str] = None):The desktop UI uses this for the ``tts.elevenlabs.voice_id`` dropdown.Only non-secret voice metadata is returned; the API key stays server-side."""- from hermes_cli.web_server import (- _config_profile_scope,- _voice_list_error_logged_once,- asyncio,- json,- load_env,- os,- urllib,- )+ from hermes_cli.web_server import _config_profile_scope, _voice_list_error_logged_once, load_env# Config-only scope (await-safe): the key lookup reads the requested# profile's .env, matching the profile the settings UI writes to.with _config_profile_scope(profile):@@ -267,7 +262,7 @@ async def speak_text(payload: TTSSpeakRequest, profile: Optional[str] = None):existing TTS provider chain (Edge / OpenAI / ElevenLabs / etc.)configured in ``~/.hermes/config.yaml`` under ``tts.``."""- from hermes_cli.web_server import _config_profile_scope, asyncio, json, os+ from hermes_cli.web_server import _config_profile_scopetext = (payload.text or "").strip()if not text:raise HTTPException(status_code=400, detail="Text is required")@@ -359,7 +354,7 @@ async def tts_lease(payload: TTSLeaseRequest, profile: Optional[str] = None):Warm-up failures are reported in the body, never as an HTTP error — thetoggle must succeed even when the engine can't preload."""- from hermes_cli.web_server import _config_profile_scope, asyncio+ from hermes_cli.web_server import _config_profile_scopelease = (payload.lease or "").strip()if not lease:raise HTTPException(status_code=400, detail="lease is required")@@ -407,8 +402,6 @@ async def speak_stream_ws(ws: "WebSocket") -> None:_split_text_for_speak_stream,_ws_auth_ok,_ws_request_is_allowed,- asyncio,- json,)if not _ws_auth_ok(ws):await ws.close(code=4401)diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex 88398f6ca94..a5a1ebbe6a0 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -7,6 +7,7 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch oimport asyncioimport functoolsimport logging+import jsonfrom fastapi import APIRouterfrom fastapi import HTTPException, WebSocket, WebSocketDisconnectfrom hermes_cli.pty_session import RegistryFull@@ -188,7 +189,6 @@ async def _console_send_result(def _console_json_payload(msg: Any) -> tuple[Optional[dict[str, Any]], Optional[str]]:- from hermes_cli.web_server import jsonraw: str | bytes | None = msg.get("text")if raw is None:raw = msg.get("bytes")diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.pyindex b28da67d9ad..5963f54216e 100644--- a/hermes_cli/web_routers/config_env.py+++ b/hermes_cli/web_routers/config_env.py@@ -6,6 +6,9 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch oimport loggingimport re+import asyncio+import time+import urllib.parsefrom fastapi import APIRouterfrom fastapi import HTTPException, Requestfrom hermes_cli.config import DEFAULT_CONFIG, OPTIONAL_ENV_VARS, read_raw_config, custom_endpoint_key_env, coerce_provider_id, find_provider_entry, redact_key, _deep_merge@@ -24,12 +27,7 @@ async def get_config(profile: Optional[str] = None):# froze the whole gateway for >1s (observed via the loop watchdog).# asyncio.to_thread copies the contextvar context, so the profile# override stays scoped to the worker thread.- from hermes_cli.web_server import (- _normalize_config_for_web,- _profile_scope,- asyncio,- load_config,- )+ from hermes_cli.web_server import _normalize_config_for_web, _profile_scope, load_configdef _run():with _profile_scope(profile):return _normalize_config_for_web(load_config())@@ -76,7 +74,6 @@ async def update_config(body: ConfigUpdate, profile: Optional[str] = None):_denormalize_config_from_web,_is_other_profile,_profile_scope,- asyncio,save_config,)def _run():@@ -230,7 +227,6 @@ def _catalog_provider_env_metadata() -> dict:async def get_env_vars(profile: Optional[str] = None):# _profile_scope takes _SKILLS_PROFILE_LOCK and load_env()/catalog# discovery read from disk — keep the whole build off the event loop.- from hermes_cli.web_server import asyncioreturn await asyncio.to_thread(_get_env_vars_sync, profile)@@ -299,7 +295,7 @@ def _get_env_vars_sync(profile: Optional[str] = None):@router.put("/api/env")async def set_env_var(body: EnvVarUpdate, profile: Optional[str] = None):- from hermes_cli.web_server import _profile_scope, asyncio+ from hermes_cli.web_server import _profile_scopedef _run():with _profile_scope(body.profile or profile):# Unified credential lifecycle: writes .env AND reconciles any@@ -472,12 +468,7 @@ def _detach_main_model_from_provider(cfg: Dict[str, Any], provider_key: str) ->def _write_custom_endpoint(cfg: Dict[str, Any], body: CustomEndpointUpdate) -> Tuple[str, Dict[str, Any]]:- from hermes_cli.web_server import (- _apply_main_model_assignment,- remove_env_value,- save_env_value,- urllib,- )+ from hermes_cli.web_server import _apply_main_model_assignment, remove_env_value, save_env_valueendpoint_id = _custom_endpoint_id(body.id or body.name)name = (body.name or "").strip()base_url = (body.base_url or "").strip().rstrip("/")@@ -795,7 +786,7 @@ async def validate_provider_credential(body: EnvVarUpdate, request: Request):@router.delete("/api/env")async def remove_env_var(body: EnvVarDelete, profile: Optional[str] = None):- from hermes_cli.web_server import _profile_scope, asyncio+ from hermes_cli.web_server import _profile_scopedef _run():with _profile_scope(body.profile or profile):# Unified credential lifecycle: clears the .env entry AND every@@ -842,9 +833,7 @@ async def reveal_env_var(_profile_scope,_require_token,_reveal_timestamps,- asyncio,load_env,- time,)# --- Token check ---_require_token(request)diff --git a/hermes_cli/web_routers/dashboard_ui.py b/hermes_cli/web_routers/dashboard_ui.pyindex 55924370a13..16a8bf8fad5 100644--- a/hermes_cli/web_routers/dashboard_ui.py+++ b/hermes_cli/web_routers/dashboard_ui.py@@ -5,6 +5,7 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o"""import logging+import asynciofrom fastapi import APIRouterfrom fastapi import HTTPException, Requestfrom fastapi.responses import FileResponse@@ -28,7 +29,6 @@ async def get_dashboard_themes():from hermes_cli.web_server import (_BUILTIN_DASHBOARD_THEMES,_discover_user_themes,- asyncio,cfg_get,load_config,)@@ -59,7 +59,7 @@ async def get_dashboard_themes():@router.put("/api/dashboard/theme")async def set_dashboard_theme(body: ThemeSetBody):"""Set the active dashboard theme (persists to config.yaml)."""- from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, asyncio, load_config, save_config+ from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, load_config, save_configdef _run():with _CONFIG_MUTATION_LOCK:config = load_config()@@ -91,7 +91,7 @@ _FONT_CHOICES = frozenset({@router.get("/api/dashboard/font")async def get_dashboard_font():"""Return the active font override (``"theme"`` = use the theme's font)."""- from hermes_cli.web_server import asyncio, cfg_get, load_config+ from hermes_cli.web_server import cfg_get, load_configdef _run():config = load_config()font = cfg_get(config, "dashboard", "font", default=_FONT_DEFAULT_ID)@@ -111,7 +111,7 @@ async def set_dashboard_font(body: FontSetBody):coerced to ``"theme"`` rather than 400'd so a stale client can't wedgethe picker."""- from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, asyncio, load_config, save_config+ from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, load_config, save_configfont = body.font if body.font in _FONT_CHOICES else _FONT_DEFAULT_IDdef _run():@@ -129,7 +129,7 @@ async def set_dashboard_font(body: FontSetBody):@router.get("/api/dashboard/plugins")async def get_dashboard_plugins():"""Return discovered dashboard plugins (excludes user-hidden and non-enabled ones)."""- from hermes_cli.web_server import _get_dashboard_plugins, asyncio, cfg_get, load_config+ from hermes_cli.web_server import _get_dashboard_plugins, cfg_get, load_configdef _run():plugins = _get_dashboard_plugins()# Read user's hidden plugins list from config.@@ -301,7 +301,6 @@ async def put_plugin_providers(request: Request, body: _PluginProvidersPutBody):_normalize_memory_provider_name,_require_memory_provider_ready,_require_token,- asyncio,)_require_token(request)from hermes_cli.plugins_cmd import (@@ -330,7 +329,6 @@ async def post_plugin_visibility(request: Request, name: str, body: _PluginVisib_CONFIG_MUTATION_LOCK,_invalidate_plugins_hub_cache,_require_token,- asyncio,load_config,save_config,)diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.pyindex 36e676ef69d..9ef3b7c19b1 100644--- a/hermes_cli/web_routers/files.py+++ b/hermes_cli/web_routers/files.py@@ -11,6 +11,11 @@ import osimport reimport statimport tempfile+import asyncio+import secrets+import shutil+import subprocess+import sysfrom datetime import datetimefrom fastapi import APIRouterfrom fastapi import File, Form, HTTPException, Request, UploadFile@@ -205,7 +210,7 @@ def _fs_find_git_root(start: Path) -> str | None:def _fs_default_cwd() -> str:- from hermes_cli.web_server import load_config, os+ from hermes_cli.web_server import load_configcfg_terminal = load_config().get("terminal") or {}raw = str(cfg_terminal.get("cwd") or os.environ.get("TERMINAL_CWD") or "").strip()if raw and raw not in {".", "auto", "cwd"}:@@ -219,7 +224,6 @@ def _fs_default_cwd() -> str:def _fs_git_branch(cwd: str) -> str:- from hermes_cli.web_server import subprocess, systry:run_kwargs: Dict[str, Any] = {"capture_output": True,@@ -377,7 +381,7 @@ async def upload_chat_image(payload: ChatImageUpload, profile: Optional[str] = N``HERMES_HOME/images/`` — the same directory ``clipboard.paste`` /``image.attach`` already use."""- from hermes_cli.web_server import _profile_scope, asyncio, get_hermes_home, secrets+ from hermes_cli.web_server import _profile_scope, get_hermes_homedef _run():data, mime_type, ext = _decode_chat_image_upload(payload)with _profile_scope(profile) as scoped_home:@@ -422,7 +426,6 @@ async def list_managed_files(request: Request, path: Optional[str] = None):_managed_file_entry,_managed_response_meta,_resolve_managed_path,- os,)policy, target, display_path = _resolve_managed_path(path, request)if not target.exists():@@ -623,7 +626,6 @@ async def upload_managed_file_stream(_managed_file_entry,_managed_response_meta,_resolve_managed_path,- os,)policy, target, display_path = _resolve_managed_path(path, request, for_write=True)if target.exists() and target.is_dir():@@ -710,7 +712,7 @@ async def create_managed_directory(payload: ManagedDirectoryCreate, request: Req@router.delete("/api/files")async def delete_managed_file(payload: ManagedFileDelete, request: Request):- from hermes_cli.web_server import _managed_response_meta, _resolve_managed_path, shutil+ from hermes_cli.web_server import _managed_response_meta, _resolve_managed_pathpolicy, target, display_path = _resolve_managed_path(payload.path, request)if policy.locked_root is not None and target == policy.locked_root:raise HTTPException(status_code=400, detail="Cannot delete the managed files root")@@ -736,7 +738,7 @@ async def delete_managed_file(payload: ManagedFileDelete, request: Request):@router.get("/api/fs/list")async def fs_list(path: str):- from hermes_cli.web_server import _FS_READDIR_HIDDEN, _fs_path, os+ from hermes_cli.web_server import _FS_READDIR_HIDDEN, _fs_pathtarget = _fs_path(path)try:entries = []@@ -798,7 +800,7 @@ async def fs_write_text(payload: FsWriteText):original. Stale-on-disk detection is the client's job (re-read before save),so both transports behave identically."""- from hermes_cli.web_server import _fs_path, os+ from hermes_cli.web_server import _fs_pathtarget = _fs_path(payload.path)text = payload.content or ""if len(text.encode("utf-8")) > _FS_TEXT_WRITE_MAX_BYTES:diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex 055e80a2dbc..465cc8f9e32 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -439,7 +439,7 @@ def local_models_hardware():"""The budget as plain facts. Polled by the pane and the statusbarresource item (throttled client-side). Sync def on purpose: the bodyshells out to nvidia-smi and probes budgets — threadpool, not loop."""- from hermes_cli.local_runtime.hardware import probe_budget, _nvidia_vram, _ram_bytes+ from hermes_cli.local_runtime.hardware import probe_budget, _ram_bytesbudget = probe_budget()ram_total, ram_avail = _ram_bytes()diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.pyindex 93f5b426db5..922730ccebb 100644--- a/hermes_cli/web_routers/memory_providers.py+++ b/hermes_cli/web_routers/memory_providers.py@@ -8,6 +8,7 @@ import loggingimport mathimport reimport shlex+import asynciofrom fastapi import APIRouterfrom fastapi import HTTPExceptionfrom hermes_cli.web_models import MemoryProviderConfigUpdate, MemoryProviderSetupRequest@@ -341,7 +342,6 @@ async def get_memory_provider_config(name: str, surface: Optional[str] = None, p_load_memory_provider,_memory_provider_setup_info,_profile_scope,- asyncio,)_require_valid_memory_provider_name(name)@@ -403,7 +403,6 @@ async def update_memory_provider_config(_require_memory_provider_ready,_stringify_submitted_values,_update_memory_provider_config,- asyncio,load_config,save_config,)diff --git a/hermes_cli/web_routers/messaging.py b/hermes_cli/web_routers/messaging.pyindex 993b2ebb0f4..30ffe6eebdb 100644--- a/hermes_cli/web_routers/messaging.py+++ b/hermes_cli/web_routers/messaging.py@@ -8,6 +8,11 @@ import loggingimport reimport subprocessimport threading+import asyncio+import json+import secrets+import time+import urllib.parsefrom datetime import datetime, timezonefrom fastapi import APIRouterfrom fastapi import HTTPException@@ -58,7 +63,6 @@ def _whatsapp_phone_from_identifier(value: Any) -> str | None:def _whatsapp_linked_account_from_session(session_path: Path) -> tuple[str | None, str | None, str | None]:- from hermes_cli.web_server import jsoncreds_path = session_path / "creds.json"try:payload = json.loads(creds_path.read_text(encoding="utf-8"))@@ -93,7 +97,6 @@ def _whatsapp_linked_account_from_session(session_path: Path) -> tuple[str | Nondef _ensure_whatsapp_bridge_dependencies(bridge_dir: Path) -> None:"""Install bridge dependencies when the dashboard is the setup surface."""- from hermes_cli.web_server import subprocessif (bridge_dir / "node_modules").exists():return@@ -204,7 +207,7 @@ def _terminate_whatsapp_pairing(proc: subprocess.Popen | None) -> None:def _watch_whatsapp_pairing(pairing_id: str, proc: subprocess.Popen) -> None:- from hermes_cli.web_server import _whatsapp_onboarding_sessions, json+ from hermes_cli.web_server import _whatsapp_onboarding_sessionstry:stream = proc.stdoutif stream is not None:@@ -295,7 +298,7 @@ def _run_whatsapp_pairing(pairing_id: str, session_path: Path, mode: str) -> Nondef _prune_whatsapp_onboarding_sessions() -> None:- from hermes_cli.web_server import _whatsapp_onboarding_sessions, time+ from hermes_cli.web_server import _whatsapp_onboarding_sessionsnow = time.time()remove_ids: list[str] = []for pairing_id, record in _whatsapp_onboarding_sessions.items():@@ -333,8 +336,6 @@ async def start_whatsapp_onboarding(body: WhatsAppOnboardingStart):_whatsapp_onboarding_payload,_whatsapp_onboarding_sessions,_whatsapp_session_path,- secrets,- time,)mode = _normalize_whatsapp_onboarding_mode(body.mode)allowed_users = _normalize_whatsapp_allowed_users(body.allowed_users)@@ -482,7 +483,6 @@ async def cancel_whatsapp_onboarding(pairing_id: str):def _parse_expiry_ts(value: str) -> float:- from hermes_cli.web_server import timetry:normalized = value.replace("Z", "+00:00")parsed = datetime.fromisoformat(normalized)@@ -494,7 +494,7 @@ def _parse_expiry_ts(value: str) -> float:def _prune_telegram_onboarding_pairings() -> None:- from hermes_cli.web_server import _telegram_onboarding_pairings, time+ from hermes_cli.web_server import _telegram_onboarding_pairingsnow = time.time()expired = [pairing_id@@ -520,7 +520,7 @@ async def _telegram_onboarding_request(body: dict[str, Any] | None = None,bearer_token: str | None = None,) -> dict[str, Any]:- from hermes_cli.web_server import _telegram_onboarding_request_sync, asyncio+ from hermes_cli.web_server import _telegram_onboarding_request_syncreturn await asyncio.to_thread(_telegram_onboarding_request_sync,method,@@ -579,7 +579,6 @@ async def get_telegram_onboarding_status(pairing_id: str):_telegram_onboarding_error_message,_telegram_onboarding_lock,_telegram_onboarding_pairings,- urllib,)with _telegram_onboarding_lock:_prune_telegram_onboarding_pairings()@@ -691,7 +690,6 @@ async def apply_telegram_onboarding(_telegram_onboarding_lock,_telegram_onboarding_pairings,_write_platform_enabled,- asyncio,save_env_value,)allowed_user_ids = []@@ -783,7 +781,6 @@ async def get_messaging_platforms(profile: Optional[str] = None):_messaging_platform_catalog,_messaging_platform_payload,_profile_scope,- asyncio,load_env,read_runtime_status,)@@ -874,7 +871,6 @@ async def update_messaging_platform(_profile_scope,_validate_messaging_env_value,_write_platform_enabled,- asyncio,remove_env_value,save_env_value,)@@ -951,7 +947,6 @@ async def test_messaging_platform(platform_id: str, profile: Optional[str] = Non_catalog_lookup,_messaging_platform_payload,_profile_scope,- asyncio,load_env,read_runtime_status,)diff --git a/hermes_cli/web_routers/models.py b/hermes_cli/web_routers/models.pyindex 12fddb7e25c..608a312bd4c 100644--- a/hermes_cli/web_routers/models.py+++ b/hermes_cli/web_routers/models.py@@ -5,6 +5,7 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o"""import logging+import asynciofrom fastapi import APIRouterfrom fastapi import HTTPExceptionfrom hermes_cli.web_models import ModelAssignment, MoaModelSlot, MoaPresetPayload, MoaConfigPayload@@ -401,7 +402,7 @@ async def set_model_assignment(body: ModelAssignment, profile: Optional[str] = NThe currently running chat PTY (if any) is not affected; use the``/model`` slash command inside a chat to hot-swap that specific session."""- from hermes_cli.web_server import _apply_model_assignment_sync, _profile_scope, asyncio+ from hermes_cli.web_server import _apply_model_assignment_sync, _profile_scopescope = (body.scope or "").strip().lower()provider = (body.provider or "").strip()model = (body.model or "").strip()diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.pyindex 55ecd581e54..f37feba229b 100644--- a/hermes_cli/web_routers/oauth.py+++ b/hermes_cli/web_routers/oauth.py@@ -5,6 +5,9 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o"""import logging+import asyncio+import sys+import timefrom fastapi import APIRouterfrom fastapi import HTTPException, Requestfrom hermes_cli.web_models import OAuthSubmitBody@@ -29,7 +32,6 @@ def _oauth_provider_disconnect_command(provider: Dict[str, Any]) -> Optional[strfile — the two sources ``read_claude_code_credentials()`` consults. ReturnsNone for providers we can't safely clear (the GUI shows a manual hint)."""- from hermes_cli.web_server import sysif provider.get("flow") != "external":return Noneif provider.get("id") == "claude-code":@@ -135,12 +137,7 @@ async def list_oauth_providers(profile: Optional[str] = None):sync with the `hermes model` picker; _OAUTH_OVERRIDES supplies per-providerflow/status/cli metadata."""- from hermes_cli.web_server import (- _external_process_cli_command,- _profile_scope,- _resolve_provider_status,- asyncio,- )+ from hermes_cli.web_server import _external_process_cli_command, _profile_scope, _resolve_provider_statusdef _run():with _profile_scope(profile):providers = []@@ -170,12 +167,7 @@ async def disconnect_oauth_provider(profile: Optional[str] = None,):"""Disconnect an OAuth provider. Token-protected (matches /env/reveal)."""- from hermes_cli.web_server import (- _profile_scope,- _require_token,- _resolve_provider_status,- asyncio,- )+ from hermes_cli.web_server import _profile_scope, _require_token, _resolve_provider_status_require_token(request)def _run():@@ -276,7 +268,7 @@ _OAUTH_SESSION_TTL_SECONDS = 15 * 60def _gc_oauth_sessions() -> None:"""Drop expired sessions. Called opportunistically on /start."""- from hermes_cli.web_server import _oauth_sessions, _oauth_sessions_lock, time+ from hermes_cli.web_server import _oauth_sessions, _oauth_sessions_lockcutoff = time.time() - _OAUTH_SESSION_TTL_SECONDSwith _oauth_sessions_lock:stale = [sid for sid, sess in _oauth_sessions.items() if sess["created_at"] < cutoff]diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.pyindex 99ccc6fb3a7..2acb3f277c6 100644--- a/hermes_cli/web_routers/ops.py+++ b/hermes_cli/web_routers/ops.py@@ -8,6 +8,9 @@ import loggingimport reimport tempfileimport zipfile+import asyncio+import os+import secretsfrom datetime import datetime, timezonefrom fastapi import APIRouterfrom fastapi import File, Form, HTTPException, UploadFile@@ -512,7 +515,6 @@ async def get_memory_status():from hermes_cli.web_server import (_discover_memory_provider_statuses,_normalize_memory_provider_name,- asyncio,get_hermes_home,load_config,)@@ -545,7 +547,6 @@ async def set_memory_provider(body: MemoryProviderSelect):_CONFIG_MUTATION_LOCK,_normalize_memory_provider_name,_require_memory_provider_ready,- asyncio,load_config,save_config,)@@ -631,7 +632,6 @@ def _dashboard_backup_dir() -> Path:def _new_dashboard_backup_path() -> Path:- from hermes_cli.web_server import secretsstamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")return _dashboard_backup_dir() / f"hermes-backup-{stamp}-{secrets.token_hex(4)}.zip"@@ -691,7 +691,7 @@ async def download_dashboard_backup(archive: str):@router.post("/api/ops/import")async def run_import(body: ImportRequest):- from hermes_cli.web_server import _spawn_hermes_action, os+ from hermes_cli.web_server import _spawn_hermes_actionarchive = (body.archive or "").strip()if not archive:raise HTTPException(status_code=400, detail="archive path is required")@@ -727,8 +727,6 @@ async def run_import_upload(_MANAGED_FILE_MAX_BYTES,_UPLOAD_CHUNK_BYTES,_spawn_hermes_action,- os,- secrets,)staging_dir = _dashboard_backup_dir()try:@@ -811,7 +809,6 @@ async def list_hooks():currently executable, plus the set of valid hook events so the createform can offer them."""- from hermes_cli.web_server import asynciodef _run():from hermes_cli.config import load_config as _load_configfrom agent import shell_hooks@@ -864,7 +861,7 @@ async def create_hook(body: HookCreate):consent in the allowlist so the hook actually fires. Takes effect on thenext session / gateway restart."""- from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, asyncio, load_config, save_config+ from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, load_config, save_configfrom agent import shell_hooksevent = (body.event or "").strip()@@ -920,7 +917,7 @@ async def create_hook(body: HookCreate):@router.delete("/api/ops/hooks")async def delete_hook(body: HookDelete):"""Remove a hook from config.yaml and revoke its consent allowlist entry."""- from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, asyncio, load_config, save_config+ from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, load_config, save_configfrom agent import shell_hooksevent = (body.event or "").strip()@@ -963,7 +960,7 @@ async def delete_hook(body: HookDelete):@router.get("/api/ops/checkpoints")async def list_checkpoints():"""List the /rollback shadow store checkpoints (read-only)."""- from hermes_cli.web_server import get_hermes_home, os+ from hermes_cli.web_server import get_hermes_home# Checkpoints live under <hermes_home>/checkpoints/. Surface a count +# total size so the dashboard can show what a prune would reclaim; the# actual prune is a spawned action so confirmation/pruning logic staysdiff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.pyindex 74c864b2832..85f39a67946 100644--- a/hermes_cli/web_routers/status.py+++ b/hermes_cli/web_routers/status.py@@ -7,6 +7,10 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch oimport concurrent.futuresimport loggingimport re+import asyncio+import os+import sys+import timefrom fastapi import APIRouterfrom fastapi import HTTPException, Requestfrom gateway.status import derive_gateway_busy, derive_gateway_drainable, normalize_updated_at, parse_active_agents, resolve_gateway_liveness@@ -150,7 +154,6 @@ async def get_status(profile: Optional[str] = None):get_runtime_status_running_pid,read_runtime_status,run_in_threadpool,- sys,)status_scope = Nonerequested_profile = (profile or "").strip()@@ -569,7 +572,7 @@ async def get_system_stats():psutil when available, with graceful degradation when it isn't. Read-onlyand non-sensitive (no env values, no paths beyond the hermes home root)."""- from hermes_cli.web_server import _display_system_platform, get_hermes_home, os, time+ from hermes_cli.web_server import _display_system_platform, get_hermes_homeimport platform as _platforminfo: Dict[str, Any] = {@@ -699,7 +702,7 @@ async def get_learning_graph(profile: Optional[str] = None):Profile-scoped view of learned, non-base skills plus memory chunks, withgraph links derived from skill relations and memory-skill overlap."""- from hermes_cli.web_server import _profile_scope, asyncio+ from hermes_cli.web_server import _profile_scopedef _run():from agent.learning_graph import build_learning_graph@@ -718,7 +721,7 @@ async def get_learning_graph(profile: Optional[str] = None):@router.get("/api/learning/node")async def get_learning_node(id: str, profile: Optional[str] = None):"""Current content of a journey node (skill SKILL.md or memory chunk), for an edit prefill."""- from hermes_cli.web_server import _profile_scope, asyncio+ from hermes_cli.web_server import _profile_scopefrom agent.learning_mutations import node_detaildef _run():@@ -734,7 +737,7 @@ async def get_learning_node(id: str, profile: Optional[str] = None):@router.delete("/api/learning/node")async def delete_learning_node(body: LearningNodeRef):"""Delete a journey node — skills are archived (restorable), memories removed."""- from hermes_cli.web_server import _profile_scope, asyncio+ from hermes_cli.web_server import _profile_scopefrom agent.learning_mutations import delete_nodedef _run():@@ -750,7 +753,7 @@ async def delete_learning_node(body: LearningNodeRef):@router.put("/api/learning/node")async def update_learning_node(body: LearningNodeEdit):"""Rewrite a journey node's content (SKILL.md or memory chunk)."""- from hermes_cli.web_server import _profile_scope, asyncio+ from hermes_cli.web_server import _profile_scopefrom agent.learning_mutations import edit_nodedef _run():@@ -780,7 +783,6 @@ def _safe_call(mod, fn_name: str, default):async def get_portal_status():# load_config() + auth/subscription snapshots are disk reads — this is a# polled endpoint, so keep them off the event loop.- from hermes_cli.web_server import asynciodef _run():return _get_portal_status_sync()@@ -878,7 +880,6 @@ async def run_debug_share_endpoint(body: DebugShareRequest | None = None):dashboard renders those as real, copyable links instead of scraping a logtail. Pastes auto-delete after 6 hours (handled inside the share core)."""- from hermes_cli.web_server import asynciofrom hermes_cli.debug import build_debug_sharereq = body or DebugShareRequest()diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 0ba0ffabfc0..707454498f1 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -9,15 +9,11 @@ Usage:python -m hermes_cli.main web --port 8080"""-import contextlibfrom contextlib import asynccontextmanager, contextmanagerimport asyncioimport atexit-import base64-import binasciiimport concurrent.futures-import functoolsfrom collections import dequefrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -28,30 +24,25 @@ import importlib.utilimport ipaddressimport jsonimport logging-import mathimport mimetypesimport os-import queueimport reimport secretsimport shleximport shutil-import statimport subprocessimport sysimport sysconfigimport tempfileimport threadingimport time-import urllib.errorimport urllib.parse-import zipfile-from hermes_cli._subprocess_compat import windows_detach_flags, windows_hide_flags+from hermes_cli._subprocess_compat import windows_detach_flagsfrom hermes_cli.install_identity import get_install_id as _shared_get_install_idimport urllib.requestfrom pathlib import Path-from typing import Any, Dict, List, Literal, Optional, Tuple+from typing import Any, Dict, List, Optional, Tupleimport yaml@@ -59,50 +50,38 @@ PROJECT_ROOT = Path(__file__).parent.parent.resolve()if str(PROJECT_ROOT) not in sys.path:sys.path.insert(0, str(PROJECT_ROOT))-from hermes_cli import __version__, __release_date__+from hermes_cli import __version__from hermes_cli.config import (build_cron_model_impact,cfg_get,DEFAULT_CONFIG,OPTIONAL_ENV_VARS,clear_model_endpoint_credentials,- get_config_path,- get_env_path,get_hermes_home,get_process_hermes_home,load_config,+ # Late-bound by extracted routers (tests monkeypatch web_server.<name>).+ check_config_version, # noqa: F401+ remove_env_value, # noqa: F401load_env,read_raw_config,resolve_cron_model_drift_defaults,save_config,save_env_value,- remove_env_value,- custom_endpoint_key_env,- coerce_provider_id,find_provider_entry,- check_config_version,detect_install_method,- format_docker_update_message,- is_nix_install_method,- recommended_update_command_for_method,redact_key,write_platform_config_field,- _deep_merge,)from plugins.memory.config_schema import (ProviderConfigSchema,ProviderField,STORAGE_HONCHO_HOST_BLOCK,- get_provider_config_schema,)from gateway.status import (- derive_gateway_busy,- derive_gateway_drainable,+ get_running_pid, # noqa: F401 — tests monkeypatch web_server.get_running_pidget_running_pid_cached,- get_running_pid,get_runtime_status_running_pid,- normalize_updated_at,- parse_active_agents,read_runtime_status,resolve_gateway_liveness,)@@ -126,13 +105,11 @@ except ImportError:from tools.lazy_deps import ensure as _lazy_ensure_lazy_ensure("tool.dashboard", prompt=False)from fastapi import (- FastAPI, File, Form, HTTPException, Query, Request, UploadFile,- WebSocket, WebSocketDisconnect,+ FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect,)from fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Responsefrom fastapi.staticfiles import StaticFiles- from pydantic import BaseModel, SecretStr, field_validatorfrom starlette.concurrency import run_in_threadpoolexcept Exception:raise SystemExit(@@ -2534,7 +2511,6 @@ _UPLOAD_CHUNK_BYTES = 1024 * 1024# these are thin, executor-offloaded wrappers (git/gh can block).# ----------------------------------------------------------------------------from hermes_cli import web_git as _web_git # noqa: E402async def _git_op(fn, *args):@@ -9479,7 +9455,7 @@ _PTY_IDLE_BACKOFF = 0.05# Keep-alive PTY sessions: a terminal connecting with ``?attach=<token>`` is# bound to a process that survives disconnect/refresh and is reattachable.-from hermes_cli.pty_session import PtySessionRegistry, RegistryFull, run_reaper # noqa: E402+from hermes_cli.pty_session import PtySessionRegistry, run_reaper # noqa: E402PTY_REGISTRY = PtySessionRegistry(ttl=30 * 60,