The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: freeze typed safe_mode/ignore_user_config in the local launch policy
Teknium53d362e18741
diff --git a/gateway/session_local.py b/gateway/session_local.pyindex a2a64467193..a3fa2184e3d 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -75,18 +75,36 @@ def authorize_local_source(runner, source):return adapter.authorize_source(source)+def _bypass_policy(params, *, private_secrets):+ """Frozen snapshot for --safe-mode / --ignore-user-config: code defaults plus the explicit+ launch options. The profile's config.yaml/.env are never read, so a malformed profile cannot+ block or shape the session; there is no default model to inherit, so one must be explicit."""+ import copy+ from gateway.session_policy import build_policy+ from hermes_cli.config_defaults import DEFAULT_CONFIG+ if not params.get('model'):+ raise RuntimeStoreError('invalid_params')+ defaults = copy.deepcopy(DEFAULT_CONFIG)+ if not isinstance(defaults.get('model'), dict): # code default is the empty string+ defaults['model'] = {}+ return build_policy(params, defaults, private_secrets=private_secrets, profile_terminal=False)++def create_local_session(authority, actor, params):if actor.profile_id != authority.profile_id:raise RuntimeStoreError('profile_mismatch')if 'session:create' not in actor.capabilities:raise RuntimeStoreError('permission_denied')- from gateway.session_policy import build_policy+ from gateway.session_policy import build_policy, BYPASS_FIELDSfrom gateway.run import _load_gateway_config, _resolve_gateway_modelfrom dataclasses import replaceprivate_secrets = {}- policy = build_policy(params, _load_gateway_config(), private_secrets=private_secrets)- if policy.model is None:- policy = replace(policy, model=_resolve_gateway_model(policy.config()))+ if any(params.get(name) is True for name in BYPASS_FIELDS):+ policy = _bypass_policy(params, private_secrets=private_secrets)+ else:+ policy = build_policy(params, _load_gateway_config(), private_secrets=private_secrets)+ if policy.model is None:+ policy = replace(policy, model=_resolve_gateway_model(policy.config()))request_id = params.get('request_id', uuid.uuid4().hex)if not isinstance(request_id, str) or not request_id or len(request_id) > 256:raise RuntimeStoreError('invalid_params')diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex d86d0ab2092..ad093ca9691 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -7,7 +7,9 @@ from pathlib import Pathfrom hermes_state_runtime import RuntimeStoreErrorCREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets',- 'provider', 'base_url', 'reasoning', 'max_turns', 'ignore_rules', 'api_key', 'editor'})+ 'provider', 'base_url', 'reasoning', 'max_turns', 'ignore_rules', 'api_key', 'editor',+ 'safe_mode', 'ignore_user_config'})+BYPASS_FIELDS = ('safe_mode', 'ignore_user_config')SURFACES = {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop', 'acp': 'acp'}@@ -24,6 +26,10 @@ class LocalSessionPolicy:credential_ref: str | None = Noneconfig_secret_ref: str | None = Noneeditor_mcp_json: str | None = None+ # Troubleshooting isolation is derived by the owner at creation and frozen with the+ # route; safe_mode always implies ignore_user_config (normalized once in build_policy).+ safe_mode: bool = False+ ignore_user_config: bool = Falsedef config(self, authority=None):config = json.loads(self.config_json)@@ -49,7 +55,7 @@ class LocalSessionPolicy:@propertydef ignore_rules(self):- return json.loads(self.request_json).get('ignore_rules', False)+ return self.safe_mode or json.loads(self.request_json).get('ignore_rules', False)@propertydef max_turns(self):@@ -63,16 +69,20 @@ class LocalSessionPolicy:return resolve_reasoning_config(self.config(), self.model or '')-def build_policy(params, config, *, private_secrets=None):+def build_policy(params, config, *, private_secrets=None, profile_terminal=True):from hermes_cli.tools_config import _get_platform_toolsfrom toolsets import validate_toolsetfrom agent.runtime_cwd import resolve_agent_cwd- from tools.terminal_scope import build_profile_terminal_scope+ from tools.terminal_scope import build_profile_terminal_scope, default_terminal_scopefrom hermes_constants import get_hermes_homesource = params.get('source', 'cli')if set(params) - CREATE_FIELDS or not isinstance(source, str) or source not in SURFACES:raise RuntimeStoreError('invalid_params')+ if any(name in params and type(params[name]) is not bool for name in BYPASS_FIELDS):+ raise RuntimeStoreError('invalid_params')+ safe_mode = params.get('safe_mode', False)+ ignore_user_config = safe_mode or params.get('ignore_user_config', False)if 'api_key' in params and (not isinstance(params['api_key'], str) or not params['api_key'].strip()):raise RuntimeStoreError('invalid_params')model = params.get('model')@@ -128,7 +138,11 @@ def build_policy(params, config, *, private_secrets=None):enabled.add('project')if source == 'gui':enabled.add('desktop_ui')- terminal = build_profile_terminal_scope(get_hermes_home())+ if safe_mode:+ # Plugin toolsets are user customizations; the safe worker never imports them.+ from hermes_cli.tools_config import _get_plugin_toolset_keys+ enabled -= _get_plugin_toolset_keys()+ terminal = build_profile_terminal_scope(get_hermes_home()) if profile_terminal else default_terminal_scope()terminal['TERMINAL_CWD'] = cwdrequest = {k: v for k, v in params.items() if k not in {'request_id', 'api_key'}}request.setdefault('source', 'cli')@@ -137,7 +151,8 @@ def build_policy(params, config, *, private_secrets=None):_extract_config_secrets(config, private_secrets)_extract_config_secrets(terminal, private_secrets, (None,))return LocalSessionPolicy(source, SURFACES[source], cwd, model, tuple(sorted(enabled)),- json.dumps(config), json.dumps(request, sort_keys=True), json.dumps(terminal))+ json.dumps(config), json.dumps(request, sort_keys=True), json.dumps(terminal),+ safe_mode=safe_mode, ignore_user_config=ignore_user_config)def _extract_config_secrets(value, private, path=()):@@ -216,7 +231,9 @@ def restore_policy(data):or not Path(policy.cwd).is_dir()or not isinstance(policy.model, str) or not policy.model.strip()or not isinstance(policy.toolsets, (list, tuple))- or any(not isinstance(name, str) for name in policy.toolsets)):+ or any(not isinstance(name, str) for name in policy.toolsets)+ or type(policy.safe_mode) is not bool or type(policy.ignore_user_config) is not bool+ or (policy.safe_mode and not policy.ignore_user_config)):raise ValueError('invalid policy')from dataclasses import replacefor value in (policy.config_json, policy.request_json, policy.terminal_json):diff --git a/tests/gateway/test_managed_worker_bypass.py b/tests/gateway/test_managed_worker_bypass.pynew file mode 100644index 00000000000..42021b5608a--- /dev/null+++ b/tests/gateway/test_managed_worker_bypass.py@@ -0,0 +1,100 @@+"""Bypass sessions execute in the admission-owned worker, which binds the safe policy first."""+import json+import os+from pathlib import Path+import subprocess+import sys+from types import SimpleNamespace++import pytest+++def _policy(tmp_path, **extra):+ from gateway.session_local import _bypass_policy+ return _bypass_policy({'cwd': str(tmp_path), 'model': 'safe-fixture', 'provider': 'custom',+ 'base_url': 'http://127.0.0.1:9/v1', **extra}, private_secrets={})+++def test_bypass_policy_routes_to_managed_worker_and_bootstrap_carries_flags(tmp_path, monkeypatch):+ from gateway import session_managed_worker as smw+ from gateway.session_policy import build_policy+ from agent.managed_worker import validate_bootstrap+ from hermes_state_runtime import RuntimeStoreError++ safe = _policy(tmp_path, safe_mode=True)+ config_only = _policy(tmp_path, ignore_user_config=True)+ ordinary = build_policy({'cwd': str(tmp_path), 'model': 'm'}, {'platform_toolsets': {'cli': ['terminal']}})+ opted = build_policy({'cwd': str(tmp_path), 'model': 'm', 'provider': 'custom', 'base_url': 'http://127.0.0.1:9/v1'},+ {'gateway': {'managed_workers': True}})+ live = SimpleNamespace(source=SimpleNamespace(user_id='u', chat_id='c'), route='route')+ authority = SimpleNamespace(sessions={'sid': live}, runner=None, profile_id=str(tmp_path))+ ref = SimpleNamespace(session_id='sid')+ for policy, expected in ((safe, safe), (config_only, config_only), (ordinary, None), (opted, opted)):+ monkeypatch.setattr('gateway.session_policy.policy_for_source', lambda runner, source, p=policy: p)+ assert smw.managed_policy(authority, ref) is expected+ # A bypass launch never depends on the profile's gateway.managed_workers opt-in.+ assert 'gateway' not in safe.config() or safe.config()['gateway'].get('managed_workers') is not True+ monkeypatch.setattr('gateway.session_policy.launch_key', lambda authority, policy: None)+ row = {'payload': {'text': 'SAFE_PROBE'}}+ scope = {'profile_id': str(tmp_path), 'session_id': 'sid', 'execution_id': 'x', 'generation': 1,+ 'pid': os.getpid(), 'birth': 0, 'secret': 's', 'epoch': 1}+ frame = smw._bootstrap(authority, ref, row, safe, scope)+ assert frame['safe_mode'] is True and frame['ignore_user_config'] is True+ assert isinstance(frame['policy']['config_json'], str)+ assert validate_bootstrap(json.loads(json.dumps(frame))) == frame+ frame = smw._bootstrap(authority, ref, row, config_only, scope)+ assert frame['safe_mode'] is False and frame['ignore_user_config'] is True+ for bad in ({'safe_mode': 1}, {'ignore_user_config': 'yes'}, {'safe_mode': True, 'ignore_user_config': False}):+ with pytest.raises(ValueError):+ validate_bootstrap({**frame, **bad})++[email protected]('mode', ['safe', 'config'])+def test_worker_binds_bypass_policy_before_runtime_imports(tmp_path, mode):+ """The frozen explicit config is what the worker's config readers return; the profile's+ config.yaml (malformed here) is never opened and plugin discovery never runs."""+ root = Path(__file__).resolve().parents[2]+ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text('model: [unterminated\n')+ plugin = home / 'plugins' / 'sentinel'+ plugin.mkdir(parents=True)+ (plugin / 'plugin.yaml').write_text('name: sentinel\nversion: 1.0.0\nkind: standalone\n')+ (plugin / '__init__.py').write_text("import os; from pathlib import Path\nPath(os.environ['HERMES_HOME'], 'plugin-executed').touch()\ndef register(ctx): pass\n")+ script = tmp_path / 'probe.py'+ script.write_text(f'''+import json, os, sys, threading+sys.path.insert(0, {str(root)!r})+from agent.managed_worker import bind_bypass_policy+home = os.environ['HERMES_HOME']+frame = {{'safe_mode': {mode == 'safe'!r}, 'ignore_user_config': True,+ 'policy': {{'config_json': json.dumps({{'model': {{'default': 'safe-fixture', 'provider': 'custom'}},+ 'plugins': {{'enabled': ['sentinel']}}, 'agent': {{'max_turns': 7}}}})}}}}+opened = []+sys.addaudithook(lambda event, args: opened.append(str(args[0])) if event == 'open' and home in str(args[0]) else None)+bind_bypass_policy(frame)+from hermes_cli.config import load_config, read_raw_config+from hermes_cli.plugins import discover_plugins, get_plugin_manager+discover_plugins()+cfg = load_config()+raw = read_raw_config()+from concurrent.futures import ThreadPoolExecutor+with ThreadPoolExecutor(1) as pool:+ helper = pool.submit(lambda: load_config()['agent']['max_turns']).result()+print(json.dumps({{'max_turns': cfg['agent']['max_turns'], 'raw_model': raw['model'], 'helper': helper,+ 'opened': opened, 'plugins': sorted(get_plugin_manager()._plugins),+ 'executed': os.path.exists(os.path.join(home, 'plugin-executed'))}}))+''')+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(tmp_path), HERMES_HOME=str(home), PYTHONPATH=str(root))+ result = subprocess.run([sys.executable, str(script)], cwd=root, env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=90)+ assert result.returncode == 0, result.stdout + result.stderr+ receipt = json.loads(result.stdout.strip().splitlines()[-1])+ assert receipt['max_turns'] == 7 and receipt['helper'] == 7+ assert receipt['raw_model'] == {'default': 'safe-fixture', 'provider': 'custom'}+ assert not [p for p in receipt['opened'] if p.endswith('config.yaml') or p.endswith('.env')], receipt+ if mode == 'safe':+ assert receipt['plugins'] == [] and receipt['executed'] is False, receipt+ else:+ assert receipt['executed'] is True, receipt # config-only keeps pluginsdiff --git a/tests/gateway/test_session_bypass_policy.py b/tests/gateway/test_session_bypass_policy.pynew file mode 100644index 00000000000..991969fb574--- /dev/null+++ b/tests/gateway/test_session_bypass_policy.py@@ -0,0 +1,77 @@+"""Bypass launches freeze a typed isolation policy chosen before any profile read."""+import json+import os++import pytest+++def test_bypass_policy_is_typed_frozen_and_safe_implies_ignore(tmp_path):+ from dataclasses import asdict+ from gateway.session_policy import build_policy, restore_policy, CREATE_FIELDS+ from hermes_state_runtime import RuntimeStoreError++ assert {'safe_mode', 'ignore_user_config'} <= CREATE_FIELDS+ cfg = {'platform_toolsets': {'cli': ['terminal']}}+ ordinary = build_policy({'cwd': str(tmp_path), 'model': 'm'}, cfg)+ assert ordinary.safe_mode is False and ordinary.ignore_user_config is False+ safe = build_policy({'cwd': str(tmp_path), 'model': 'm', 'safe_mode': True}, cfg)+ assert safe.safe_mode is True and safe.ignore_user_config is True+ config_only = build_policy({'cwd': str(tmp_path), 'model': 'm', 'ignore_user_config': True}, cfg)+ assert config_only.safe_mode is False and config_only.ignore_user_config is True+ # Safe launches also skip project rules: the request fingerprint still records only what was sent.+ assert safe.ignore_rules is True and json.loads(safe.request_json) == {'cwd': str(tmp_path), 'model': 'm', 'safe_mode': True, 'source': 'cli'}+ restored = restore_policy(asdict(safe))+ assert restored == safe and restored.safe_mode is True+ for bad in ({'safe_mode': 1}, {'safe_mode': 'true'}, {'ignore_user_config': None}):+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ build_policy({'cwd': str(tmp_path), **bad}, cfg)+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):+ restore_policy({**asdict(safe), 'safe_mode': 'yes'})+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):+ restore_policy({**asdict(safe), 'ignore_user_config': False}) # implication must hold in cold receipts too+++def test_bypass_session_freezes_code_defaults_without_reading_profile(tmp_path, monkeypatch):+ """The frozen snapshot of a bypass session is code defaults + explicit options; the profile's+ (possibly malformed) config.yaml, .env and plugin toolsets are never consulted."""+ from types import SimpleNamespace+ from gateway.session_local import _bypass_policy+ from hermes_cli.config_defaults import DEFAULT_CONFIG+ import gateway.session_policy, hermes_cli.tools_config, toolsets, tools.terminal_scope # noqa: F401,E401+ from hermes_cli.plugins import discover_plugins++ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text('model: [unterminated\n terminal: {backend: docker}\n', encoding='utf-8')+ (home / '.env').write_text('TERMINAL_ENV=docker\n', encoding='utf-8')+ monkeypatch.setenv('HERMES_HOME', str(home))+ # The ordinary owner discovered plugins at startup, long before this launch (contract J:+ # an owner that boots against broken config is a separate limitation).+ discover_plugins()+ opened = []+ active = [True]++ def witness(event, args):+ if event == 'hermes.test.done':+ active[0] = False+ elif active[0] and event == 'open' and str(home) in str(args[0]):+ import traceback+ opened.append((str(args[0]), ''.join(traceback.format_stack(limit=25))))+ import sys+ sys.addaudithook(witness)+ cwd = tmp_path / 'work'+ cwd.mkdir()+ params = {'cwd': str(cwd), 'model': 'safe-fixture', 'provider': 'custom',+ 'base_url': 'http://127.0.0.1:9/v1', 'safe_mode': True, 'toolsets': ['terminal']}+ private = {}+ policy = _bypass_policy(params, private_secrets=private)+ sys.audit('hermes.test.done') # audit hooks cannot be removed; close the witness window+ assert not opened, '\n'.join(p + '\n' + s for p, s in opened)+ config = policy.config()+ assert config['model']['provider'] == 'custom' and config['model']['base_url'] == params['base_url']+ assert config.get('plugins', {}).get('enabled', DEFAULT_CONFIG.get('plugins', {}).get('enabled')) in (None, [])+ from hermes_cli.plugins import get_plugin_toolset_keys_nowait+ assert 'terminal' in policy.toolsets and not set(policy.toolsets) & get_plugin_toolset_keys_nowait()+ terminal = json.loads(policy.terminal_json)+ assert terminal['TERMINAL_ENV'] == 'local' and terminal['TERMINAL_CWD'] == str(cwd)+ assert dict(os.environ).get('HERMES_SAFE_MODE') is Nonediff --git a/tools/terminal_scope.py b/tools/terminal_scope.pyindex b87c74a2e14..22011618a98 100644--- a/tools/terminal_scope.py+++ b/tools/terminal_scope.py@@ -86,6 +86,31 @@ def terminal_env(name: str, default: str = "") -> str:return default if value is None else str(value)+def _apply_terminal_mapping(scope: Dict[str, str], mapping: Dict[str, Any]) -> None:+ from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP, _terminal_env_value++ for cfg_key, value in mapping.items():+ # cwd placeholders are resolved per-surface later; not a policy value.+ if value is None or (cfg_key == "cwd" and str(value).strip() in {".", "auto", "cwd"}):+ continue+ env_var = TERMINAL_CONFIG_ENV_MAP.get(cfg_key)+ if env_var:+ # List/dict config values must be JSON (same contract as+ # apply_terminal_config_to_env). str() yields Python repr, which+ # json.loads in terminal_tool rejects.+ scope[env_var] = _terminal_env_value(value)+++def default_terminal_scope() -> Dict[str, str]:+ """Code-default ``TERMINAL_*`` policy: what a profile-bypassing session freezes instead of+ reading ``.env``/``config.yaml``. Total like the profile projection, minus the profile."""+ from hermes_cli.config_defaults import DEFAULT_CONFIG++ scope: Dict[str, str] = {}+ _apply_terminal_mapping(scope, {**_TOOL_LEVEL_DEFAULTS, **(DEFAULT_CONFIG.get("terminal") or {})})+ return scope++def build_profile_terminal_scope(hermes_home: "Any") -> Dict[str, str]:"""Build the COMPLETE effective ``TERMINAL_*`` policy for a profile home.@@ -93,25 +118,8 @@ def build_profile_terminal_scope(hermes_home: "Any") -> Dict[str, str]:``config.yaml`` ``terminal:``. Total by construction, so a bound scope never widens back toambient authority. Raises :class:`TerminalPolicyUnavailable` if a present file is unreadable."""- from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP, _terminal_env_value- from hermes_cli.config_defaults import DEFAULT_CONFIG-home = Path(hermes_home)- scope: Dict[str, str] = {}-- def _apply(mapping: Dict[str, Any]) -> None:- for cfg_key, value in mapping.items():- # cwd placeholders are resolved per-surface later; not a policy value.- if value is None or (cfg_key == "cwd" and str(value).strip() in {".", "auto", "cwd"}):- continue- env_var = TERMINAL_CONFIG_ENV_MAP.get(cfg_key)- if env_var:- # List/dict config values must be JSON (same contract as- # apply_terminal_config_to_env). str() yields Python repr, which- # json.loads in terminal_tool rejects.- scope[env_var] = _terminal_env_value(value)-- _apply({**_TOOL_LEVEL_DEFAULTS, **(DEFAULT_CONFIG.get("terminal") or {})})+ scope = default_terminal_scope()env_path = home / ".env"if env_path.exists():# load_env_file swallows OSError by design (secret scope fails soft); an unreadable@@ -141,7 +149,7 @@ def build_profile_terminal_scope(hermes_home: "Any") -> Dict[str, str]:raise TerminalPolicyUnavailable(f"cannot parse {config_path}: {exc}") from excraw_terminal = raw.get("terminal") if isinstance(raw, dict) else Noneif isinstance(raw_terminal, dict):- _apply(raw_terminal)+ _apply_terminal_mapping(scope, raw_terminal)return scope