The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(multiplex): a served profile's turn sees its own cwd, approvals, redaction and tool policy
Teknium9c9e7ab6e5cf
diff --git a/agent/auxiliary_health.py b/agent/auxiliary_health.pyindex 7ba2cf0bfa7..9b6c0418257 100644--- a/agent/auxiliary_health.py+++ b/agent/auxiliary_health.py@@ -5,13 +5,17 @@ from typing import Any, Optionalfrom hermes_cli.route_identity import normalize_route_base_urldef _unhealthy_cache_key(provider: str, base_url: Optional[str] = None) -> Any:- """Provider-wide key, or endpoint-specific key for an explicit custom endpoint."""+ """Provider-wide key, or endpoint-specific key for an explicit custom endpoint — prefixed with the+ active profile home: a 402 on profile A's account must not hide the provider from profile B's+ (differently funded) account in the same multiplexed process."""from agent.auxiliary_client import _normalize_chain_label+ from hermes_constants import hermes_home_keylabel = _normalize_chain_label(provider)endpoint = normalize_route_base_url(_custom_health_base_url(provider, base_url))+ home_key = hermes_home_key()if endpoint:- return "custom-endpoint", endpoint- return label+ return home_key, "custom-endpoint", endpoint+ return home_key, labeldef _custom_health_base_url(provider: str, explicit_base_url: Optional[str] = None) -> str:diff --git a/agent/lsp/__init__.py b/agent/lsp/__init__.pyindex 5eb01ac707c..933655b00ff 100644--- a/agent/lsp/__init__.py+++ b/agent/lsp/__init__.py@@ -18,6 +18,10 @@ from agent.lsp.manager import LSPServicelogger = logging.getLogger("agent.lsp")_service: Optional[LSPService] = None+# Routed multiplex profiles (HERMES_HOME override) each get their own service: ``lsp.*`` config+# (enabled, servers, idle timeout) is per profile, so one process-wide singleton would let the first+# profile's settings decide whether every other profile gets diagnostics.+_services_by_home: dict = {}_atexit_registered = False_service_lock = threading.Lock()@@ -26,35 +30,52 @@ def _active(svc: Optional[LSPService]) -> Optional[LSPService]:return svc if (svc is not None and svc.is_active()) else None+def _register_atexit_once() -> None:+ global _atexit_registered+ if not _atexit_registered:+ atexit.register(_atexit_shutdown)+ _atexit_registered = True++def get_service() -> Optional[LSPService]:- """Return the lazily created process-wide LSP service singleton, or None when disabled.+ """Return the lazily created LSP service for the active profile (process-wide singleton when no+ profile override is bound), or None when disabled.Also registers an :mod:`atexit` hook so a clean exit tears down spawned servers:without it every ``hermes chat`` exit leaks pyright processes for a few secondswhile their stdout buffers drain. (SIGKILL/os._exit skip atexit — fine, thekernel reaps the stateless servers with their parent.)"""- global _service, _atexit_registered+ global _service+ from hermes_constants import get_hermes_home_override, hermes_home_key+ if get_hermes_home_override() is not None:+ home_key = hermes_home_key()+ with _service_lock:+ if home_key not in _services_by_home:+ _services_by_home[home_key] = LSPService.create_from_config()+ _register_atexit_once()+ return _active(_services_by_home[home_key])if _service is None:with _service_lock:if _service is None:_service = LSPService.create_from_config()- if not _atexit_registered:- atexit.register(_atexit_shutdown)- _atexit_registered = True+ _register_atexit_once()return _active(_service)def shutdown_service() -> None:- """Tear down the LSP service if one was started. Idempotent."""+ """Tear down every LSP service that was started. Idempotent."""global _servicewith _service_lock:- svc, _service = _service, None- if svc is not None:- try:- svc.shutdown()- except Exception as e: # noqa: BLE001- logger.debug("LSP shutdown error: %s", e)+ services = [_service, *_services_by_home.values()]+ _service = None+ _services_by_home.clear()+ for svc in services:+ if svc is not None:+ try:+ svc.shutdown()+ except Exception as e: # noqa: BLE001+ logger.debug("LSP shutdown error: %s", e)def _atexit_shutdown() -> None:diff --git a/agent/redact.py b/agent/redact.pyindex 136c1fb487b..bba13d2882c 100644--- a/agent/redact.py+++ b/agent/redact.py@@ -95,6 +95,40 @@ _SENSITIVE_QUERY_PARAMS = frozenset({# see `_log_redaction_status()` in gateway/run.py and cli.py._REDACT_ENABLED = os.getenv("HERMES_REDACT_SECRETS", "true").lower() in {"1", "true", "yes", "on"}+# Routed multiplex profiles: the import-time snapshot above is the LAUNCH profile's policy. A profile+# served under a HERMES_HOME override resolves its own ``security.redact_secrets`` (its ``.env``+# value first, like the standalone bridge in hermes_cli/main.py), cached per home so the hot path+# stays a dict lookup. Still not a live ``os.environ`` read, so a shell ``export`` cannot flip it.+_REDACT_ENABLED_BY_HOME: dict = {}+_REDACT_ENABLED_LOCK = threading.Lock()+++def _redact_enabled() -> bool:+ """Effective redaction switch for the active profile (launch snapshot when no override)."""+ from hermes_constants import get_hermes_home_override, hermes_home_key+ if get_hermes_home_override() is None:+ return _REDACT_ENABLED+ home_key = hermes_home_key()+ cached = _REDACT_ENABLED_BY_HOME.get(home_key)+ if cached is not None:+ return cached+ enabled = True+ try:+ from agent.secret_scope import current_secret_scope+ scope = current_secret_scope()+ raw = scope.get("HERMES_REDACT_SECRETS") if scope else None+ if raw is None:+ from hermes_cli.config import load_config_readonly+ cfg_val = (load_config_readonly().get("security") or {}).get("redact_secrets")+ raw = None if cfg_val is None else str(cfg_val)+ if raw is not None:+ enabled = str(raw).strip().lower() in {"1", "true", "yes", "on"}+ except Exception:+ enabled = True # unreadable policy: keep the secure default+ with _REDACT_ENABLED_LOCK:+ _REDACT_ENABLED_BY_HOME[home_key] = enabled+ return enabled+# Known API key prefixes -- match the prefix + contiguous token chars.# Every pattern MUST start with a literal prefix: _PREFIX_SUBSTRINGS (the cheap# pre-screen gate) is derived from these literals and must stay false-negative-free.@@ -645,7 +679,7 @@ def redact_sensitive_text(text: str, *, force: bool = False, code_file: bool = Freturn text# Vault secrets are a hard model-egress boundary: scrubbed regardless of the redact_secrets preference.text = redact_registered_vault_values(text)- if not (force or _REDACT_ENABLED):+ if not (force or _redact_enabled()):return textcode_file = code_file or file_readdiff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex 518b714f1b0..3fc5f6b8b58 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -939,7 +939,8 @@ def _begin_tool_execution(agent, ref: _ToolCallRef, display_index: int | None) -elif function_name == "terminal":command = function_args.get("command", "")if _is_destructive_command(command):- cwd = function_args.get("workdir") or os.getenv("TERMINAL_CWD", os.getcwd())+ from agent.runtime_cwd import scope_terminal_cwd+ cwd = function_args.get("workdir") or scope_terminal_cwd() or os.getcwd()agent._checkpoint_mgr.ensure_checkpoint(cwd, f"before terminal: {command[:60]}")diff --git a/tests/tools/test_credential_files.py b/tests/tools/test_credential_files.pyindex eb41a99997e..cf6665f2293 100644--- a/tests/tools/test_credential_files.py+++ b/tests/tools/test_credential_files.py@@ -24,10 +24,10 @@ def _clean_state():"""Reset module state between tests."""import tools.credential_files as _cred_modclear_credential_files()- _cred_mod._config_files = None+ _cred_mod._config_files = {}yieldclear_credential_files()- _cred_mod._config_files = None+ _cred_mod._config_files = {}class TestRegisterCredentialFiles:diff --git a/tests/tools/test_multiplex_turn_parity.py b/tests/tools/test_multiplex_turn_parity.pynew file mode 100644index 00000000000..dca02ce74a2--- /dev/null+++ b/tests/tools/test_multiplex_turn_parity.py@@ -0,0 +1,145 @@+"""Multiplexed-gateway parity for what a TURN sees: a profile served by the default multiplexer+(``_profile_runtime_scope``) must observe the same tool-side policy its standalone gateway+(``HERMES_HOME=<profile>``) would — never the launch profile's values frozen into process caches or+read from the process env.++Every test warms the site under launch home A, then reads under routed profile B with different+config (real temp homes, real config.yaml, real terminal scope; no mocks of the thing under test).+"""++from __future__ import annotations++from pathlib import Path++import pytest+import yaml++from hermes_constants import reset_hermes_home_override, set_hermes_home_override+++def two_homes(tmp_path, monkeypatch):+ """Launch home A (HERMES_HOME) and routed profile B, differing in every setting under test."""+ a = tmp_path / ".hermes"+ b = a / "profiles" / "b"+ b.mkdir(parents=True)+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(a))+ for name, home in (("a", a), ("b", b)):+ (home / f"cred_{name}.txt").write_text("x", encoding="utf-8")+ (home / "config.yaml").write_text(yaml.safe_dump({+ "terminal": {"backend": "local" if name == "a" else "docker",+ "credential_files": [f"cred_{name}.txt"]},+ "command_allowlist": [f"{name}-only-cmd *"],+ "security": {"redact_secrets": name == "b"},+ "browser": {"engine": "chrome" if name == "a" else "lightpanda", "headed": name == "b"},+ "lsp": {"enabled": name == "b"},+ }), encoding="utf-8")+ return a, b+++def _under(home: Path, fn):+ token = set_hermes_home_override(str(home))+ try:+ return fn()+ finally:+ reset_hermes_home_override(token)+++def test_routed_local_profile_cwd_matches_standalone_gateway(tmp_path, two_homes):+ """A standalone gateway resolves an unset ``terminal.cwd`` on a local backend to ``$HOME`` at+ import; the routed profile's terminal scope must yield the same cwd, not the multiplexer's+ process cwd — otherwise the system prompt, context files and the terminal all start in+ wherever ``hermes gateway`` happened to be launched from."""+ from tools.terminal_scope import build_profile_terminal_scope, install_and_reset_profile_terminal_scope+ from agent.runtime_cwd import resolve_agent_cwd++ a, _ = two_homes+ assert build_profile_terminal_scope(a)["TERMINAL_CWD"] == str(tmp_path)+ with install_and_reset_profile_terminal_scope(a):+ assert resolve_agent_cwd() == tmp_path+ # Non-local backends stay unset (sandbox default), exactly like gateway/run.py's placeholder rule.+ assert "TERMINAL_CWD" not in build_profile_terminal_scope(two_homes[1])+++def test_terminal_backend_consumers_read_the_routed_scope(two_homes):+ """Every ``TERMINAL_ENV`` reader that shapes a turn (image-source locality, credential-file path+ translation, image-gen cache base, skill readiness) resolves the ROUTED profile's backend."""+ from gateway.run import _profile_runtime_scope+ from tools import credential_files, image_generation_tool, image_source++ a, b = two_homes++ def observe():+ return (+ image_source._is_local_terminal_backend(),+ image_generation_tool._agent_cache_base_for_env(None),+ credential_files.to_agent_visible_cache_path("/host/.hermes/x.png", "/root/.hermes"),+ sorted(Path(m["host_path"]).name for m in credential_files.get_credential_file_mounts()),+ )++ with _profile_runtime_scope(a):+ assert observe() == (True, None, "/host/.hermes/x.png", ["cred_a.txt"])+ with _profile_runtime_scope(b):+ local, cache_base, translated, mounts = observe()+ assert local is False+ assert cache_base == "/root/.hermes"+ assert translated != "/host/.hermes/x.png" or mounts == ["cred_b.txt"]+ assert mounts == ["cred_b.txt"]+++def test_permanent_allowlist_is_per_profile(two_homes):+ """Profile A's ``command_allowlist`` must not pre-approve commands for routed profile B, and+ B's own 'always' approvals must not be folded into A's set."""+ from tools import approval++ a, b = two_homes+ approval.load_permanent_allowlist() # launch-profile startup load (A)+ assert approval.is_approved("s", "a-only-cmd *")+ assert _under(b, lambda: approval.is_approved("s", "a-only-cmd *")) is False+ assert _under(b, lambda: approval.is_approved("s", "b-only-cmd *")) is True+ _under(b, lambda: approval.approve_permanent("b-always *"))+ assert not approval.is_approved("s", "b-always *")+ assert _under(a, lambda: approval.is_approved("s", "a-only-cmd *"))+++def test_profile_scoped_process_caches_follow_routed_home(two_homes, monkeypatch):+ """Config-derived singletons (redaction switch, aux unhealthy marks, LSP service, browser+ engine/headed flags, MCP stderr log path) are keyed by the routed profile home."""+ from agent import auxiliary_client, lsp, redact+ from tools import browser_tool_cloud, mcp_tool_config+ from tools.browser_tool_lifecycle import cleanup_all_browsers++ a, b = two_homes+ monkeypatch.setattr(redact, "_REDACT_ENABLED", False) # launch profile opted out+ redact._REDACT_ENABLED_BY_HOME.clear()+ token = "sk-abcdefghijklmnopqrstuvwxyz0123456789"+ assert redact.redact_sensitive_text(token) == token+ assert _under(b, lambda: redact.redact_sensitive_text(token)) != token++ auxiliary_client._reset_aux_unhealthy_cache()+ _under(a, lambda: auxiliary_client._mark_provider_unhealthy("openrouter"))+ assert _under(a, lambda: auxiliary_client._is_provider_unhealthy("openrouter")) is True+ assert _under(b, lambda: auxiliary_client._is_provider_unhealthy("openrouter")) is False++ lsp.shutdown_service()+ try:+ assert _under(a, lsp.get_service) is None+ assert _under(b, lsp.get_service) is not None+ finally:+ lsp.shutdown_service()++ cleanup_all_browsers()+ assert _under(a, browser_tool_cloud._get_browser_engine) == "chrome"+ assert _under(b, browser_tool_cloud._get_browser_engine) == "lightpanda"+ assert _under(a, browser_tool_cloud._is_headed_mode) is False+ assert _under(b, browser_tool_cloud._is_headed_mode) is True++ mcp_tool_config._mcp_stderr_log_fh.clear()+ try:+ assert Path(_under(a, mcp_tool_config._get_mcp_stderr_log).name).parent == a / "logs"+ assert Path(_under(b, mcp_tool_config._get_mcp_stderr_log).name).parent == b / "logs"+ finally:+ for fh in mcp_tool_config._mcp_stderr_log_fh.values():+ fh.close()+ mcp_tool_config._mcp_stderr_log_fh.clear()diff --git a/tests/tools/test_tool_result_storage.py b/tests/tools/test_tool_result_storage.pyindex 4e04ffc47c4..8e3cc1eb643 100644--- a/tests/tools/test_tool_result_storage.py+++ b/tests/tools/test_tool_result_storage.py@@ -324,7 +324,7 @@ class TestSpillover:monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))# Reset the once-per-process prune flag so each test is independent.import tools.tool_result_storage as trs- monkeypatch.setattr(trs, "_spillover_pruned_once", False)+ monkeypatch.setattr(trs, "_spillover_pruned_homes", set())yielddef test_env_none_persists_to_spillover(self):diff --git a/tools/approval.py b/tools/approval.pyindex 503ab01d8fd..7fb8d43f9d2 100644--- a/tools/approval.py+++ b/tools/approval.py@@ -52,6 +52,8 @@ _pending: dict[str, dict] = {}_session_approved: dict[str, set] = {}_session_yolo: set[str] = set()_permanent_approved: set = set()+# Routed multiplex profiles: one permanent allowlist per profile home (see ``_permanent_set``).+_permanent_approved_by_home: dict[str, set] = {}# --- Consecutive-denial circuit breaker for smart approvals ---------------------------------------------------------# Each retry of a smart-denied command burns another guardian LLM call. After ``approvals.denial_breaker_threshold``@@ -288,25 +290,47 @@ def _yolo_active() -> bool:return _YOLO_MODE_FROZEN or is_current_session_yolo_enabled()+def _permanent_set() -> set:+ """The permanent allowlist that governs the ACTIVE profile. Unscoped (single-profile process,+ or the multiplexer's own launch profile) → the module-level set tests and the CLI seed. A routed+ profile (HERMES_HOME override) → its own set, lazily loaded from ITS ``command_allowlist``: the+ launch profile's "always" approvals must not pre-approve commands for a secondary, nor may a+ secondary's "always" choice be written back into the launch profile's config. Callers hold ``_lock``.+ """+ from hermes_constants import get_hermes_home_override, hermes_home_key+ if get_hermes_home_override() is None:+ return _permanent_approved+ home_key = hermes_home_key()+ approved = _permanent_approved_by_home.get(home_key)+ if approved is None:+ try:+ approved = _read_permanent_allowlist()+ except Exception as e:+ logger.warning("Failed to load permanent allowlist: %s", e)+ approved = set()+ _permanent_approved_by_home[home_key] = approved+ return approved++def is_approved(session_key: str, pattern_key: str) -> bool:"""Session-scoped or permanent approval. Accepts the canonical key and the legacyregex-derived key so existing command_allowlist entries survive key migrations."""aliases = _approval_key_aliases(pattern_key)with _lock:- approved = _permanent_approved | _session_approved.get(session_key, set())+ approved = _permanent_set() | _session_approved.get(session_key, set())return any(alias in approved for alias in aliases)def approve_permanent(pattern_key: str):"""Add a pattern to the permanent allowlist."""with _lock:- _permanent_approved.add(pattern_key)+ _permanent_set().add(pattern_key)def load_permanent(patterns: set):"""Bulk-load permanent allowlist entries from config."""with _lock:- _permanent_approved.update(patterns)+ _permanent_set().update(patterns)def _persist_choice(session_key: str, choice: str, warnings: list[tuple]) -> None:@@ -319,34 +343,41 @@ def _persist_choice(session_key: str, choice: str, warnings: list[tuple]) -> Nonapprove_session(session_key, key)if choice == "always" and not is_tirith:approve_permanent(key)- save_permanent_allowlist(_permanent_approved)+ with _lock:+ snapshot = set(_permanent_set())+ save_permanent_allowlist(snapshot)# --- Config persistence for permanent allowlist ---------------------------------------------------------------------+def _read_permanent_allowlist() -> set:+ """``command_allowlist`` of the active profile's config as a set (empty on malformed input)."""+ from hermes_cli.config import load_config_readonly+ config = load_config_readonly()+ raw = config.get("command_allowlist")+ legacy = isinstance(raw, str)+ if legacy:+ # Old config-set versions serialized list values as scalar strings.+ import yaml+ try:+ raw = yaml.safe_load(raw)+ except yaml.YAMLError:+ raw = False+ if raw is None and not legacy:+ raw = []+ if not isinstance(raw, list) or any(not isinstance(item, str) for item in raw):+ logger.warning("Ignoring malformed command_allowlist; configure a list of strings.")+ return set()+ if legacy:+ logger.warning("Recovered legacy string command_allowlist; re-save it as a list of strings.")+ return set(raw)++def load_permanent_allowlist() -> set:"""Load ``command_allowlist`` from config and sync it into the approval stateso is_approved() honors 'always' choices from previous sessions."""try:- from hermes_cli.config import load_config_readonly- config = load_config_readonly()- raw = config.get("command_allowlist")- legacy = isinstance(raw, str)- if legacy:- # Old config-set versions serialized list values as scalar strings.- import yaml- try:- raw = yaml.safe_load(raw)- except yaml.YAMLError:- raw = False- if raw is None and not legacy:- raw = []- if not isinstance(raw, list) or any(not isinstance(item, str) for item in raw):- logger.warning("Ignoring malformed command_allowlist; configure a list of strings.")- return set()- if legacy:- logger.warning("Recovered legacy string command_allowlist; re-save it as a list of strings.")- patterns = set(raw)+ patterns = _read_permanent_allowlist()if patterns:load_permanent(patterns)return patternsdiff --git a/tools/approval_floors.py b/tools/approval_floors.pyindex d85c4c60c98..66172bbad62 100644--- a/tools/approval_floors.py+++ b/tools/approval_floors.py@@ -195,7 +195,7 @@ def _command_matches_permanent_allowlist(command: str) -> bool:if not command or _has_allowlist_shell_operator(command):return Falsewith _a._lock:- patterns = tuple(_a._permanent_approved)+ patterns = tuple(_a._permanent_set())for pattern in patterns:pattern = pattern.strip() if isinstance(pattern, str) else ""if pattern and (command == pattern or (any(ch in pattern for ch in "*?[")diff --git a/tools/browser_tool_cloud.py b/tools/browser_tool_cloud.pyindex 3d52d382491..d2ca2e46c59 100644--- a/tools/browser_tool_cloud.py+++ b/tools/browser_tool_cloud.py@@ -19,7 +19,14 @@ from tools import browser_tool_cdp as _cdpdef _memo(_bt, resolved_attr: str, cache_attr: str, compute: Callable[[], object]):- """Process-lifetime cache on ``_bt``: the resolved flag is set BEFORE computing, then the final value is stored."""+ """Process-lifetime cache on ``_bt``: the resolved flag is set BEFORE computing, then the final value is stored.++ Under a routed profile (HERMES_HOME override, multiplexed gateway) the slot is NOT consulted: every+ ``_memo`` here caches a ``browser.*`` config read, and one process-wide slot would hand the launch+ profile's engine/headed/private-URL policy to every other profile (same rule as ``_allow_private_urls``).+ """+ if get_hermes_home_override() is not None:+ return compute()if not getattr(_bt, resolved_attr):setattr(_bt, resolved_attr, True)setattr(_bt, cache_attr, compute())diff --git a/tools/credential_files.py b/tools/credential_files.pyindex d39e5c3250f..6693478ba57 100644--- a/tools/credential_files.py+++ b/tools/credential_files.py@@ -29,8 +29,8 @@ logger = logging.getLogger(__name__)# Session-scoped registry; ContextVar prevents cross-session bleed in the gateway._registered_files_var: ContextVar[Dict[str, str]] = ContextVar("_registered_files")-# Cache for config-based file list (loaded once per process; tests reset it).-_config_files: List[Dict[str, str]] | None = None+# Cache for config-based file list, one entry per profile home (tests reset it).+_config_files: Dict[str, List[Dict[str, str]]] = {}# Reused across calls so sanitized skill copies don't accumulate._safe_skills_tempdir: Path | None = None@@ -118,10 +118,14 @@ def register_credential_files(entries: list, container_base: str = "/root/.hermedef _load_config_files() -> List[Dict[str, str]]:- """Load ``terminal.credential_files`` from config.yaml (cached)."""- global _config_files- if _config_files is not None:- return _config_files+ """Load ``terminal.credential_files`` from config.yaml (cached per profile home: the+ multiplexed gateway must never mount the launch profile's credential files into a+ secondary profile's sandbox)."""+ from hermes_constants import hermes_home_key+ home_key = hermes_home_key()+ cached = _config_files.get(home_key)+ if cached is not None:+ return cachedresult: List[Dict[str, str]] = []try:@@ -141,8 +145,8 @@ def _load_config_files() -> List[Dict[str, str]]:except Exception as e:logger.warning("Could not read terminal.credential_files from config: %s", e)- _config_files = result- return _config_files+ _config_files[home_key] = result+ return resultdef get_credential_file_mounts() -> List[Dict[str, str]]:@@ -301,7 +305,7 @@ def map_cache_path_to_container(host_path: str, container_base: str = "/root/.hedef from_agent_visible_cache_path(container_path: str, container_base: str = "/root/.hermes") -> str:"""Inverse of :func:`to_agent_visible_cache_path`; unchanged unless Docker + cache dir."""- if os.environ.get("TERMINAL_ENV", "local") != "docker":+ if _terminal_backend() != "docker":return container_pathmapped = _remap_cache_path(container_path, container_base, "container_path", "host_path", lambda root, rel: str(Path(root) / rel))return mapped if mapped is not None else container_path@@ -312,6 +316,13 @@ def from_agent_visible_cache_path(container_path: str, container_base: str = "/r_HOME_RELATIVE_BACKENDS = frozenset({"ssh", "daytona", "vercel_sandbox"})+def _terminal_backend() -> str:+ """Active ``TERMINAL_ENV`` through the per-turn terminal scope (a routed multiplex profile's+ backend, never the launch profile's process env)."""+ from tools.terminal_scope import terminal_env+ return (terminal_env("TERMINAL_ENV") or "local").strip().lower()++def to_agent_visible_cache_path(host_path: str, container_base: str = "/root/.hermes") -> str:"""Translate a host cache path to where the active backend (TERMINAL_ENV) sees it.@@ -326,7 +337,7 @@ def to_agent_visible_cache_path(host_path: str, container_base: str = "/root/.heactual remote home. Previously these backends synced the bytes but still rendered the dangling host path(#76577 gap)."""- backend = (os.environ.get("TERMINAL_ENV") or "local").strip().lower()+ backend = _terminal_backend()if backend in _HOME_RELATIVE_BACKENDS:container_base = "~/.hermes"elif backend not in ("docker", "modal"):diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.pyindex f9823c11cc3..46e913f88e6 100644--- a/tools/delegate_tool_progress.py+++ b/tools/delegate_tool_progress.py@@ -187,8 +187,9 @@ def _build_child_system_prompt(def _resolve_workspace_hint(parent_agent) -> Optional[str]:"""Best-effort local workspace hint for child prompts: only a concreteabsolute directory is ever injected (never a fake container path)."""+ from agent.runtime_cwd import scope_terminal_cwdcandidates = [- os.getenv("TERMINAL_CWD"), getattr(getattr(parent_agent, "_subdirectory_hints", None), "working_dir", None),+ scope_terminal_cwd(), getattr(getattr(parent_agent, "_subdirectory_hints", None), "working_dir", None),getattr(parent_agent, "terminal_cwd", None), getattr(parent_agent, "cwd", None),]for candidate in filter(None, candidates):diff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.pyindex 887d390e833..7c0b8fc2575 100644--- a/tools/image_generation_tool.py+++ b/tools/image_generation_tool.py@@ -319,7 +319,8 @@ def _agent_cache_base_for_env(env: Any) -> str | None:return f"{str(remote_home).rstrip('/')}/.hermes"if env.__class__.__name__ in _CONTAINER_HOME_ENVS:return "/root/.hermes"- backend = (os.getenv("TERMINAL_ENV") or "local").strip().lower()+ from tools.terminal_scope import terminal_env+ backend = (terminal_env("TERMINAL_ENV") or "local").strip().lower()return _CACHE_BASE_BY_BACKEND.get(backend)@@ -713,7 +714,8 @@ def _confine_source_images(image_url, reference_image_urls, task_id, *, permittecredential guard) so generation obeys the same confinement as vision. URLs/data: passthrough; local backend is a no-op. Returns ``(image_url, reference_image_urls, error_json_or_None)``."""- if (os.getenv("TERMINAL_ENV") or "local").strip().lower() in ("", "local"):+ from tools.terminal_scope import terminal_env+ if (terminal_env("TERMINAL_ENV") or "local").strip().lower() in ("", "local"):return image_url, reference_image_urls, Nonefrom model_tools import _run_asyncfrom tools.image_source import ImageResolutionError, resolve_local_source_to_data_urldiff --git a/tools/image_source.py b/tools/image_source.pyindex feeed2d069d..c780cf7ef74 100644--- a/tools/image_source.py+++ b/tools/image_source.py@@ -144,8 +144,10 @@ async def _download_to_bytes(url: str) -> bytes:def _is_local_terminal_backend() -> bool:- """True when the terminal backend runs directly on the host (keys off ``TERMINAL_ENV``)."""- return os.getenv("TERMINAL_ENV", "local").strip().lower() in ("local", "")+ """True when the terminal backend runs directly on the host (keys off ``TERMINAL_ENV``, read+ through the per-turn terminal scope so a routed multiplex profile sees ITS backend)."""+ from tools.terminal_scope import terminal_env+ return terminal_env("TERMINAL_ENV", "local").strip().lower() in ("local", "")# Host-side media caches: the only host paths vision may read under a non-local backenddiff --git a/tools/mcp_tool_config.py b/tools/mcp_tool_config.pyindex c981144ff00..c7064ab32a9 100644--- a/tools/mcp_tool_config.py+++ b/tools/mcp_tool_config.py@@ -15,31 +15,33 @@ from tools.mcp_tool_common import _env_ref_name, _prepend_pathlogger = logging.getLogger("tools.mcp_tool")-_mcp_stderr_log_fh: Optional[Any] = None+_mcp_stderr_log_fh: Dict[str, Any] = {} # profile home key -> handle_mcp_stderr_log_lock = threading.Lock()def _get_mcp_stderr_log() -> Any:- """Shared append-mode handle for MCP subprocess stderr, opened once per process. Must expose a- real fd (asyncio wires the child's stderr to it); falls back to ``/dev/null``, then real stderr."""- global _mcp_stderr_log_fh+ """Shared append-mode handle for MCP subprocess stderr, opened once per process PER PROFILE HOME (a+ multiplexed gateway's secondary profile must log under ITS ``logs/``, not the launch profile's). Must+ expose a real fd (asyncio wires the child's stderr to it); falls back to ``/dev/null``, then real stderr."""+ from hermes_constants import get_hermes_home, hermes_home_key+ home_key = hermes_home_key()with _mcp_stderr_log_lock:- if _mcp_stderr_log_fh is None:+ fh = _mcp_stderr_log_fh.get(home_key)+ if fh is None:try:- from hermes_constants import get_hermes_homelog_dir = get_hermes_home() / "logs"log_dir.mkdir(parents=True, exist_ok=True)# Line-buffered so output lands promptly; errors="replace" tolerates garbled binary.fh = open(log_dir / "mcp-stderr.log", "a", encoding="utf-8", errors="replace", buffering=1)fh.fileno() # confirm a real fd before committing- _mcp_stderr_log_fh = fhexcept Exception as exc: # pragma: no cover — best-effort fallbacklogger.debug("Failed to open MCP stderr log, using devnull: %s", exc)try:- _mcp_stderr_log_fh = open(os.devnull, "w", encoding="utf-8")+ fh = open(os.devnull, "w", encoding="utf-8")except Exception:- _mcp_stderr_log_fh = sys.stderr- return _mcp_stderr_log_fh+ fh = sys.stderr+ _mcp_stderr_log_fh[home_key] = fh+ return fhdef _write_stderr_log_header(server_name: str) -> None:diff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex ed7b318df13..63e4ff1d179 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -412,7 +412,8 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dictallows) and register what's available for sandboxes. Returns ``(fields, extras)``: fields gobefore ``_source_path`` in the skill_view result, extras after — key order is tool output."""required_env_vars = _get_required_environment_variables(frontmatter)- backend = str(os.getenv("TERMINAL_ENV", "local")).strip().lower() or "local"+ from tools.terminal_scope import terminal_env+ backend = str(terminal_env("TERMINAL_ENV", "local")).strip().lower() or "local"env_snapshot = load_env()missing_required_env_vars = [e for e in required_env_varsdiff --git a/tools/terminal_scope.py b/tools/terminal_scope.pyindex b87c74a2e14..5c90b4b6f3f 100644--- a/tools/terminal_scope.py+++ b/tools/terminal_scope.py@@ -142,9 +142,32 @@ def build_profile_terminal_scope(hermes_home: "Any") -> Dict[str, str]:raw_terminal = raw.get("terminal") if isinstance(raw, dict) else Noneif isinstance(raw_terminal, dict):_apply(raw_terminal)+ _resolve_scope_cwd_placeholder(scope)return scope+def _resolve_scope_cwd_placeholder(scope: Dict[str, str]) -> None:+ """Give a scope with no explicit ``terminal.cwd`` the same resolved ``TERMINAL_CWD`` a standalone+ gateway computes at import (``gateway/run.py``: local backend → ``$HOME``; docker with the+ workspace mount → the host cwd signal; other backends → unset). Without it a routed turn's+ ``resolve_agent_cwd()`` falls back to the multiplexer PROCESS cwd (wherever ``hermes gateway``+ was launched), so the system prompt, context-file discovery and the local terminal all run in+ a directory the profile's standalone gateway would never have used."""+ if scope.get("TERMINAL_CWD"):+ return+ from gateway.cwd_placeholder import resolve_placeholder_terminal_cwd++ resolved = resolve_placeholder_terminal_cwd(+ configured_cwd="", terminal_backend=scope.get("TERMINAL_ENV", ""),+ messaging_cwd=None,+ docker_mount_cwd_to_workspace=scope.get(+ "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").strip().lower() in {"true", "1", "yes"},+ home_fallback=str(Path.home()),+ )+ if resolved:+ scope["TERMINAL_CWD"] = resolved++def install_profile_terminal_scope(hermes_home: "Any") -> Token:"""Build AND install a profile's policy; on failure install the refusal scope. Never raises."""try:diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.pyindex 216d843b5cc..550106c7174 100644--- a/tools/tool_result_storage.py+++ b/tools/tool_result_storage.py@@ -26,7 +26,7 @@ _UNSAFE_RESULT_FILENAME_CHARS = re.compile(r"[^A-Za-z0-9_.-]+")_MAX_RESULT_FILENAME_STEM = 120_spillover_prune_lock = threading.Lock()-_spillover_pruned_once = False+_spillover_pruned_homes: set = set() # profile home keys already swept this processdef get_spillover_dir():@@ -55,12 +55,15 @@ def cleanup_spillover_cache(max_age_hours: int = SPILLOVER_MAX_AGE_HOURS) -> intdef _prune_spillover_once() -> None:- """Best-effort prune, at most once per process (CLI-only installs never run housekeeping)."""- global _spillover_pruned_once+ """Best-effort prune, at most once per process PER PROFILE HOME (CLI-only installs never run+ housekeeping; a multiplexed gateway must sweep every profile's ``cache/spillover``, not just the+ first one that spilled)."""+ from hermes_constants import hermes_home_key+ home_key = hermes_home_key()with _spillover_prune_lock:- if _spillover_pruned_once:+ if home_key in _spillover_pruned_homes:return- _spillover_pruned_once = True+ _spillover_pruned_homes.add(home_key)try:if removed := cleanup_spillover_cache():logger.debug("Pruned %d expired spillover file(s)", removed)diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.mdindex 45f6205911f..0ae62f4df8f 100644--- a/website/docs/user-guide/multi-profile-gateways.md+++ b/website/docs/user-guide/multi-profile-gateways.md@@ -349,6 +349,9 @@ profile and never shares with the default or any sibling:| Session namespace | `agent:<profile>:…` (default keeps `agent:main:…`) | Two profiles on the same chat never share history || Logs | `agent.log` / `errors.log` / `gateway.log` under the profile's own home | — || Terminal sandbox settings (`terminal.*`, SSH targets) | The profile's `config.yaml` | Documented default; unparsable config → execution refused |+| Working directory of a turn (unset `terminal.cwd`) | Same rule as a standalone gateway: `$HOME` for the local backend, sandbox default otherwise | Never the directory the multiplexer process was launched from |+| Command approvals (`command_allowlist`, "always" choices) | The profile's own `config.yaml` | A default-profile "always" never pre-approves a secondary's command; a secondary's choice is saved to its own config |+| Sandbox credential-file mounts (`terminal.credential_files`), `security.redact_secrets`, `browser.*` engine/headed flags, `lsp.*`, auxiliary-provider health marks, `logs/mcp-stderr.log` | The profile's own `config.yaml` / `.env` | Documented default — never the launch profile's cached value |What is **shared** by design: the process, its PID/lock and `gateway_state.json`(default home), the one HTTP listener, and the `profile_routes` table (declared