Skip to content

The agent that grows with you

fix(acp): respawn editor MCP on a workspace move, catch live schema drift

unsupportedpastels167ff27c02c4
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index 27fa51b0a82..bf8382ebca3 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
from contextlib import suppress
import logging
+import os
import uuid
import acp
@@ -100,6 +101,17 @@ def _submit_fingerprint(session_id, text, attachments):
return session_id, digest.hexdigest()
+def _bypass_route():
+ """--safe-mode / --ignore-user-config read no profile default model, so the session freezes the
+ launch's explicit one (``hermes -m <model> [--provider <name>] --safe-mode acp``), as the TUI does."""
+ model = (os.environ.get("HERMES_MODEL") or os.environ.get("HERMES_INFERENCE_MODEL") or "").strip()
+ if not model:
+ raise GatewayClientError("--safe-mode / --ignore-user-config read no profile default model: launch "
+ "with one, e.g. hermes -m <model> --provider <provider> --safe-mode acp")
+ provider = os.environ.get("HERMES_INFERENCE_PROVIDER", "").strip()
+ return {"model": model, **({"provider": provider} if provider else {})}
+
+
def _tools_changed_notice(payload):
"""The owner re-froze this session's editor MCP tools (a changed config or changed schemas)."""
servers = ", ".join(payload.get("mcp_servers") or []) or "none"
@@ -270,10 +282,13 @@ class GatewayACPAgent(acp.Agent):
from hermes_cli.gateway_chat import env_launch_flags
# `hermes acp --yolo` / `--safe-mode` / ... reach this process as their env equivalents; the
# owner does not inherit them, so they freeze into this session's policy or not at all.
+ flags = env_launch_flags()
+ if flags.get("safe_mode") or flags.get("ignore_user_config"):
+ flags.update(_bypass_route())
snapshot = await client.rpc("session.create", request_id=uuid.uuid4().hex,
source="acp", cwd=_translate_acp_cwd(cwd),
editor={"mcp_servers": [s.model_dump(by_alias=True) for s in mcp_servers or []],
- "edit_approval_policy": "ask"}, **env_launch_flags())
+ "edit_approval_policy": "ask"}, **flags)
session_id = snapshot["session_id"]
self._snapshots[session_id] = snapshot
if mcp_servers:
diff --git a/gateway/session_local_mcp.py b/gateway/session_local_mcp.py
index 54dec630767..da736d05144 100644
--- a/gateway/session_local_mcp.py
+++ b/gateway/session_local_mcp.py
@@ -27,6 +27,7 @@ logger = logging.getLogger(__name__)
PRIVATE_KEY = ('editor_mcp',)
_HELD_LOCK = threading.Lock()
+_RELIST_TIMEOUT = 5 # seconds an admission start waits on a held server's tools/list
def _json(value):
@@ -172,11 +173,13 @@ def _borrowed(authority, scope, servers, names, cwd, *, partial=False):
from tools.registry import registry, session_tool_scope
from tools.mcp_tool_discovery import register_mcp_servers
held = _held(authority, scope)
- wanted = fingerprint(servers)
+ # The cwd too: stdio servers run in it, so a committed workspace move respawns them there.
+ wanted = fingerprint([servers, cwd])
with session_tool_scope(scope):
with held.lock:
if held.fingerprint not in (None, wanted):
- # A committed editor_mcp swapped the credentials: no execution may still run on the old ones.
+ # A committed editor_mcp swapped the credentials (or a workspace move the cwd): no
+ # execution may still run on the old ones.
if held.users:
raise RuntimeStoreError('session_busy')
_disconnect(held, scope)
@@ -277,6 +280,14 @@ def resume_editor_mcp(authority, ref, editor):
attach_editor_mcp(authority, policy, servers)
+def retire_editor_mcp(authority, sid):
+ """An empty selection committed: *sid*'s held editor connections close now (blocking), viewer or not."""
+ scope = session_scope(authority, sid)
+ held = _held(authority, scope)
+ with held.lock:
+ _disconnect(held, scope)
+
+
def install_editor_mcp(authority, sid, servers):
"""After a committed change: *sid*'s borrowed credentials follow its committed policy (memory only)."""
from gateway.session_policy import restore_policy
@@ -316,29 +327,64 @@ async def prepare_editor_mcp(authority, live, payload, prepared, *, servers):
mcp_servers=[servers[int(i)]['name'] for i in sorted(names, key=int)])
+def _live_tools_changed(scope, names):
+ """Whether a held server's live ``tools/list`` differs from the tools its connection was
+ discovered with. Editor servers ignore ``tools/list_changed`` (the manifest is frozen), so
+ the admission start asks; an unanswered list (bounded) counts as unchanged."""
+ from tools import mcp_tool_loop
+ from tools.mcp_tool import _paginate_full_list, _servers
+ from tools.mcp_tool_scope import _server_key
+
+ def dump(tools):
+ return _json([tool.model_dump(mode='json') for tool in tools])
+
+ for name in names.values():
+ server = _servers.get(_server_key(name, scope))
+ if server is None:
+ continue
+
+ async def relist(server=server):
+ async with server._rpc_lock:
+ if server.session is None:
+ return None
+ return await _paginate_full_list(server.session.list_tools, 'tools', server.name)
+ try:
+ tools = mcp_tool_loop._run_on_mcp_loop(relist, timeout=_RELIST_TIMEOUT)
+ except Exception:
+ logger.warning('Editor MCP server %r: tools/list for the drift check failed', name, exc_info=True)
+ continue
+ if tools is not None and dump(tools) != dump(server._tools):
+ return True
+ return False
+
+
async def refreeze_editor_mcp(authority, ref, live):
"""The drain, before it claims the FIFO head (claim gate and mutation lock held, nothing
executing), re-checks the editor schemas; a drifted manifest is re-frozen through the
``editor_mcp`` writer path, so the turn runs on it instead of failing ``acp_mcp_schema_changed``."""
- from gateway.config import Platform
- from gateway.session_local_recovery import local_adapter_map
- # The policy the claim just restored (``restore_local_session``) for this local route.
- adapter = local_adapter_map(authority).get(Platform.LOCAL)
- policy = adapter.policies.get(live.source.chat_id) if adapter is not None else None
- if policy is None or not policy.editor_mcp_json:
+ if not getattr(authority, '_local_editor_mcp', None):
+ return # no session of this owner borrows editor servers: nothing to re-check
+ from gateway.session_policy import restore_policy
+ from hermes_state_local import local_receipt
+ # The committed policy the claim just restored (``restore_local_session``).
+ receipt = await asyncio.to_thread(local_receipt, authority.db, ref.session_id)
+ policy = restore_policy(receipt['policy'])
+ if not policy.editor_mcp_json:
return
data = json.loads(policy.editor_mcp_json)
- servers = getattr(authority, '_local_editor_mcp', {}).get(data['scope'])
+ servers = authority._local_editor_mcp.get(data['scope'])
if servers is None:
return # the execution reports launch_credentials_unavailable
def probe():
names = _frozen_names(data, servers)
with _borrowed(authority, data['scope'], servers, names, policy.cwd, partial=True) as (schemas, connected):
- return schemas, len(connected) == len(names)
- schemas, complete = await asyncio.to_thread(probe)
+ complete = len(connected) == len(names)
+ # A held connection keeps the registry schemas it was discovered with: ask the server.
+ return schemas, complete, complete and _live_tools_changed(data['scope'], names)
+ schemas, complete, drifted = await asyncio.to_thread(probe)
# A server that is down right now is the execution's discovery failure, never a narrowed manifest.
- if not complete or schemas == data['schemas']:
+ if not complete or (schemas == data['schemas'] and not drifted):
return
try:
await _commit_refreeze(authority, ref, live, servers)
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index 7704bb36639..9ff7bd6619e 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -199,6 +199,10 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):
# Before the policy publication below, so no execution sees the policy without them.
from gateway.session_local_mcp import install_editor_mcp
install_editor_mcp(authority, result.get('branched_session_id', ref.session_id), editor_servers)
+ if operation == 'editor_mcp' and not editor_servers:
+ # An empty selection: the old servers must not keep running for a viewer.
+ from gateway.session_local_mcp import retire_editor_mcp
+ await asyncio.to_thread(retire_editor_mcp, authority, ref.session_id)
if operation not in {*_POLICY, 'reset', 'compress', 'rewind'} or owns_projection:
_project_committed(authority, ref, operation, result)
if live is not None:
diff --git a/hermes_cli/main_agent_cmds.py b/hermes_cli/main_agent_cmds.py
index 649a5bce126..9921767564b 100644
--- a/hermes_cli/main_agent_cmds.py
+++ b/hermes_cli/main_agent_cmds.py
@@ -85,6 +85,11 @@ def cmd_acp(args):
for attr, name in (("accept_hooks", "HERMES_ACCEPT_HOOKS"), ("ignore_rules", "HERMES_IGNORE_RULES")):
if getattr(args, attr, False):
os.environ[name] = "1"
+ # -m / --provider: the route a --safe-mode / --ignore-user-config session freezes (it reads no
+ # profile default), carried like the TUI launcher's.
+ for attr, name in (("model", "HERMES_MODEL"), ("provider", "HERMES_INFERENCE_PROVIDER")):
+ if getattr(args, attr, None):
+ os.environ[name] = getattr(args, attr)
try:
from acp_adapter.entry import main as acp_main
acp_main([flag for attr, flag in _ACP_FLAGS if getattr(args, attr, False)])
diff --git a/tests/acp_adapter/test_gateway_editor_mcp_held.py b/tests/acp_adapter/test_gateway_editor_mcp_held.py
new file mode 100644
index 00000000000..9f827ff9c83
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_editor_mcp_held.py
@@ -0,0 +1,83 @@
+"""Held editor MCP connections follow the session's committed selection (#134889 ACP-8, ACP-10).
+
+A viewed session keeps its editor servers connected between turns. Such a connection still sees
+the server's changed tool list at the next admission start, and an empty selection closes it.
+These run against a real gateway, real stdio MCP peers and a loopback model peer.
+"""
+import json
+import sys
+
+import pytest
+
+from tests.acp_adapter.test_gateway_editor_mcp import MCPModelPeer, _completed, _peers_running, _policies
+from tests.acp_adapter.test_gateway_sessions import viewer
+from tests.waiting import async_wait_until
+
+# The tool description is read on every tools/list, so one live process can change its tools.
+PEER = '''import json, os, sys
+from pathlib import Path
+description = Path(os.environ['DESCRIPTION'])
+for line in sys.stdin:
+ r=json.loads(line); method=r.get('method'); ident=r.get('id')
+ if ident is None: continue
+ if method=='initialize': result={'protocolVersion':r['params']['protocolVersion'],'capabilities':{'tools':{}},'serverInfo':{'name':'held-peer','version':'1'}}
+ elif method=='tools/list': result={'tools':[{'name':'echo','description':description.read_text(),'inputSchema':{'type':'object','properties':{}}}]}
+ elif method=='tools/call': result={'content':[{'type':'text','text':'OWNED_RESULT_'+description.read_text().replace(' ','_')}]}
+ else: result={}
+ print(json.dumps({'jsonrpc':'2.0','id':ident,'result':result}),flush=True)
+'''
+
+
+def spec(tmp_path, model_peer):
+ model_peer.RequestHandlerClass = MCPModelPeer
+ (tmp_path / 'peer.py').write_text(PEER)
+ (tmp_path / 'description').write_text('owned echo')
+ return {'name': 'held', 'command': sys.executable, 'args': [str(tmp_path / 'peer.py')],
+ 'env': [{'name': 'DESCRIPTION', 'value': str(tmp_path / 'description')}]}
+
+
+async def _viewed_turn(ws, spec, tmp_path, frames):
+ """An acp session with *spec*, viewed by *ws*, after one settled turn through the editor tool."""
+ created = await ws.rpc('session.create', request_id='held-owner', source='acp', cwd=str(tmp_path),
+ editor={'mcp_servers': [spec], 'edit_approval_policy': 'ask'})
+ sid = created['session_id']
+ await ws.rpc('session.resume', session_id=sid)
+ await ws.rpc('prompt.submit', session_id=sid, input_id='first', text='Use owned echo')
+ await async_wait_until(_completed(ws, frames, 'OWNED_RESULT_owned_echo'), timeout=30, what='first turn settled')
+ return sid
+
+
+async def test_held_server_changing_its_tools_refreezes_at_the_next_admission(daemon, spec, tmp_path):
+ frames = []
+ async with viewer(daemon) as ws:
+ sid = await _viewed_turn(ws, spec, tmp_path, frames)
+ assert _peers_running(daemon[1]['pid']), 'a viewed session holds its editor server between turns'
+ # The same live process now lists a changed tool.
+ (tmp_path / 'description').write_text('owned echo v2')
+ await ws.rpc('prompt.submit', session_id=sid, input_id='second', text='Use owned echo')
+ await async_wait_until(_completed(ws, frames, 'OWNED_RESULT_owned_echo_v2'), timeout=30,
+ what='turn after the drift settled')
+ changed = [frame['params'] for frame in frames if frame['params'].get('type') == 'session.tools_changed']
+ assert [event['payload']['mcp_servers'] for event in changed] == [['held']]
+ (frozen,) = _policies(daemon[0], sid)
+ assert 'owned echo v2' in json.dumps(frozen['schemas'])
+
+
+async def test_empty_selection_closes_the_held_connections(daemon, spec, tmp_path):
+ frames = []
+ async with viewer(daemon) as ws:
+ sid = await _viewed_turn(ws, spec, tmp_path, frames)
+ assert _peers_running(daemon[1]['pid']), 'a viewed session holds its editor server between turns'
+ idle = await ws.rpc('session.resume', session_id=sid)
+ await ws.rpc('session.mutate', request_id='empty', session_id=sid, operation='editor_mcp',
+ payload={'mcp_servers': []}, expected_revision=idle['revision'],
+ expected_generation=idle['execution_generation'])
+ # The viewer is still attached: only the committed empty selection may close the process.
+ await async_wait_until(lambda: not _peers_running(daemon[1]['pid']), timeout=20,
+ what='held editor server closed by the empty selection')
+ assert _policies(daemon[0], sid) == [None]
diff --git a/tests/acp_adapter/test_gateway_launch_flags.py b/tests/acp_adapter/test_gateway_launch_flags.py
index ef1dcc40e84..a62a1682401 100644
--- a/tests/acp_adapter/test_gateway_launch_flags.py
+++ b/tests/acp_adapter/test_gateway_launch_flags.py
@@ -7,7 +7,8 @@ import pytest
from acp_adapter.gateway_server import GatewayACPAgent
_ENV = ('HERMES_YOLO_MODE', 'HERMES_SAFE_MODE', 'HERMES_IGNORE_USER_CONFIG', 'HERMES_IGNORE_RULES',
- 'HERMES_ACCEPT_HOOKS')
+ 'HERMES_ACCEPT_HOOKS', 'HERMES_MODEL', 'HERMES_INFERENCE_MODEL', 'HERMES_INFERENCE_PROVIDER')
+_FLAGS = ('yolo', 'safe_mode', 'ignore_user_config', 'ignore_rules', 'accept_hooks')
def _agent(created):
@@ -27,13 +28,46 @@ def _agent(created):
@pytest.mark.asyncio
async def test_launch_env_rides_session_create(monkeypatch, tmp_path):
- for name in _ENV:
+ for name in _ENV[:5]:
monkeypatch.setenv(name, '1')
+ monkeypatch.setenv('HERMES_MODEL', 'explicit-model') # a bypass session needs one (below)
+ created = []
+ await _agent(created).new_session(cwd=str(tmp_path))
+ assert {k: created[0].get(k) for k in _FLAGS} == dict.fromkeys(_FLAGS, True)
+
+
+async def test_safe_mode_acp_session_freezes_the_launch_model(monkeypatch, tmp_path):
+ """`hermes -m <model> --provider <name> --safe-mode acp`: the owner reads no profile default, so the
+ launch's model rides session.create and the owner's bypass policy accepts it."""
+ for name in _ENV:
+ monkeypatch.setenv(name, '') # recorded, so cmd_acp's exports are undone after the test
+ monkeypatch.setenv('HERMES_SAFE_MODE', '1') # what main() exports for --safe-mode
+ monkeypatch.setenv('HERMES_IGNORE_USER_CONFIG', '1')
+ import acp_adapter.entry
+ from gateway.session_local import _bypass_policy
+ from hermes_cli.main_agent_cmds import cmd_acp
+ monkeypatch.setattr(acp_adapter.entry, 'main', lambda argv: None)
+ cmd_acp(SimpleNamespace(model='anthropic/claude-sonnet-4', provider='openrouter'))
created = []
await _agent(created).new_session(cwd=str(tmp_path))
- assert {k: created[0].get(k) for k in ('yolo', 'safe_mode', 'ignore_user_config', 'ignore_rules',
- 'accept_hooks')} == dict.fromkeys(
- ('yolo', 'safe_mode', 'ignore_user_config', 'ignore_rules', 'accept_hooks'), True)
+ params = created[0]
+ assert (params['model'], params['provider'], params['safe_mode']) == ('anthropic/claude-sonnet-4', 'openrouter', True)
+ frozen = _bypass_policy({k: v for k, v in params.items() if k != 'request_id'}, private_secrets={})
+ assert frozen.model == 'anthropic/claude-sonnet-4' and frozen.safe_mode
+
+
[email protected]('flag', ['HERMES_SAFE_MODE', 'HERMES_IGNORE_USER_CONFIG'])
+async def test_bypass_without_a_model_names_the_missing_flag(monkeypatch, tmp_path, flag):
+ from hermes_cli.gateway_client import GatewayClientError
+ for name in _ENV:
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv(flag, '1')
+ created = []
+ with pytest.raises(GatewayClientError, match='hermes -m <model>'):
+ await _agent(created).new_session(cwd=str(tmp_path))
+ assert created == []
@pytest.mark.asyncio
diff --git a/tests/acp_adapter/test_session_mcp_workspace_move.py b/tests/acp_adapter/test_session_mcp_workspace_move.py
new file mode 100644
index 00000000000..8d12eb07475
--- /dev/null
+++ b/tests/acp_adapter/test_session_mcp_workspace_move.py
@@ -0,0 +1,36 @@
+"""A held editor connection follows a committed workspace move (#134889 ACP-12).
+
+Stdio editor servers run in the session's cwd. A viewed session keeps them connected between
+turns, so the move must respawn them in the new folder rather than keep running them in the old one.
+"""
+from dataclasses import replace
+from types import SimpleNamespace
+
+from gateway.session_policy import policy_scope
+from tests.acp_adapter.test_session_mcp_policy import owner, policy
+
+
+def test_workspace_move_respawns_held_stdio_servers_in_the_new_folder(server_spec, tmp_path):
+ from gateway.session_local_mcp import release_editor_mcp
+ from tools.registry import registry
+ script = tmp_path / 'owned_mcp.py'
+ script.write_text(script.read_text().replace("os.environ['BORROWED_CREDENTIAL']", 'os.getcwd()'))
+ old, new = tmp_path / 'project-a', tmp_path / 'project-b'
+ old.mkdir()
+ new.mkdir()
+ authority = owner()
+ live = SimpleNamespace(subscribers={'editor': object()})
+ authority.sessions = {'moved': live}
+ before = policy(authority, 'moved', server_spec, old)
+ try:
+ with policy_scope(before, authority=authority):
+ name = next(n for n in registry.get_all_tool_names() if n.startswith('mcp__'))
+ assert str(old.resolve()) in registry.dispatch(name, {})
+ # What a committed ``workspace`` mutation freezes: the same editor selection, a new cwd.
+ moved = replace(before, cwd=str(new))
+ with policy_scope(moved, authority=authority):
+ result = registry.dispatch(name, {})
+ assert str(new.resolve()) in result and str(old.resolve()) not in result
+ finally:
+ live.subscribers.clear()
+ release_editor_mcp(authority, ['moved'])