diff --git a/hermes_cli/web_routers/actions.py b/hermes_cli/web_routers/actions.py index 41d61e4d26..b3aa17c6ce 100644 --- a/hermes_cli/web_routers/actions.py +++ b/hermes_cli/web_routers/actions.py @@ -9,6 +9,7 @@ import asyncio import secrets import subprocess from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException, Request from hermes_cli import __version__ from hermes_cli.config import format_docker_update_message, recommended_update_command_for_method @@ -18,11 +19,20 @@ _log = logging.getLogger("hermes_cli.web_server") router = APIRouter() status_router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_dashboard_local_update_managed_externally = late("_dashboard_local_update_managed_externally") +_durable_completed_update_action_id = late("_durable_completed_update_action_id") +_record_completed_action = late("_record_completed_action") +_spawn_gateway_restart = late("_spawn_gateway_restart") +_spawn_hermes_action = late("_spawn_hermes_action") +_tail_lines = late("_tail_lines") +detect_install_method = late("detect_install_method") +get_hermes_home = late("get_hermes_home") + @router.post("/api/gateway/restart") async def restart_gateway(profile: Optional[str] = None): """Kick off a ``hermes gateway restart`` in the background.""" - from hermes_cli.web_server import _spawn_gateway_restart try: proc, _reused = _spawn_gateway_restart(profile) except HTTPException: @@ -113,14 +123,7 @@ async def gateway_drain(request: Request): @router.post("/api/hermes/update") async def update_hermes(): """Kick off ``hermes update`` in the background.""" - from hermes_cli.web_server import ( - PROJECT_ROOT, - _ACTION_IDS, - _ACTION_PROCS, - _dashboard_local_update_managed_externally, - _record_completed_action, - _spawn_hermes_action, - ) + from hermes_cli.web_server import PROJECT_ROOT, _ACTION_IDS, _ACTION_PROCS if _dashboard_local_update_managed_externally(): message = ( "Hermes updates are managed outside this dashboard in " @@ -278,12 +281,7 @@ async def check_hermes_update(force: bool = False): desktop's remote update overlay renders this as "what's changed". Additive: existing consumers ignore it. """ - from hermes_cli.web_server import ( - PROJECT_ROOT, - _dashboard_local_update_managed_externally, - detect_install_method, - get_hermes_home, - ) + from hermes_cli.web_server import PROJECT_ROOT if _dashboard_local_update_managed_externally(): return { "install_method": "managed-runtime", @@ -363,8 +361,6 @@ async def get_action_status(name: str, lines: int = 200): _ACTION_LOG_FILES, _ACTION_PROCS, _ACTION_RESULTS, - _durable_completed_update_action_id, - _tail_lines, ) log_file_name = _ACTION_LOG_FILES.get(name) if log_file_name is None: diff --git a/hermes_cli/web_routers/analytics.py b/hermes_cli/web_routers/analytics.py index c42c1e0be2..e55bc6e008 100644 --- a/hermes_cli/web_routers/analytics.py +++ b/hermes_cli/web_routers/analytics.py @@ -8,6 +8,7 @@ import yaml import asyncio import time from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException, Query from hermes_cli.config import get_config_path, read_raw_config from hermes_cli.web_models import RawConfigUpdate @@ -15,6 +16,17 @@ from typing import Any, Dict, List, Optional router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_approval_mode_of = late("_approval_mode_of") +_aux_task_summary = late("_aux_task_summary") +_aux_usage_rows = late("_aux_usage_rows") +_broadcast_gateway_session_info = late("_broadcast_gateway_session_info") +_is_other_profile = late("_is_other_profile") +_merge_aux_into_by_model = late("_merge_aux_into_by_model") +_open_session_db_for_profile = late("_open_session_db_for_profile") +_profile_scope = late("_profile_scope") +save_config = late("save_config") + # --------------------------------------------------------------------------- # Computer Use (cua-driver) — cross-platform readiness + macOS permission grant @@ -42,7 +54,6 @@ async def get_config_raw(profile: Optional[str] = None): ``config_path`` is machine-global and always reports the dashboard process's own profile, which is wrong under the global profile switcher. """ - from hermes_cli.web_server import _profile_scope def _run(): with _profile_scope(profile): path = get_config_path() @@ -55,13 +66,6 @@ async def get_config_raw(profile: Optional[str] = None): @router.put("/api/config/raw") async def update_config_raw(body: RawConfigUpdate, profile: Optional[str] = None): - from hermes_cli.web_server import ( - _approval_mode_of, - _broadcast_gateway_session_info, - _is_other_profile, - _profile_scope, - save_config, - ) def _run(): parsed = yaml.safe_load(body.yaml_text) if not isinstance(parsed, dict): @@ -84,12 +88,6 @@ async def update_config_raw(body: RawConfigUpdate, profile: Optional[str] = None def _get_usage_analytics(days: int = 30, profile: Optional[str] = None): - from hermes_cli.web_server import ( - _aux_task_summary, - _aux_usage_rows, - _merge_aux_into_by_model, - _open_session_db_for_profile, - ) from agent.insights import InsightsEngine db = _open_session_db_for_profile(profile, read_only=True) @@ -179,7 +177,6 @@ def _get_models_analytics(days: int = 30, profile: Optional[str] = None): Returns token/cost/session breakdown per model plus capability metadata from models.dev (context window, vision, tools, reasoning, etc.). """ - from hermes_cli.web_server import _aux_usage_rows, _open_session_db_for_profile db = _open_session_db_for_profile(profile, read_only=True) try: cutoff = time.time() - (days * 86400) diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.py index a8ceb52134..bb5ff5ee7f 100644 --- a/hermes_cli/web_routers/audio.py +++ b/hermes_cli/web_routers/audio.py @@ -17,6 +17,7 @@ import os import urllib.parse import urllib.request from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException, WebSocket, WebSocketDisconnect from hermes_cli.web_models import AudioTranscriptionRequest, TTSSpeakRequest, TTSLeaseRequest from typing import Any, Dict, Optional @@ -24,16 +25,21 @@ from typing import Any, Dict, Optional _log = logging.getLogger("hermes_cli.web_server") router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_audio_extension_for_mime = late("_audio_extension_for_mime") +_config_profile_scope = late("_config_profile_scope") +_split_text_for_speak_stream = late("_split_text_for_speak_stream") +_voice_list_error_logged_once = late("_voice_list_error_logged_once") +_ws_auth_ok = late("_ws_auth_ok") +_ws_request_is_allowed = late("_ws_request_is_allowed") +load_env = late("load_env") + @router.post("/api/audio/transcribe") async def transcribe_audio_upload( payload: AudioTranscriptionRequest, profile: Optional[str] = None ): - from hermes_cli.web_server import ( - _MAX_TRANSCRIPTION_UPLOAD_BYTES, - _audio_extension_for_mime, - _config_profile_scope, - ) + from hermes_cli.web_server import _MAX_TRANSCRIPTION_UPLOAD_BYTES data_url = (payload.data_url or "").strip() if not data_url.startswith("data:") or "," not in data_url: raise HTTPException(status_code=400, detail="Invalid audio payload") @@ -140,7 +146,6 @@ 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 from tools.voice_client_config import resolve_client_voice_config def _resolve_scoped(): @@ -175,7 +180,6 @@ 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, 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): @@ -262,7 +266,6 @@ 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 text = (payload.text or "").strip() if not text: raise HTTPException(status_code=400, detail="Text is required") @@ -354,7 +357,6 @@ async def tts_lease(payload: TTSLeaseRequest, profile: Optional[str] = None): Warm-up failures are reported in the body, never as an HTTP error — the toggle must succeed even when the engine can't preload. """ - from hermes_cli.web_server import _config_profile_scope lease = (payload.lease or "").strip() if not lease: raise HTTPException(status_code=400, detail="lease is required") @@ -397,12 +399,6 @@ async def speak_stream_ws(ws: "WebSocket") -> None: server → ``{"type": "fallback"}`` when the configured provider has no chunked API — the client uses the POST endpoint instead. """ - from hermes_cli.web_server import ( - _config_profile_scope, - _split_text_for_speak_stream, - _ws_auth_ok, - _ws_request_is_allowed, - ) if not _ws_auth_ok(ws): await ws.close(code=4401) return diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.py index a5a1ebbe6a..24dbbceddd 100644 --- a/hermes_cli/web_routers/chat_ws.py +++ b/hermes_cli/web_routers/chat_ws.py @@ -9,6 +9,7 @@ import functools import logging import json from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException, WebSocket, WebSocketDisconnect from hermes_cli.pty_session import RegistryFull from pathlib import Path @@ -17,6 +18,27 @@ from typing import Any, Dict, Optional _log = logging.getLogger("hermes_cli.web_server") router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_active_session_file_for_channel = late("_active_session_file_for_channel") +_broadcast_event = late("_broadcast_event") +_build_sidecar_url = late("_build_sidecar_url") +_channel_or_close_code = late("_channel_or_close_code") +_forget_active_session_file = late("_forget_active_session_file") +_get_console_executor = late("_get_console_executor") +_get_event_state = late("_get_event_state") +_legacy_pump = late("_legacy_pump") +_profile_scope = late("_profile_scope") +_read_active_session_file = late("_read_active_session_file") +_resolve_chat_argv_async = late("_resolve_chat_argv_async") +_resolve_profile_dir = late("_resolve_profile_dir") +_ws_auth_mode = late("_ws_auth_mode") +_ws_auth_ok = late("_ws_auth_ok") +_ws_auth_reason = late("_ws_auth_reason") +_ws_client_reason = late("_ws_client_reason") +_ws_close_reason = late("_ws_close_reason") +_ws_host_origin_reason = late("_ws_host_origin_reason") +_ws_request_is_allowed = late("_ws_request_is_allowed") + # --------------------------------------------------------------------------- # /api/console — safe Hermes Console command WebSocket. @@ -49,7 +71,6 @@ def _execute_console_line( ) -> Any: # _profile_scope swaps process-global skill module paths; keep it inside # the worker thread and never hold it across awaits. - from hermes_cli.web_server import _profile_scope with _profile_scope(profile): return engine.execute(line, confirmed=confirmed) @@ -210,17 +231,7 @@ def _console_json_payload(msg: Any) -> tuple[Optional[dict[str, Any]], Optional[ @router.websocket("/api/console") async def console_ws(ws: WebSocket) -> None: - from hermes_cli.web_server import ( - _DASHBOARD_EMBEDDED_CHAT_ENABLED, - _get_console_executor, - _resolve_profile_dir, - _ws_auth_mode, - _ws_auth_reason, - _ws_client_reason, - _ws_close_reason, - _ws_host_origin_reason, - asyncio, - ) + from hermes_cli.web_server import _DASHBOARD_EMBEDDED_CHAT_ENABLED, asyncio peer = ws.client.host if ws.client else "?" if not _DASHBOARD_EMBEDDED_CHAT_ENABLED: @@ -578,18 +589,6 @@ async def pty_ws(ws: WebSocket) -> None: _DASHBOARD_EMBEDDED_CHAT_ENABLED, _PTY_BRIDGE_AVAILABLE, _RESIZE_RE, - _active_session_file_for_channel, - _build_sidecar_url, - _channel_or_close_code, - _forget_active_session_file, - _legacy_pump, - _read_active_session_file, - _resolve_chat_argv_async, - _ws_auth_mode, - _ws_auth_reason, - _ws_client_reason, - _ws_close_reason, - _ws_host_origin_reason, ) peer = ws.client.host if ws.client else "?" @@ -787,11 +786,7 @@ async def pty_ws(ws: WebSocket) -> None: @router.websocket("/api/ws") async def gateway_ws(ws: WebSocket) -> None: - from hermes_cli.web_server import ( - _DASHBOARD_EMBEDDED_CHAT_ENABLED, - _ws_auth_ok, - _ws_request_is_allowed, - ) + from hermes_cli.web_server import _DASHBOARD_EMBEDDED_CHAT_ENABLED if not _DASHBOARD_EMBEDDED_CHAT_ENABLED: await ws.close(code=4403) return @@ -831,13 +826,7 @@ async def gateway_ws(ws: WebSocket) -> None: @router.websocket("/api/pub") async def pub_ws(ws: WebSocket) -> None: - from hermes_cli.web_server import ( - _DASHBOARD_EMBEDDED_CHAT_ENABLED, - _broadcast_event, - _channel_or_close_code, - _ws_auth_ok, - _ws_request_is_allowed, - ) + from hermes_cli.web_server import _DASHBOARD_EMBEDDED_CHAT_ENABLED if not _DASHBOARD_EMBEDDED_CHAT_ENABLED: await ws.close(code=4403) return @@ -866,13 +855,7 @@ async def pub_ws(ws: WebSocket) -> None: @router.websocket("/api/events") async def events_ws(ws: WebSocket) -> None: - from hermes_cli.web_server import ( - _DASHBOARD_EMBEDDED_CHAT_ENABLED, - _channel_or_close_code, - _get_event_state, - _ws_auth_ok, - _ws_request_is_allowed, - ) + from hermes_cli.web_server import _DASHBOARD_EMBEDDED_CHAT_ENABLED if not _DASHBOARD_EMBEDDED_CHAT_ENABLED: await ws.close(code=4403) return diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.py index 5963f54216..da35621d46 100644 --- a/hermes_cli/web_routers/config_env.py +++ b/hermes_cli/web_routers/config_env.py @@ -10,6 +10,7 @@ import asyncio import time import urllib.parse from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException, Request from 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 from hermes_cli.web_models import ConfigUpdate, EnvVarUpdate, EnvVarDelete, EnvVarReveal, CustomEndpointUpdate @@ -19,6 +20,25 @@ _log = logging.getLogger("hermes_cli.web_server") config_router = APIRouter() router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_apply_main_model_assignment = late("_apply_main_model_assignment") +_approval_mode_of = late("_approval_mode_of") +_broadcast_gateway_session_info = late("_broadcast_gateway_session_info") +_channel_managed_env_keys = late("_channel_managed_env_keys") +_config_profile_scope = late("_config_profile_scope") +_denormalize_config_from_web = late("_denormalize_config_from_web") +_is_other_profile = late("_is_other_profile") +_normalize_config_for_web = late("_normalize_config_for_web") +_parse_model_ids = late("_parse_model_ids") +_profile_scope = late("_profile_scope") +_require_token = late("_require_token") +_schema_with_dynamic_provider_options = late("_schema_with_dynamic_provider_options") +load_config = late("load_config") +load_env = late("load_env") +remove_env_value = late("remove_env_value") +save_config = late("save_config") +save_env_value = late("save_env_value") + @config_router.get("/api/config") async def get_config(profile: Optional[str] = None): @@ -27,7 +47,6 @@ 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, load_config def _run(): with _profile_scope(profile): return _normalize_config_for_web(load_config()) @@ -47,11 +66,7 @@ async def get_schema(profile: Optional[str] = None): # Discovery-driven provider options (voice command providers + memory # provider plugins) are merged per-request so providers added after server # start still show up, scoped to the requested profile's config. - from hermes_cli.web_server import ( - _CATEGORY_ORDER, - _config_profile_scope, - _schema_with_dynamic_provider_options, - ) + from hermes_cli.web_server import _CATEGORY_ORDER with _config_profile_scope(profile): fields = _schema_with_dynamic_provider_options() return {"fields": fields, "category_order": _CATEGORY_ORDER} @@ -67,15 +82,7 @@ async def get_egress_status(): @router.put("/api/config") async def update_config(body: ConfigUpdate, profile: Optional[str] = None): - from hermes_cli.web_server import ( - _CONFIG_MUTATION_LOCK, - _approval_mode_of, - _broadcast_gateway_session_info, - _denormalize_config_from_web, - _is_other_profile, - _profile_scope, - save_config, - ) + from hermes_cli.web_server import _CONFIG_MUTATION_LOCK def _run(): approvals_mode_changed = False with _profile_scope(body.profile or profile): @@ -231,7 +238,6 @@ async def get_env_vars(profile: Optional[str] = None): def _get_env_vars_sync(profile: Optional[str] = None): - from hermes_cli.web_server import _channel_managed_env_keys, _profile_scope, load_env with _profile_scope(profile): env_on_disk = load_env() channel_keys = _channel_managed_env_keys() @@ -295,7 +301,6 @@ 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 def _run(): with _profile_scope(body.profile or profile): # Unified credential lifecycle: writes .env AND reconciles any @@ -468,7 +473,6 @@ 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 endpoint_id = _custom_endpoint_id(body.id or body.name) name = (body.name or "").strip() base_url = (body.base_url or "").strip().rstrip("/") @@ -572,7 +576,6 @@ def list_custom_endpoints(profile: Optional[str] = None): active profile, so read/write must resolve that profile's home rather than the process-level HERMES_HOME. Mirrors ``/api/config``'s profile scoping. """ - from hermes_cli.web_server import _config_profile_scope, load_config try: with _config_profile_scope(profile): return _custom_endpoint_response(load_config()) @@ -586,7 +589,6 @@ def list_custom_endpoints(profile: Optional[str] = None): @router.post("/api/providers/custom-endpoints") def upsert_custom_endpoint(body: CustomEndpointUpdate, profile: Optional[str] = None): """Create or update a v12+ ``providers`` custom endpoint entry.""" - from hermes_cli.web_server import _config_profile_scope, load_config, save_config try: with _config_profile_scope(profile): cfg = load_config() @@ -606,12 +608,6 @@ def upsert_custom_endpoint(body: CustomEndpointUpdate, profile: Optional[str] = @router.post("/api/providers/custom-endpoints/{endpoint_id}/activate") def activate_custom_endpoint(endpoint_id: str, profile: Optional[str] = None): """Set a configured custom endpoint as the default model provider.""" - from hermes_cli.web_server import ( - _apply_main_model_assignment, - _config_profile_scope, - load_config, - save_config, - ) try: with _config_profile_scope(profile): cfg = load_config() @@ -663,12 +659,6 @@ def activate_custom_endpoint(endpoint_id: str, profile: Optional[str] = None): @router.delete("/api/providers/custom-endpoints/{endpoint_id}") def delete_custom_endpoint(endpoint_id: str, profile: Optional[str] = None): """Remove a configured custom endpoint from ``providers``.""" - from hermes_cli.web_server import ( - _config_profile_scope, - load_config, - remove_env_value, - save_config, - ) try: with _config_profile_scope(profile): cfg = load_config() @@ -695,7 +685,6 @@ def delete_custom_endpoint(endpoint_id: str, profile: Optional[str] = None): @router.post("/api/providers/custom-endpoints/validate") async def validate_custom_endpoint(body: CustomEndpointUpdate): """Probe a custom endpoint by calling its OpenAI-compatible /models URL.""" - from hermes_cli.web_server import _parse_model_ids import httpx base_url = (body.base_url or "").strip().rstrip("/") @@ -730,7 +719,6 @@ async def validate_provider_credential(body: EnvVarUpdate, request: Request): reachable=False means the network probe couldn't run (caller may save with a warning rather than hard-blocking offline users). """ - from hermes_cli.web_server import _parse_model_ids, _require_token _require_token(request) import httpx @@ -786,7 +774,6 @@ 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 def _run(): with _profile_scope(body.profile or profile): # Unified credential lifecycle: clears the .env entry AND every @@ -830,10 +817,7 @@ async def reveal_env_var( from hermes_cli.web_server import ( _REVEAL_MAX_PER_WINDOW, _REVEAL_WINDOW_SECONDS, - _profile_scope, - _require_token, _reveal_timestamps, - load_env, ) # --- Token check --- _require_token(request) diff --git a/hermes_cli/web_routers/dashboard_ui.py b/hermes_cli/web_routers/dashboard_ui.py index 16a8bf8fad..6753e26f5e 100644 --- a/hermes_cli/web_routers/dashboard_ui.py +++ b/hermes_cli/web_routers/dashboard_ui.py @@ -7,6 +7,7 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o import logging import asyncio from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException, Request from fastapi.responses import FileResponse from hermes_cli.web_models import ThemeSetBody, FontSetBody, _AgentPluginInstallBody, _PluginProvidersPutBody, _PluginVisibilityBody @@ -15,6 +16,18 @@ from pathlib import Path _log = logging.getLogger("hermes_cli.web_server") router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_discover_user_themes = late("_discover_user_themes") +_get_dashboard_plugins = late("_get_dashboard_plugins") +_invalidate_plugins_hub_cache = late("_invalidate_plugins_hub_cache") +_merged_plugins_hub = late("_merged_plugins_hub") +_normalize_memory_provider_name = late("_normalize_memory_provider_name") +_require_memory_provider_ready = late("_require_memory_provider_ready") +_require_token = late("_require_token") +cfg_get = late("cfg_get") +load_config = late("load_config") +save_config = late("save_config") + @router.get("/api/dashboard/themes") async def get_dashboard_themes(): @@ -26,12 +39,7 @@ async def get_dashboard_themes(): normalised definition under `definition`, so the client can apply them without a stub. """ - from hermes_cli.web_server import ( - _BUILTIN_DASHBOARD_THEMES, - _discover_user_themes, - cfg_get, - load_config, - ) + from hermes_cli.web_server import _BUILTIN_DASHBOARD_THEMES def _run(): config = load_config() active = cfg_get(config, "dashboard", "theme", default="default") @@ -59,7 +67,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, load_config, save_config + from hermes_cli.web_server import _CONFIG_MUTATION_LOCK def _run(): with _CONFIG_MUTATION_LOCK: config = load_config() @@ -91,7 +99,6 @@ _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 cfg_get, load_config def _run(): config = load_config() font = cfg_get(config, "dashboard", "font", default=_FONT_DEFAULT_ID) @@ -111,7 +118,7 @@ async def set_dashboard_font(body: FontSetBody): coerced to ``"theme"`` rather than 400'd so a stale client can't wedge the picker. """ - from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, load_config, save_config + from hermes_cli.web_server import _CONFIG_MUTATION_LOCK font = body.font if body.font in _FONT_CHOICES else _FONT_DEFAULT_ID def _run(): @@ -129,7 +136,6 @@ 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, cfg_get, load_config def _run(): plugins = _get_dashboard_plugins() # Read user's hidden plugins list from config. @@ -174,7 +180,6 @@ async def get_dashboard_plugins(): @router.get("/api/dashboard/plugins/rescan") async def rescan_dashboard_plugins(): """Force re-scan of dashboard plugins.""" - from hermes_cli.web_server import _get_dashboard_plugins plugins = _get_dashboard_plugins(force_rescan=True) return {"ok": True, "count": len(plugins)} @@ -182,7 +187,6 @@ async def rescan_dashboard_plugins(): @router.get("/api/dashboard/plugins/hub") async def get_plugins_hub(request: Request): """Unified agent plugins + dashboard extension metadata (session protected).""" - from hermes_cli.web_server import _merged_plugins_hub, _require_token _require_token(request) try: return _merged_plugins_hub() @@ -193,11 +197,6 @@ async def get_plugins_hub(request: Request): @router.post("/api/dashboard/agent-plugins/install") async def post_agent_plugin_install(request: Request, body: _AgentPluginInstallBody): - from hermes_cli.web_server import ( - _get_dashboard_plugins, - _invalidate_plugins_hub_cache, - _require_token, - ) _require_token(request) from hermes_cli.plugins_cmd import dashboard_install_plugin @@ -228,7 +227,6 @@ def _validate_plugin_name(name: str) -> str: @router.post("/api/dashboard/agent-plugins/{name:path}/enable") async def post_agent_plugin_enable(request: Request, name: str): - from hermes_cli.web_server import _invalidate_plugins_hub_cache, _require_token _require_token(request) name = _validate_plugin_name(name) from hermes_cli.plugins_cmd import dashboard_set_agent_plugin_enabled @@ -242,7 +240,6 @@ async def post_agent_plugin_enable(request: Request, name: str): @router.post("/api/dashboard/agent-plugins/{name:path}/disable") async def post_agent_plugin_disable(request: Request, name: str): - from hermes_cli.web_server import _invalidate_plugins_hub_cache, _require_token _require_token(request) name = _validate_plugin_name(name) from hermes_cli.plugins_cmd import dashboard_set_agent_plugin_enabled @@ -256,11 +253,6 @@ async def post_agent_plugin_disable(request: Request, name: str): @router.post("/api/dashboard/agent-plugins/{name:path}/update") async def post_agent_plugin_update(request: Request, name: str): - from hermes_cli.web_server import ( - _get_dashboard_plugins, - _invalidate_plugins_hub_cache, - _require_token, - ) _require_token(request) name = _validate_plugin_name(name) from hermes_cli.plugins_cmd import dashboard_update_user_plugin @@ -275,11 +267,6 @@ async def post_agent_plugin_update(request: Request, name: str): @router.delete("/api/dashboard/agent-plugins/{name:path}") async def delete_agent_plugin(request: Request, name: str): - from hermes_cli.web_server import ( - _get_dashboard_plugins, - _invalidate_plugins_hub_cache, - _require_token, - ) _require_token(request) name = _validate_plugin_name(name) from hermes_cli.plugins_cmd import dashboard_remove_user_plugin @@ -295,13 +282,7 @@ async def delete_agent_plugin(request: Request, name: str): @router.put("/api/dashboard/plugin-providers") async def put_plugin_providers(request: Request, body: _PluginProvidersPutBody): """Persist memory provider / context engine selection (writes config.yaml).""" - from hermes_cli.web_server import ( - _CONFIG_MUTATION_LOCK, - _invalidate_plugins_hub_cache, - _normalize_memory_provider_name, - _require_memory_provider_ready, - _require_token, - ) + from hermes_cli.web_server import _CONFIG_MUTATION_LOCK _require_token(request) from hermes_cli.plugins_cmd import ( _save_context_engine, @@ -325,13 +306,7 @@ async def put_plugin_providers(request: Request, body: _PluginProvidersPutBody): @router.post("/api/dashboard/plugins/{name:path}/visibility") async def post_plugin_visibility(request: Request, name: str, body: _PluginVisibilityBody): """Toggle a plugin's sidebar visibility (persists to config.yaml dashboard.hidden_plugins).""" - from hermes_cli.web_server import ( - _CONFIG_MUTATION_LOCK, - _invalidate_plugins_hub_cache, - _require_token, - load_config, - save_config, - ) + from hermes_cli.web_server import _CONFIG_MUTATION_LOCK _require_token(request) name = _validate_plugin_name(name) @@ -378,7 +353,6 @@ async def serve_plugin_asset(plugin_name: str, file_path: str): User plugins must be in plugins.enabled before their assets are served. (#46435, GHSA-mcfc-hp25-cjv7) """ - from hermes_cli.web_server import _get_dashboard_plugins plugins = _get_dashboard_plugins() plugin = next((p for p in plugins if p["name"] == plugin_name), None) if not plugin: diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py index 9ef3b7c19b..c91b3d9949 100644 --- a/hermes_cli/web_routers/files.py +++ b/hermes_cli/web_routers/files.py @@ -18,6 +18,7 @@ import subprocess import sys from datetime import datetime from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import File, Form, HTTPException, Request, UploadFile from fastapi.responses import FileResponse from hermes_cli._subprocess_compat import windows_hide_flags @@ -27,6 +28,15 @@ from typing import Any, Dict, Optional router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_fs_path = late("_fs_path") +_managed_file_entry = late("_managed_file_entry") +_managed_response_meta = late("_managed_response_meta") +_profile_scope = late("_profile_scope") +_resolve_managed_path = late("_resolve_managed_path") +get_hermes_home = late("get_hermes_home") +load_config = late("load_config") + # Directory names whose entire subtree is credential material. Both canonical # guards deny these as directory trees, not basenames: @@ -175,7 +185,6 @@ def _fs_looks_binary(data: bytes) -> bool: def _fs_regular_file(path: Path) -> tuple[Path, os.stat_result]: - from hermes_cli.web_server import _fs_path target = _fs_path(str(path)) try: st = target.stat() @@ -210,7 +219,6 @@ def _fs_find_git_root(start: Path) -> str | None: def _fs_default_cwd() -> str: - from hermes_cli.web_server import load_config cfg_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"}: @@ -251,7 +259,6 @@ def _media_serve_roots() -> list[Path]: key or a screenshot outside the cache) merely because the suffix passes the allowlist. """ - from hermes_cli.web_server import get_hermes_home home = get_hermes_home() roots = [home / "images", home / "screenshots", home / "cache"] out: list[Path] = [] @@ -381,7 +388,6 @@ 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, get_hermes_home def _run(): data, mime_type, ext = _decode_chat_image_upload(payload) with _profile_scope(profile) as scoped_home: @@ -422,11 +428,6 @@ async def upload_chat_image(payload: ChatImageUpload, profile: Optional[str] = N @router.get("/api/files") async def list_managed_files(request: Request, path: Optional[str] = None): - from hermes_cli.web_server import ( - _managed_file_entry, - _managed_response_meta, - _resolve_managed_path, - ) policy, target, display_path = _resolve_managed_path(path, request) if not target.exists(): raise HTTPException(status_code=404, detail="Path not found") @@ -460,11 +461,7 @@ async def list_managed_files(request: Request, path: Optional[str] = None): @router.get("/api/files/read") async def read_managed_file(request: Request, path: str): - from hermes_cli.web_server import ( - _MANAGED_FILE_MAX_BYTES, - _managed_response_meta, - _resolve_managed_path, - ) + from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES policy, target, display_path = _resolve_managed_path(path, request) if not target.exists(): raise HTTPException(status_code=404, detail="File not found") @@ -506,11 +503,7 @@ def _managed_file_response( media_only: bool = False, ) -> FileResponse: """Build a range-aware response after applying managed-file policy.""" - from hermes_cli.web_server import ( - _MANAGED_FILE_MAX_BYTES, - _STREAMABLE_MEDIA_EXTENSIONS, - _resolve_managed_path, - ) + from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES, _STREAMABLE_MEDIA_EXTENSIONS policy, target, _display_path = _resolve_managed_path(path, request) if not target.exists(): raise HTTPException(status_code=404, detail="File not found") @@ -585,11 +578,6 @@ async def stream_managed_file(request: Request, path: str): @router.post("/api/files/upload") async def upload_managed_file(payload: ManagedFileUpload, request: Request): - from hermes_cli.web_server import ( - _managed_file_entry, - _managed_response_meta, - _resolve_managed_path, - ) policy, target, display_path = _resolve_managed_path(payload.path, request, for_write=True) if target.exists() and target.is_dir(): raise HTTPException(status_code=409, detail="A directory already exists at that path") @@ -620,13 +608,7 @@ async def upload_managed_file_stream( path: str = Form(...), overwrite: bool = Form(True), ): - from hermes_cli.web_server import ( - _MANAGED_FILE_MAX_BYTES, - _UPLOAD_CHUNK_BYTES, - _managed_file_entry, - _managed_response_meta, - _resolve_managed_path, - ) + from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES, _UPLOAD_CHUNK_BYTES policy, target, display_path = _resolve_managed_path(path, request, for_write=True) if target.exists() and target.is_dir(): raise HTTPException(status_code=409, detail="A directory already exists at that path") @@ -686,11 +668,6 @@ async def upload_managed_file_stream( @router.post("/api/files/mkdir") async def create_managed_directory(payload: ManagedDirectoryCreate, request: Request): - from hermes_cli.web_server import ( - _managed_file_entry, - _managed_response_meta, - _resolve_managed_path, - ) policy, target, display_path = _resolve_managed_path(payload.path, request, for_write=True) if target.exists() and not target.is_dir(): raise HTTPException(status_code=409, detail="A file already exists at that path") @@ -712,7 +689,6 @@ 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 policy, 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") @@ -738,7 +714,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 + from hermes_cli.web_server import _FS_READDIR_HIDDEN target = _fs_path(path) try: entries = [] @@ -765,7 +741,6 @@ async def fs_list(path: str): @router.get("/api/fs/read-text") async def fs_read_text(path: str): - from hermes_cli.web_server import _fs_path target, st = _fs_regular_file(_fs_path(path)) if st.st_size > _FS_TEXT_SOURCE_MAX_BYTES: raise HTTPException(status_code=413, detail="File too large") @@ -800,7 +775,6 @@ 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 target = _fs_path(payload.path) text = payload.content or "" if len(text.encode("utf-8")) > _FS_TEXT_WRITE_MAX_BYTES: @@ -838,7 +812,7 @@ async def fs_write_text(payload: FsWriteText): @router.get("/api/fs/read-data-url") async def fs_read_data_url(path: str): - from hermes_cli.web_server import _FS_DATA_URL_MAX_BYTES, _fs_path + from hermes_cli.web_server import _FS_DATA_URL_MAX_BYTES target, st = _fs_regular_file(_fs_path(path)) if st.st_size > _FS_DATA_URL_MAX_BYTES: raise HTTPException(status_code=413, detail="File too large") @@ -853,7 +827,6 @@ async def fs_read_data_url(path: str): @router.get("/api/fs/download") async def fs_download(path: str): - from hermes_cli.web_server import _fs_path target, _st = _fs_regular_file(_fs_path(path)) if _is_sensitive_path(target): raise HTTPException(status_code=403, detail="Access to sensitive files is not allowed") @@ -867,7 +840,6 @@ async def fs_download(path: str): @router.get("/api/fs/git-root") async def fs_git_root(path: str): - from hermes_cli.web_server import _fs_path target = _fs_path(path) try: st = target.stat() diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.py index 922730cceb..841856c0e8 100644 --- a/hermes_cli/web_routers/memory_providers.py +++ b/hermes_cli/web_routers/memory_providers.py @@ -10,6 +10,7 @@ import re import shlex import asyncio from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException from hermes_cli.web_models import MemoryProviderConfigUpdate, MemoryProviderSetupRequest from plugins.memory.config_schema import get_provider_config_schema @@ -18,11 +19,38 @@ from typing import Any, Dict, List, Optional _log = logging.getLogger("hermes_cli.web_server") router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_coerce_bool = late("_coerce_bool") +_command_result = late("_command_result") +_declared_provider_payload = late("_declared_provider_payload") +_discover_memory_provider_statuses = late("_discover_memory_provider_statuses") +_field_default = late("_field_default") +_field_is_set = late("_field_is_set") +_field_value = late("_field_value") +_field_visible = late("_field_visible") +_install_memory_provider_pip_dependencies = late("_install_memory_provider_pip_dependencies") +_invalidate_plugins_hub_cache = late("_invalidate_plugins_hub_cache") +_load_memory_provider = late("_load_memory_provider") +_memory_provider_label = late("_memory_provider_label") +_memory_provider_manifest = late("_memory_provider_manifest") +_memory_provider_setup_info = late("_memory_provider_setup_info") +_memory_provider_setup_manifest = late("_memory_provider_setup_manifest") +_normalize_memory_provider_schema = late("_normalize_memory_provider_schema") +_profile_scope = late("_profile_scope") +_read_memory_provider_existing_values = late("_read_memory_provider_existing_values") +_require_memory_provider_ready = late("_require_memory_provider_ready") +_run_setup_command = late("_run_setup_command") +_stringify_submitted_values = late("_stringify_submitted_values") +_update_memory_provider_config = late("_update_memory_provider_config") +get_hermes_home = late("get_hermes_home") +load_config = late("load_config") +save_config = late("save_config") +save_env_value = late("save_env_value") + def _install_memory_provider_external_dependencies( dependencies: List[Dict[str, str]], ) -> List[Dict[str, Any]]: - from hermes_cli.web_server import _command_result, _run_setup_command results: List[Dict[str, Any]] = [] for dep in dependencies: name = dep.get("name") or "dependency" @@ -132,14 +160,6 @@ def _install_memory_provider_external_dependencies( def _install_memory_provider_setup(name: str) -> Dict[str, Any]: - from hermes_cli.web_server import ( - _command_result, - _discover_memory_provider_statuses, - _install_memory_provider_pip_dependencies, - _load_memory_provider, - _memory_provider_manifest, - _memory_provider_setup_manifest, - ) provider = _load_memory_provider(name) manifest = _memory_provider_manifest(name) if provider is None and not manifest: @@ -172,7 +192,6 @@ def _install_memory_provider_setup(name: str) -> Dict[str, Any]: def _public_memory_provider_field(field: Dict[str, Any], data: Dict[str, Any]) -> Dict[str, Any]: - from hermes_cli.web_server import _field_is_set, _field_value entry = { "key": field["key"], "label": field["label"], @@ -193,12 +212,6 @@ def _public_memory_provider_field(field: Dict[str, Any], data: Dict[str, Any]) - def _memory_provider_payload(name: str, provider: Any) -> Dict[str, Any]: - from hermes_cli.web_server import ( - _memory_provider_label, - _memory_provider_setup_info, - _normalize_memory_provider_schema, - _read_memory_provider_existing_values, - ) data = _read_memory_provider_existing_values(name) fields = [ _public_memory_provider_field(field, data) @@ -213,7 +226,6 @@ def _memory_provider_payload(name: str, provider: Any) -> Dict[str, Any]: def _coerce_schema_field(field: Dict[str, Any], raw: Any) -> Any: - from hermes_cli.web_server import _coerce_bool, _field_default if field["kind"] == "boolean": return _coerce_bool(raw, default=_coerce_bool(_field_default(field), default=False)) @@ -255,7 +267,6 @@ def _coerce_schema_field(field: Dict[str, Any], raw: Any) -> Any: def _save_memory_provider_native_config(name: str, provider: Any, values: Dict[str, Any]) -> None: - from hermes_cli.web_server import get_hermes_home, load_config, save_config if provider is not None and hasattr(provider, "save_config"): try: from agent.memory_provider import MemoryProvider as _BaseMemoryProvider @@ -284,13 +295,6 @@ def _write_memory_provider_config_values( provider: Any, values: Dict[str, Any], ) -> None: - from hermes_cli.web_server import ( - _field_default, - _field_visible, - _normalize_memory_provider_schema, - _read_memory_provider_existing_values, - save_env_value, - ) existing = _read_memory_provider_existing_values(name) fields = _normalize_memory_provider_schema(name, provider) fields_by_key = {field["key"]: field for field in fields} @@ -337,12 +341,6 @@ def _require_valid_memory_provider_name(name: str) -> None: @router.get("/api/memory/providers/{name}/config") async def get_memory_provider_config(name: str, surface: Optional[str] = None, profile: Optional[str] = None): - from hermes_cli.web_server import ( - _declared_provider_payload, - _load_memory_provider, - _memory_provider_setup_info, - _profile_scope, - ) _require_valid_memory_provider_name(name) def _run(): @@ -367,11 +365,6 @@ async def get_memory_provider_config(name: str, surface: Optional[str] = None, p @router.post("/api/memory/providers/{name}/setup") async def setup_memory_provider(name: str, body: MemoryProviderSetupRequest): - from hermes_cli.web_server import ( - _invalidate_plugins_hub_cache, - _load_memory_provider, - _memory_provider_manifest, - ) _require_valid_memory_provider_name(name) provider = _load_memory_provider(name) if provider is None and not _memory_provider_manifest(name): @@ -396,16 +389,6 @@ async def setup_memory_provider(name: str, body: MemoryProviderSetupRequest): async def update_memory_provider_config( name: str, body: MemoryProviderConfigUpdate, surface: Optional[str] = None, profile: Optional[str] = None ): - from hermes_cli.web_server import ( - _invalidate_plugins_hub_cache, - _load_memory_provider, - _profile_scope, - _require_memory_provider_ready, - _stringify_submitted_values, - _update_memory_provider_config, - load_config, - save_config, - ) _require_valid_memory_provider_name(name) values = body.values or {} diff --git a/hermes_cli/web_routers/messaging.py b/hermes_cli/web_routers/messaging.py index 30ffe6eebd..a1488403e6 100644 --- a/hermes_cli/web_routers/messaging.py +++ b/hermes_cli/web_routers/messaging.py @@ -15,6 +15,7 @@ import time import urllib.parse from datetime import datetime, timezone from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException from hermes_cli._subprocess_compat import windows_hide_flags from hermes_cli.config import get_env_path @@ -25,6 +26,27 @@ from typing import Any, Optional _log = logging.getLogger("hermes_cli.web_server") router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_catalog_lookup = late("_catalog_lookup") +_config_profile_scope = late("_config_profile_scope") +_gateway_display_command = late("_gateway_display_command") +_messaging_platform_catalog = late("_messaging_platform_catalog") +_messaging_platform_payload = late("_messaging_platform_payload") +_profile_scope = late("_profile_scope") +_resolve_profile_dir = late("_resolve_profile_dir") +_restart_gateway_after_whatsapp_onboarding = late("_restart_gateway_after_whatsapp_onboarding") +_spawn_gateway_restart = late("_spawn_gateway_restart") +_telegram_onboarding_error_message = late("_telegram_onboarding_error_message") +_telegram_onboarding_request_sync = late("_telegram_onboarding_request_sync") +_validate_messaging_env_value = late("_validate_messaging_env_value") +_whatsapp_onboarding_payload = late("_whatsapp_onboarding_payload") +_whatsapp_session_path = late("_whatsapp_session_path") +_write_platform_enabled = late("_write_platform_enabled") +load_env = late("load_env") +read_runtime_status = late("read_runtime_status") +remove_env_value = late("remove_env_value") +save_env_value = late("save_env_value") + _WHATSAPP_ONBOARDING_TTL_SECONDS = 600 @@ -330,13 +352,7 @@ def _supersede_whatsapp_onboarding_sessions(session_path: Path) -> None: @router.post("/api/messaging/whatsapp/onboarding/start") async def start_whatsapp_onboarding(body: WhatsAppOnboardingStart): - from hermes_cli.web_server import ( - _WhatsAppOnboardingSession, - _config_profile_scope, - _whatsapp_onboarding_payload, - _whatsapp_onboarding_sessions, - _whatsapp_session_path, - ) + from hermes_cli.web_server import _WhatsAppOnboardingSession, _whatsapp_onboarding_sessions mode = _normalize_whatsapp_onboarding_mode(body.mode) allowed_users = _normalize_whatsapp_allowed_users(body.allowed_users) effective_profile = body.profile @@ -394,7 +410,7 @@ async def start_whatsapp_onboarding(body: WhatsAppOnboardingStart): @router.get("/api/messaging/whatsapp/onboarding/{pairing_id}") async def get_whatsapp_onboarding_status(pairing_id: str): - from hermes_cli.web_server import _whatsapp_onboarding_payload, _whatsapp_onboarding_sessions + from hermes_cli.web_server import _whatsapp_onboarding_sessions with _whatsapp_onboarding_lock: _prune_whatsapp_onboarding_sessions() record = _whatsapp_onboarding_sessions.get(pairing_id) @@ -412,13 +428,7 @@ async def get_whatsapp_onboarding_status(pairing_id: str): async def apply_whatsapp_onboarding( pairing_id: str, body: WhatsAppOnboardingApply, profile: Optional[str] = None ): - from hermes_cli.web_server import ( - _config_profile_scope, - _restart_gateway_after_whatsapp_onboarding, - _whatsapp_onboarding_sessions, - _write_platform_enabled, - save_env_value, - ) + from hermes_cli.web_server import _whatsapp_onboarding_sessions with _whatsapp_onboarding_lock: _prune_whatsapp_onboarding_sessions() record = _whatsapp_onboarding_sessions.get(pairing_id) @@ -520,7 +530,6 @@ 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 return await asyncio.to_thread( _telegram_onboarding_request_sync, method, @@ -575,11 +584,7 @@ async def start_telegram_onboarding(body: TelegramOnboardingStart): @router.get("/api/messaging/telegram/onboarding/{pairing_id}") async def get_telegram_onboarding_status(pairing_id: str): - from hermes_cli.web_server import ( - _telegram_onboarding_error_message, - _telegram_onboarding_lock, - _telegram_onboarding_pairings, - ) + from hermes_cli.web_server import _telegram_onboarding_lock, _telegram_onboarding_pairings with _telegram_onboarding_lock: _prune_telegram_onboarding_pairings() record = _telegram_onboarding_pairings.get(pairing_id) @@ -660,7 +665,6 @@ def _restart_gateway_after_telegram_onboarding(profile: Optional[str] = None) -> broken from the chat side. Keep the config save authoritative, but report restart failures so the UI can fall back to the existing manual banner. """ - from hermes_cli.web_server import _spawn_gateway_restart try: proc, reused = _spawn_gateway_restart(profile) except Exception as exc: @@ -685,13 +689,7 @@ def _restart_gateway_after_telegram_onboarding(profile: Optional[str] = None) -> async def apply_telegram_onboarding( pairing_id: str, body: TelegramOnboardingApply, profile: Optional[str] = None ): - from hermes_cli.web_server import ( - _profile_scope, - _telegram_onboarding_lock, - _telegram_onboarding_pairings, - _write_platform_enabled, - save_env_value, - ) + from hermes_cli.web_server import _telegram_onboarding_lock, _telegram_onboarding_pairings allowed_user_ids = [] seen = set() for raw_id in body.allowed_user_ids: @@ -776,14 +774,6 @@ async def get_messaging_platforms(profile: Optional[str] = None): # load_env() honors the HERMES_HOME contextvar override; the gateway # status readers do NOT (they resolve process-level paths), so the # profile directory is passed explicitly for those (#71211). - from hermes_cli.web_server import ( - _gateway_display_command, - _messaging_platform_catalog, - _messaging_platform_payload, - _profile_scope, - load_env, - read_runtime_status, - ) def _run(): with _profile_scope(profile) as scoped_dir: env_on_disk = load_env() @@ -826,7 +816,6 @@ def _multiplex_port_binding_conflict( *enabling* is blocked; disabling/clearing stays allowed so users can repair an already-invalid profile. """ - from hermes_cli.web_server import _config_profile_scope, _resolve_profile_dir from gateway.config import PORT_BINDING_PLATFORM_VALUES, load_gateway_config if platform_id not in PORT_BINDING_PLATFORM_VALUES: @@ -866,14 +855,6 @@ def _multiplex_port_binding_conflict( async def update_messaging_platform( platform_id: str, body: MessagingPlatformUpdate, profile: Optional[str] = None ): - from hermes_cli.web_server import ( - _catalog_lookup, - _profile_scope, - _validate_messaging_env_value, - _write_platform_enabled, - remove_env_value, - save_env_value, - ) entry = _catalog_lookup(platform_id) if not entry: raise HTTPException( @@ -943,13 +924,6 @@ async def update_messaging_platform( @router.post("/api/messaging/platforms/{platform_id}/test") async def test_messaging_platform(platform_id: str, profile: Optional[str] = None): - from hermes_cli.web_server import ( - _catalog_lookup, - _messaging_platform_payload, - _profile_scope, - load_env, - read_runtime_status, - ) entry = _catalog_lookup(platform_id) if not entry: raise HTTPException( diff --git a/hermes_cli/web_routers/models.py b/hermes_cli/web_routers/models.py index 608a312bd4..2e3338c2d6 100644 --- a/hermes_cli/web_routers/models.py +++ b/hermes_cli/web_routers/models.py @@ -7,6 +7,7 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o import logging import asyncio from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException from hermes_cli.web_models import ModelAssignment, MoaModelSlot, MoaPresetPayload, MoaConfigPayload from typing import Optional @@ -14,6 +15,15 @@ from typing import Optional _log = logging.getLogger("hermes_cli.web_server") router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_apply_model_assignment_sync = late("_apply_model_assignment_sync") +_config_profile_scope = late("_config_profile_scope") +_dashboard_code_skew_guard = late("_dashboard_code_skew_guard") +_profile_scope = late("_profile_scope") +load_config = late("load_config") +run_in_threadpool = late("run_in_threadpool") +save_config = late("save_config") + @router.get("/api/model/info") def get_model_info(profile: Optional[str] = None): @@ -23,7 +33,7 @@ def get_model_info(profile: Optional[str] = None): frontend can display "Auto-detected: 200K" alongside the override field. Also returns model capabilities (vision, reasoning, tools) when available. """ - from hermes_cli.web_server import _EMPTY_MODEL_INFO, _profile_scope, load_config + from hermes_cli.web_server import _EMPTY_MODEL_INFO try: with _profile_scope(profile): cfg = load_config() @@ -120,11 +130,6 @@ async def get_model_options( re-fetches its live catalog — used by the picker's explicit "Refresh Models" control. Normal opens leave it false to stay on the 1h cache. """ - from hermes_cli.web_server import ( - _config_profile_scope, - _dashboard_code_skew_guard, - run_in_threadpool, - ) try: skew_msg = _dashboard_code_skew_guard() if skew_msg: @@ -267,7 +272,7 @@ def get_auxiliary_models(profile: Optional[str] = None): the dashboard profile's auxiliary pins while /api/model/set wrote the selected profile's (read/write asymmetry). """ - from hermes_cli.web_server import _AUX_TASK_SLOTS, _profile_scope, load_config + from hermes_cli.web_server import _AUX_TASK_SLOTS try: with _profile_scope(profile): cfg = load_config() @@ -305,7 +310,6 @@ def get_auxiliary_models(profile: Optional[str] = None): @router.get("/api/model/moa") def get_moa_models(profile: Optional[str] = None): """Return the configured Mixture-of-Agents provider/model slots.""" - from hermes_cli.web_server import _profile_scope, load_config try: from hermes_cli.moa_config import normalize_moa_config @@ -322,7 +326,6 @@ def get_moa_models(profile: Optional[str] = None): @router.put("/api/model/moa") def set_moa_models(body: MoaConfigPayload, profile: Optional[str] = None): """Persist the Mixture-of-Agents provider/model slots.""" - from hermes_cli.web_server import _profile_scope, load_config, save_config try: from hermes_cli.moa_config import normalize_moa_config, validate_moa_payload @@ -402,7 +405,6 @@ async def set_model_assignment(body: ModelAssignment, profile: Optional[str] = N The 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 scope = (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.py index f37feba229..cbd97dd66d 100644 --- a/hermes_cli/web_routers/oauth.py +++ b/hermes_cli/web_routers/oauth.py @@ -9,6 +9,7 @@ import asyncio import sys import time from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import HTTPException, Request from hermes_cli.web_models import OAuthSubmitBody from typing import Any, Dict, Optional @@ -16,6 +17,15 @@ from typing import Any, Dict, Optional _log = logging.getLogger("hermes_cli.web_server") router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_external_process_cli_command = late("_external_process_cli_command") +_oauth_profile_name = late("_oauth_profile_name") +_profile_scope = late("_profile_scope") +_require_token = late("_require_token") +_resolve_profile_dir = late("_resolve_profile_dir") +_resolve_provider_status = late("_resolve_provider_status") +_start_device_code_flow = late("_start_device_code_flow") + def _oauth_provider_disconnect_command(provider: Dict[str, Any]) -> Optional[str]: """Shell command that clears an external provider's credentials. @@ -137,7 +147,6 @@ async def list_oauth_providers(profile: Optional[str] = None): sync with the `hermes model` picker; _OAUTH_OVERRIDES supplies per-provider flow/status/cli metadata. """ - from hermes_cli.web_server import _external_process_cli_command, _profile_scope, _resolve_provider_status def _run(): with _profile_scope(profile): providers = [] @@ -167,7 +176,6 @@ 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 _require_token(request) def _run(): @@ -277,7 +285,6 @@ def _gc_oauth_sessions() -> None: def _validate_oauth_profile(profile: Optional[str]) -> None: - from hermes_cli.web_server import _oauth_profile_name, _resolve_profile_dir profile_name = _oauth_profile_name(profile) if profile_name: _resolve_profile_dir(profile_name) @@ -290,11 +297,7 @@ async def start_oauth_login( profile: Optional[str] = None, ): """Initiate an OAuth login flow. Token-protected.""" - from hermes_cli.web_server import ( - _OAUTH_PROVIDER_CATALOG, - _require_token, - _start_device_code_flow, - ) + from hermes_cli.web_server import _OAUTH_PROVIDER_CATALOG _require_token(request) _gc_oauth_sessions() _validate_oauth_profile(profile) @@ -326,7 +329,6 @@ async def submit_oauth_code( profile: Optional[str] = None, ): """Submit the auth code for PKCE flows. Token-protected.""" - from hermes_cli.web_server import _require_token _require_token(request) raise HTTPException(status_code=400, detail=f"submit not supported for {provider_id}") @@ -343,7 +345,7 @@ async def poll_oauth_session( Each surfaces progress through the same background-worker-updated ``status`` field, so a single poll endpoint serves them all. """ - from hermes_cli.web_server import _oauth_profile_name, _oauth_sessions, _oauth_sessions_lock + from hermes_cli.web_server import _oauth_sessions, _oauth_sessions_lock _validate_oauth_profile(profile) requested_profile = _oauth_profile_name(profile) with _oauth_sessions_lock: @@ -376,12 +378,7 @@ async def cancel_oauth_session( polling/exchanging/saving instead of completing the login after the user believed it was aborted. """ - from hermes_cli.web_server import ( - _oauth_profile_name, - _oauth_sessions, - _oauth_sessions_lock, - _require_token, - ) + from hermes_cli.web_server import _oauth_sessions, _oauth_sessions_lock _require_token(request) _validate_oauth_profile(profile) requested_profile = _oauth_profile_name(profile) diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.py index 2acb3f277c..46157f57e4 100644 --- a/hermes_cli/web_routers/ops.py +++ b/hermes_cli/web_routers/ops.py @@ -13,6 +13,7 @@ import os import secrets from datetime import datetime, timezone from fastapi import APIRouter +from hermes_cli.web_deps import late from fastapi import File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse from hermes_cli.config import redact_key @@ -23,6 +24,20 @@ from typing import Any, Dict, List, Optional _log = logging.getLogger("hermes_cli.web_server") router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_discover_memory_provider_statuses = late("_discover_memory_provider_statuses") +_gateway_subcommand = late("_gateway_subcommand") +_normalize_memory_provider_name = late("_normalize_memory_provider_name") +_path_is_under = late("_path_is_under") +_require_memory_provider_ready = late("_require_memory_provider_ready") +_resolve_profile_dir = late("_resolve_profile_dir") +_restart_gateway_after_webhook_enable = late("_restart_gateway_after_webhook_enable") +_spawn_hermes_action = late("_spawn_hermes_action") +_write_platform_enabled = late("_write_platform_enabled") +get_hermes_home = late("get_hermes_home") +load_config = late("load_config") +save_config = late("save_config") + # --------------------------------------------------------------------------- # Pairing endpoints — approve / revoke / list messaging pairing codes. @@ -45,7 +60,6 @@ def _pairing_store(profile: Optional[str] = None): ``_profile_scope`` needed, and nothing process-global is swapped across the ``await`` boundary. """ - from hermes_cli.web_server import _resolve_profile_dir from gateway.pairing import PairingStore requested = (profile or "").strip() @@ -169,7 +183,6 @@ async def list_webhooks(): @router.post("/api/webhooks/enable") async def enable_webhooks(): - from hermes_cli.web_server import _restart_gateway_after_webhook_enable, _write_platform_enabled try: _write_platform_enabled("webhook", True) except Exception as exc: @@ -288,7 +301,6 @@ async def set_webhook_enabled(name: str, body: WebhookEnabledToggle): @router.post("/api/gateway/start") async def start_gateway(profile: Optional[str] = None): - from hermes_cli.web_server import _gateway_subcommand, _spawn_hermes_action try: proc = _spawn_hermes_action(_gateway_subcommand(profile, "start"), "gateway-start") except HTTPException: @@ -301,7 +313,6 @@ async def start_gateway(profile: Optional[str] = None): @router.post("/api/gateway/stop") async def stop_gateway(profile: Optional[str] = None): - from hermes_cli.web_server import _gateway_subcommand, _spawn_hermes_action try: proc = _spawn_hermes_action(_gateway_subcommand(profile, "stop"), "gateway-stop") except HTTPException: @@ -512,12 +523,6 @@ async def remove_credential_pool_entry(provider: str, index: int): async def get_memory_status(): # load_config(), file stats and provider discovery are disk reads — keep # them off the event loop. - from hermes_cli.web_server import ( - _discover_memory_provider_statuses, - _normalize_memory_provider_name, - get_hermes_home, - load_config, - ) def _run(): cfg = load_config() active = "" @@ -543,13 +548,7 @@ async def get_memory_status(): @router.put("/api/memory/provider") async def set_memory_provider(body: MemoryProviderSelect): - from hermes_cli.web_server import ( - _CONFIG_MUTATION_LOCK, - _normalize_memory_provider_name, - _require_memory_provider_ready, - load_config, - save_config, - ) + from hermes_cli.web_server import _CONFIG_MUTATION_LOCK provider = _normalize_memory_provider_name(body.provider) def _run(): @@ -568,7 +567,6 @@ async def set_memory_provider(body: MemoryProviderSelect): @router.post("/api/memory/reset") async def reset_memory(body: MemoryReset): - from hermes_cli.web_server import get_hermes_home target = (body.target or "all").strip().lower() if target not in {"all", "memory", "user"}: raise HTTPException(status_code=400, detail="target must be all, memory, or user") @@ -606,7 +604,6 @@ async def reset_memory(body: MemoryReset): @router.post("/api/ops/doctor") async def run_doctor(): - from hermes_cli.web_server import _spawn_hermes_action try: proc = _spawn_hermes_action(["doctor"], "doctor") except Exception as exc: @@ -617,7 +614,6 @@ async def run_doctor(): @router.post("/api/ops/security-audit") async def run_security_audit(): - from hermes_cli.web_server import _spawn_hermes_action try: proc = _spawn_hermes_action(["security", "audit"], "security-audit") except Exception as exc: @@ -627,7 +623,6 @@ async def run_security_audit(): def _dashboard_backup_dir() -> Path: - from hermes_cli.web_server import get_hermes_home return get_hermes_home() / "backups" @@ -638,7 +633,6 @@ def _new_dashboard_backup_path() -> Path: @router.post("/api/ops/backup") async def run_backup(body: BackupRequest): - from hermes_cli.web_server import _spawn_hermes_action args = ["backup"] archive: Optional[Path] = None output = (body.output or "").strip() @@ -667,7 +661,6 @@ async def run_backup(body: BackupRequest): @router.get("/api/ops/backup/download") async def download_dashboard_backup(archive: str): - from hermes_cli.web_server import _path_is_under try: backup_dir = _dashboard_backup_dir().expanduser().resolve(strict=False) target = Path(archive).expanduser().resolve(strict=True) @@ -691,7 +684,6 @@ 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 archive = (body.archive or "").strip() if not archive: raise HTTPException(status_code=400, detail="archive path is required") @@ -723,11 +715,7 @@ async def run_import_upload( file: UploadFile = File(...), force: bool = Form(False), ): - from hermes_cli.web_server import ( - _MANAGED_FILE_MAX_BYTES, - _UPLOAD_CHUNK_BYTES, - _spawn_hermes_action, - ) + from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES, _UPLOAD_CHUNK_BYTES staging_dir = _dashboard_backup_dir() try: staging_dir.mkdir(parents=True, exist_ok=True) @@ -861,7 +849,7 @@ async def create_hook(body: HookCreate): consent in the allowlist so the hook actually fires. Takes effect on the next session / gateway restart. """ - from hermes_cli.web_server import _CONFIG_MUTATION_LOCK, load_config, save_config + from hermes_cli.web_server import _CONFIG_MUTATION_LOCK from agent import shell_hooks event = (body.event or "").strip() @@ -917,7 +905,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, load_config, save_config + from hermes_cli.web_server import _CONFIG_MUTATION_LOCK from agent import shell_hooks event = (body.event or "").strip() @@ -960,7 +948,6 @@ 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 # Checkpoints live under /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 stays @@ -994,7 +981,6 @@ async def list_checkpoints(): @router.post("/api/ops/checkpoints/prune") async def prune_checkpoints(): - from hermes_cli.web_server import _spawn_hermes_action try: proc = _spawn_hermes_action(["checkpoints", "prune"], "checkpoints-prune") except Exception as exc: diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py index 85f39a6794..38dee79846 100644 --- a/hermes_cli/web_routers/status.py +++ b/hermes_cli/web_routers/status.py @@ -12,6 +12,7 @@ import os import sys import time from fastapi import APIRouter +from hermes_cli.web_deps import LateState, late from fastapi import HTTPException, Request from gateway.status import derive_gateway_busy, derive_gateway_drainable, normalize_updated_at, parse_active_agents, resolve_gateway_liveness from hermes_cli import __version__, __release_date__ @@ -25,10 +26,34 @@ router = APIRouter() # Mounted separately by web_server so /api/logs keeps its original route-table position. logs_router = APIRouter() +# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative. +_collect_profile_gateway_topology_cached = late("_collect_profile_gateway_topology_cached") +_config_profile_scope = late("_config_profile_scope") +_dashboard_local_update_managed_externally = late("_dashboard_local_update_managed_externally") +_display_system_platform = late("_display_system_platform") +_load_configured_gateway_platforms = late("_load_configured_gateway_platforms") +_probe_gateway_health = late("_probe_gateway_health") +_profile_scope = late("_profile_scope") +_require_token = late("_require_token") +_resolve_profile_dir = late("_resolve_profile_dir") +_resolve_restart_drain_timeout = late("_resolve_restart_drain_timeout") +_spawn_hermes_action = late("_spawn_hermes_action") +_ssh_runtime_intact = late("_ssh_runtime_intact") +_status_active_sessions = late("_status_active_sessions") +app = LateState("app") # the FastAPI instance (app.state.*) +check_config_version = late("check_config_version") +get_hermes_home = late("get_hermes_home") +get_install_id = late("get_install_id") +get_running_pid_cached = late("get_running_pid_cached") +get_runtime_status_running_pid = late("get_runtime_status_running_pid") +load_config = late("load_config") +read_runtime_status = late("read_runtime_status") +run_in_threadpool = late("run_in_threadpool") + @router.get("/api/ssh/ownership") async def get_ssh_ownership(request: Request): - from hermes_cli.web_server import _SSH_OWNER_NONCE, _require_token, _ssh_runtime_intact + from hermes_cli.web_server import _SSH_OWNER_NONCE _require_token(request) if not _SSH_OWNER_NONCE: raise HTTPException(status_code=404, detail="SSH ownership is not active") @@ -43,7 +68,6 @@ async def get_ssh_ownership(request: Request): @router.get("/api/health") async def get_health(): """Lightweight process liveness for desktop/backend readiness probes.""" - from hermes_cli.web_server import app return { "ok": True, "version": __version__, @@ -138,22 +162,6 @@ async def get_status(profile: Optional[str] = None): DASHBOARD_HEALTH, _GATEWAY_HEALTH_ROUTE_TIMEOUT, _GATEWAY_HEALTH_URL, - _collect_profile_gateway_topology_cached, - _config_profile_scope, - _dashboard_local_update_managed_externally, - _load_configured_gateway_platforms, - _probe_gateway_health, - _resolve_profile_dir, - _resolve_restart_drain_timeout, - _status_active_sessions, - app, - check_config_version, - get_hermes_home, - get_install_id, - get_running_pid_cached, - get_runtime_status_running_pid, - read_runtime_status, - run_in_threadpool, ) status_scope = None requested_profile = (profile or "").strip() @@ -572,7 +580,6 @@ async def get_system_stats(): psutil when available, with graceful degradation when it isn't. Read-only and non-sensitive (no env values, no paths beyond the hermes home root). """ - from hermes_cli.web_server import _display_system_platform, get_hermes_home import platform as _platform info: Dict[str, Any] = { @@ -687,7 +694,6 @@ async def set_curator_paused(body: CuratorPause): @router.post("/api/curator/run") async def run_curator(): """Trigger a curator review now (backgrounded; tail via action status).""" - from hermes_cli.web_server import _spawn_hermes_action try: proc = _spawn_hermes_action(["curator", "run"], "curator-run") except Exception as exc: @@ -702,7 +708,6 @@ async def get_learning_graph(profile: Optional[str] = None): Profile-scoped view of learned, non-base skills plus memory chunks, with graph links derived from skill relations and memory-skill overlap. """ - from hermes_cli.web_server import _profile_scope def _run(): from agent.learning_graph import build_learning_graph @@ -721,7 +726,6 @@ 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 from agent.learning_mutations import node_detail def _run(): @@ -737,7 +741,6 @@ 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 from agent.learning_mutations import delete_node def _run(): @@ -753,7 +756,6 @@ 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 from agent.learning_mutations import edit_node def _run(): @@ -790,7 +792,6 @@ async def get_portal_status(): def _get_portal_status_sync(): - from hermes_cli.web_server import load_config cfg = load_config() or {} auth: Dict[str, Any] = {} try: @@ -841,7 +842,6 @@ def _get_portal_status_sync(): @router.post("/api/ops/prompt-size") async def run_prompt_size(): - from hermes_cli.web_server import _spawn_hermes_action try: proc = _spawn_hermes_action(["prompt-size"], "prompt-size") except Exception as exc: @@ -851,7 +851,6 @@ async def run_prompt_size(): @router.post("/api/ops/dump") async def run_dump(): - from hermes_cli.web_server import _spawn_hermes_action try: proc = _spawn_hermes_action(["dump"], "dump") except Exception as exc: @@ -861,7 +860,6 @@ async def run_dump(): @router.post("/api/ops/config-migrate") async def run_config_migrate(): - from hermes_cli.web_server import _spawn_hermes_action try: proc = _spawn_hermes_action(["config", "migrate"], "config-migrate") except Exception as exc: @@ -918,7 +916,6 @@ async def get_logs( component: Optional[str] = None, search: Optional[str] = None, ): - from hermes_cli.web_server import get_hermes_home from hermes_cli.logs import _read_tail, LOG_FILES log_name = LOG_FILES.get(file)