The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): editor users can answer the agent's clarification questions
Teknium1780f3fadcd1
diff --git a/acp_adapter/elicitation.py b/acp_adapter/elicitation.pynew file mode 100644index 00000000000..5a3f8384b54--- /dev/null+++ b/acp_adapter/elicitation.py@@ -0,0 +1,71 @@+"""A canonical ``clarify`` prompt in an ACP editor, answered through ``clarify.respond``.++A client that advertises ``elicitation.form`` in ``initialize`` gets the question as an+``elicitation/create`` form (free text or the offered choices); any other client gets a permission+card whose options are the choices plus Skip, the one interaction every ACP client renders.+Form schema and capability detection adapted from #126313 (Utku Bakir).+"""+from __future__ import annotations++import json+from typing import Any++ELICITATION_METHOD = "elicitation/create"+SKIP_OPTION = "skip"+++def client_supports_form_elicitation(initialize_params: Any) -> bool:+ """ACP names an elicitation mode as supported only by its presence (``"form": {}``), under+ v1 ``clientCapabilities`` or v2 ``capabilities``. Read from the raw initialize params:+ the pinned SDK's ``ClientCapabilities`` model drops the field."""+ if not isinstance(initialize_params, dict):+ return False+ for key in ("clientCapabilities", "capabilities"):+ capabilities = initialize_params.get(key)+ elicitation = capabilities.get("elicitation") if isinstance(capabilities, dict) else None+ if isinstance(elicitation, dict) and elicitation.get("form") is not None:+ return True+ return False+++def build_clarify_elicitation(session_id: str, prompt: dict) -> dict[str, Any]:+ choices = list(prompt.get("choices") or [])+ schema: dict[str, Any] = {"type": "string"}+ if choices:+ schema = {"type": "string", "enum": choices}+ if prompt.get("multi_select"):+ schema = {"type": "array", "items": schema}+ return {"sessionId": session_id, "mode": "form", "message": prompt["question"],+ "requestedSchema": {"type": "object", "properties": {"answer": schema}, "required": ["answer"]}}+++def elicited_answer(response: Any) -> str | None:+ """Accept -> the answer (a multi-select list as the JSON array clarify decodes); decline or+ cancel -> ``""``, the skip every surface sends; anything else -> ``None`` (not answered)."""+ if not isinstance(response, dict) or response.get("action") not in {"accept", "decline", "cancel"}:+ return None+ if response["action"] != "accept":+ return ""+ value = (response.get("content") or {}).get("answer")+ if isinstance(value, list) and all(isinstance(item, str) for item in value):+ return json.dumps(value, ensure_ascii=False)+ return value if isinstance(value, str) else None+++def build_clarify_permission(prompt: dict):+ """``(tool_call, options, answers)``: one option per offered choice plus Skip; ``answers``+ maps each option id to the exact ``clarify.respond`` answer."""+ import acp+ from acp.schema import PermissionOption++ choices = list(prompt.get("choices") or [])+ options = [PermissionOption(option_id=f"choice-{index}", kind="allow_once", name=choice)+ for index, choice in enumerate(choices)]+ options.append(PermissionOption(option_id=SKIP_OPTION, kind="reject_once", name="Skip"))+ answers = {f"choice-{index}": choice for index, choice in enumerate(choices)}+ answers[SKIP_OPTION] = ""+ tool_call = acp.update_tool_call(+ f"clarify-{prompt['prompt_id']}", title=prompt["question"], kind="other", status="pending",+ content=[acp.tool_content(acp.text_block(prompt["question"]))],+ raw_input={"question": prompt["question"], "choices": choices})+ return tool_call, options, answersdiff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex d41c0f26c22..2ff8b8e58b5 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -83,11 +83,23 @@ class GatewayACPAgent(acp.Agent):self._tool_args = {}# Editor-held compression-tip id -> logical session id (see ``_resume``).self._aliases = {}+ self._form_elicitation = Falsefrom hermes_cli.gateway_mutations import PreparedMutationsself._mutations = PreparedMutations()def on_connect(self, conn):self._conn = conn+ add_observer = getattr(getattr(conn, "_conn", None), "add_observer", None)+ if callable(add_observer):+ add_observer(self._observe_client_message)++ def _observe_client_message(self, event):+ """``initialize``'s raw capabilities (the SDK's typed model drops ``elicitation``)."""+ message = getattr(event, "message", None)+ if getattr(event, "direction", None) == "incoming" and isinstance(message, dict) \+ and message.get("method") == "initialize":+ from acp_adapter.elicitation import client_supports_form_elicitation+ self._form_elicitation = client_supports_form_elicitation(message.get("params"))async def initialize(self, **kwargs):from hermes_cli import __version__@@ -343,10 +355,10 @@ class GatewayACPAgent(acp.Agent):aid = event.get("admission_id")if kind == "session.replay_gap":raise GatewayClientError("session_replay_gap")- if kind == "approval.request":+ if kind in {"approval.request", "clarify.request"}:self._permission(sid, payload)return- if kind == "approval.settled":+ if kind in {"approval.settled", "clarify.settled"}:task = self._permissions.pop((sid, payload["prompt_id"], payload["execution_generation"]), None)if task:task.cancel()@@ -393,11 +405,37 @@ class GatewayACPAgent(acp.Agent):self._changed.notify_all()def _permission(self, session_id, prompt):- if prompt.get("kind") != "approval" or self._conn is None:+ answer = {"approval": self._answer_permission, "clarify": self._answer_clarify}.get(prompt.get("kind"))+ if answer is None or self._conn is None:returnkey = (session_id, prompt["prompt_id"], prompt["execution_generation"])if key not in self._permissions:- self._permissions[key] = asyncio.create_task(self._answer_permission(session_id, prompt))+ self._permissions[key] = asyncio.create_task(answer(session_id, prompt))++ async def _answer_clarify(self, session_id, prompt):+ from acp.schema import AllowedOutcome+ from acp_adapter.elicitation import (+ ELICITATION_METHOD, build_clarify_elicitation, build_clarify_permission, elicited_answer,+ )+ editor_id = self._editor_id(session_id)+ try:+ if self._form_elicitation:+ answer = elicited_answer(await self._conn._conn.send_request(+ ELICITATION_METHOD, build_clarify_elicitation(editor_id, prompt)))+ else:+ tool_call, options, answers = build_clarify_permission(prompt)+ response = await self._conn.request_permission(+ session_id=editor_id, tool_call=tool_call, options=options)+ answer = (answers.get(response.outcome.option_id)+ if isinstance(response.outcome, AllowedOutcome) else None)+ # No answer (transport loss, editor cancel) leaves the canonical waiter to other viewers.+ if answer is None:+ return+ await self._gateway.rpc("clarify.respond", session_id=session_id, prompt_id=prompt["prompt_id"],+ execution_generation=prompt["execution_generation"], answer=answer)+ except Exception:+ # Boundary: as for approvals, a detached editor or expired prompt is not an answer.+ logger.info("ACP clarify viewer detached or control expired", exc_info=True)async def _answer_permission(self, session_id, prompt):from acp.schema import AllowedOutcomediff --git a/tests/acp_adapter/test_gateway_editor_clarify.py b/tests/acp_adapter/test_gateway_editor_clarify.pynew file mode 100644index 00000000000..1bc434cd3b9--- /dev/null+++ b/tests/acp_adapter/test_gateway_editor_clarify.py@@ -0,0 +1,69 @@+"""A canonical clarify question reaches the ACP editor and its answer reaches the model.++Real gateway daemon, real ACP stdio process, loopback model that calls the real clarify tool. The+session is created by the CLI (whose frozen tools include clarify), so the turn blocks on a+question the editor must be able to answer: live while its own prompt runs, or restored from the+snapshot when it attaches after another surface's turn already asked.+"""+import asyncio+import json++import pytest++from tests.acp_adapter.test_gateway_sessions import editor, viewer++[email protected]("linux")[email protected]("form, restored", [(False, False), (True, True)],+ ids=["live-permission-card", "restored-form-elicitation"])+async def test_editor_answers_canonical_clarify_through_clarify_respond(+ daemon, tmp_path, model_peer, form, restored):+ from tests.gateway.fixtures.authority_clarify_peer import ModelPeer as ClarifyPeer++ model_peer.RequestHandlerClass = ClarifyPeer+ async with viewer(daemon) as ws:+ created = await ws.rpc("session.create", request_id="acp-clarify", source="cli", cwd=str(tmp_path))+ sid = created["session_id"]+ turn = None+ if restored:+ accepted = await ws.rpc("prompt.submit", session_id=sid, input_id="cli-turn", text="Ask my color")+ async with asyncio.timeout(30):+ while not (await ws.rpc("session.resume", session_id=sid))["prompts"]:+ await asyncio.sleep(.05)+ async with editor(daemon, tmp_path) as acp:+ capabilities = {"elicitation": {"form": {}}} if form else {}+ assert "result" in await acp.rpc("initialize", protocolVersion=1, clientCapabilities=capabilities)+ assert "result" in await acp.rpc("session/load", cwd=str(tmp_path), sessionId=sid, mcpServers=[])+ if not restored:+ turn = asyncio.create_task(acp.rpc("session/prompt", sessionId=sid,+ prompt=[{"type": "text", "text": "Ask my color"}]))+ method = "elicitation/create" if form else "session/request_permission"+ async with asyncio.timeout(30):+ while not any(f.get("method") == method for f in acp.frames):+ assert turn is None or not turn.done(), turn.result()+ await asyncio.sleep(.05)+ request = next(f for f in acp.frames if f.get("method") == method)+ params = request["params"]+ assert params["sessionId"] == sid+ if form:+ assert params["message"].startswith("Pick a color")+ assert params["requestedSchema"]["properties"]["answer"]["enum"][1] == "green"+ result = {"action": "accept", "content": {"answer": "green"}}+ else:+ assert params["toolCall"]["title"].startswith("Pick a color")+ option = next(o for o in params["options"] if o["name"] == "green")+ result = {"outcome": {"outcome": "selected", "optionId": option["optionId"]}}+ acp.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}).encode()+ + b"\n")+ await acp.process.stdin.drain()+ if turn is not None:+ reply = await asyncio.wait_for(turn, 40)+ assert reply.get("result", {}).get("stopReason") == "end_turn", reply+ else:+ async with asyncio.timeout(40):+ while (await ws.rpc("prompt.receipt", session_id=sid,+ admission_id=accepted["admission_id"]))["status"] != "terminal":+ await asyncio.sleep(.05)+ tool_results = [m for messages in model_peer.requests for m in messages if m["role"] == "tool"]+ assert any("green" in json.dumps(m) for m in tool_results), tool_results