Skip to content

The agent that grows with you

feat: run bypass sessions in the managed worker with the safe policy bound first

Tekniumae6ad67bdd52
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index 0b0f77ceec6..afe90007e96 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -11,7 +11,8 @@ import sys
import threading
MAX_FRAME = 4 * 1024 * 1024
-BOOTSTRAP_FIELDS = {'version', 'home', 'scope', 'policy', 'api_key', 'text', 'route', 'user_id', 'chat_id'}
+BOOTSTRAP_FIELDS = {'version', 'home', 'scope', 'policy', 'api_key', 'text', 'route', 'user_id', 'chat_id',
+ 'safe_mode', 'ignore_user_config'}
def read_frame(stream):
@@ -42,11 +43,26 @@ def validate_bootstrap(frame):
or scope['profile_id'] != frame['home'] or not Path(frame['home']).is_absolute()
or not isinstance(frame['policy'], dict)
or any(not isinstance(frame[k], str) for k in ('text', 'route', 'user_id', 'chat_id'))
+ or type(frame['safe_mode']) is not bool or type(frame['ignore_user_config']) is not bool
+ or (frame['safe_mode'] and not frame['ignore_user_config'])
or (frame['api_key'] is not None and not isinstance(frame['api_key'], str))):
raise ValueError('invalid_managed_worker_bootstrap')
return frame
+def bind_bypass_policy(frame):
+ """Freeze the owner's bypass assignment process-wide before any config/provider/agent import.
+
+ Ordinary assignments bind nothing; the frozen explicit config (never the profile) is what
+ every config reader in this process returns afterwards.
+ """
+ if not frame['ignore_user_config']:
+ return
+ from agent.safe_worker_policy import _bind_safe_worker_policy
+ _bind_safe_worker_policy(safe_mode=frame['safe_mode'], ignore_user_config=True,
+ config=json.loads(frame['policy']['config_json']))
+
+
class WorkerChannel:
def __init__(self, stream):
self.stream = stream
@@ -134,6 +150,9 @@ class WorkerControls:
def execute(frame, channel):
+ # The owner RPC below imports gateway/config modules (hermes_cli.config, providers,
+ # hermes_cli.plugins) transitively; the policy must already be frozen when they load.
+ bind_bypass_policy(frame)
from agent.runtime_session_store import RuntimeSessionStore, WorkerRPC
scope = dict(frame['scope'])
rpc = WorkerRPC(frame['home'])
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index 2ffd4f8bfcc..87264f549a4 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -15,14 +15,18 @@ from hermes_state_runtime import RuntimeStoreError
def managed_policy(authority, ref):
- """Initial opt-in slice: explicit local custom-provider sessions only.
+ """Bypass (safe / config-only) sessions always execute out of process; other local
+ sessions only under the explicit custom-provider opt-in.
The frozen creation snapshot, not current profile config, chooses execution.
- Safe-mode policy can reuse execute_managed after its early-import gates land.
"""
from gateway.session_policy import policy_for_source
policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)
- if policy is None or policy.config().get('gateway', {}).get('managed_workers') is not True:
+ if policy is None:
+ return None
+ if policy.ignore_user_config:
+ return policy
+ if policy.config().get('gateway', {}).get('managed_workers') is not True:
return None
request = json.loads(policy.request_json)
if policy.source != 'cli' or request.get('provider') != 'custom' or not request.get('base_url'):
@@ -44,7 +48,8 @@ def _bootstrap(authority, ref, row, policy, scope):
return {'version': 1, 'home': authority.profile_id, 'scope': scope,
'policy': asdict(hydrated), 'api_key': launch_key(authority, policy),
'text': row['payload']['text'], 'route': live.route,
- 'user_id': live.source.user_id, 'chat_id': live.source.chat_id}
+ 'user_id': live.source.user_id, 'chat_id': live.source.chat_id,
+ 'safe_mode': policy.safe_mode, 'ignore_user_config': policy.ignore_user_config}
class ManagedWorker:
diff --git a/tests/gateway/test_managed_worker_bypass.py b/tests/gateway/test_managed_worker_bypass.py
index 42021b5608a..9da4b84b791 100644
--- a/tests/gateway/test_managed_worker_bypass.py
+++ b/tests/gateway/test_managed_worker_bypass.py
@@ -41,7 +41,8 @@ def test_bypass_policy_routes_to_managed_worker_and_bootstrap_carries_flags(tmp_
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
+ wire = json.loads(json.dumps(frame))
+ assert validate_bootstrap(wire) is wire
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}):
@@ -56,11 +57,11 @@ def test_worker_binds_bypass_policy_before_runtime_imports(tmp_path, mode):
root = Path(__file__).resolve().parents[2]
home = tmp_path / 'home'
home.mkdir()
- (home / 'config.yaml').write_text('model: [unterminated\n')
+ (home / 'config.yaml').write_text('model: [unterminated\n', encoding='utf-8')
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")
+ (plugin / 'plugin.yaml').write_text('name: sentinel\nversion: 1.0.0\nkind: standalone\n', encoding='utf-8')
+ (plugin / '__init__.py').write_text("import os; from pathlib import Path\nPath(os.environ['HERMES_HOME'], 'plugin-executed').touch()\ndef register(ctx): pass\n", encoding='utf-8')
script = tmp_path / 'probe.py'
script.write_text(f'''
import json, os, sys, threading
@@ -84,7 +85,7 @@ with ThreadPoolExecutor(1) as pool:
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'))}}))
-''')
+''', encoding='utf-8')
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,