The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): forward hermes acp flags, keep editor MCP names, rebind moved sessions
unsupportedpastelsd28c07b3f24c
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 475d67d655e..a6316dce837 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -261,10 +261,13 @@ class GatewayACPAgent(acp.Agent):if ("acp" not in descriptor.get("session_create", {}).get("sources", [])or "acp-editor-policy-v1" not in descriptor.get("capabilities", [])):raise GatewayClientError("acp_policy_unavailable")+ 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.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"})+ "edit_approval_policy": "ask"}, **env_launch_flags())session_id = snapshot["session_id"]self._snapshots[session_id] = snapshotif mcp_servers:@@ -324,8 +327,8 @@ class GatewayACPAgent(acp.Agent):if session_id != held_id:self._aliases[held_id] = session_idinfo = await self._attach_info(client, session_id)- if "cwd" in info and _normalize_cwd_for_compare(info["cwd"]) != _normalize_cwd_for_compare(_translate_acp_cwd(cwd)):- raise GatewayClientError("cwd_policy_conflict")+ if self._moved(info, cwd):+ info = await self._move_workspace(client, session_id, cwd)if "cwd" not in info and self._conn:await self._conn.session_update(session_id=held_id, update=acp.update_agent_message_text("Attached to the gateway's existing session policy; editor cwd is not applied.\n"))@@ -348,6 +351,19 @@ class GatewayACPAgent(acp.Agent):await self._notify_unknown(session_id)return await self._session_fields(session_id, {**info, **(snapshot.get("info") or {})}, held_id)+ @staticmethod+ def _moved(info, cwd):+ return "cwd" in info and _normalize_cwd_for_compare(info["cwd"]) != _normalize_cwd_for_compare(_translate_acp_cwd(cwd))++ async def _move_workspace(self, client, session_id, cwd):+ """Main rebound a session opened from another folder to that folder; the owner's ``workspace``+ mutation (Move to project) moves execution cwd and TERMINAL_CWD together, idle sessions only."""+ payload = {'cwd': _translate_acp_cwd(cwd)}+ self._unacked.pop(session_id, None)+ await self._mutations.apply(client, session_id, 'workspace', payload)+ self._mutations.acknowledge(session_id, 'workspace', payload)+ return await client.rpc("session.info", session_id=session_id)+async def load_session(self, cwd, session_id, mcp_servers=None, **kwargs):return LoadSessionResponse(**await self._resume(cwd, session_id, mcp_servers))@@ -396,12 +412,15 @@ class GatewayACPAgent(acp.Agent):session_id = self._aliases.get(session_id, session_id)client = await self._client()info = await client.rpc('session.info', session_id=session_id)- if (mcp_servers or _normalize_cwd_for_compare(info.get('cwd', '')) !=- _normalize_cwd_for_compare(_translate_acp_cwd(cwd))):+ if mcp_servers:+ # The branch inherits the parent's borrowed-MCP scope; binding other servers to the child+ # (or giving it its own scope) has no owner verb.raise GatewayClientError('cwd_policy_conflict')self._unacked.pop(session_id, None)result = await self._mutations.apply(client, session_id, 'branch', {})child = result['branched_session_id']+ if self._moved(info, cwd):+ await self._move_workspace(client, child, cwd)self._snapshots[child] = await client.rpc('session.resume', session_id=child)self._mutations.acknowledge(session_id, 'branch', {})info = self._snapshots[child].get('info') or await client.rpc('session.info', session_id=child)diff --git a/gateway/session_local_mcp.py b/gateway/session_local_mcp.pyindex 71167db8b0c..de81502fa72 100644--- a/gateway/session_local_mcp.py+++ b/gateway/session_local_mcp.py@@ -9,9 +9,12 @@ from dataclasses import replaceimport hashlibimport hmacimport json+import loggingfrom hermes_state_runtime import RuntimeStoreError+logger = logging.getLogger(__name__)+PRIVATE_KEY = ('editor_mcp',)@@ -52,11 +55,26 @@ def private_editor_request(request, private):request['editor'] = {**editor, 'mcp_servers': {'fingerprint': fingerprint(servers)}}-def _configs(scope, servers, cwd):+def _server_names(scope, servers):+ """Index -> ledger name: the editor's own server name (the model sees ``mcp__editor_github_<tag>__x``)+ plus a per-session tag, so two sessions borrowing same-named servers never adopt one connection."""+ from tools.mcp_tool_schema import sanitize_mcp_name_component+ return {i: f"editor_{sanitize_mcp_name_component(spec['name'])}_"+ f"{hashlib.sha256(f'{scope}:{i}'.encode()).hexdigest()[:8]}" for i, spec in enumerate(servers)}+++def _frozen_names(data, servers):+ """The names a session's manifest was frozen under; manifests without ``names`` predate them."""+ if 'names' in data:+ return {int(i): name for i, name in data['names'].items()}+ prefix = hashlib.sha256(data['scope'].encode()).hexdigest()[:20]+ return {i: f'editor_{prefix}_{i}' for i in range(len(servers))}+++def _configs(servers, names, cwd):configs = {}- prefix = hashlib.sha256(scope.encode()).hexdigest()[:20]- for i, spec in enumerate(servers):- name = f'editor_{prefix}_{i}'+ for i, name in names.items():+ spec = servers[i]if spec.get('type', 'stdio') == 'stdio':config = {'command': spec['command'], 'args': spec['args'],'env': {e['name']: e['value'] for e in spec.get('env', [])}, 'cwd': cwd}@@ -71,23 +89,26 @@ def _configs(scope, servers, cwd):@contextmanager-def _registered(scope, servers, cwd):+def _registered(scope, servers, names, cwd, *, partial=False):+ """Yield ``(schemas, connected indexes)``. Only ``partial`` (the creation-time selection) may+ leave a server out; an execution needs every server its manifest was frozen with."""from tools.registry import registry, session_tool_scopefrom tools.mcp_tool_discovery import register_mcp_serversfrom tools.mcp_tool_lifecycle import shutdown_mcp_serversfrom tools.mcp_tool import _serversfrom tools.mcp_tool_scope import _server_key- configs = _configs(scope, servers, cwd)+ configs = _configs(servers, names, cwd)with session_tool_scope(scope):try:register_mcp_servers(configs)# Inside the scope the ledger keys are ``(scope, name)``, never bare names.- keys = [_server_key(name, scope) for name in configs]- if any(key not in _servers or _servers[key].session is None for key in keys):+ connected = [i for i, name in names.items()+ if _server_key(name, scope) in _servers and _servers[_server_key(name, scope)].session]+ if len(connected) != len(names) and not partial:raise RuntimeStoreError('acp_mcp_discovery_failed')- names = [n for n in registry.get_all_tool_names()- if registry.get_toolset_for_tool(n) in {f'mcp-{k}' for k in configs}]- yield {n: registry.get_schema(n) for n in sorted(names)}, tuple(f'mcp-{k}' for k in configs)+ toolsets = {f'mcp-{names[i]}' for i in connected}+ tools = [n for n in registry.get_all_tool_names() if registry.get_toolset_for_tool(n) in toolsets]+ yield {n: registry.get_schema(n) for n in sorted(tools)}, connectedfinally:shutdown_mcp_servers(scope=scope)@@ -96,10 +117,18 @@ def bind_editor_mcp(authority, sid, policy, servers):if not servers:return policyscope = 'editor-session:' + hashlib.sha256(f'{authority.profile_id}:{sid}'.encode()).hexdigest()- with _registered(scope, servers, policy.cwd) as (schemas, toolsets):- data = {'scope': scope, 'fingerprint': fingerprint(servers), 'schemas': schemas}+ names = _server_names(scope, servers)+ with _registered(scope, servers, names, policy.cwd, partial=True) as (schemas, connected):+ # One broken editor server must not refuse the session (main skipped it too): it is left out+ # of the frozen selection, so no later execution respawns it.+ for i in sorted(set(names) - set(connected)):+ logger.warning("Editor MCP server %r failed discovery; session %s continues without it",+ servers[i].get('name'), sid)+ names = {i: names[i] for i in connected}+ data = {'scope': scope, 'fingerprint': fingerprint(servers), 'schemas': schemas,+ 'names': {str(i): name for i, name in names.items()}}policy = replace(policy, editor_mcp_json=_json(data),- toolsets=tuple(sorted(set(policy.toolsets) | set(toolsets))))+ toolsets=tuple(sorted(set(policy.toolsets) | {f'mcp-{name}' for name in names.values()})))attach_editor_mcp(authority, policy, servers)return policy@@ -139,7 +168,7 @@ def editor_mcp_scope(authority, policy):servers = getattr(authority, '_local_editor_mcp', {}).get(data['scope'])if servers is None:raise RuntimeStoreError('launch_credentials_unavailable')- with _registered(data['scope'], servers, policy.cwd) as (schemas, _):+ with _registered(data['scope'], servers, _frozen_names(data, servers), policy.cwd) as (schemas, _):if schemas != data['schemas']:raise RuntimeStoreError('acp_mcp_schema_changed')yielddiff --git a/hermes_cli/main_agent_cmds.py b/hermes_cli/main_agent_cmds.pyindex 000943e965d..649a5bce126 100644--- a/hermes_cli/main_agent_cmds.py+++ b/hermes_cli/main_agent_cmds.py@@ -79,6 +79,12 @@ _ACP_FLAGS = (def cmd_acp(args):"""Launch Hermes Agent as an ACP server."""+ import os+ # The gateway-backed ACP server forwards launch flags from their documented env equivalents+ # (main() already exported --yolo / --safe-mode / --ignore-user-config).+ for attr, name in (("accept_hooks", "HERMES_ACCEPT_HOOKS"), ("ignore_rules", "HERMES_IGNORE_RULES")):+ if getattr(args, attr, False):+ os.environ[name] = "1"try:from acp_adapter.entry import main as acp_mainacp_main([flag for attr, flag in _ACP_FLAGS if getattr(args, attr, False)])diff --git a/tests/acp_adapter/test_gateway_editor_wire.py b/tests/acp_adapter/test_gateway_editor_wire.pyindex 406a0ab7ee0..c4d07019bb0 100644--- a/tests/acp_adapter/test_gateway_editor_wire.py+++ b/tests/acp_adapter/test_gateway_editor_wire.py@@ -51,7 +51,9 @@ class EditPeer(BaseHTTPRequestHandler):@pytest.mark.platforms("linux")@pytest.mark.asyncio-async def test_acp_load_checks_authoritative_cwd(daemon, tmp_path):+async def test_acp_load_from_another_folder_moves_the_session_there(daemon, tmp_path):+ """Main rebound a session opened from another folder (#134889 ACP-12): the owner's workspace+ mutation moves the authoritative cwd, which every viewer then reads."""other = tmp_path / 'other'other.mkdir()async with viewer(daemon) as ws:@@ -60,10 +62,17 @@ async def test_acp_load_checks_authoritative_cwd(daemon, tmp_path):assert created['info']['cwd'] == str(tmp_path)async with editor(daemon, tmp_path) as acp:await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})- refused = await acp.rpc('session/load', sessionId=sid, cwd=str(other), mcpServers=[])- assert 'cwd_policy_conflict' in json.dumps(refused)- loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])- assert 'result' in loaded+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(other), mcpServers=[])+ assert 'result' in loaded, loaded+ assert (await ws.rpc('session.info', session_id=sid))['cwd'] == str(other)+ resumed = await acp.rpc('session/resume', sessionId=sid, cwd=str(tmp_path), mcpServers=[])+ assert 'result' in resumed, resumed+ assert (await ws.rpc('session.info', session_id=sid))['cwd'] == str(tmp_path)+ forked = await acp.rpc('session/fork', sessionId=sid, cwd=str(other), mcpServers=[])+ assert 'result' in forked, forked+ child = forked['result']['sessionId']+ assert (await ws.rpc('session.info', session_id=child))['cwd'] == str(other)+ assert (await ws.rpc('session.info', session_id=sid))['cwd'] == str(tmp_path)@pytest.mark.platforms("linux")diff --git a/tests/acp_adapter/test_gateway_launch_flags.py b/tests/acp_adapter/test_gateway_launch_flags.pynew file mode 100644index 00000000000..ef1dcc40e84--- /dev/null+++ b/tests/acp_adapter/test_gateway_launch_flags.py@@ -0,0 +1,51 @@+"""`hermes acp` launch flags freeze into the gateway session they create (#134889 ACP-13)."""+from types import SimpleNamespace+from unittest.mock import AsyncMock++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')+++def _agent(created):+ async def rpc(method, **params):+ if method == 'runtime.describe':+ return {'session_create': {'sources': ['acp']}, 'capabilities': ['acp-editor-policy-v1']}+ assert method == 'session.create', method+ created.append(params)+ return {'session_id': 's', 'info': {'cwd': params['cwd']}}++ agent = GatewayACPAgent()+ agent._gateway = AsyncMock()+ agent._gateway.rpc.side_effect = rpc+ agent._session_fields = AsyncMock(return_value={})+ return agent+++async def test_launch_env_rides_session_create(monkeypatch, tmp_path):+ for name in _ENV:+ monkeypatch.setenv(name, '1')+ 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)+++async def test_cli_only_acp_flags_reach_the_session(monkeypatch, tmp_path):+ """--accept-hooks / --ignore-rules have no other route from the `hermes acp` parser to the owner."""+ for name in _ENV:+ monkeypatch.setenv(name, '') # recorded, so cmd_acp's exports are undone after the test+ import acp_adapter.entry+ from hermes_cli.main_agent_cmds import cmd_acp+ monkeypatch.setattr(acp_adapter.entry, 'main', lambda argv: None)+ cmd_acp(SimpleNamespace(accept_hooks=True, ignore_rules=True))+ created = []+ await _agent(created).new_session(cwd=str(tmp_path))+ assert created[0].get('accept_hooks') is True and created[0].get('ignore_rules') is True+ assert 'yolo' not in created[0] and 'safe_mode' not in created[0]diff --git a/tests/acp_adapter/test_session_mcp_frozen.py b/tests/acp_adapter/test_session_mcp_frozen.pyindex 21d0c7242a5..5187a6e200d 100644--- a/tests/acp_adapter/test_session_mcp_frozen.py+++ b/tests/acp_adapter/test_session_mcp_frozen.py@@ -80,8 +80,8 @@ def test_silent_editor_discovery_is_bounded_and_reaps_only_itself(server_spec, t'args': ['-c', 'import time; time.sleep(120)'], 'env': []}with policy_scope(healthy, authority=authority):started = time.monotonic()- with pytest.raises(RuntimeStoreError, match='acp_mcp_discovery_failed'):- policy(authority, 'silent', silent, tmp_path)+ # Left out of its session's selection (#134889 ACP-8), never fatal to it.+ assert json.loads(policy(authority, 'silent', silent, tmp_path).editor_mcp_json)['schemas'] == {}assert time.monotonic() - started < 25names = [n for n in registry.get_all_tool_names() if n.startswith('mcp__')]assert len(names) == 1diff --git a/tests/acp_adapter/test_session_mcp_selection.py b/tests/acp_adapter/test_session_mcp_selection.pynew file mode 100644index 00000000000..38b3b336e9f--- /dev/null+++ b/tests/acp_adapter/test_session_mcp_selection.py@@ -0,0 +1,60 @@+"""Which editor MCP servers a session freezes, and under which names (#134889 ACP-8, ACP-9)."""+import json+import sys+import time++from gateway.session_policy import build_policy, bind_launch_key, policy_scope+from tests.acp_adapter.test_session_mcp_policy import owner+++def _policy(authority, sid, specs, tmp_path):+ private = {}+ result = build_policy({'source': 'acp', 'cwd': str(tmp_path), 'model': 'local',+ 'toolsets': [], 'editor': {'mcp_servers': specs}}, {}, private_secrets=private)+ return bind_launch_key(authority, sid, result, None, config_secrets=private)+++def _editor_tools():+ from tools.registry import registry+ return [n for n in registry.get_all_tool_names() if n.startswith('mcp__')]+++def test_a_broken_editor_server_is_left_out_of_the_session(server_spec, tmp_path):+ from tools.registry import registry+ from tools.mcp_tool import _servers+ silent = {'name': 'silent', 'command': sys.executable, 'args': ['-c', 'import time; time.sleep(120)'], 'env': []}+ authority = owner()+ started = time.monotonic()+ p = _policy(authority, 'mixed', [silent, server_spec], tmp_path)+ assert time.monotonic() - started < 25+ started = time.monotonic()+ with policy_scope(p, authority=authority):+ names = _editor_tools()+ assert len(names) == 1 and 'PRIVATE_A' in registry.dispatch(names[0], {})+ # The execution never respawned the broken server (that alone would cost its connect timeout).+ assert time.monotonic() - started < 4+ assert not any(key[-1].startswith('editor_') for key in _servers)+++def test_editor_tool_names_keep_the_server_name(server_spec, tmp_path, monkeypatch):+ authority = owner()+ p = _policy(authority, 'named', [server_spec], tmp_path)+ with policy_scope(p, authority=authority):+ (name,) = _editor_tools()+ assert name.startswith('mcp__editor_same_editor_name_') and name.endswith('__echo')+ # A manifest frozen before names were recorded keeps executing under the names it froze.+ import gateway.session_local_mcp as local_mcp+ import hashlib+ def legacy(scope, servers):+ prefix = hashlib.sha256(scope.encode()).hexdigest()[:20]+ return {i: f'editor_{prefix}_{i}' for i in range(len(servers))}+ with monkeypatch.context() as patched:+ patched.setattr(local_mcp, '_server_names', legacy)+ old = _policy(authority, 'legacy', [server_spec], tmp_path)+ data = json.loads(old.editor_mcp_json)+ del data['names']+ from dataclasses import replace+ old = replace(old, editor_mcp_json=json.dumps(data))+ with policy_scope(old, authority=authority):+ (legacy_name,) = _editor_tools()+ assert legacy_name in data['schemas']