Skip to content

The agent that grows with you

refactor(hermes_cli/web_routers): reuse _common.scoped_to_thread for profile-scoped off-loop handlers

Teknium95589a420fd5
diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.py
index 1cc926329d3..4996c9e0429 100644
--- a/hermes_cli/web_routers/config_env.py
+++ b/hermes_cli/web_routers/config_env.py
@@ -11,7 +11,7 @@ import asyncio
import time
import urllib.parse
from fastapi import APIRouter
-from hermes_cli.web_routers._common import http_failure
+from hermes_cli.web_routers._common import http_failure, scoped_to_thread
from hermes_cli.web_deps import LateState, 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
@@ -82,11 +82,7 @@ async def get_config(profile: Optional[str] = None):
# load_config() reads from disk; a slow lock-holder on the event loop froze
# the whole gateway for >1s. asyncio.to_thread copies the contextvar
# context, so the profile override stays scoped to the worker thread.
- def _run():
- with _profile_scope(profile):
- return _normalize_config_for_web(load_config())
-
- config = await asyncio.to_thread(_run)
+ config = await scoped_to_thread(profile, lambda: _normalize_config_for_web(load_config()))
# Strip internal keys that the frontend shouldn't see or send back
return {k: v for k, v in config.items() if not k.startswith("_")}
@@ -285,19 +281,16 @@ def _get_env_vars_sync(profile: Optional[str] = None):
@router.put("/api/env")
async def set_env_var(body: EnvVarUpdate, profile: Optional[str] = None):
- def _run():
- with _profile_scope(body.profile or profile):
- # Unified credential lifecycle: writes .env AND reconciles any
- # config.yaml mirror still holding the previous value of this var
- # (model.api_key / auxiliary.*.api_key / custom_providers[*]), so a
- # rotation can't leave a stale higher-precedence copy that keeps
- # authenticating with the old key.
- from hermes_cli.credential_lifecycle import save_provider_env_credential
-
- return save_provider_env_credential(body.key, body.value)
-
+ # Unified credential lifecycle: writes .env AND reconciles any config.yaml
+ # mirror still holding the previous value of this var (model.api_key /
+ # auxiliary.*.api_key / custom_providers[*]), so a rotation can't leave a
+ # stale higher-precedence copy that keeps authenticating with the old key.
with _env_write_errors("PUT /api/env failed", http_passthrough=False):
- return await asyncio.to_thread(_run)
+ from hermes_cli.credential_lifecycle import save_provider_env_credential
+
+ return await scoped_to_thread(
+ body.profile or profile, lambda: save_provider_env_credential(body.key, body.value)
+ )
# Live credential probes keyed by env var: (url, auth) where auth is "bearer"
@@ -713,20 +706,17 @@ async def validate_provider_credential(body: EnvVarUpdate, request: Request):
@router.delete("/api/env")
async def remove_env_var(body: EnvVarDelete, profile: Optional[str] = None):
- def _run():
- with _profile_scope(body.profile or profile):
- # Unified credential lifecycle: clears the .env entry AND every
- # mirror of the credential — env-seeded credential_pool entries in
- # auth.json (stale ones kept providers alive in the model picker),
- # the affected providers' model-cache rows, and value-matched
- # config.yaml api_key mirrors. OAuth/device-code/manual pool entries
- # for the same provider are preserved.
- from hermes_cli.credential_lifecycle import remove_provider_env_credential
-
- return remove_provider_env_credential(body.key)
-
+ # Unified credential lifecycle: clears the .env entry AND every mirror of
+ # the credential — env-seeded credential_pool entries in auth.json (stale
+ # ones kept providers alive in the model picker), the affected providers'
+ # model-cache rows, and value-matched config.yaml api_key mirrors.
+ # OAuth/device-code/manual pool entries for the same provider are preserved.
with _env_write_errors("DELETE /api/env failed", http_passthrough=True):
- result = await asyncio.to_thread(_run)
+ from hermes_cli.credential_lifecycle import remove_provider_env_credential
+
+ result = await scoped_to_thread(
+ body.profile or profile, lambda: remove_provider_env_credential(body.key)
+ )
if not result.get("found"):
raise HTTPException(status_code=404, detail=f"{body.key} not found in .env")
return result
@@ -750,11 +740,7 @@ async def reveal_env_var(
raise HTTPException(status_code=429, detail="Too many reveal requests. Try again shortly.")
_reveal_timestamps.append(now)
- def _run():
- with _profile_scope(body.profile or profile):
- return load_env()
-
- env_on_disk = await asyncio.to_thread(_run)
+ env_on_disk = await scoped_to_thread(body.profile or profile, load_env)
value = env_on_disk.get(body.key)
if value is None:
raise HTTPException(status_code=404, detail=f"{body.key} not found in .env")
diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.py
index 05cebdd0665..7e6d016045a 100644
--- a/hermes_cli/web_routers/memory_providers.py
+++ b/hermes_cli/web_routers/memory_providers.py
@@ -8,9 +8,9 @@ import logging
import math
import re
import shlex
-import asyncio
from fastapi import APIRouter
from hermes_cli.web_deps import late
+from hermes_cli.web_routers._common import scoped_to_thread
from fastapi import HTTPException
from hermes_cli.web_models import MemoryProviderConfigUpdate, MemoryProviderSetupRequest
from plugins.memory.config_schema import get_provider_config_schema
@@ -36,7 +36,6 @@ _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")
@@ -646,21 +645,20 @@ async def get_memory_provider_config(name: str, surface: Optional[str] = None, p
_require_valid_memory_provider_name(name)
def _run():
- with _profile_scope(profile):
- # Undeclared providers (e.g. builtin) have no config surface; an
- # empty schema makes the generic panel render nothing.
- if surface == "declared":
- declared = get_provider_config_schema(name)
- if declared is None:
- return {"name": name, "label": name, "docs_url": "", "fields": []}
- return _declared_provider_payload(declared)
+ # Undeclared providers (e.g. builtin) have no config surface; an
+ # empty schema makes the generic panel render nothing.
+ if surface == "declared":
+ declared = get_provider_config_schema(name)
+ if declared is None:
+ return {"name": name, "label": name, "docs_url": "", "fields": []}
+ return _declared_provider_payload(declared)
- provider = _load_memory_provider(name)
- if provider is None:
- return {"name": name, "label": name, "fields": [], "setup": _memory_provider_setup_info(name)}
- return _memory_provider_payload(name, provider)
+ provider = _load_memory_provider(name)
+ if provider is None:
+ return {"name": name, "label": name, "fields": [], "setup": _memory_provider_setup_info(name)}
+ return _memory_provider_payload(name, provider)
- return await asyncio.to_thread(_run)
+ return await scoped_to_thread(profile, _run)
@router.post("/api/memory/providers/{name}/setup")
@@ -693,28 +691,27 @@ async def update_memory_provider_config(
values = body.values or {}
def _run():
- with _profile_scope(profile):
- if surface == "declared":
- declared = get_provider_config_schema(name)
- if declared is None:
- raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}")
- _update_memory_provider_config(declared, _stringify_submitted_values(values))
- _invalidate_plugins_hub_cache()
- return {"ok": True}
-
- provider = _load_memory_provider(name)
- if provider is None:
+ if surface == "declared":
+ declared = get_provider_config_schema(name)
+ if declared is None:
raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}")
- _write_memory_provider_config_values(name, provider, values)
- _require_memory_provider_ready(name)
- config = load_config()
- _memory_section(config)["provider"] = name
- save_config(config)
+ _update_memory_provider_config(declared, _stringify_submitted_values(values))
_invalidate_plugins_hub_cache()
- return {"ok": True, "active": name}
+ return {"ok": True}
+
+ provider = _load_memory_provider(name)
+ if provider is None:
+ raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}")
+ _write_memory_provider_config_values(name, provider, values)
+ _require_memory_provider_ready(name)
+ config = load_config()
+ _memory_section(config)["provider"] = name
+ save_config(config)
+ _invalidate_plugins_hub_cache()
+ return {"ok": True, "active": name}
try:
- return await asyncio.to_thread(_run)
+ return await scoped_to_thread(profile, _run)
except HTTPException:
raise
except ValueError as exc:
diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.py
index 405f4d8e1dc..86d2cfe995e 100644
--- a/hermes_cli/web_routers/oauth.py
+++ b/hermes_cli/web_routers/oauth.py
@@ -10,6 +10,7 @@ import sys
import time
from fastapi import APIRouter
from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_routers._common import scoped_to_thread
from fastapi import HTTPException, Request
from hermes_cli.web_models import OAuthSubmitBody
from typing import Any, Callable, Dict, Optional
@@ -597,25 +598,24 @@ async def list_oauth_providers(profile: Optional[str] = None):
(last N chars, never the full token), expires_at, has_refresh_token}.
"""
def _run():
- with _profile_scope(profile):
- providers = []
- for p in _build_oauth_catalog():
- status = _resolve_provider_status(p["id"], p.get("status_fn"))
- disconnect_hint = _oauth_provider_disconnect_hint(p, status)
- providers.append({
- "id": p["id"],
- "name": p["name"],
- "flow": p["flow"],
- "cli_command": _external_process_cli_command(p["id"], p["cli_command"]),
- "docs_url": p["docs_url"],
- "disconnect_hint": disconnect_hint,
- "disconnect_command": _oauth_provider_disconnect_command(p),
- "disconnectable": disconnect_hint is None,
- "status": status,
- })
- return {"providers": providers}
-
- return await asyncio.to_thread(_run)
+ providers = []
+ for p in _build_oauth_catalog():
+ status = _resolve_provider_status(p["id"], p.get("status_fn"))
+ disconnect_hint = _oauth_provider_disconnect_hint(p, status)
+ providers.append({
+ "id": p["id"],
+ "name": p["name"],
+ "flow": p["flow"],
+ "cli_command": _external_process_cli_command(p["id"], p["cli_command"]),
+ "docs_url": p["docs_url"],
+ "disconnect_hint": disconnect_hint,
+ "disconnect_command": _oauth_provider_disconnect_command(p),
+ "disconnectable": disconnect_hint is None,
+ "status": status,
+ })
+ return {"providers": providers}
+
+ return await scoped_to_thread(profile, _run)
def _reject_if_not_disconnectable(provider: Dict[str, Any], status: Dict[str, Any]) -> None:
@@ -635,54 +635,53 @@ async def disconnect_oauth_provider(
_require_token(request)
def _run():
- with _profile_scope(profile):
- catalog_by_id = {p["id"]: p for p in _build_oauth_catalog()}
- provider = catalog_by_id.get(provider_id)
- if provider is None:
- raise HTTPException(
- status_code=400,
- detail=f"Unknown provider: {provider_id}. "
- f"Available: {', '.join(sorted(catalog_by_id))}",
- )
-
- _reject_if_not_disconnectable(provider, {})
- _reject_if_not_disconnectable(
- provider, _resolve_provider_status(provider_id, provider.get("status_fn"))
+ catalog_by_id = {p["id"]: p for p in _build_oauth_catalog()}
+ provider = catalog_by_id.get(provider_id)
+ if provider is None:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Unknown provider: {provider_id}. "
+ f"Available: {', '.join(sorted(catalog_by_id))}",
)
- # Anthropic clears only the Hermes-managed PKCE file and auth-store
- # entry; the external claude-code row was rejected above so we never
- # pretend to remove ~/.claude/* credentials owned by the CLI.
- if provider_id == "anthropic":
- cleared = False
- try:
- from agent.anthropic_adapter import _get_hermes_oauth_file
- oauth_file = _get_hermes_oauth_file()
- if oauth_file.exists():
- oauth_file.unlink()
- cleared = True
- except Exception:
- pass
- try:
- from hermes_cli.auth import clear_provider_auth
- cleared = clear_provider_auth("anthropic") or cleared
- except Exception:
- pass
- _log.info("oauth/disconnect: %s", provider_id)
- return {"ok": bool(cleared), "provider": provider_id}
+ _reject_if_not_disconnectable(provider, {})
+ _reject_if_not_disconnectable(
+ provider, _resolve_provider_status(provider_id, provider.get("status_fn"))
+ )
+ # Anthropic clears only the Hermes-managed PKCE file and auth-store
+ # entry; the external claude-code row was rejected above so we never
+ # pretend to remove ~/.claude/* credentials owned by the CLI.
+ if provider_id == "anthropic":
+ cleared = False
try:
- from hermes_cli.auth import clear_provider_auth, invalidate_nous_auth_status_cache
- cleared = clear_provider_auth(provider_id)
- if provider_id == "nous":
- invalidate_nous_auth_status_cache()
- _log.info("oauth/disconnect: %s (cleared=%s)", provider_id, cleared)
- return {"ok": bool(cleared), "provider": provider_id}
- except Exception as e:
- _log.exception("disconnect %s failed", provider_id)
- raise HTTPException(status_code=500, detail=str(e))
-
- return await asyncio.to_thread(_run)
+ from agent.anthropic_adapter import _get_hermes_oauth_file
+ oauth_file = _get_hermes_oauth_file()
+ if oauth_file.exists():
+ oauth_file.unlink()
+ cleared = True
+ except Exception:
+ pass
+ try:
+ from hermes_cli.auth import clear_provider_auth
+ cleared = clear_provider_auth("anthropic") or cleared
+ except Exception:
+ pass
+ _log.info("oauth/disconnect: %s", provider_id)
+ return {"ok": bool(cleared), "provider": provider_id}
+
+ try:
+ from hermes_cli.auth import clear_provider_auth, invalidate_nous_auth_status_cache
+ cleared = clear_provider_auth(provider_id)
+ if provider_id == "nous":
+ invalidate_nous_auth_status_cache()
+ _log.info("oauth/disconnect: %s (cleared=%s)", provider_id, cleared)
+ return {"ok": bool(cleared), "provider": provider_id}
+ except Exception as e:
+ _log.exception("disconnect %s failed", provider_id)
+ raise HTTPException(status_code=500, detail=str(e))
+
+ return await scoped_to_thread(profile, _run)
# In-browser device-code flows (Nous, OpenAI Codex, MiniMax, xAI):