Skip to content

The agent that grows with you

feat: bind immutable private worker config before runtime imports

Teknium4cc3f42087e6
diff --git a/agent/safe_worker_policy.py b/agent/safe_worker_policy.py
new file mode 100644
index 00000000000..36f3c72bf37
--- /dev/null
+++ b/agent/safe_worker_policy.py
@@ -0,0 +1,66 @@
+"""Private bootstrap policy for admission-owned troubleshooting workers.
+
+Bind once in a fresh exec, before config/agent/plugin imports. This is not a
+sandbox or a public launch switch: only the managed worker bootstrap consumes
+the owner's validated assignment. No environment flag grants this policy and
+no reset exists; helper threads see the same immutable snapshot.
+"""
+from dataclasses import dataclass
+import json
+import os
+import sys
+from threading import Lock
+
+
+@dataclass(frozen=True, slots=True)
+class _SafeWorkerPolicy:
+ pid: int
+ safe_mode: bool
+ ignore_user_config: bool
+ config_json: str
+
+
+_policy: _SafeWorkerPolicy | None = None
+_bind_lock = Lock()
+_RUNTIME_IMPORTS = frozenset({
+ "run_agent", "model_tools", "hermes_cli.config", "hermes_cli.env_loader",
+ "hermes_cli.plugins", "providers", "agent.agent_init",
+})
+
+
+def _bind_safe_worker_policy(*, safe_mode: bool, ignore_user_config: bool,
+ config: dict) -> _SafeWorkerPolicy:
+ """Called by the private worker bootstrap, never by the owner or public CLI."""
+ global _policy
+ if type(safe_mode) is not bool or type(ignore_user_config) is not bool:
+ raise TypeError("worker bypass policy fields must be booleans")
+ if not (safe_mode or ignore_user_config):
+ raise ValueError("ordinary execution does not bind a bypass policy")
+ if type(config) is not dict:
+ raise TypeError("worker config must be a JSON object")
+ serialized = json.dumps(config, allow_nan=False)
+ with _bind_lock:
+ if _policy is not None:
+ raise RuntimeError("worker policy is already bound")
+ if _RUNTIME_IMPORTS.intersection(sys.modules):
+ raise RuntimeError("worker policy must bind before runtime imports")
+ _policy = _SafeWorkerPolicy(os.getpid(), safe_mode,
+ safe_mode or ignore_user_config, serialized)
+ return _policy
+
+
+def _current_policy() -> _SafeWorkerPolicy | None:
+ if _policy is not None and _policy.pid != os.getpid():
+ raise RuntimeError("worker policy cannot cross a fork; use a fresh exec")
+ return _policy
+
+
+def safe_worker_enabled() -> bool:
+ policy = _current_policy()
+ return policy is not None and policy.safe_mode
+
+
+def worker_config_snapshot() -> dict | None:
+ """Return detached explicit config; None means the ordinary loader owns it."""
+ policy = _current_policy()
+ return json.loads(policy.config_json) if policy is not None else None
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index b70ff27022d..4a95d540255 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -1883,6 +1883,11 @@ def cfg_get(cfg: Optional[Dict[str, Any]], *keys: str, default: Any = None) -> A
def _read_raw_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:
+ from agent.safe_worker_policy import worker_config_snapshot
+
+ snapshot = worker_config_snapshot()
+ if snapshot is not None:
+ return snapshot
with _CONFIG_LOCK:
try:
config_path = get_config_path()
@@ -2176,6 +2181,11 @@ def _merge_managed_overlay(expanded: Dict[str, Any]) -> Tuple[Dict[str, Any], An
def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:
+ from agent.safe_worker_policy import worker_config_snapshot
+
+ snapshot = worker_config_snapshot()
+ if snapshot is not None:
+ return _deep_merge(copy.deepcopy(DEFAULT_CONFIG), snapshot)
with _CONFIG_LOCK:
ensure_hermes_home()
config_path = get_config_path()
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.py
index 7508f53c257..39f3993c42f 100644
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@ -316,6 +316,12 @@ def load_hermes_dotenv(
) -> list[Path]:
"""Load Hermes env files: ``~/.hermes/.env`` overrides stale shell exports; project ``.env`` is a dev
fallback that only fills gaps when the user env exists (and overrides shell vars when it does not)."""
+ from agent.safe_worker_policy import worker_config_snapshot
+
+ # The private bootstrap supplies credentials explicitly; do not rehydrate
+ # profile behavior, external secret plugins, or managed env in this worker.
+ if worker_config_snapshot() is not None:
+ return []
home_path = Path(hermes_home or os.getenv("HERMES_HOME", Path.home() / ".hermes"))
# Multiplex gateway: while a routed profile-home override is active, copying that profile's .env
diff --git a/tests/agent/test_safe_worker_policy.py b/tests/agent/test_safe_worker_policy.py
new file mode 100644
index 00000000000..dca06e41910
--- /dev/null
+++ b/tests/agent/test_safe_worker_policy.py
@@ -0,0 +1,103 @@
+"""Fresh exec probes for the private managed safe-worker bootstrap contract."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import textwrap
+
+import pytest
+
+
+def run_worker(tmp_path, body, mode="safe"):
+ home = tmp_path / mode
+ home.mkdir(exist_ok=True)
+ (home / "config.yaml").write_text("agent:\n max_turns: 17\n", encoding="utf-8")
+ env = dict(os.environ, HERMES_HOME=str(home), HOME=str(home), PROBE_MODE=mode)
+ for key in ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG", "HERMES_IGNORE_RULES"):
+ env.pop(key, None)
+ result = subprocess.run(
+ [sys.executable, "-c", textwrap.dedent(body)], env=env,
+ cwd=Path(__file__).resolve().parents[2], stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, timeout=45,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ return json.loads(result.stdout.strip().splitlines()[-1])
+
+
[email protected]("mode", ["safe", "config", "ordinary"])
+def test_worker_config_is_frozen_before_any_profile_read(tmp_path, mode):
+ result = run_worker(tmp_path, '''
+ import json, os, sys, threading
+ from pathlib import Path
+ mode = os.environ["PROBE_MODE"]
+ if mode != "ordinary":
+ from agent.safe_worker_policy import _bind_safe_worker_policy
+ snapshot = {"agent": {"max_turns": 3}, "terminal": {"cwd": "/explicit"}}
+ _bind_safe_worker_policy(safe_mode=mode == "safe", ignore_user_config=True, config=snapshot)
+ snapshot["agent"]["max_turns"] = 999
+ reads = []
+ def audit(event, args):
+ if event == "open" and str(args[0]).endswith("config.yaml") and args[1] != "w":
+ reads.append(str(args[0]))
+ sys.addaudithook(audit)
+ from hermes_cli.config import load_config, load_config_readonly, read_raw_config, read_raw_config_readonly, DEFAULT_CONFIG
+ from hermes_cli import env_loader
+ callbacks = []
+ env_loader._apply_managed_env = lambda: callbacks.append("managed")
+ env_loader._apply_external_secret_sources = lambda home: callbacks.append("secrets")
+ env_loader._reapply_terminal_config_bridge = lambda home: callbacks.append("terminal")
+ env_loader.load_hermes_dotenv()
+ cfg = load_config()
+ assert cfg["compression"] == DEFAULT_CONFIG["compression"]
+ first = cfg["agent"]["max_turns"]
+ cfg["agent"]["max_turns"] = 123
+ if mode != "ordinary":
+ Path(os.environ["HERMES_HOME"], "config.yaml").write_text("[broken YAML")
+ # Audit excludes this fixture write, not the preceding reads.
+ results = []
+ def check():
+ for loader in (load_config, load_config_readonly, read_raw_config, read_raw_config_readonly):
+ results.append(loader()["agent"]["max_turns"])
+ t = threading.Thread(target=check); t.start(); t.join()
+ print(json.dumps({"first": first, "values": results, "reads": reads, "callbacks": callbacks}))
+ ''', mode)
+ if mode == "ordinary":
+ assert result["first"] == 17 and result["reads"]
+ assert result["callbacks"] == ["secrets", "managed", "terminal"]
+ else:
+ assert result == {"first": 3, "values": [3, 3, 3, 3], "reads": [], "callbacks": []}
+
+
+def test_private_worker_binding_is_one_shot_typed_and_not_env_selected(tmp_path):
+ result = run_worker(tmp_path, '''
+ import json, os
+ from dataclasses import FrozenInstanceError
+ from agent.safe_worker_policy import _bind_safe_worker_policy, safe_worker_enabled, worker_config_snapshot
+ os.environ["HERMES_SAFE_MODE"] = "1"
+ assert not safe_worker_enabled()
+ for value in (1, "true", None):
+ try:
+ _bind_safe_worker_policy(safe_mode=value, ignore_user_config=True, config={})
+ except (TypeError, ValueError):
+ pass
+ else:
+ raise AssertionError("non-boolean accepted")
+ policy = _bind_safe_worker_policy(safe_mode=True, ignore_user_config=False, config={})
+ assert policy.ignore_user_config and safe_worker_enabled()
+ try:
+ policy.safe_mode = False
+ except FrozenInstanceError:
+ pass
+ else:
+ raise AssertionError("mutable policy")
+ try:
+ _bind_safe_worker_policy(safe_mode=False, ignore_user_config=True, config={})
+ except RuntimeError:
+ pass
+ else:
+ raise AssertionError("rebound policy")
+ assert worker_config_snapshot() == {}
+ print(json.dumps({"bound": safe_worker_enabled()}))
+ ''')
+ assert result == {"bound": True}