Skip to content

The agent that grows with you

simplify(compat): web_routers — repoint 231 web_server.<name> seams to the owning module (105 direct imports, 113 late()/LateState() with module arg, 12 lazy imports + kanban plugin _ws_auth_ok)

Teknium08bd8aea74e8
diff --git a/hermes_cli/web_routers/_common.py b/hermes_cli/web_routers/_common.py
index a32f7c3e278..1301353f5b8 100644
--- a/hermes_cli/web_routers/_common.py
+++ b/hermes_cli/web_routers/_common.py
@@ -1,6 +1,6 @@
"""Shared plumbing for the extracted dashboard routers — thin wrappers over the
late-binding seam in :mod:`hermes_cli.web_deps` (web_server owns helpers/state;
-every access resolves at call time so ``monkeypatch.setattr(web_server, ...)`` wins)."""
+every access resolves at call time so ``monkeypatch.setattr(<owning module>, ...)`` wins)."""
from __future__ import annotations
@@ -12,13 +12,13 @@ from typing import Any, Callable, Optional
from fastapi import HTTPException
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_server_profiles import _profile_cli_args
# Same logger the handlers used before extraction (identical logger object).
log = logging.getLogger("hermes_cli.web_server")
-_profile_scope = late("_profile_scope")
-_spawn_hermes_action = late("_spawn_hermes_action")
-_profile_cli_args = late("_profile_cli_args")
+_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
+_spawn_hermes_action = late("_spawn_hermes_action", "hermes_cli.web_server_gateway")
# Config read-modify-write serialization for off-loop handlers (live lock —
# LateState supports ``with``-blocks).
_CONFIG_MUTATION_LOCK = LateState("_CONFIG_MUTATION_LOCK")
diff --git a/hermes_cli/web_routers/actions.py b/hermes_cli/web_routers/actions.py
index 4251139ab26..e5026f61d22 100644
--- a/hermes_cli/web_routers/actions.py
+++ b/hermes_cli/web_routers/actions.py
@@ -19,30 +19,31 @@ from fastapi import APIRouter, HTTPException, Request
from hermes_cli import __version__
from hermes_cli.config import format_docker_update_message, recommended_update_command_for_method
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_server_gateway import _ACTION_LOG_FILES
from hermes_cli.web_routers._common import http_failure
_log = logging.getLogger("hermes_cli.web_server")
router = APIRouter()
status_router = APIRouter()
-# web_server helpers/state, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative.
-_dashboard_local_update_managed_externally = late("_dashboard_local_update_managed_externally")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_dashboard_local_update_managed_externally = late("_dashboard_local_update_managed_externally", "hermes_cli.web_server_files")
_spawn_gateway_restart = late("_spawn_gateway_restart")
-_spawn_hermes_action = late("_spawn_hermes_action")
-detect_install_method = late("detect_install_method")
-get_hermes_home = late("get_hermes_home")
-_ACTION_COMMANDS = LateState("_ACTION_COMMANDS")
-_ACTION_IDS = LateState("_ACTION_IDS")
-_ACTION_LOG_FILES = LateState("_ACTION_LOG_FILES")
-_ACTION_PROCS = LateState("_ACTION_PROCS")
-_ACTION_RESULTS = LateState("_ACTION_RESULTS")
+_spawn_hermes_action = late("_spawn_hermes_action", "hermes_cli.web_server_gateway")
+detect_install_method = late("detect_install_method", "hermes_cli.config")
+get_hermes_home = late("get_hermes_home", "hermes_cli.config")
+_ACTION_COMMANDS = LateState("_ACTION_COMMANDS", "hermes_cli.web_server_gateway")
+_ACTION_IDS = LateState("_ACTION_IDS", "hermes_cli.web_server_gateway")
+_ACTION_PROCS = LateState("_ACTION_PROCS", "hermes_cli.web_server_gateway")
+_ACTION_RESULTS = LateState("_ACTION_RESULTS", "hermes_cli.web_server_gateway")
def _server_path(name: str) -> Path:
- """Live ``web_server.<name>`` Path value (``_ACTION_LOG_DIR`` / ``PROJECT_ROOT``; plain
- values are not proxied by LateState)."""
+ """Live Path value (``_ACTION_LOG_DIR`` on web_server_gateway, ``PROJECT_ROOT`` on
+ web_server; plain values are not proxied by LateState)."""
import hermes_cli.web_server as ws
- return getattr(ws, name)
+ import hermes_cli.web_server_gateway as gw
+ return getattr(gw if name == "_ACTION_LOG_DIR" else ws, name)
_ACTION_LOG_TAIL_MAX_BYTES = 256 * 1024
diff --git a/hermes_cli/web_routers/analytics.py b/hermes_cli/web_routers/analytics.py
index 46cd3eae9d9..d3dac5f9bfc 100644
--- a/hermes_cli/web_routers/analytics.py
+++ b/hermes_cli/web_routers/analytics.py
@@ -1,7 +1,7 @@
"""Raw-YAML config and token/cost analytics dashboard routes.
-Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch on
-``web_server`` stay there and are imported lazily at call time (cycle-safe).
+Extracted from ``hermes_cli.web_server``; app state and helpers are late-bound through
+:mod:`hermes_cli.web_deps` (cycle-safe, monkeypatch-friendly).
"""
import asyncio
@@ -13,20 +13,17 @@ from fastapi import APIRouter, HTTPException, Query
from hermes_cli.config import get_config_path, read_raw_config
from hermes_cli.web_deps import late
+from hermes_cli.web_server_profiles import (
+ _approval_mode_of, _aux_task_summary, _aux_usage_rows, _broadcast_gateway_session_info, _is_other_profile, _merge_aux_into_by_model,
+)
from hermes_cli.web_models import RawConfigUpdate
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")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_open_session_db_for_profile = late("_open_session_db_for_profile", "hermes_cli.web_server_sessions")
+_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
+save_config = late("save_config", "hermes_cli.config")
# ── Raw YAML config ──────────────────────────────────────────────────────────
diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.py
index 9ba73d41260..ec49c904677 100644
--- a/hermes_cli/web_routers/audio.py
+++ b/hermes_cli/web_routers/audio.py
@@ -19,6 +19,8 @@ import urllib.request
from fastapi import APIRouter
from hermes_cli.web_routers._common import http_failure
from hermes_cli.web_deps import late
+from hermes_cli.web_server_chat import _ws_auth_ok, _ws_request_is_allowed
+from hermes_cli.web_server_gateway import _split_text_for_speak_stream
from fastapi import HTTPException, WebSocket, WebSocketDisconnect
from hermes_cli.web_models import AudioTranscriptionRequest, TTSSpeakRequest, TTSLeaseRequest
from typing import Any, Dict, Optional
@@ -26,13 +28,10 @@ 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.
-_config_profile_scope = late("_config_profile_scope")
-_split_text_for_speak_stream = late("_split_text_for_speak_stream")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
_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")
+load_env = late("load_env", "hermes_cli.config")
_AUDIO_MIME_EXTENSIONS: Dict[str, str] = {
"audio/aac": ".aac", "audio/flac": ".flac", "audio/m4a": ".m4a", "audio/mp3": ".mp3",
diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.py
index d83d6075a73..64f792d3f3f 100644
--- a/hermes_cli/web_routers/chat_ws.py
+++ b/hermes_cli/web_routers/chat_ws.py
@@ -17,23 +17,21 @@ from fastapi import APIRouter, FastAPI, HTTPException, WebSocket, WebSocketDisco
from hermes_cli.pty_session import RegistryFull
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_server_chat import (
+ _build_sidecar_url, _get_console_executor, _legacy_pump, _ws_auth_ok, _ws_request_is_allowed,
+)
_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")
-_build_sidecar_url = late("_build_sidecar_url")
-_get_console_executor = late("_get_console_executor")
-_legacy_pump = late("_legacy_pump")
-_profile_scope = late("_profile_scope")
-_resolve_chat_argv_async = late("_resolve_chat_argv_async")
-_resolve_profile_dir = late("_resolve_profile_dir")
-_ws_auth_ok = late("_ws_auth_ok")
-_ws_auth_reason = late("_ws_auth_reason")
-_ws_client_reason = late("_ws_client_reason")
-_ws_host_origin_reason = late("_ws_host_origin_reason")
-_ws_request_is_allowed = late("_ws_request_is_allowed")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_active_session_file_for_channel = late("_active_session_file_for_channel", "hermes_cli.web_server_chat")
+_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
+_resolve_chat_argv_async = late("_resolve_chat_argv_async", "hermes_cli.web_server_chat")
+_resolve_profile_dir = late("_resolve_profile_dir", "hermes_cli.web_server_profiles")
+_ws_auth_reason = late("_ws_auth_reason", "hermes_cli.web_server_chat")
+_ws_client_reason = late("_ws_client_reason", "hermes_cli.web_server_chat")
+_ws_host_origin_reason = late("_ws_host_origin_reason", "hermes_cli.web_server_chat")
_DASHBOARD_EMBEDDED_CHAT_ENABLED = LateState("_DASHBOARD_EMBEDDED_CHAT_ENABLED")
@@ -54,7 +52,8 @@ _VALID_CHANNEL_RE = re.compile(r"^[A-Za-z0-9._-]{1,128}$")
def _ws_auth_mode() -> str:
"""Short label for the active WS auth mode — logged on every connection."""
- from hermes_cli.web_server import _LOOPBACK_HOSTS, app
+ from hermes_cli.web_server_chat import _LOOPBACK_HOSTS
+ from hermes_cli.web_server import app
if getattr(app.state, "auth_required", False):
return "gated"
bound_host = (getattr(app.state, "bound_host", "") or "").strip().lower()
@@ -403,13 +402,7 @@ async def _pty_fail(ws: WebSocket, text: str) -> None:
@router.websocket("/api/pty")
async def pty_ws(ws: WebSocket) -> None:
- from hermes_cli.web_server import (
- PTY_REGISTRY,
- PtyBridge,
- PtyUnavailableError,
- _PTY_BRIDGE_AVAILABLE,
- _RESIZE_RE,
- )
+ from hermes_cli.web_server_chat import PTY_REGISTRY, PtyBridge, PtyUnavailableError, _PTY_BRIDGE_AVAILABLE, _RESIZE_RE
gate = await _ws_gate(ws, "pty")
if gate is None:
return
diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.py
index 1592cc63a38..f6ed0089610 100644
--- a/hermes_cli/web_routers/config_env.py
+++ b/hermes_cli/web_routers/config_env.py
@@ -13,6 +13,12 @@ import urllib.parse
from fastapi import APIRouter
from hermes_cli.web_routers._common import http_failure, scoped_to_thread
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_server_config import (
+ _apply_main_model_assignment, _denormalize_config_from_web, _normalize_config_for_web, _schema_with_dynamic_provider_options,
+)
+from hermes_cli.web_server_profiles import (
+ _approval_mode_of, _broadcast_gateway_session_info, _is_other_profile, _parse_model_ids,
+)
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
@@ -22,24 +28,16 @@ _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")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_channel_managed_env_keys = late("_channel_managed_env_keys", "hermes_cli.web_server_messaging")
+_config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
+_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
_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")
+load_config = late("load_config", "hermes_cli.config")
+load_env = late("load_env", "hermes_cli.config")
+remove_env_value = late("remove_env_value", "hermes_cli.config")
+save_config = late("save_config", "hermes_cli.config")
+save_env_value = late("save_env_value", "hermes_cli.config")
_CONFIG_MUTATION_LOCK = LateState("_CONFIG_MUTATION_LOCK")
# Simple rate limiter for the reveal endpoint
diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.py
index 33ba3af36e0..bb1e571735b 100644
--- a/hermes_cli/web_routers/cron.py
+++ b/hermes_cli/web_routers/cron.py
@@ -1,8 +1,8 @@
"""Cron dashboard routes.
The ``*_sync`` workers, profile resolution and the threadpool wrapper
-(``_run_cron_dashboard_io``) live in web_server and are reached through the
-late-binding seam so ``monkeypatch.setattr(web_server, ...)`` keeps working.
+(``_run_cron_dashboard_io``) live in web_server_cron and are reached through the
+late-binding seam so ``monkeypatch.setattr(web_server_cron, ...)`` keeps working.
"""
import asyncio
@@ -15,31 +15,25 @@ from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from hermes_cli.web_deps import late
+from hermes_cli.config import cfg_get
+from hermes_cli.web_server_cron import (
+ _create_cron_job_sync, _cron_optional_text, _cron_string_list, _mutate_cron_for_profile, _normalize_dashboard_cron_script, _raise_if_cron_registration_error, _run_cron_dashboard_io, _validate_dashboard_cron_context_from, _validate_dashboard_cron_effective_job,
+)
from hermes_cli.web_models import AutomationBlueprintInstantiate, CronJobCreate, CronJobUpdate
from hermes_cli.web_routers._common import log as _log
router = APIRouter()
-_run_cron_dashboard_io = late("_run_cron_dashboard_io")
-_create_cron_job_sync = late("_create_cron_job_sync")
-_find_cron_job_profile = late("_find_cron_job_profile")
-_fire_cron_job_for_profile = late("_fire_cron_job_for_profile")
-_forward_cron_fire_to_gateway = late("_forward_cron_fire_to_gateway")
-_gateway_intentionally_stopped = late("_gateway_intentionally_stopped")
-_notify_cron_provider_for_profile = late("_notify_cron_provider_for_profile")
-_call_cron_for_profile = late("_call_cron_for_profile")
-_raise_if_cron_registration_error = late("_raise_if_cron_registration_error")
-load_config = late("load_config")
-cfg_get = late("cfg_get")
-_cron_profile_dicts = late("_cron_profile_dicts")
-_cron_profile_home = late("_cron_profile_home")
-_mutate_cron_for_profile = late("_mutate_cron_for_profile")
-_open_session_db_for_profile = late("_open_session_db_for_profile")
-_validate_dashboard_cron_context_from = late("_validate_dashboard_cron_context_from")
-_validate_dashboard_cron_effective_job = late("_validate_dashboard_cron_effective_job")
-_cron_optional_text = late("_cron_optional_text")
-_cron_string_list = late("_cron_string_list")
-_normalize_dashboard_cron_script = late("_normalize_dashboard_cron_script")
+_find_cron_job_profile = late("_find_cron_job_profile", "hermes_cli.web_server_cron")
+_fire_cron_job_for_profile = late("_fire_cron_job_for_profile", "hermes_cli.web_server_cron")
+_forward_cron_fire_to_gateway = late("_forward_cron_fire_to_gateway", "hermes_cli.web_server_cron")
+_gateway_intentionally_stopped = late("_gateway_intentionally_stopped", "hermes_cli.web_server_cron")
+_notify_cron_provider_for_profile = late("_notify_cron_provider_for_profile", "hermes_cli.web_server_cron")
+_call_cron_for_profile = late("_call_cron_for_profile", "hermes_cli.web_server_cron")
+load_config = late("load_config", "hermes_cli.config")
+_cron_profile_dicts = late("_cron_profile_dicts", "hermes_cli.web_server_cron")
+_cron_profile_home = late("_cron_profile_home", "hermes_cli.web_server_cron")
+_open_session_db_for_profile = late("_open_session_db_for_profile", "hermes_cli.web_server_sessions")
def _job_not_found() -> HTTPException:
return HTTPException(status_code=404, detail="Job not found")
diff --git a/hermes_cli/web_routers/dashboard_ui.py b/hermes_cli/web_routers/dashboard_ui.py
index bdfcf0345c6..caead11fa31 100644
--- a/hermes_cli/web_routers/dashboard_ui.py
+++ b/hermes_cli/web_routers/dashboard_ui.py
@@ -13,6 +13,11 @@ from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import FileResponse
from hermes_cli.web_deps import LateState, late
+from hermes_cli.config import cfg_get
+from hermes_cli.web_server_dashboard import (
+ _BUILTIN_DASHBOARD_THEMES, _discover_user_themes, _invalidate_plugins_hub_cache, _merged_plugins_hub,
+)
+from hermes_cli.web_server_memory import _normalize_memory_provider_name, _require_memory_provider_ready
from hermes_cli.web_models import (
FontSetBody, ThemeSetBody, _AgentPluginInstallBody, _PluginProvidersPutBody, _PluginVisibilityBody,
)
@@ -20,18 +25,11 @@ from hermes_cli.web_models import (
_log = logging.getLogger("hermes_cli.web_server")
router = APIRouter()
-# web_server helpers/state, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative.
-_discover_user_themes = late("_discover_user_themes")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
_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")
-_BUILTIN_DASHBOARD_THEMES = LateState("_BUILTIN_DASHBOARD_THEMES")
+load_config = late("load_config", "hermes_cli.config")
+save_config = late("save_config", "hermes_cli.config")
_CONFIG_MUTATION_LOCK = LateState("_CONFIG_MUTATION_LOCK")
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index de2a3b8659a..5b5de6adb6a 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -26,22 +26,19 @@ from fastapi.responses import FileResponse
from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_cli.web_deps import late
+from hermes_cli.web_server_files import (
+ _fs_path, _managed_file_entry, _managed_response_meta, _resolve_managed_path,
+)
from hermes_cli.web_models import (
ChatImageUpload, FsWriteText, ManagedDirectoryCreate, ManagedFileDelete, ManagedFileUpload,
)
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")
-
-
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
+get_hermes_home = late("get_hermes_home", "hermes_cli.config")
+load_config = late("load_config", "hermes_cli.config")
# Image types GET /api/media serves — extension-allowlisted so an authenticated
# caller can't pull non-image files through it.
_MEDIA_CONTENT_TYPES = {
diff --git a/hermes_cli/web_routers/git.py b/hermes_cli/web_routers/git.py
index b775cc066f4..a8bbe0ea5d0 100644
--- a/hermes_cli/web_routers/git.py
+++ b/hermes_cli/web_routers/git.py
@@ -16,6 +16,7 @@ from fastapi import APIRouter, HTTPException
from hermes_cli import web_git as _web_git
from hermes_cli.web_deps import late
+from hermes_cli.web_server_files import _fs_path
from hermes_cli.web_models import (
GitBranchSwitchBody,
GitCommitBody,
@@ -28,8 +29,7 @@ from hermes_cli.web_models import (
router = APIRouter()
-# web_server helper, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative.
-_fs_path = late("_fs_path")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
async def _git_op(fn, *args):
diff --git a/hermes_cli/web_routers/mcp.py b/hermes_cli/web_routers/mcp.py
index 52116784832..3308d68e1de 100644
--- a/hermes_cli/web_routers/mcp.py
+++ b/hermes_cli/web_routers/mcp.py
@@ -17,6 +17,7 @@ from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_server_mcp import _mcp_oauth_flows, _mcp_server_summary, _normalize_mcp_server_create
from hermes_cli.web_models import MCPCatalogInstall, MCPEnabledToggle, MCPServerCreate, MCPServersReplace
from hermes_cli.web_routers._common import (
_profile_cli_args, _profile_scope, _spawn_hermes_action, config_write_scope, http_failure,
@@ -25,16 +26,13 @@ from hermes_cli.web_routers._common import (
router = APIRouter()
-_config_profile_scope = late("_config_profile_scope")
-_mcp_server_summary = late("_mcp_server_summary")
-_normalize_mcp_server_create = late("_normalize_mcp_server_create")
+_config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
_require_token = late("_require_token")
-_run_dashboard_mcp_oauth = late("_run_dashboard_mcp_oauth")
-load_config = late("load_config")
-save_config = late("save_config")
-save_env_value = late("save_env_value")
+_run_dashboard_mcp_oauth = late("_run_dashboard_mcp_oauth", "hermes_cli.web_server_mcp")
+load_config = late("load_config", "hermes_cli.config")
+save_config = late("save_config", "hermes_cli.config")
+save_env_value = late("save_env_value", "hermes_cli.config")
-_mcp_oauth_flows = LateState("_mcp_oauth_flows")
_mcp_oauth_flows_lock = threading.Lock()
_MCP_DASHBOARD_OAUTH_TTL = 15 * 60
_MAX_PENDING_MCP_OAUTH_FLOWS = 8
@@ -67,7 +65,7 @@ def _mcp_install_action_name(name: str) -> str:
"""Unique per-entry mcp-install action name (+ registered log file), so a
re-click or a second catalog install doesn't overwrite the first's tracked
process/log while its git clone is still running."""
- from hermes_cli.web_server import _ACTION_LOG_FILES
+ from hermes_cli.web_server_gateway import _ACTION_LOG_FILES
slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:48] or "server"
digest = hashlib.sha1(name.encode()).hexdigest()[:8]
action = f"mcp-install-{slug}-{digest}"
diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.py
index 77a2a288f22..11485d22926 100644
--- a/hermes_cli/web_routers/memory_providers.py
+++ b/hermes_cli/web_routers/memory_providers.py
@@ -17,6 +17,10 @@ from typing import Any, Dict, List, Optional
from fastapi import APIRouter, HTTPException
from hermes_cli.web_deps import late
+from hermes_cli.web_server_dashboard import _invalidate_plugins_hub_cache
+from hermes_cli.web_server_memory import (
+ _coerce_bool, _field_default, _field_is_set, _field_value, _field_visible, _load_memory_provider, _memory_provider_manifest, _memory_provider_setup_info, _memory_provider_setup_manifest, _normalize_memory_provider_schema, _read_memory_provider_existing_values, _require_memory_provider_ready, _run_setup_command,
+)
from hermes_cli.web_models import MemoryProviderConfigUpdate, MemoryProviderSetupRequest
from hermes_cli.web_routers._common import scoped_to_thread
from plugins.memory.config_schema import (
@@ -26,29 +30,14 @@ from plugins.memory.config_schema import (
_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")
-_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")
-_invalidate_plugins_hub_cache = late("_invalidate_plugins_hub_cache")
-_load_memory_provider = late("_load_memory_provider")
-_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")
-_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")
-get_hermes_home = late("get_hermes_home")
-load_config = late("load_config")
-save_config = late("save_config")
-save_env_value = late("save_env_value")
-_dependency_importable = late("_dependency_importable")
-load_env = late("load_env")
-
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_discover_memory_provider_statuses = late("_discover_memory_provider_statuses", "hermes_cli.web_server_memory")
+get_hermes_home = late("get_hermes_home", "hermes_cli.config")
+load_config = late("load_config", "hermes_cli.config")
+save_config = late("save_config", "hermes_cli.config")
+save_env_value = late("save_env_value", "hermes_cli.config")
+_dependency_importable = late("_dependency_importable", "hermes_cli.web_server_memory")
+load_env = late("load_env", "hermes_cli.config")
# Sentinel: remove this key so it falls back to the host or built-in default.
_UNSET: Any = object()
diff --git a/hermes_cli/web_routers/messaging.py b/hermes_cli/web_routers/messaging.py
index 56e3c169f15..6c38c5c9dc1 100644
--- a/hermes_cli/web_routers/messaging.py
+++ b/hermes_cli/web_routers/messaging.py
@@ -25,6 +25,10 @@ from gateway.status import resolve_gateway_liveness
from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_cli.config import OPTIONAL_ENV_VARS, get_env_path, redact_key
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_server_gateway import _restart_gateway_after
+from hermes_cli.web_server_messaging import (
+ _TelegramOnboardingPairing, _WhatsAppOnboardingSession, _messaging_platform_catalog, _telegram_onboarding_error_message, _telegram_onboarding_lock, _telegram_onboarding_pairings, _whatsapp_onboarding_payload, _whatsapp_onboarding_sessions,
+)
from hermes_cli.web_routers._common import http_failure
from hermes_cli.web_models import (
MessagingPlatformUpdate, TelegramOnboardingApply, TelegramOnboardingStart,
@@ -34,35 +38,24 @@ from hermes_cli.web_models import (
_log = logging.getLogger("hermes_cli.web_server")
router = APIRouter()
-# web_server helpers/state, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative.
-_config_profile_scope = late("_config_profile_scope")
-_messaging_platform_catalog = late("_messaging_platform_catalog")
-_profile_scope = late("_profile_scope")
-_resolve_profile_dir = late("_resolve_profile_dir")
-_restart_gateway_after_whatsapp_onboarding = late("_restart_gateway_after_whatsapp_onboarding")
-_restart_gateway_after = late("_restart_gateway_after")
-_telegram_onboarding_error_message = late("_telegram_onboarding_error_message")
-_telegram_onboarding_request_sync = late("_telegram_onboarding_request_sync")
-_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")
-load_config = late("load_config")
-read_runtime_status = late("read_runtime_status")
-remove_env_value = late("remove_env_value")
-save_env_value = late("save_env_value")
-_gateway_subcommand = late("_gateway_subcommand")
-_probe_gateway_health = late("_probe_gateway_health")
-get_running_pid_cached = late("get_running_pid_cached")
-get_runtime_status_running_pid = late("get_runtime_status_running_pid")
-_WhatsAppOnboardingSession = late("_WhatsAppOnboardingSession")
-_TelegramOnboardingPairing = late("_TelegramOnboardingPairing")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
+_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
+_resolve_profile_dir = late("_resolve_profile_dir", "hermes_cli.web_server_profiles")
+_restart_gateway_after_whatsapp_onboarding = late("_restart_gateway_after_whatsapp_onboarding", "hermes_cli.web_server_messaging")
+_telegram_onboarding_request_sync = late("_telegram_onboarding_request_sync", "hermes_cli.web_server_messaging")
+_whatsapp_session_path = late("_whatsapp_session_path", "hermes_cli.web_server_messaging")
+_write_platform_enabled = late("_write_platform_enabled", "hermes_cli.web_server_messaging")
+load_env = late("load_env", "hermes_cli.config")
+load_config = late("load_config", "hermes_cli.config")
+read_runtime_status = late("read_runtime_status", "gateway.status")
+remove_env_value = late("remove_env_value", "hermes_cli.config")
+save_env_value = late("save_env_value", "hermes_cli.config")
+_gateway_subcommand = late("_gateway_subcommand", "hermes_cli.web_server_gateway")
+_probe_gateway_health = late("_probe_gateway_health", "hermes_cli.web_server_gateway")
+get_running_pid_cached = late("get_running_pid_cached", "gateway.status")
+get_runtime_status_running_pid = late("get_runtime_status_running_pid", "gateway.status")
_GATEWAY_HEALTH_URL = LateState("_GATEWAY_HEALTH_URL")
-_whatsapp_onboarding_sessions = LateState("_whatsapp_onboarding_sessions")
-_telegram_onboarding_lock = LateState("_telegram_onboarding_lock")
-_telegram_onboarding_pairings = LateState("_telegram_onboarding_pairings")
-
-
# Display labels for env vars not in OPTIONAL_ENV_VARS (bridge toggles, Twilio, HASS, Email, ...)
# so the UI can still render a friendly label. Rows: (key, description, prompt, extra flags).
_MESSAGING_ENV_FALLBACKS: dict[str, dict[str, Any]] = {
diff --git a/hermes_cli/web_routers/models.py b/hermes_cli/web_routers/models.py
index c116e17619b..c997e52c021 100644
--- a/hermes_cli/web_routers/models.py
+++ b/hermes_cli/web_routers/models.py
@@ -11,21 +11,21 @@ from typing import Optional
from fastapi import APIRouter, HTTPException
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_server_config import (
+ _AUX_TASK_SLOTS, _apply_model_assignment_sync, _dashboard_code_skew_guard,
+)
+from starlette.concurrency import run_in_threadpool
from hermes_cli.web_models import ModelAssignment, MoaConfigPayload, MoaModelSlot
from hermes_cli.web_routers._common import http_failure
_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")
-_AUX_TASK_SLOTS = LateState("_AUX_TASK_SLOTS")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
+_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
+load_config = late("load_config", "hermes_cli.config")
+save_config = late("save_config", "hermes_cli.config")
_EMPTY_MODEL_INFO: dict = {
diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.py
index fb37c12fbf9..fd50f4bcb29 100644
--- a/hermes_cli/web_routers/oauth.py
+++ b/hermes_cli/web_routers/oauth.py
@@ -16,25 +16,20 @@ from typing import Any, Callable, Dict, Optional
from fastapi import APIRouter, HTTPException, Request
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_server_oauth import (
+ _external_process_cli_command, _minimax_poller, _nous_poller, _oauth_profile_name, _oauth_sessions, _oauth_sessions_lock, _truncate_token, _xai_device_poller,
+)
from hermes_cli.web_models import OAuthSubmitBody
from hermes_cli.web_routers._common import scoped_to_thread
_log = logging.getLogger("hermes_cli.web_server")
router = APIRouter()
-# web_server helpers/state, 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")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
_require_token = late("_require_token")
-_resolve_profile_dir = late("_resolve_profile_dir")
-_minimax_poller = late("_minimax_poller")
-_nous_poller = late("_nous_poller")
-_truncate_token = late("_truncate_token")
-_xai_device_poller = late("_xai_device_poller")
-_oauth_sessions = LateState("_oauth_sessions")
-_oauth_sessions_lock = LateState("_oauth_sessions_lock")
-_OAUTH_PROVIDER_CATALOG = LateState("_OAUTH_PROVIDER_CATALOG")
+_resolve_profile_dir = late("_resolve_profile_dir", "hermes_cli.web_server_profiles")
+_OAUTH_PROVIDER_CATALOG = LateState("_OAUTH_PROVIDER_CATALOG", "hermes_cli.web_server_oauth")
_CODEX_ISSUER = "https://auth.openai.com"
_JSON_HEADERS = {"Content-Type": "application/json"}
diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.py
index e39813d471b..1bfe78043db 100644
--- a/hermes_cli/web_routers/ops.py
+++ b/hermes_cli/web_routers/ops.py
@@ -22,6 +22,9 @@ from fastapi.responses import FileResponse
from hermes_cli.config import redact_key
from hermes_cli.web_deps import late
+from hermes_cli.web_server_files import _path_is_under
+from hermes_cli.web_server_gateway import _restart_gateway_after
+from hermes_cli.web_server_memory import _normalize_memory_provider_name, _require_memory_provider_ready
from hermes_cli.web_models import (
BackupRequest, CredentialPoolAdd, HookCreate, HookDelete, ImportRequest, MemoryProviderSelect,
MemoryReset, PairingApprove, PairingRevoke, WebhookCreate, WebhookEnabledToggle,
@@ -32,19 +35,15 @@ from hermes_cli.web_routers.files import stream_upload_to_path
_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")
-_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")
-_restart_gateway_after = late("_restart_gateway_after")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_discover_memory_provider_statuses = late("_discover_memory_provider_statuses", "hermes_cli.web_server_memory")
+_gateway_subcommand = late("_gateway_subcommand", "hermes_cli.web_server_gateway")
+_resolve_profile_dir = late("_resolve_profile_dir", "hermes_cli.web_server_profiles")
+_spawn_hermes_action = late("_spawn_hermes_action", "hermes_cli.web_server_gateway")
+_write_platform_enabled = late("_write_platform_enabled", "hermes_cli.web_server_messaging")
+get_hermes_home = late("get_hermes_home", "hermes_cli.config")
+load_config = late("load_config", "hermes_cli.config")
+save_config = late("save_config", "hermes_cli.config")
def _spawn_action(argv: List[str], name: str, *, log_msg: str, prefix: str) -> dict:
diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.py
index dcba4fe9ce7..1f0da2fb174 100644
--- a/hermes_cli/web_routers/profiles.py
+++ b/hermes_cli/web_routers/profiles.py
@@ -5,8 +5,8 @@ projects/tree, pull-requests) was registered long before the generic
``/api/profiles/{name}`` routes on ``router``; the original global registration order is
preserved rather than relying on Starlette's literal-before-param matching.
-web_server-owned helpers are reached via the late-binding seam in :mod:`hermes_cli.web_deps`
-so tests that ``monkeypatch.setattr(web_server, "_helper", ...)`` keep working.
+Shared helpers are reached via the late-binding seam in :mod:`hermes_cli.web_deps`
+so a test's ``monkeypatch.setattr(<owning module>, "_helper", ...)`` keeps working.
"""
import contextlib
@@ -27,6 +27,13 @@ from typing import Any, Callable, Dict, List, Optional, Tuple
from fastapi import APIRouter, HTTPException, Query
from hermes_cli.web_deps import late
+from hermes_cli.web_server_config import _apply_main_model_assignment, _normalize_main_model_assignment
+from hermes_cli.web_server_gateway import _strip_session_list_rows
+from hermes_cli.web_server_profiles import (
+ _fallback_profile_dicts, _hub_action_name, _write_profile_mcp_servers,
+)
+from hermes_cli.web_server_sessions import _open_session_db_at_path
+from starlette.concurrency import run_in_threadpool
from hermes_cli.web_models import (
ProfileCreate, ProfileActiveUpdate, ProfileExport, ProfileImport, ProfileRename,
ProfileSoulUpdate, ProfileDescriptionUpdate, ProfileModelUpdate, ProfileDescribeAuto,
@@ -54,18 +61,9 @@ sessions_router = APIRouter()
router = APIRouter()
# Late-bound web_server helpers (resolved at call time; cycle-safe, monkeypatch-transparent).
-_cron_profile_home = late("_cron_profile_home")
-_fallback_profile_dicts = late("_fallback_profile_dicts")
-_hub_action_name = late("_hub_action_name")
-_open_session_db_at_path = late("_open_session_db_at_path")
-_resolve_profile_dir = late("_resolve_profile_dir")
-_spawn_hermes_action = late("_spawn_hermes_action")
-run_in_threadpool = late("run_in_threadpool")
-_strip_session_list_rows = late("_strip_session_list_rows")
-_write_profile_mcp_servers = late("_write_profile_mcp_servers")
-_apply_main_model_assignment = late("_apply_main_model_assignment")
-_normalize_main_model_assignment = late("_normalize_main_model_assignment")
-
+_cron_profile_home = late("_cron_profile_home", "hermes_cli.web_server_cron")
+_resolve_profile_dir = late("_resolve_profile_dir", "hermes_cli.web_server_profiles")
+_spawn_hermes_action = late("_spawn_hermes_action", "hermes_cli.web_server_gateway")
# ---------------------------------------------------------------------------
# Profile management endpoints (minimal — list/create/rename/delete + SOUL.md)
@@ -99,7 +97,7 @@ def _profile_setup_command(name: str) -> str:
def _write_profile_model(profile_dir: Path, provider: str, model: str) -> None:
"""Write the main model assignment into ``profile_dir``'s config.yaml (HERMES_HOME-scoped);
clears stale ``base_url`` / ``context_length`` like ``POST /api/model/set`` does."""
- from hermes_cli.web_server import load_config, save_config
+ from hermes_cli.config import load_config, save_config
with _hermes_home_scope(profile_dir):
provider, model = _normalize_main_model_assignment(provider, model)
cfg = load_config()
@@ -112,7 +110,7 @@ def _disable_unselected_skills(profile_dir: Path, keep: List[str]) -> int:
newly disabled. Profiles manage activation via a *disabled* list (everything installed is
active by default); the builder's skill step has "replace" semantics. Hub skills are
installed separately via subprocess and are active on install."""
- from hermes_cli.web_server import load_config
+ from hermes_cli.config import load_config
from hermes_cli.skills_config import get_disabled_skills, save_disabled_skills
keep_set = {s.strip() for s in keep if s and s.strip()}
with _hermes_home_scope(profile_dir):
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index 0b5a4e21058..4831d836ed4 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -18,6 +18,8 @@ from fastapi.encoders import jsonable_encoder
from fastapi.responses import StreamingResponse
from hermes_cli.web_deps import late
+from hermes_cli.web_server_gateway import _strip_session_list_rows
+from hermes_cli.web_server_sessions import _maybe_auto_archive_for_profile, _session_latest_descendant
from hermes_cli.web_models import (
BulkDeleteSessions, SessionImport, SessionOwnerBackfill, SessionPrune, SessionRename)
from hermes_cli.web_routers._common import log as _log, http_failure
@@ -28,12 +30,9 @@ list_router = APIRouter()
search_router = APIRouter()
manage_router = APIRouter()
-_cron_default_profile = late("_cron_default_profile")
-_cron_profile_home = late("_cron_profile_home")
-_maybe_auto_archive_for_profile = late("_maybe_auto_archive_for_profile")
-_open_session_db_for_profile = late("_open_session_db_for_profile")
-_session_latest_descendant = late("_session_latest_descendant")
-_strip_session_list_rows = late("_strip_session_list_rows")
+_cron_default_profile = late("_cron_default_profile", "hermes_cli.web_server_cron")
+_cron_profile_home = late("_cron_profile_home", "hermes_cli.web_server_cron")
+_open_session_db_for_profile = late("_open_session_db_for_profile", "hermes_cli.web_server_sessions")
_NOT_FOUND = "Session not found"
@@ -71,7 +70,7 @@ _PRUNE_ROW_KEYS = ("id", "source", "title", "model", "started_at", "last_active"
def _prune_sessions(body: SessionPrune):
"""Delete ended sessions matching filters (mirrors `hermes sessions prune`)."""
- from hermes_cli.web_server import get_hermes_home
+ from hermes_cli.config import get_hermes_home
has_window = body.started_before is not None or body.started_after is not None
if body.older_than_days is not None and body.older_than_days < 1 and not has_window:
raise HTTPException(status_code=400, detail="older_than_days must be >= 1")
diff --git a/hermes_cli/web_routers/skills.py b/hermes_cli/web_routers/skills.py
index 2d936b4d09c..84829a32129 100644
--- a/hermes_cli/web_routers/skills.py
+++ b/hermes_cli/web_routers/skills.py
@@ -3,8 +3,8 @@
Two routers because global route order matters: ``hub_router`` (skills-hub
install/search/scan) was registered before the profiles router include in
web_server, the plain skills CRUD ``router`` after it — each is mounted at its
-original registration point. web_server-owned helpers are reached via the
-late-binding seam so ``monkeypatch.setattr(web_server, ...)`` keeps working.
+original registration point. Shared helpers are reached via the late-binding
+seam so ``monkeypatch.setattr(<owning module>, ...)`` keeps working.
"""
import asyncio
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index 08b43947782..3d565dc5b40 100644
--- a/hermes_cli/web_routers/status.py
+++ b/hermes_cli/web_routers/status.py
@@ -1,8 +1,8 @@
"""Status dashboard routes: health, /api/status, system stats, curator, learning graph,
portal and diagnostics actions.
-Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch on
-``web_server`` stay there and are imported lazily at call time (cycle-safe).
+Extracted from ``hermes_cli.web_server``; app state and helpers are late-bound through
+:mod:`hermes_cli.web_deps` (cycle-safe, monkeypatch-friendly).
"""
import concurrent.futures
@@ -15,6 +15,8 @@ import sys
import time
from fastapi import APIRouter
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_server_gateway import _display_system_platform
+from starlette.concurrency import run_in_threadpool
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__
@@ -29,28 +31,26 @@ 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")
+# Late-bound so a test's monkeypatch on the owning module wins at call time.
+_collect_profile_gateway_topology_cached = late("_collect_profile_gateway_topology_cached", "hermes_cli.web_server_gateway")
+_config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
+_dashboard_local_update_managed_externally = late("_dashboard_local_update_managed_externally", "hermes_cli.web_server_files")
+_load_configured_gateway_platforms = late("_load_configured_gateway_platforms", "hermes_cli.web_server_gateway")
+_probe_gateway_health = late("_probe_gateway_health", "hermes_cli.web_server_gateway")
_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")
+_resolve_profile_dir = late("_resolve_profile_dir", "hermes_cli.web_server_profiles")
+_resolve_restart_drain_timeout = late("_resolve_restart_drain_timeout", "hermes_cli.web_server_lifecycle")
+_spawn_hermes_action = late("_spawn_hermes_action", "hermes_cli.web_server_gateway")
_ssh_runtime_intact = late("_ssh_runtime_intact")
app = LateState("app") # the FastAPI instance (app.state.*)
-check_config_version = late("check_config_version")
-get_hermes_home = late("get_hermes_home")
+check_config_version = late("check_config_version", "hermes_cli.config")
+get_hermes_home = late("get_hermes_home", "hermes_cli.config")
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")
-_open_session_db_for_profile = late("_open_session_db_for_profile")
+get_running_pid_cached = late("get_running_pid_cached", "gateway.status")
+get_runtime_status_running_pid = late("get_runtime_status_running_pid", "gateway.status")
+load_config = late("load_config", "hermes_cli.config")
+read_runtime_status = late("read_runtime_status", "gateway.status")
+_open_session_db_for_profile = late("_open_session_db_for_profile", "hermes_cli.web_server_sessions")
_STATUS_ACTIVE_SESSIONS_TIMEOUT = 0.75
@@ -183,7 +183,7 @@ def _merge_profile_gateway_platforms(gateway_platforms: dict, profile_platforms:
# status) are written to the per-profile home, not the process-level HERMES_HOME (see issue #69143). Plain
# /api/status keeps the exact zero-arg call so its behavior (and cache signature) is unchanged. The
# module-level probe references are handed to the resolver so the long-standing
-# `monkeypatch.setattr(web_server, "get_running_pid_cached", ...)` seam used across the test-suite still
+# `monkeypatch.setattr(gateway.status, "get_running_pid_cached", ...)` seam used across the test-suite still
# intercepts them.
def _bounded_health_probe():
"""Health probe with the route's blocking-call budget preserved. The resolver only
@@ -228,7 +228,7 @@ async def _resolve_gateway_status(profile_dir: Optional[Path], health_url) -> Di
scoped to that profile's directory (gateway identity files live in the per-profile
home); plain /api/status keeps the exact zero-arg call so its cache signature is
unchanged. The module-level probe references are handed to the resolver so the
- ``monkeypatch.setattr(web_server, "get_running_pid_cached", ...)`` seam still intercepts.
+ ``monkeypatch.setattr(gateway.status, "get_running_pid_cached", ...)`` seam still intercepts.
"""
local_runtime = (read_runtime_status(path=profile_dir / "gateway_state.json")
if profile_dir else read_runtime_status())
diff --git a/hermes_cli/web_routers/tools.py b/hermes_cli/web_routers/tools.py
index fb18a05af89..d09adb2a34c 100644
--- a/hermes_cli/web_routers/tools.py
+++ b/hermes_cli/web_routers/tools.py
@@ -14,6 +14,8 @@ from typing import Any, Dict, List, Optional
from fastapi import APIRouter, HTTPException
from hermes_cli.web_deps import late
+from hermes_cli.web_server_profiles import _plugin_terminal_backend_rows
+from starlette.concurrency import run_in_threadpool
from hermes_cli.web_models import (
TerminalBackendSelect, ToolsetEnvUpdate, ToolsetModelSelect, ToolsetPostSetup,
ToolsetProviderSelect, ToolsetToggle)
@@ -23,10 +25,8 @@ from hermes_cli.web_routers._common import (
router = APIRouter()
-load_config = late("load_config")
-save_config = late("save_config")
-run_in_threadpool = late("run_in_threadpool")
-_plugin_terminal_backend_rows = late("_plugin_terminal_backend_rows")
+load_config = late("load_config", "hermes_cli.config")
+save_config = late("save_config", "hermes_cli.config")
def _env_value(name: str) -> str:
@@ -50,7 +50,7 @@ def _terminal_cfg_value(terminal_cfg: dict, key: str, env_var: str) -> str:
def _terminal_backend_rows() -> List[Dict[str, str]]:
"""Built-in picker rows plus plugin-registered backends, computed per request
so a plugin installed after server start still shows up."""
- from hermes_cli.web_server import _TERMINAL_BACKENDS
+ from hermes_cli.web_server_profiles import _TERMINAL_BACKENDS
return [*_TERMINAL_BACKENDS, *_plugin_terminal_backend_rows()]