The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): a guarded deferred model pick asks the editor at the turn boundary
Tekniumcc9442326c10
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 2f67bf9da82..3897c39c010 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -461,6 +461,44 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):update=acp.update_agent_message_text(deferred_pick_text(result) + "\n"))return SetSessionModelResponse()+ async def _confirm_deferred_pick(self, session_id, editor_id, ask):+ """The owner's boundary ask for a guarded deferred pick (``confirmation_required``; nothing+ written, the pick stays pending): the same permission request as an idle pick. Yes re-sends+ the same selection once with the owner's token (as Ink/Desktop); no, or no editor, keeps the+ committed model, and the editor is told which outcome it got, never left on the promise."""+ from acp_adapter.gateway_commands import _model_text, deferred_pick_text, refused_pick_text+ from hermes_cli.gateway_mutations import model_refusal_text++ async def say(text):+ if self._conn:+ await self._conn.session_update(session_id=editor_id, update=acp.update_agent_message_text(text + "\n"))+ target = ask.get("target_model") or (ask.get("payload") or {}).get("model")+ committed = {"model": ask.get("committed_model"), "provider": ask.get("committed_provider"),+ "target_model": target}+ confirm = self._model_confirmer(session_id)+ try:+ if confirm is None or not await confirm(ask):+ await say(refused_pick_text({**committed, "reason": "not confirmed"}))+ return+ client = await self._client()+ snapshot = await client.rpc("session.resume", session_id=session_id)+ result = await client.rpc("session.mutate", session_id=session_id, operation="model",+ request_id=uuid.uuid4().hex, expected_revision=snapshot["revision"],+ expected_generation=snapshot["execution_generation"],+ payload={**(ask.get("payload") or {}), "confirm": ask["confirm"]})+ if result.get("status") == "confirmation_required":+ # Another pick or a turn moved the session first: said once, never re-asked in a loop.+ await say(model_refusal_text(result, confirmed=True))+ return+ if session_id in self._snapshots:+ self._snapshots[session_id] = await client.rpc("session.resume", session_id=session_id)+ # Confirmed while a turn runs: stored again for the next boundary, said as such.+ await say(deferred_pick_text(result) if result.get("status") == "deferred"+ else _model_text("Model switched to", result))+ except GatewayClientError as exc:+ logger.info("Deferred model pick on %s not confirmed: %s", session_id, exc)+ await say(refused_pick_text({**committed, "reason": str(exc)}))+def _model_confirmer(self, session_id):"""The owner's guarded-model confirmation as an ACP permission request (the mechanismapprovals use): "Switch anyway" re-sends the mutation once with the owner's token; deny,@@ -785,6 +823,14 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):await self._conn.session_update(session_id=editor_id, update=acp.update_agent_message_text(refused_pick_text(payload) + "\n"))return+ if (kind == "session.updated" and payload.get("operation") == "model"+ and payload.get("status") == "confirmation_required" and isinstance(payload.get("confirm"), str)):+ # A deferred pick whose target needs consent at the turn boundary: asked like an idle+ # pick (off the event pump: the answer may take as long as the user does).+ task = asyncio.create_task(self._confirm_deferred_pick(sid, editor_id, payload))+ self._background.add(task)+ task.add_done_callback(self._background.discard)+ returnif kind == "session.info" and sid in self._snapshots and "pending" in payload:async with self._changed:self._snapshots[sid]["pending"] = payload["pending"]diff --git a/tests/acp_adapter/test_gateway_model_pick_provider.py b/tests/acp_adapter/test_gateway_model_pick_provider.pyindex 495f0134e81..35782844989 100644--- a/tests/acp_adapter/test_gateway_model_pick_provider.py+++ b/tests/acp_adapter/test_gateway_model_pick_provider.py@@ -102,3 +102,65 @@ async def test_deferred_pick_that_no_longer_resolves_is_named_to_the_editor(daemshown = _shown(acp.frames, start)assert 'second-model was not applied' in shown and 'local-wire-stub' in shown, shownassert model_peer.requests[-1]['model'] == 'local-wire-stub', model_peer.requests[-1]+++_GUARDED = {**_SECOND, 'model': {'switch_context_confirm_tokens': 1}}+++def _measured(model_peer):+ """Streamed replies report provider usage, so the owner measures the session's context."""+ from tests.gateway.fixtures.shared_authority_peer import ModelPeer++ class Measured(ModelPeer):+ def send_header(self, key, value):+ super().send_header(key, value)+ self._stream = value == 'text/event-stream' or getattr(self, '_stream', False)++ def end_headers(self):+ super().end_headers()+ if getattr(self, '_stream', False):+ write = self.wfile.write++ def with_usage(data):+ if data.startswith(b'data: {') and b'"finish_reason": "stop"' in data:+ chunk = json.loads(data[6:])+ chunk['usage'] = {'prompt_tokens': 250000, 'completion_tokens': 5, 'total_tokens': 250005}+ data = ('data: ' + json.dumps(chunk) + '\n\n').encode()+ return write(data)+ self.wfile.write = with_usage+ model_peer.RequestHandlerClass = Measured++[email protected]('linux')[email protected]('daemon', [_GUARDED], indirect=True)+async def test_guarded_deferred_pick_asks_the_editor_at_the_boundary_and_lands_on_yes(daemon, tmp_path, model_peer):+ """Any measured context trips the large-context guard: at the turn boundary the owner asks+ (``confirmation_required``) instead of applying. ACP asks through its permission request and the+ yes commits the pick; it never stays silently pending (#140190 review)."""+ _second_on_peer(daemon, model_peer)+ _measured(model_peer)+ async with viewer(daemon) as ws:+ sid = (await ws.rpc('session.create', request_id='acp-guard', source='cli', cwd=str(tmp_path)))['session_id']+ async with editor(daemon, tmp_path) as acp:+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})+ assert 'result' in await acp.rpc('session/load', cwd=str(tmp_path), sessionId=sid, mcpServers=[])+ warm = await acp.rpc('session/prompt', sessionId=sid, prompt=[{'type': 'text', 'text': 'WS_SHARED warm'}])+ assert warm['result']['stopReason'] == 'end_turn', warm+ running, start = await _pick_during_a_turn(acp, sid, model_peer)+ model_peer.release.set()+ assert (await running)['result']['stopReason'] == 'end_turn'+ await async_wait_until(lambda: any(f.get('method') == 'session/request_permission'+ for f in acp.frames[start:]), timeout=20,+ what='the guarded deferred pick asked through ACP')+ ask = next(f for f in acp.frames[start:] if f.get('method') == 'session/request_permission')+ assert 'second-model' in json.dumps(ask['params']), ask+ assert model_peer.requests[-1]['model'] == 'local-wire-stub' # nothing applied without consent+ acp.process.stdin.write(json.dumps({'jsonrpc': '2.0', 'id': ask['id'], 'result': {+ 'outcome': {'outcome': 'selected', 'optionId': 'allow_once'}}}).encode() + b'\n')+ await acp.process.stdin.drain()+ await async_wait_until(lambda: 'Model switched to: second-model' in _shown(acp.frames, start),+ timeout=15, what='the confirmed pick reported')+ after = await acp.rpc('session/prompt', sessionId=sid, prompt=[{'type': 'text', 'text': 'WS_SHARED after'}])+ assert after['result']['stopReason'] == 'end_turn', after+ assert model_peer.requests[-1]['model'] == 'second-model', model_peer.requests[-1]