Skip to content

The agent that grows with you

fix(terminal): per-turn terminal scope applies managed scope last

emozillabd2fb30d2e84
diff --git a/hermes_cli/managed_scope.py b/hermes_cli/managed_scope.py
index 78d03f4b2fe..a00ac0630d4 100644
--- a/hermes_cli/managed_scope.py
+++ b/hermes_cli/managed_scope.py
@@ -178,3 +178,11 @@ def is_key_managed(dotted_key: str) -> bool:
def is_env_managed(name: str) -> bool:
"""True if the env var name is pinned by the managed .env layer."""
return name in load_managed_env()
+
+
+def pinned_terminal_backend() -> Optional[str]:
+ """The non-empty ``terminal.backend`` the managed config pins, or None. An empty or null value
+ names no backend to run, so it pins nothing."""
+ terminal = apply_managed_overlay({}).get("terminal")
+ backend = terminal.get("backend") if isinstance(terminal, dict) else None
+ return (backend.strip() or None) if isinstance(backend, str) else None
diff --git a/tests/tools/test_terminal_scope_managed.py b/tests/tools/test_terminal_scope_managed.py
new file mode 100644
index 00000000000..ac52e4a18fe
--- /dev/null
+++ b/tests/tools/test_terminal_scope_managed.py
@@ -0,0 +1,123 @@
+"""Managed scope pins the per-turn terminal policy the way load_config() pins the standalone bridge.
+
+A sandbox launcher pins ``terminal.backend`` through managed scope and withholds the profile's .env.
+The per-turn scope takes the managed ``terminal:`` values over the profile's own, merged per key, and
+an unreadable .env blocks turns only while nothing pins the backend.
+"""
+
+import builtins
+import io
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import managed_scope
+from tools.terminal_scope import TerminalPolicyUnavailable, build_profile_terminal_scope
+
+
+def managed(tmp_path, monkeypatch):
+ md = tmp_path / "managed"
+ md.mkdir()
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(md))
+ managed_scope.invalidate_managed_cache()
+ yield md
+ managed_scope.invalidate_managed_cache()
+
+
+def _write_managed(md: Path, body: str) -> None:
+ (md / "config.yaml").write_text(body, encoding="utf-8")
+ managed_scope.invalidate_managed_cache()
+
+
+def _profile(tmp_path: Path, *, config_yaml: str = "", dotenv: str = "") -> Path:
+ home = tmp_path / "profiles" / "work"
+ home.mkdir(parents=True)
+ if config_yaml:
+ (home / "config.yaml").write_text(config_yaml, encoding="utf-8")
+ if dotenv:
+ (home / ".env").write_text(dotenv, encoding="utf-8")
+ return home
+
+
+def _deny_reads(monkeypatch, path: Path) -> None:
+ """Make *path* exist but refuse every read, as Windows does for a file a sandbox denies."""
+ denied = os.path.abspath(path)
+ real_open = io.open
+
+ def guarded_open(file, *args, **kwargs):
+ if isinstance(file, (str, os.PathLike)) and os.path.abspath(file) == denied:
+ raise PermissionError(13, "Access is denied", os.fspath(file))
+ return real_open(file, *args, **kwargs)
+
+ monkeypatch.setattr(io, "open", guarded_open)
+ monkeypatch.setattr(builtins, "open", guarded_open)
+
+
+def test_managed_backend_beats_profile_config(tmp_path, managed):
+ _write_managed(managed, "terminal:\n backend: busybox\n")
+ home = _profile(tmp_path, config_yaml="terminal:\n backend: local\n timeout: 77\n")
+
+ scope = build_profile_terminal_scope(home)
+
+ assert scope["TERMINAL_ENV"] == "busybox"
+ assert scope["TERMINAL_TIMEOUT"] == "77"
+
+
+def test_managed_mapping_merges_with_the_profile_mapping(tmp_path, managed):
+ _write_managed(managed, "terminal:\n docker_env:\n A: managed\n")
+ home = _profile(tmp_path, config_yaml="terminal:\n docker_env:\n A: profile\n B: keep\n")
+
+ scope = build_profile_terminal_scope(home)
+
+ assert json.loads(scope["TERMINAL_DOCKER_ENV"]) == {"A": "managed", "B": "keep"}
+
+
+def test_managed_docker_image_pins_the_image(tmp_path, managed):
+ _write_managed(managed, "terminal:\n docker_image: lab/image:1\n")
+ home = _profile(tmp_path)
+
+ scope = build_profile_terminal_scope(home)
+
+ assert scope["TERMINAL_DOCKER_IMAGE"] == "lab/image:1"
+ assert scope["TERMINAL_DOCKER_IMAGE_PINNED"] == "1"
+
+
+def test_null_managed_values_pin_nothing(tmp_path, managed):
+ _write_managed(managed, "terminal:\n backend:\n docker_image:\n")
+ home = _profile(tmp_path, config_yaml="terminal:\n backend: docker\n")
+
+ scope = build_profile_terminal_scope(home)
+
+ assert scope["TERMINAL_ENV"] == "docker"
+ assert scope["TERMINAL_DOCKER_IMAGE_PINNED"] == "0"
+
+
+def test_unreadable_env_reads_as_empty_under_a_pinned_backend(tmp_path, managed, monkeypatch):
+ _write_managed(managed, "terminal:\n backend: busybox\n")
+ home = _profile(tmp_path, dotenv="TERMINAL_ENV=docker\nTERMINAL_TIMEOUT=999\n")
+ _deny_reads(monkeypatch, home / ".env")
+
+ scope = build_profile_terminal_scope(home, env_overlay={"TERMINAL_TIMEOUT": "42"})
+
+ assert scope["TERMINAL_ENV"] == "busybox"
+ assert scope["TERMINAL_TIMEOUT"] == "42"
+
+
[email protected]("managed_yaml", [
+ None,
+ "terminal:\n timeout: 5\n",
+ "terminal:\n backend:\n",
+ "terminal:\n backend: ''\n",
+ "terminal:\n backend: ' '\n",
+])
+def test_unreadable_env_fails_closed_without_a_pinned_backend(tmp_path, managed, monkeypatch, managed_yaml):
+ if managed_yaml is not None:
+ _write_managed(managed, managed_yaml)
+ home = _profile(tmp_path, config_yaml="terminal:\n backend: local\n", dotenv="TERMINAL_ENV=docker\n")
+ _deny_reads(monkeypatch, home / ".env")
+
+ with pytest.raises(TerminalPolicyUnavailable):
+ build_profile_terminal_scope(home)
diff --git a/tools/terminal_scope.py b/tools/terminal_scope.py
index 240c4f6c8e5..ce50cdf164e 100644
--- a/tools/terminal_scope.py
+++ b/tools/terminal_scope.py
@@ -116,9 +116,10 @@ def build_profile_terminal_scope(
"""Build the COMPLETE effective ``TERMINAL_*`` policy for a profile home.
Projection: ``DEFAULT_CONFIG['terminal']`` <- profile ``.env`` TERMINAL_* <- *env_overlay*
- <- profile ``config.yaml`` ``terminal:``. Total by construction, so a bound scope never
- widens back to ambient authority. Raises :class:`TerminalPolicyUnavailable` if a present
- file is unreadable.
+ <- profile ``config.yaml`` ``terminal:`` <- managed-scope ``terminal:``. Total by construction,
+ so a bound scope never widens back to ambient authority. Raises :class:`TerminalPolicyUnavailable`
+ if a present file is unreadable, except a ``.env`` that refuses reads while managed scope pins
+ ``terminal.backend``.
*env_overlay* is a TRUSTED ``TERMINAL_*`` mapping captured from the launch process before
multiplexing began (``tui_gateway/launch_profile_policy.py``): the launch profile's
@@ -127,6 +128,8 @@ def build_profile_terminal_scope(
closes. It sits where the process env sits in the standalone bridge — explicit YAML keys
still win (``apply_terminal_config_to_env``).
"""
+ from hermes_cli import managed_scope
+ from hermes_cli.config import _deep_merge
from hermes_cli.config_backend import config_exists
home = Path(hermes_home)
@@ -135,11 +138,13 @@ def build_profile_terminal_scope(
env_path = home / ".env"
if env_path.exists():
# load_env_file swallows OSError by design (secret scope fails soft); an unreadable
- # profile .env must fail closed here.
+ # profile .env must fail closed here, unless managed scope pins the backend: a sandbox
+ # launcher withholds the .env and pins the backend there, and load_env_file reads it as {}.
try:
env_path.read_bytes()
except Exception as exc:
- raise TerminalPolicyUnavailable(f"cannot read {env_path}: {exc}") from exc
+ if not isinstance(exc, PermissionError) or managed_scope.pinned_terminal_backend() is None:
+ raise TerminalPolicyUnavailable(f"cannot read {env_path}: {exc}") from exc
from agent.secret_scope import load_env_file
profile_env = load_env_file(env_path)
@@ -164,6 +169,7 @@ def build_profile_terminal_scope(
has_config = config_exists(config_path)
except Exception as exc:
raise TerminalPolicyUnavailable(f"cannot resolve terminal config in {home}: {exc}") from exc
+ raw_terminal = None
if has_config:
from hermes_cli.config_backend import read_config_doc_readonly
@@ -176,6 +182,13 @@ def build_profile_terminal_scope(
if isinstance(raw_terminal, dict):
_apply_terminal_mapping(scope, raw_terminal)
image_pinned = image_pinned or "docker_image" in raw_terminal
+ managed_terminal = managed_scope.apply_managed_overlay({}).get("terminal")
+ if isinstance(managed_terminal, dict):
+ # Managed scope applies last, merged per key into the profile's mapping as load_config() merges
+ # them, so a managed docker_env entry keeps the profile's other entries. A null value pins nothing.
+ _apply_terminal_mapping(
+ scope, _deep_merge(raw_terminal if isinstance(raw_terminal, dict) else {}, managed_terminal))
+ image_pinned = image_pinned or managed_terminal.get("docker_image") is not None
scope["TERMINAL_DOCKER_IMAGE_PINNED"] = "1" if image_pinned else "0"
_resolve_scope_cwd_placeholder(scope)
return scope