The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): honor explicit config keys over stale env
ajzrva-sys34c11fa6894b
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 0e653fd6d5c..6668677bd52 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -3233,14 +3233,17 @@ def apply_terminal_config_to_env(gives those child-process launch paths the same config bridge as classicCLI without importing ``cli.py`` and paying for its startup side effects.- When the user config contains a ``terminal`` section, config.yaml is- authoritative and overrides existing env values. Otherwise defaults only- backfill missing env vars so exported/.env values keep working.+ Explicit keys in the user config's ``terminal`` section are authoritative+ and override their matching env values. Merged defaults only backfill+ missing env vars; they never replace unrelated exported/.env values."""target = os.environ if env is None else envraw_config = read_raw_config()- file_has_terminal_config = isinstance(raw_config.get("terminal"), dict)+ raw_terminal_cfg = raw_config.get("terminal")+ file_has_terminal_config = isinstance(raw_terminal_cfg, dict)+ if not file_has_terminal_config:+ raw_terminal_cfg = {}should_override = file_has_terminal_config if override is None else overridecfg = config if config is not None else load_config_readonly()@@ -3248,6 +3251,12 @@ def apply_terminal_config_to_env(if not isinstance(terminal_cfg, dict):return target+ # A caller-supplied config is its own source of explicit keys. For the+ # normal merged-config path, only keys present in raw config.yaml may+ # override existing env values; keys inherited from DEFAULT_CONFIG are+ # backfill-only.+ explicit_keys = terminal_cfg.keys() if config is not None else raw_terminal_cfg.keys()+for cfg_key, env_var in TERMINAL_CONFIG_ENV_MAP.items():if cfg_key not in terminal_cfg:continue@@ -3258,7 +3267,7 @@ def apply_terminal_config_to_env(continueif isinstance(value, str):value = os.path.expanduser(value)- if should_override or env_var not in target:+ if (should_override and cfg_key in explicit_keys) or env_var not in target:target[env_var] = _terminal_env_value(value)return targetdiff --git a/tests/tools/test_terminal_env_bridge.py b/tests/tools/test_terminal_env_bridge.pyindex acfc0b4d5fa..b1f9ffb7a2c 100644--- a/tests/tools/test_terminal_env_bridge.py+++ b/tests/tools/test_terminal_env_bridge.py@@ -1,16 +1,9 @@-"""Regression tests for the terminal config → env fallback bridge.--``terminal_tool._get_env_config()`` reads all settings from TERMINAL_* env-vars, which the CLI / gateway / TUI-PTY launchers bridge from config.yaml at-startup. Processes that skip every launcher bridge (``hermes serve`` and the-Desktop app's in-process agents, the desktop cron ticker, ACP) used to fall-back silently to the local backend even when config.yaml selected-``terminal.backend: docker`` — commands the user intended to sandbox ran on-the host (#63141 / #54449 / #61115 / #65696).--``_ensure_terminal_env_bridged()`` closes that hole at the chokepoint: when-TERMINAL_ENV is unset, backfill TERMINAL_* from config.yaml before the-local default applies. An explicitly-set TERMINAL_ENV always wins.+"""Behavioral regressions for the terminal config → env bridge.++``terminal_tool._get_env_config()`` reads TERMINAL_* variables. The bridge+must let explicitly configured terminal keys override stale launcher/.env+values while preserving environment values for terminal keys omitted from+config.yaml."""import os@@ -23,13 +16,15 @@ from hermes_constants import get_hermes_home@pytest.fixture(autouse=True)def _reset_bridge_state(monkeypatch):- """Each test starts with an un-attempted bridge and no TERMINAL_ENV."""+ """Each test starts with an un-attempted bridge and clean mapped env."""monkeypatch.setattr(terminal_tool, "_terminal_config_bridge_attempted", False)- monkeypatch.delenv("TERMINAL_ENV", raising=False)- monkeypatch.delenv("TERMINAL_CWD", raising=False)- monkeypatch.delenv("TERMINAL_DOCKER_IMAGE", raising=False)- # The config layer caches by (path, mtime, size); leave it alone — each- # test writes its own config.yaml which changes the signature.+ for name in (+ "TERMINAL_ENV",+ "TERMINAL_CWD",+ "TERMINAL_DOCKER_IMAGE",+ "TERMINAL_SSH_HOST",+ ):+ monkeypatch.delenv(name, raising=False)yield@@ -40,8 +35,6 @@ def _write_config(text: str) -> None:def test_unset_terminal_env_backfills_backend_from_config():- """The core #63141 fix: config's docker backend reaches _get_env_config- even when no launcher bridged TERMINAL_ENV into this process."""_write_config("terminal:\n"" backend: docker\n"@@ -52,32 +45,76 @@ def test_unset_terminal_env_backfills_backend_from_config():assert config["env_type"] == "docker"assert config["docker_image"] == "custom/image:1"- assert os.environ.get("TERMINAL_ENV") == "docker"+ assert os.environ["TERMINAL_ENV"] == "docker"-def test_explicit_terminal_env_wins_over_config(monkeypatch):- """An explicit env choice (launcher bridge or .env) is never overridden —- honor explicit choice vs accidental fallback."""+def test_explicit_config_backend_overrides_stale_env(monkeypatch):_write_config("terminal:\n backend: docker\n")monkeypatch.setenv("TERMINAL_ENV", "local")config = terminal_tool._get_env_config()+ assert config["env_type"] == "docker"+ assert os.environ["TERMINAL_ENV"] == "docker"+++def test_partial_terminal_config_preserves_unrelated_env_values(monkeypatch):+ _write_config("terminal:\n backend: docker\n")+ monkeypatch.setenv("TERMINAL_ENV", "ssh")+ monkeypatch.setenv("TERMINAL_DOCKER_IMAGE", "env/image:2")++ config = terminal_tool._get_env_config()++ assert config["env_type"] == "docker"+ assert config["docker_image"] == "env/image:2"+ assert os.environ["TERMINAL_DOCKER_IMAGE"] == "env/image:2"+++def test_explicit_config_key_overrides_matching_env_value(monkeypatch):+ _write_config(+ "terminal:\n"+ " backend: docker\n"+ " docker_image: config/image:1\n"+ )+ monkeypatch.setenv("TERMINAL_ENV", "ssh")+ monkeypatch.setenv("TERMINAL_DOCKER_IMAGE", "env/image:2")++ config = terminal_tool._get_env_config()++ assert config["env_type"] == "docker"+ assert config["docker_image"] == "config/image:1"+++def test_env_is_preserved_when_config_has_no_terminal_section(monkeypatch):+ _write_config("agent:\n max_turns: 100\n")+ monkeypatch.setenv("TERMINAL_ENV", "ssh")+ monkeypatch.setenv("TERMINAL_SSH_HOST", "example.test")++ config = terminal_tool._get_env_config()++ assert config["env_type"] == "ssh"+ assert config["ssh_host"] == "example.test"+++def test_defaults_backfill_when_neither_config_nor_env_selects_backend():+ _write_config("{}\n")++ config = terminal_tool._get_env_config()+assert config["env_type"] == "local"+ assert os.environ["TERMINAL_ENV"] == "local"def test_bridge_only_attempted_once(monkeypatch):- """The config load runs at most once per process when TERMINAL_ENV stays- unset (e.g. empty config) — later calls skip the bridge entirely."""calls = []import hermes_cli.config as config_modreal = config_mod.apply_terminal_config_to_env- def _counting(*a, **k):+ def _counting(*args, **kwargs):calls.append(1)- return real(*a, **k)+ return real(*args, **kwargs)monkeypatch.setattr(config_mod, "apply_terminal_config_to_env", _counting)_write_config("{}\n")@@ -86,3 +123,20 @@ def test_bridge_only_attempted_once(monkeypatch):terminal_tool._get_env_config()assert len(calls) == 1+++def test_bridge_config_failure_does_not_crash(monkeypatch):+ import hermes_cli.config as config_mod++ monkeypatch.setattr(+ config_mod,+ "read_raw_config",+ lambda: (_ for _ in ()).throw(RuntimeError("config read failed")),+ )+ monkeypatch.setenv("TERMINAL_ENV", "ssh")+ monkeypatch.setenv("TERMINAL_SSH_HOST", "example.test")++ config = terminal_tool._get_env_config()++ assert config["env_type"] == "ssh"+ assert config["ssh_host"] == "example.test"diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex 6e06e55b2cb..92ead50a21a 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -1391,21 +1391,34 @@ def _ensure_terminal_env_bridged() -> None:config.yaml selects ``terminal.backend: docker``, running commands on thehost the user intended to sandbox (#63141, #54449, #61115, #65696).- Explicit env always wins: when TERMINAL_ENV is already set (a launcher's- bridge or the user's .env made a deliberate choice) this is a no-op. The- config bridge only fills the unset case, so it changes an accidental- default — never an explicit selection.+ Explicit terminal config keys win: when config.yaml has a ``terminal``+ section, each key present there overrides its matching env value (which may+ be stale from ``hermes setup``). Environment values for omitted terminal+ keys are preserved. When no terminal section exists, exported/.env values+ keep working unchanged."""global _terminal_config_bridge_attempted- if "TERMINAL_ENV" in os.environ or _terminal_config_bridge_attempted:+ if _terminal_config_bridge_attempted:return_terminal_config_bridge_attempted = Truetry:- from hermes_cli.config import apply_terminal_config_to_env-- # env=None targets os.environ inside the helper; override=False keeps- # any already-set TERMINAL_* values (e.g. from .env) authoritative.- apply_terminal_config_to_env(env=None, override=False)+ from hermes_cli.config import apply_terminal_config_to_env, read_raw_config++ # If config.yaml has an explicit terminal section, bridge with+ # override enabled. The helper only overrides env vars for keys present+ # in that raw section; merged defaults remain backfill-only. Without a+ # terminal section, preserve an existing TERMINAL_ENV selection or+ # backfill defaults when no selection exists.+ raw_config = read_raw_config()+ has_terminal_section = isinstance(raw_config.get("terminal"), dict)++ if has_terminal_section:+ # Explicit terminal keys in config.yaml win over matching env values.+ apply_terminal_config_to_env(env=None, override=True)+ elif "TERMINAL_ENV" not in os.environ:+ # No terminal section in config.yaml, TERMINAL_ENV not set —+ # backfill from config defaults+ apply_terminal_config_to_env(env=None, override=False)except Exception:# Never let a config problem take the terminal tool down — the# historical local default still applies.