Skip to content

The agent that grows with you

fix(worker): ordinary managed workers serve the frozen session config

Teknium749102ac3528
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index 71bea7b6a38..fe03fb49ad0 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -100,17 +100,21 @@ def validate_bootstrap(frame):
return frame
-def bind_bypass_policy(frame):
- """Freeze the owner's bypass assignment process-wide before any config/provider/agent import.
+def bind_worker_policy(frame):
+ """Freeze the owner's 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.
+ The session's frozen config (never the live profile file) is what every config reader in
+ this process returns afterwards, so a profile edit after creation cannot reshape it (MCP
+ server definitions included). Ordinary sessions keep plugins, MCP and hooks; bypass sessions
+ also bind the safe / ignore-user-config policy.
"""
+ config = json.loads(frame['policy']['config_json'])
if not frame['ignore_user_config']:
+ from agent.safe_worker_policy import _bind_worker_config
+ _bind_worker_config(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']))
+ _bind_safe_worker_policy(safe_mode=frame['safe_mode'], ignore_user_config=True, config=config)
class WorkerChannel:
@@ -275,7 +279,7 @@ def tool_frame(call_id, name, args, *result):
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)
+ bind_worker_policy(frame)
from agent.runtime_session_store import RuntimeSessionStore, WorkerRPC
scope = dict(frame['scope'])
rpc = WorkerRPC(frame['home'])
diff --git a/agent/safe_worker_policy.py b/agent/safe_worker_policy.py
index 72226c92b76..fee28e9986b 100644
--- a/agent/safe_worker_policy.py
+++ b/agent/safe_worker_policy.py
@@ -1,4 +1,5 @@
-"""Private bootstrap policy for admission-owned troubleshooting workers.
+"""Private bootstrap policy for admission-owned workers: the frozen session config every
+config reader returns, plus (troubleshooting workers only) the safe/ignore-user-config bypass.
Stdlib-only: hermes_cli's config/env layer imports it, so it ships in the installer's
hermes_cli + i18n-kernel tail and must never import beyond the standard library.
@@ -34,11 +35,22 @@ _RUNTIME_IMPORTS = frozenset({
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")
+ raise ValueError("ordinary execution binds its config with _bind_worker_config")
+ return _bind(safe_mode, True, config)
+
+
+def _bind_worker_config(config: dict) -> _SafeWorkerPolicy:
+ """An ordinary managed worker's frozen session config: every config reader returns it (the
+ session never follows later profile edits), while plugins, MCP, hooks and providers load as
+ usual — ``safe_worker_enabled()`` stays False. Same one-shot, pre-import rules as bypass."""
+ return _bind(False, False, config)
+
+
+def _bind(safe_mode: bool, ignore_user_config: bool, config: dict) -> _SafeWorkerPolicy:
+ global _policy
if type(config) is not dict:
raise TypeError("worker config must be a JSON object")
serialized = json.dumps(config, allow_nan=False)
@@ -47,8 +59,7 @@ def _bind_safe_worker_policy(*, safe_mode: bool, ignore_user_config: bool,
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)
+ _policy = _SafeWorkerPolicy(os.getpid(), safe_mode, ignore_user_config, serialized)
return _policy
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index 0e8cf1ac294..67de4b1b306 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -64,7 +64,7 @@ def _bootstrap(authority, ref, row, policy, scope):
request = dict(json.loads(policy.request_json), turn_v1={
'finite': row['payload'].get('finite', False), 'unattended': row['payload'].get('unattended') is True,
'yolo': _session_yolo(authority, live.route, policy)})
- hydrated = replace(policy, config_json=json.dumps(policy.config(authority)), request_json=json.dumps(request),
+ hydrated = replace(policy, config_json=json.dumps(_worker_config(authority, policy)), request_json=json.dumps(request),
terminal_json=json.dumps(terminal), credential_ref=None, config_secret_ref=None)
return {'version': 1, 'home': authority.profile_id, 'scope': scope,
'policy': asdict(hydrated), 'api_key': launch_key(authority, policy),
@@ -75,6 +75,24 @@ def _bootstrap(authority, ref, row, policy, scope):
'safe_mode': policy.safe_mode, 'ignore_user_config': policy.ignore_user_config}
+def _worker_config(authority, policy):
+ """The frozen session config the child binds as its only config (``bind_worker_policy``).
+ ``command_allowlist`` is approval state rather than launch policy: an ``always`` grant an
+ earlier worker of an ordinary session persisted, or one the operator removed by hand, comes
+ from the live profile file, as it did before the child's config was frozen. Bypass sessions
+ never read the profile."""
+ config = policy.config(authority)
+ home = Path(str(authority.profile_id))
+ if policy.ignore_user_config or not home.is_absolute():
+ return config
+ from gateway.run import _load_gateway_config
+ live = _load_gateway_config(home / 'config.yaml')
+ config.pop('command_allowlist', None)
+ if live.get('command_allowlist') is not None:
+ config['command_allowlist'] = live['command_allowlist']
+ return config
+
+
def _session_yolo(authority, route, policy):
"""The route's bypass as the in-process turn arms it on the owner, the one place a revocation
is recorded: a ``--yolo`` launch seeded once per boundary, then the persisted ``/yolo`` copy."""
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index 95fcbd42b8e..316d1afd79c 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -2502,8 +2502,8 @@ def save_config(
# swallows transient stat/open errors into ``{}``, and a ``{}`` at this point makes the
# strip pass drop every user section whose value matches a default (#113301).
_raw_for_paths = require_readable_config_before_write(config_path)
- if merge_existing and _raw_for_paths:
- config = _merge_partial_save(_raw_for_paths, config)
+ from hermes_cli.config_worker_save import rebase_for_save # frozen-worker writes + merge_existing
+ config = rebase_for_save(config, _raw_for_paths, merge_existing)
current_normalized = _canonicalize_config(config)
normalized = current_normalized
diff --git a/hermes_cli/config_worker_save.py b/hermes_cli/config_worker_save.py
new file mode 100644
index 00000000000..ba7de61558b
--- /dev/null
+++ b/hermes_cli/config_worker_save.py
@@ -0,0 +1,43 @@
+"""What ``save_config`` persists when the process serves a frozen session config.
+
+A managed worker binds its session's creation-time config (``agent.safe_worker_policy``), so its
+``load_config()`` is that snapshot, not the profile file. A read-modify-write in such a worker
+(an ``always`` approval, a connector enable) must land only what it changed on the LIVE file:
+writing the whole snapshot back would revert every profile edit made since the session was
+created. Outside a frozen worker this is ``save_config``'s ordinary ``merge_existing`` handling.
+"""
+
+from __future__ import annotations
+
+import copy
+from typing import Any
+
+
+def rebase_for_save(config: dict[str, Any], live_raw: dict[str, Any], merge_existing: bool) -> dict[str, Any]:
+ from hermes_cli import config as _config
+
+ if _config._worker_config_snapshot() is not None:
+ return _three_way(live_raw or {}, config, _config.load_config())
+ if merge_existing and live_raw:
+ return _config._merge_partial_save(live_raw, config)
+ return config
+
+
+def _three_way(live: Any, desired: Any, base: Any) -> Any:
+ """*live* with the caller's edits (*desired* relative to the *base* it loaded) applied.
+ Mappings recurse; list edits add/remove items; a key the caller dropped is left alone."""
+ if desired == base:
+ return copy.deepcopy(live)
+ if isinstance(desired, dict) and isinstance(base, dict) and isinstance(live, dict):
+ merged = copy.deepcopy(live)
+ for key, value in desired.items():
+ if key not in base:
+ merged[key] = copy.deepcopy(value)
+ elif value != base[key]:
+ merged[key] = _three_way(live.get(key), value, base[key])
+ return merged
+ if isinstance(desired, list) and isinstance(base, list) and isinstance(live, list):
+ removed = [item for item in base if item not in desired]
+ kept = [item for item in live if item not in removed]
+ return kept + [copy.deepcopy(item) for item in desired if item not in base and item not in kept]
+ return copy.deepcopy(desired)
diff --git a/tests/gateway/test_managed_turn_contract.py b/tests/gateway/test_managed_turn_contract.py
index 701fcf7ef0c..0736defbae1 100644
--- a/tests/gateway/test_managed_turn_contract.py
+++ b/tests/gateway/test_managed_turn_contract.py
@@ -67,7 +67,7 @@ def test_child_executes_under_finite_policy_and_preserves_receipt(tmp_path, monk
def approval(self, data): pytest.fail('unexpected approval')
def clarify(self, questions): pytest.fail('unexpected question')
- monkeypatch.setattr(worker, 'bind_bypass_policy', lambda frame: None)
+ monkeypatch.setattr(worker, 'bind_worker_policy', lambda frame: None)
monkeypatch.setattr(worker, 'discover_profile_mcp', lambda policy: None)
monkeypatch.setattr(worker, 'retire_agent', lambda agent: None)
monkeypatch.setattr(worker, 'WorkerControls', Controls)
diff --git a/tests/gateway/test_managed_worker_bypass.py b/tests/gateway/test_managed_worker_bypass.py
index 78fe15b4475..426bc09a1ac 100644
--- a/tests/gateway/test_managed_worker_bypass.py
+++ b/tests/gateway/test_managed_worker_bypass.py
@@ -66,14 +66,14 @@ def test_worker_binds_bypass_policy_before_runtime_imports(tmp_path, mode):
script.write_text(f'''
import json, os, sys, threading
sys.path.insert(0, {str(root)!r})
-from agent.managed_worker import bind_bypass_policy
+from agent.managed_worker import bind_worker_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)
+bind_worker_policy(frame)
from hermes_cli.config import load_config, read_raw_config
from hermes_cli.plugins import discover_plugins, get_plugin_manager
discover_plugins()
diff --git a/tests/gateway/test_managed_worker_frozen_config.py b/tests/gateway/test_managed_worker_frozen_config.py
new file mode 100644
index 00000000000..3c7c421621b
--- /dev/null
+++ b/tests/gateway/test_managed_worker_frozen_config.py
@@ -0,0 +1,165 @@
+"""An ordinary managed worker serves its session's frozen config, never the live profile file.
+
+The owner hydrates the creation-time snapshot into the bootstrap; the child binds it before any
+config import, so an edit to an already-selected MCP server's transport after creation reaches
+only sessions created after the edit (andrexibiza N1). Plugins, MCP and hooks stay ordinary.
+"""
+import asyncio
+from contextlib import closing
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import sqlite3
+import subprocess
+import sys
+import textwrap
+import threading
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket
+
+PEER = '''import json, sys
+for line in sys.stdin:
+ r = json.loads(line); ident = r.get("id")
+ if ident is None: continue
+ if r.get("method") == "initialize":
+ result = {"protocolVersion": r["params"]["protocolVersion"], "capabilities": {"tools": {}},
+ "serverInfo": {"name": "peer", "version": "1"}}
+ elif r.get("method") == "tools/list":
+ result = {"tools": [{"name": "echo_" + sys.argv[1], "description": "x",
+ "inputSchema": {"type": "object", "properties": {}}}]}
+ else:
+ result = {}
+ print(json.dumps({"jsonrpc": "2.0", "id": ident, "result": result}), flush=True)
+'''
+
+
+class Model(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ if body.get('messages'):
+ self.server.requests.append(body)
+ choice = {'index': 0, 'delta': {'role': 'assistant', 'content': 'OK'}, 'finish_reason': 'stop'}
+ frame = {'id': 'f', 'model': 'frozen-model', 'choices': [choice],
+ 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}}
+ if body.get('stream'):
+ payload, kind = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode(), 'text/event-stream'
+ else:
+ choice['message'] = choice.pop('delta')
+ payload, kind = json.dumps(frame).encode(), 'application/json'
+ self.send_response(200)
+ self.send_header('Content-Type', kind)
+ self.send_header('Content-Length', str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+
+def test_existing_session_keeps_frozen_mcp_transport_after_profile_edit(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ peer.requests = []
+ threading.Thread(target=peer.serve_forever, daemon=True).start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ (home / 'peer.py').write_text(PEER)
+ config = {'gateway': {'multiplex_profiles': False, 'managed_workers': True},
+ 'model': {'provider': 'custom', 'default': 'frozen-model', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False}},
+ 'mcp_servers': {'owned': {'command': sys.executable, 'args': [str(home / 'peer.py'), 'FROZEN_A']}},
+ 'platform_toolsets': {'cli': ['owned']}}
+ (home / 'config.yaml').write_text(json.dumps(config))
+ env = {**child_env(), **{k: os.environ[k] for k in ('TIRITH_ENABLED',) if k in os.environ}}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)
+
+ def status(request_id):
+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:
+ return db.execute('SELECT status FROM session_admissions WHERE request_id=?', (request_id,)).fetchall()
+
+ async def create(ws, name):
+ created = await rpc(ws, 'session.create', request_id=name, source='cli', cwd=str(home), model='frozen-model',
+ provider='custom', base_url=url, api_key='loopback-only', toolsets=['owned'], ignore_rules=True)
+ assert 'result' in created, created
+ return created['result']['session_id']
+
+ async def tools_seen(ws, sid, request_id):
+ before = len(peer.requests)
+ submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=request_id, text='HELLO')
+ assert 'result' in submitted, submitted
+ async with asyncio.timeout(120):
+ while status(request_id) != [('terminal',)]:
+ await asyncio.sleep(.05)
+ tools = json.dumps([r.get('tools') for r in peer.requests[before:]])
+ return [tag for tag in ('echo_FROZEN_A', 'echo_LIVE_B') if tag in tools]
+
+ async def exercise(desc):
+ async with websocket(home, desc) as ws:
+ existing = await create(ws, 'existing')
+ edited = json.loads((home / 'config.yaml').read_text())
+ edited['mcp_servers']['owned']['args'] = [str(home / 'peer.py'), 'LIVE_B']
+ (home / 'config.yaml').write_text(json.dumps(edited))
+ fresh = await create(ws, 'fresh')
+ assert await tools_seen(ws, existing, 'existing-turn') == ['echo_FROZEN_A']
+ assert await tools_seen(ws, fresh, 'fresh-turn') == ['echo_LIVE_B']
+ try:
+ with daemon(root, home, env, barrier=False) as (_owner, desc):
+ asyncio.run(exercise(desc))
+ finally:
+ peer.shutdown()
+ peer.server_close()
+
+
+def test_ordinary_worker_binding_freezes_readers_but_keeps_customizations(tmp_path):
+ """The ordinary binding serves the snapshot to every config reader without the bypass policy
+ (plugins still load), and a worker write-back lands only its own change on the live file."""
+ root = Path(__file__).resolve().parents[2]
+ home = tmp_path / 'home'
+ plugin = home / 'plugins' / 'sentinel'
+ plugin.mkdir(parents=True)
+ (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')
+ frozen = {'plugins': {'enabled': ['sentinel']}, 'agent': {'max_turns': 7}, 'command_allowlist': ['echo *'],
+ 'mcp_servers': {'x': {'command': 'FROZEN_A'}}}
+ live = {**frozen, 'agent': {'max_turns': 99}, 'mcp_servers': {'x': {'command': 'LIVE_B'}},
+ 'display': {'personality': 'EDITED_AFTER_CREATE'}}
+ (home / 'config.yaml').write_text(json.dumps(live), encoding='utf-8')
+ script = tmp_path / 'probe.py'
+ script.write_text(textwrap.dedent(f'''
+ import json, os, sys
+ sys.path.insert(0, {str(root)!r})
+ from agent.managed_worker import bind_worker_policy
+ bind_worker_policy({{'safe_mode': False, 'ignore_user_config': False,
+ 'policy': {{'config_json': json.dumps({frozen!r})}}}})
+ from agent.safe_worker_policy import safe_worker_enabled
+ from hermes_cli.config import load_config, read_raw_config
+ from hermes_cli.config_effective import load_user_config_effective
+ from hermes_cli.plugins import discover_plugins
+ from tools.mcp_tool_config import _load_mcp_config
+ discover_plugins()
+ from tools import approval
+ approval.save_permanent_allowlist({{'echo *', 'ls *'}})
+ print(json.dumps({{'safe': safe_worker_enabled(), 'turns': [load_config()['agent']['max_turns'],
+ read_raw_config()['agent']['max_turns'], load_user_config_effective()['agent']['max_turns']],
+ 'mcp': _load_mcp_config()['x']['command'],
+ 'plugin': os.path.exists(os.path.join(os.environ['HERMES_HOME'], 'plugin-executed'))}}))
+ '''), encoding='utf-8')
+ env = {**child_env(), **{k: os.environ[k] for k in ('TIRITH_ENABLED',) if k in os.environ}}
+ env.update(HOME=str(tmp_path), USERPROFILE=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 == {'safe': False, 'turns': [7, 7, 7], 'mcp': 'FROZEN_A', 'plugin': True}, receipt
+ from hermes_cli.config import fast_safe_load
+ saved = fast_safe_load((home / 'config.yaml').read_text(encoding='utf-8'))
+ assert saved['command_allowlist'] == ['echo *', 'ls *']
+ assert saved['agent']['max_turns'] == 99 and saved['mcp_servers']['x']['command'] == 'LIVE_B', saved
+ assert saved['display']['personality'] == 'EDITED_AFTER_CREATE', saved