Skip to content

The agent that grows with you

fix(dashboard): profile-routed routers run under the profile's secret scope; console `send` never writes the process env

teknium15ca670b398c4
diff --git a/hermes_cli/send_cmd.py b/hermes_cli/send_cmd.py
index 94f0885bcdc..0f1e9df0905 100644
--- a/hermes_cli/send_cmd.py
+++ b/hermes_cli/send_cmd.py
@@ -132,21 +132,36 @@ def _list_targets(platform_filter: Optional[str], *, json_mode: bool) -> int:
def _load_hermes_env() -> None:
- """Populate ``os.environ`` from ``~/.hermes/.env`` AND bridge top-level ``config.yaml`` keys into
- the environment so the gateway config loader sees platform credentials and home channels."""
+ """Populate the credential environment from ``~/.hermes/.env`` AND bridge top-level ``config.yaml``
+ keys into it so the gateway config loader sees platform credentials and home channels.
+
+ The target is ``os.environ`` for the standalone CLI. Inside a multi-profile host (dashboard console
+ running ``send`` for profile B under its secret scope) it is the installed scope mapping: writing B's
+ ``.env`` into the shared process env would hand every other profile's later reads B's tokens
+ (``gateway.config._getenv`` reads the scope first, so the loader sees the same values either way).
+ """
import os
try:
from hermes_cli.config import get_hermes_home
home = get_hermes_home()
except Exception:
return
- env_path = home / ".env"
- if env_path.exists():
- try:
- from hermes_cli.env_loader import _load_dotenv_with_fallback
- _load_dotenv_with_fallback(env_path, override=True)
- except Exception:
- pass
+ from agent.secret_scope import current_secret_scope, is_multiplex_active, load_env_file
+ scope = current_secret_scope() if is_multiplex_active() else None
+ if isinstance(scope, dict):
+ target: dict = scope
+ env_path = home / ".env"
+ if env_path.exists():
+ target.update(load_env_file(env_path))
+ else:
+ target = os.environ
+ env_path = home / ".env"
+ if env_path.exists():
+ try:
+ from hermes_cli.env_loader import _load_dotenv_with_fallback
+ _load_dotenv_with_fallback(env_path, override=True)
+ except Exception:
+ pass
# Bridge top-level scalars the user (or the managed layer) actually wrote — never DEFAULT_CONFIG —
# into the environment, without overriding existing values.
@@ -159,8 +174,8 @@ def _load_hermes_env() -> None:
except Exception:
return
for key, val in cfg.items():
- if isinstance(val, (str, int, float, bool)) and key not in os.environ:
- os.environ[key] = str(val)
+ if isinstance(val, (str, int, float, bool)) and key not in target:
+ target[key] = str(val)
def cmd_send(args: argparse.Namespace) -> None:
diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.py
index d70b194bbc2..09a9a4c4699 100644
--- a/hermes_cli/web_routers/audio.py
+++ b/hermes_cli/web_routers/audio.py
@@ -397,8 +397,7 @@ async def speak_stream_ws(ws: "WebSocket") -> None:
# Profile via query param, like /api/pty and /api/console: the provider
# chain + API keys must resolve from the requesting profile's config, not
- # the dashboard's own. The streamer captures its config at resolve time,
- # so scoping resolution scopes the whole session.
+ # the dashboard's own — at resolve time AND in the synthesis thread.
profile = (ws.query_params.get("profile") or "").strip() or None
loop = asyncio.get_running_loop()
@@ -432,6 +431,13 @@ async def speak_stream_ws(ws: "WebSocket") -> None:
chunks: asyncio.Queue = asyncio.Queue() # PCM out; None = synthesis done
def _produce():
+ # Every streamer re-resolves its API key on each stream() call (tts_streaming ->
+ # resolve_provider_secret), so the whole synthesis body runs under the requesting
+ # profile's scope, not only the resolve step above (else the launch profile's key).
+ with _config_profile_scope(profile):
+ _synthesize()
+
+ def _synthesize():
from tools.tts_streaming import SentenceChunker
from tools.tts_text_normalize import _strip_markdown_for_tts
diff --git a/hermes_cli/web_routers/mcp.py b/hermes_cli/web_routers/mcp.py
index fa17cba2fb7..4c440327e5a 100644
--- a/hermes_cli/web_routers/mcp.py
+++ b/hermes_cli/web_routers/mcp.py
@@ -8,7 +8,6 @@ web_server — reached via the late-binding seam so tests that mutate
import asyncio
import hashlib
from contextlib import contextmanager
-from pathlib import Path
import re
import secrets
import threading
@@ -18,7 +17,7 @@ from typing import Any, Dict, Optional
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse
-from hermes_cli.web_deps import LateState, late
+from hermes_cli.web_deps import 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 (
@@ -42,26 +41,12 @@ _MAX_PENDING_MCP_OAUTH_FLOWS = 8
@contextmanager
def _profile_secret_scope(profile: Optional[str]):
- """Home + secret scope for a probe-class request: config.yaml's ``${VAR}`` expansion
- (``config._env_ref_lookup``) and the probe's own interpolation read plain ``os.environ``
- while no scope is installed — the dashboard process's env, i.e. the DEFAULT profile's
- values — so a secondary profile whose credential lives only in Bitwarden/1Password sent
- the literal placeholder or the default's token (#109901). Same wrapping as the OAuth
- worker (``_run_dashboard_mcp_oauth``). Home-only ``_config_profile_scope``, NOT
+ """Home + secret scope for a probe-class request (#109901). ``_config_profile_scope`` now binds
+ the secret scope itself; this stays the probe/OAuth callers' name. Home-only, NOT
``_profile_scope``: the body can block for seconds and the latter holds the process-global
- skills lock. A scope miss still falls through to ``os.environ`` outside multiplexing."""
- from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope
- from hermes_cli.env_loader import hydrate_profile_secret_sources
- from hermes_constants import get_hermes_home
-
+ skills lock."""
with _config_profile_scope(profile):
- home = Path(get_hermes_home())
- hydrate_profile_secret_sources(home) # first call may block on the source's fetch
- token = set_secret_scope(build_profile_secret_scope(home))
- try:
- yield
- finally:
- reset_secret_scope(token)
+ yield
def _secret_scoped(profile: Optional[str], fn):
diff --git a/hermes_cli/web_routers/tools.py b/hermes_cli/web_routers/tools.py
index c6bf5046a4f..a9e586d0510 100644
--- a/hermes_cli/web_routers/tools.py
+++ b/hermes_cli/web_routers/tools.py
@@ -233,9 +233,12 @@ async def get_toolsets(profile: Optional[str] = None):
platform: _get_platform_tools(config, platform, include_default_mcp_servers=False)
for platform in target_platforms}
features = get_nous_subscription_features(config)
- return config, toolset_rows, enabled_by_platform, features
+ # Credential presence resolves through the profile's secret scope: outside this block
+ # it read the dashboard process env (another profile's keys) or fails closed.
+ configured = {name: _toolset_has_keys(name, config, features=features) for name, _, _ in toolset_rows}
+ return config, toolset_rows, enabled_by_platform, configured
- config, toolset_rows, enabled_by_platform, features = await run_in_threadpool(_read)
+ config, toolset_rows, enabled_by_platform, configured = await run_in_threadpool(_read)
result = []
for name, label, desc in toolset_rows:
try:
@@ -256,7 +259,7 @@ async def get_toolsets(profile: Optional[str] = None):
"platform": target_platform,
"platform_label": gui_toolset_label(platform_label(target_platform, target_platform)),
"enabled": is_enabled, "available": is_enabled,
- "configured": _toolset_has_keys(name, config, features=features), "tools": tools})
+ "configured": configured[name], "tools": tools})
return result
diff --git a/hermes_cli/web_server_profiles.py b/hermes_cli/web_server_profiles.py
index 9e1404fafac..7507898affe 100644
--- a/hermes_cli/web_server_profiles.py
+++ b/hermes_cli/web_server_profiles.py
@@ -8,7 +8,7 @@ import os
import re
import sys
import threading
-from contextlib import contextmanager
+from contextlib import contextmanager, nullcontext
from fastapi import HTTPException
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
@@ -230,20 +230,48 @@ def _profile_scope(profile: Optional[str]):
@contextmanager
def _config_profile_scope(profile: Optional[str]):
- """Await-safe, config-only profile scope: touches ONLY the task-local HERMES_HOME
- contextvar, never the process-global skills-module attributes ``_profile_scope`` swaps
- (holding those across an ``await`` lets a concurrent request restore THIS request's dir
- on its ``finally``). None/""/"current" = no override.
+ """Await-safe profile scope: the task-local HERMES_HOME contextvar PLUS the profile's secret
+ scope, never the process-global skills-module attributes ``_profile_scope`` swaps (holding
+ those across an ``await`` lets a concurrent request restore THIS request's dir on its
+ ``finally``). None/""/"current" = no override.
+
+ Home alone left ``get_secret`` on the dashboard process's ``os.environ`` - the DEFAULT
+ profile's values - so ``GET /api/config?profile=B`` expanded B's ``${VAR}`` refs to the default
+ profile's plaintext credentials and ``load_gateway_config()`` under B's home bridged B's YAML
+ settings into the shared process env (``yaml_env_setter`` skips only under a secret scope).
+ A request for another profile's home also flips this process to fail-closed multi-profile
+ hosting (``tui_gateway/launch_profile_policy.py``), so any remaining unscoped read raises
+ instead of borrowing; the dashboard's own profile then runs under its frozen-launch-env scope.
Explicit names resolving to the process home retain current-profile semantics.
Still enter the requested home so a nested scope cannot retain another profile.
"""
+ from agent.secret_scope import (
+ build_profile_secret_scope, is_multiplex_active, reset_secret_scope, set_secret_scope)
+ from hermes_cli.env_loader import hydrate_profile_secret_sources
+ from tui_gateway.launch_profile_policy import activate_multi_profile_hosting, launch_secret_scope
+
+ process_home = get_process_hermes_home()
if _is_current_profile(profile):
- yield None
- return
- profile_dir = _resolve_profile_dir(profile.strip())
- with _hermes_home_scope(profile_dir):
- yield None if profile_dir.resolve() == get_process_hermes_home().resolve() else profile_dir
+ profile_dir, scoped = None, None # the dashboard's own profile: no home override
+ else:
+ profile_dir = _resolve_profile_dir(profile.strip())
+ scoped = None if profile_dir.resolve() == process_home.resolve() else profile_dir
+ if scoped is not None:
+ activate_multi_profile_hosting()
+ hydrate_profile_secret_sources(scoped) # first call may block on the source's fetch
+ secrets = build_profile_secret_scope(scoped)
+ elif is_multiplex_active():
+ secrets = launch_secret_scope(process_home)
+ else:
+ secrets = None # single-profile dashboard: legacy os.environ precedence (systemd / op-run injection)
+ with (_hermes_home_scope(profile_dir) if profile_dir is not None else nullcontext()):
+ token = set_secret_scope(secrets) if secrets is not None else None
+ try:
+ yield scoped
+ finally:
+ if token is not None:
+ reset_secret_scope(token)
# Terminal backend picker rows — GUI counterpart of terminal.backend. Keep in sync with