The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): require a provider under bypass flags; best-effort, parallel drift check
unsupportedpastels379cf1220fe2
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 31c646a853a..67f09b91c45 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -102,14 +102,18 @@ def _submit_fingerprint(session_id, text, attachments):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."""+ """--safe-mode / --ignore-user-config read no profile default route, so the session freezes the+ launch's explicit one (``hermes -m <model> --provider <name> --safe-mode acp``). Both, refused at+ session/new: a model alone is accepted by the owner, then its first turn cannot build the agent."""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 {})}+ if not provider:+ raise GatewayClientError("--safe-mode / --ignore-user-config read no profile provider: launch with "+ "--provider too, e.g. hermes -m <model> --provider <provider> --safe-mode acp")+ return {"model": model, "provider": provider}def _tools_changed_notice(payload):@@ -355,14 +359,14 @@ class GatewayACPAgent(acp.Agent):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"))resume_params = {}- if mcp_servers is not None:- # A list, empty included, is the editor's selection (load always carries one); a resume- # that omits it keeps the session's servers. An owner without editor MCP bound none.+ if mcp_servers:+ # A non-empty list is the editor's selection. An empty one (load always carries a list)+ # keeps the session's servers, as fork does: a second editor without MCP config must not+ # strip the first one's tools. An owner without editor MCP bound none.descriptor = await client.rpc("runtime.describe")- if "acp-session-mcp-v1" in descriptor.get("capabilities", []):- resume_params['editor'] = {'mcp_servers': [s.model_dump(by_alias=True) for s in mcp_servers]}- elif mcp_servers:+ if "acp-session-mcp-v1" not in descriptor.get("capabilities", []):raise GatewayClientError("acp_mcp_policy_unavailable")+ resume_params['editor'] = {'mcp_servers': [s.model_dump(by_alias=True) for s in mcp_servers]}try:snapshot = await client.rpc("session.resume", session_id=session_id, **resume_params)except GatewayRPCError as exc:@@ -373,10 +377,8 @@ class GatewayACPAgent(acp.Agent):await self._rebind_editor_mcp(client, session_id, resume_params['editor'])snapshot = await client.rpc("session.resume", session_id=session_id, **resume_params)self._snapshots[session_id] = snapshot- if resume_params.get('editor', {}).get('mcp_servers'):+ if 'editor' in resume_params:self._editor_mcp[session_id] = resume_params['editor']- elif 'editor' in resume_params:- self._editor_mcp.pop(session_id, None)from acp_adapter.server import _history_replay_updatesif self._conn:for update in _history_replay_updates(snapshot["messages"]):diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex a4495f58c21..bd25116f75b 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -775,9 +775,6 @@ class SessionAuthority:if first is not None and live.source.platform == Platform.LOCAL:from gateway.session_local_recovery import restore_local_sessionrestore_local_session(self, ref.session_id)- # Editor MCP schema drift re-freezes here, at this admission's start: a turn boundary.- from gateway.session_local_mcp import refreeze_editor_mcp- await refreeze_editor_mcp(self, ref, live)if first['request_id'].startswith('hosted:'):from gateway.session_hosted_transport import check_remote_hosted_admissionif not await asyncio.to_thread(check_remote_hosted_admission, self, ref, first):@@ -796,6 +793,10 @@ class SessionAuthority:else:from gateway.session_operator import check_local_inputcheck_local_input(self, ref, first)+ # Editor MCP schema drift re-freezes here, at this admission's start (a turn boundary),+ # once the head is authorized: a refused head spawns no server and commits no change.+ from gateway.session_local_mcp import refreeze_editor_mcp+ await refreeze_editor_mcp(self, ref, live)# The first real turn reopens a finalized row (#85303): mounts are reads, and# SessionStore would route a stamped row as stale onto a FRESH session. A write: off-loop,# tracked so retirement and the shutdown close gate count it.diff --git a/gateway/session_local_mcp.py b/gateway/session_local_mcp.pyindex 8331f3c16ec..559bd99fa6c 100644--- a/gateway/session_local_mcp.py+++ b/gateway/session_local_mcp.py@@ -266,24 +266,23 @@ def attach_editor_mcp(authority, policy, servers):def resume_editor_mcp(authority, ref, editor):- """Call after ordinary resume authorization, before attaching the viewer. An explicit empty list- is a selection too: on a session holding editor servers it conflicts, so the editor removes them- through the fenced ``editor_mcp`` change; an omitted list keeps them."""+ """Call after ordinary resume authorization, before attaching the viewer. An empty or omitted+ list keeps the session's servers: ACP load always carries one, so a second editor without MCP+ config must not strip the first one's tools for every viewer. Removal is only the fenced+ ``editor_mcp`` change with ``[]``."""if editor is None:return+ servers = editor.get('mcp_servers') if isinstance(editor, dict) else None+ if servers == []:+ returnfrom gateway.session_local_editor import validate_editorfrom gateway.session_policy import policy_for_sourcepolicy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)- servers = editor.get('mcp_servers') if isinstance(editor, dict) else None- if servers == [] and (policy is None or not policy.editor_mcp_json):- return # nothing to remove, whichever surface created the sessionif policy is None:raise RuntimeStoreError('acp_mcp_policy_conflict')validate_editor(policy.source, editor)if servers:attach_editor_mcp(authority, policy, servers)- elif servers is not None:- raise RuntimeStoreError('acp_mcp_policy_conflict')def retire_editor_mcp(authority, sid):@@ -344,32 +343,59 @@ def _live_tools_changed(scope, names):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+ held = [server for server in (_servers.get(_server_key(name, scope)) for name in names.values())+ if server is not None]++ async def relist(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)- 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)+ async def relist_all():+ # Every held server at once: one bound for the whole check, not one per server.+ tasks = [asyncio.ensure_future(relist(server)) for server in held]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+ if tasks:+ await asyncio.wait(tasks, timeout=_RELIST_TIMEOUT)+ finally:+ for task in tasks:+ task.cancel() # an unanswered list (bounded) counts as unchanged+ answered = []+ for server, task in zip(held, tasks):+ settled = task.done() and not task.cancelled()+ error = task.exception() if settled else None+ if settled and error is None:+ answered.append((server, task.result()))+ else:+ logger.warning('Editor MCP server %r: tools/list for the drift check failed', server.name,+ exc_info=error)+ return answered+ try:+ # The loop's own bound is a backstop; relist_all settles within _RELIST_TIMEOUT.+ answered = mcp_tool_loop._run_on_mcp_loop(relist_all, timeout=_RELIST_TIMEOUT + 1)+ except (RuntimeError, TimeoutError, InterruptedError):+ logger.warning('Editor MCP drift check of %s failed', scope, exc_info=True)+ return False+ return any(tools is not None and dump(tools) != dump(server._tools) for server, tools in answered)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``."""+ """The drain, once the FIFO head is authorized and before it is claimed (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``.+ Best-effort: the FIFO must not pause on it, so a failed re-check only logs and the turn then+ reports real drift as before."""if not getattr(authority, '_local_editor_mcp', None):return # no session of this owner borrows editor servers: nothing to re-check+ try:+ await _refreeze(authority, ref)+ except Exception: # health: allow BLE001 -- the probe spawns arbitrary editor servers; nothing it raises may kill the drain+ logger.warning('Editor MCP re-check of session %s failed; the turn runs on its frozen manifest',+ ref.session_id, exc_info=True)+++async def _refreeze(authority, ref):from gateway.session_policy import restore_policyfrom hermes_state_local import local_receipt# The committed policy the claim just restored (``restore_local_session``).@@ -392,11 +418,7 @@ async def refreeze_editor_mcp(authority, ref, live):# A server that is down right now is the execution's discovery failure, never a narrowed manifest.if not complete or (schemas == data['schemas'] and not drifted):return- try:- await _commit_refreeze(authority, ref, servers)- except RuntimeStoreError:- # The FIFO must not pause on it: the turn then reports the drift as before.- logger.warning('Editor MCP schemas of session %s changed; re-freeze failed', ref.session_id, exc_info=True)+ await _commit_refreeze(authority, ref, servers)async def _commit_refreeze(authority, ref, servers):diff --git a/tests/acp_adapter/test_gateway_editor_mcp_held.py b/tests/acp_adapter/test_gateway_editor_mcp_held.pyindex 111cb29a9d6..b73914fb36e 100644--- a/tests/acp_adapter/test_gateway_editor_mcp_held.py+++ b/tests/acp_adapter/test_gateway_editor_mcp_held.py@@ -86,10 +86,11 @@ async def test_empty_selection_closes_the_held_connections(daemon, spec, tmp_pat@pytest.mark.platforms("linux")@pytest.mark.asyncio-async def test_acp_load_with_no_servers_removes_them_and_resume_without_a_list_keeps_them(daemon, spec, tmp_path):- """``session/load`` always carries ``mcpServers`` (the schema requires it), so ``[]`` there is the- editor's selection: the owner's ``editor_mcp`` removal. ``session/resume`` may omit the list,- which keeps the session's servers."""+async def test_acp_load_with_no_servers_keeps_them_and_direct_editor_mcp_empty_removes_them(daemon, spec, tmp_path):+ """``session/load`` always carries ``mcpServers`` (the schema requires it), so a second editor with+ no MCP config loads with ``[]``: that keeps the session's servers for every viewer, as an omitted+ list on ``session/resume`` and ``[]`` on ``session/fork`` do. Removal is only the owner's fenced+ ``editor_mcp`` change with ``[]``, which also stops the held process."""async with editor(daemon, tmp_path) as acp:await initialize(acp)created = await acp.rpc('session/new', cwd=str(tmp_path), mcpServers=[spec])@@ -100,10 +101,17 @@ async def test_acp_load_with_no_servers_removes_them_and_resume_without_a_list_kresumed = await acp.rpc('session/resume', sessionId=sid, cwd=str(tmp_path))assert 'result' in resumed, resumedassert _peers_running(daemon[1]['pid']), 'an omitted list keeps the servers'- assert _policies(daemon[0], sid) != [None]+ frozen = _policies(daemon[0], sid)+ assert frozen != [None]loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])assert 'result' in loaded, loaded- # The editor 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 load')+ assert _peers_running(daemon[1]['pid']), 'an empty load keeps the held server'+ assert _policies(daemon[0], sid) == frozen+ async with viewer(daemon) as ws:+ idle = await ws.rpc('session.resume', session_id=sid)+ await ws.rpc('session.mutate', request_id='remove', session_id=sid, operation='editor_mcp',+ payload={'mcp_servers': []}, expected_revision=idle['revision'],+ expected_generation=idle['execution_generation'])+ await async_wait_until(lambda: not _peers_running(daemon[1]['pid']), timeout=20,+ what='held editor server closed by the direct empty editor_mcp')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.pyindex a62a1682401..ea503a6e3e4 100644--- a/tests/acp_adapter/test_gateway_launch_flags.py+++ b/tests/acp_adapter/test_gateway_launch_flags.py@@ -30,7 +30,8 @@ def _agent(created):async def test_launch_env_rides_session_create(monkeypatch, tmp_path):for name in _ENV[:5]:monkeypatch.setenv(name, '1')- monkeypatch.setenv('HERMES_MODEL', 'explicit-model') # a bypass session needs one (below)+ monkeypatch.setenv('HERMES_MODEL', 'explicit-model') # a bypass session needs a route (below)+ monkeypatch.setenv('HERMES_INFERENCE_PROVIDER', 'openrouter')created = []await _agent(created).new_session(cwd=str(tmp_path))assert {k: created[0].get(k) for k in _FLAGS} == dict.fromkeys(_FLAGS, True)@@ -70,6 +71,22 @@ async def test_bypass_without_a_model_names_the_missing_flag(monkeypatch, tmp_paassert created == [][email protected]('flag', ['HERMES_SAFE_MODE', 'HERMES_IGNORE_USER_CONFIG'])+async def test_bypass_with_a_model_but_no_provider_is_refused_at_session_new(monkeypatch, tmp_path, flag):+ """`hermes -m <model> --safe-mode acp`: the owner would accept the session, then its first turn+ could not build the agent. Refused before session.create, naming the missing flag."""+ from hermes_cli.gateway_client import GatewayClientError+ for name in _ENV:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv(flag, '1')+ monkeypatch.setenv('HERMES_MODEL', 'gpt-4o-mini')+ created = []+ with pytest.raises(GatewayClientError, match='launch with --provider too'):+ await _agent(created).new_session(cwd=str(tmp_path))+ assert created == []++@pytest.mark.asyncioasync 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."""diff --git a/tests/gateway/test_session_local_mcp_refreeze.py b/tests/gateway/test_session_local_mcp_refreeze.pynew file mode 100644index 00000000000..82522cabb4a--- /dev/null+++ b/tests/gateway/test_session_local_mcp_refreeze.py@@ -0,0 +1,113 @@+"""The admission-start editor MCP re-check is best-effort, bounded and runs only for an authorized head.++The drain re-checks an editor session's held MCP servers before it claims the FIFO head+(``refreeze_editor_mcp``). Nothing that check raises may pause or kill the drain, every held+server is re-listed under one shared bound, and a head the drain refuses never reaches it.+"""+import asyncio+import json+import time+from types import SimpleNamespace++import pytest++from gateway.config import Platform+from hermes_state_runtime import RuntimeStoreError+from tests.gateway.test_session_authority_cancel_settlement import REF, _authority, _submit+from tests.waiting import async_wait_until+++def _local_authority(tmp_path, monkeypatch):+ from gateway import session_local_recovery+ db, authority = _authority(tmp_path, monkeypatch, platform=Platform.LOCAL)+ monkeypatch.setattr(session_local_recovery, 'restore_local_session', lambda authority, sid: None)+ monkeypatch.setattr(session_local_recovery, 'reopen_local_session', lambda authority, ref: None)+ return db, authority++[email protected]('error', [RuntimeStoreError('session_busy'), OSError('editor server crashed')],+ ids=['runtime-store-error', 'other-exception'])+async def test_a_failing_editor_mcp_probe_does_not_stop_the_admission(tmp_path, monkeypatch, error):+ import hermes_state_local+ from gateway import session_finite, session_local_mcp, session_policy+ db, authority = _local_authority(tmp_path, monkeypatch)+ # An editor session whose borrowed servers the probe re-checks; the probe itself fails.+ data = {'scope': 'editor-session:probe', 'schemas': {}, 'names': {'0': 'editor_probe_0'}}+ authority._local_editor_mcp = {data['scope']: [{'name': 'probe'}]}+ monkeypatch.setattr(hermes_state_local, 'local_receipt', lambda db, sid: {'policy': 'frozen'})+ monkeypatch.setattr(session_policy, 'restore_policy',+ lambda saved: SimpleNamespace(editor_mcp_json=json.dumps(data), cwd=str(tmp_path)))++ def failing_probe(*args, **kwargs):+ raise error+ monkeypatch.setattr(session_local_mcp, '_borrowed', failing_probe)+ executed = []++ async def execute(authority, ref, row):+ executed.append(row['request_id'])+ return 'done'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)+ with db:+ await _submit(authority, 'work')+ await async_wait_until(lambda: executed, timeout=10, what='the head to run past the failed probe')+ assert executed == ['work']+++async def test_a_refused_head_triggers_no_editor_mcp_probe(tmp_path, monkeypatch):+ from gateway import session_local_mcp+ db, authority = _local_authority(tmp_path, monkeypatch)+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ probed = []++ async def refreeze(authority, ref, live):+ probed.append(ref.session_id)+ monkeypatch.setattr(session_local_mcp, 'refreeze_editor_mcp', refreeze)+ live = authority.sessions['s']+ with db:+ await _submit(authority, 'refused')+ # The submitter no longer owns the session's source: check_local_input refuses the head.+ live.source = SimpleNamespace(platform=Platform.LOCAL, user_id='someone-else')+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ await authority._claim_next(REF, live)+ assert probed == []+ live.source = SimpleNamespace(platform=Platform.LOCAL, user_id='human')+ row, _ = await authority._claim_next(REF, live)+ assert row and probed == ['s'], 'an authorized head is still re-checked'+++def mcp_loop():+ from tools import mcp_tool_loop+ mcp_tool_loop._ensure_mcp_loop()+ yield+ mcp_tool_loop._stop_mcp_loop()+++def test_held_servers_are_relisted_together_under_one_bound(monkeypatch, mcp_loop):+ """Two held servers that never answer cost one bound, not one each: each list only gets past+ its rendezvous while the other's is in flight too."""+ from gateway import session_local_mcp+ from tools import mcp_tool+ from tools.mcp_tool_scope import _server_key+ bound = 2+ monkeypatch.setattr(session_local_mcp, '_RELIST_TIMEOUT', bound)+ scope, names = 'editor-session:slow', {0: 'editor_a', 1: 'editor_b'}+ started, met = [asyncio.Event(), asyncio.Event()], []++ def server(i):+ async def list_tools():+ started[i].set()+ await started[1 - i].wait()+ met.append(i)+ await asyncio.Event().wait() # never answers+ return SimpleNamespace(name=names[i], _rpc_lock=asyncio.Lock(), _tools=[],+ session=SimpleNamespace(list_tools=list_tools))+ for i, name in names.items():+ monkeypatch.setitem(mcp_tool._servers, _server_key(name, scope), server(i))+ began = time.monotonic()+ assert session_local_mcp._live_tools_changed(scope, names) is False # unanswered counts as unchanged+ elapsed = time.monotonic() - began+ assert sorted(met) == [0, 1], 'the re-lists ran one after another'+ assert elapsed < 2 * bound, elapsed