The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): answer a clarify batch on the surface, not by sentinel text
KeyArgo242ff24ff7e9
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex d37c5d58495..d4e1de521e2 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1294,16 +1294,49 @@ class TurnRunner:logger.warning("%s boundary timed out or failed: %s", reason, err)return False- def _clarify_callback_sync(self, question: str, choices, multi_select: bool = False) -> str:+ def _clarify_callback_sync(self, question: str, choices, multi_select: bool = False,+ questions=None) -> str:"""Present a clarify prompt and block on a response (clarify_tool's synchronous contract):schedule send_clarify on the gateway loop, block on the primitive's threading.Event with a- timeout. Returns the response string, or a sentinel when none arrived."""+ timeout. Returns the response string, or a sentinel when none arrived.++ ``questions`` (clarify_tool's batch form) is answered here, one card per question, because+ this surface knows whether an answer arrived: the loop that would otherwise call this+ callback once per question can only recognize "no answer" from the returned sentinel text,+ and treated that text as the question's answer.+ """+ if questions:+ return self._clarify_batch_sync(questions)+ response, _answered = self._ask_clarify_question(question, choices, multi_select)+ return response++ def _clarify_batch_sync(self, questions) -> str:+ """Answer a batch: one card per question, stop at the first the user never answers.+ Returns the JSON shape clarify_tool's batch path reads. The stream/typing re-arm waits for+ the last question — between two cards it only opens a bubble the next boundary closes."""+ answers: Dict[str, Any] = {}+ timed_out = False+ last = len(questions) - 1+ for index, entry in enumerate(questions):+ raw, answered = self._ask_clarify_question(+ entry.get("question", ""), entry.get("choices"), bool(entry.get("multi_select")),+ rearm=index == last)+ if not answered:+ timed_out = True+ break+ answers[entry.get("qid") or f"q{index}"] = raw+ return json.dumps({"answers": answers, "timed_out": timed_out}, ensure_ascii=False)++ def _ask_clarify_question(self, question, choices, multi_select, rearm: bool = True) -> tuple[str, bool]:+ """One card: register, send, wait, then retire it (no answer) or re-arm (answer).+ Returns ``(response, answered)``; the caller decides what "no answer" means — a sentinel+ for a single question, the batch's ``timed_out`` flag."""from gateway.run import _clarify_send_then_waitfrom tools import clarify_gateway as clarify_modimport uuidctx = self._ctxif not ctx._status_adapter:- return ""+ return "", Falsesession_key = ctx.session_key or ""clarify_id = uuid.uuid4().hex[:10]choices = list(choices) if choices else None@@ -1349,7 +1382,7 @@ class TurnRunner:self._schedule(retire(ctx._status_adapter, clarify_id, _CLARIFY_EXPIRED_NOTICE),"Clarify card retire failed to schedule")- else:+ elif rearm:# Reopen typing IMMEDIATELY, not on the LLM's first post-answer token (native streaming# otherwise re-seeds lazily on the first delta: ~48s of dead air). request_reopen_seed is# a no-op outside the reopen-pending native state.@@ -1363,7 +1396,7 @@ class TurnRunner:ctx._status_adapter.resume_typing_for_chat(ctx._status_chat_id)except Exception:logger.debug("resume_typing_for_chat after clarify answer failed", exc_info=True)- return response+ return response, answereddef _approval_notify_sync(self, approval_data: dict) -> None:"""Send the approval request from the agent thread: the adapter's interactive buttondiff --git a/tests/gateway/test_clarify_card_retire_on_timeout.py b/tests/gateway/test_clarify_card_retire_on_timeout.pyindex e3480c355a0..ec72648f2c7 100644--- a/tests/gateway/test_clarify_card_retire_on_timeout.py+++ b/tests/gateway/test_clarify_card_retire_on_timeout.py@@ -6,23 +6,29 @@ notice; an adapter without that method (text-prompt platforms) gets nothing sche"""import asyncio+import jsonfrom types import SimpleNamespacefrom unittest.mock import patch+import pytest+from gateway.platforms.base import SendResultclass _CardAdapter:def __init__(self):self.retired: list[tuple[str, str]] = []+ self.asked: list[str] = []+ self.resumed: int = 0def pause_typing_for_chat(self, chat_id):return Nonedef resume_typing_for_chat(self, chat_id):- return None+ self.resumed += 1async def send_clarify(self, **kwargs):+ self.asked.append(kwargs["question"])return SendResult(success=True, message_id="1.2")async def retire_clarify_card(self, clarify_id, notice):@@ -33,10 +39,15 @@ class _TextAdapter(_CardAdapter):retire_clarify_card = None # type: ignore[assignment]-def _run_clarify(adapter, answer=None):- """Returns (clarify response, labels of every coroutine the runner scheduled).- ``answer`` resolves the pending clarify with that text instead of letting it time out."""+def _run_clarify(adapter, answer=None, questions=None, answers=(), via_tool=False):+ """Returns (clarify result, labels of every coroutine the runner scheduled).++ ``answer`` resolves a single question with that text instead of letting it time out.+ ``questions`` drives clarify_tool's batch form instead: question i resolves from+ ``answers[i]``, and ``None`` leaves it unanswered so it expires. ``via_tool`` routes the+ batch through ``clarify_tool`` itself rather than calling the runner's callback directly."""from gateway.run_turn_runner import TurnRunner+ from tools import clarify_gateway as cmrunner = object.__new__(TurnRunner)runner._ctx = SimpleNamespace(@@ -54,19 +65,27 @@ def _run_clarify(adapter, answer=None):runner._schedule = _schedulerunner._close_native_stream_boundary = lambda *a, **k: None- if answer is not None:- from tools import clarify_gateway as cm- real_register = cm.register-- def _register_and_answer(**kwargs):- entry = real_register(**kwargs)- cm.resolve_gateway_clarify(kwargs["clarify_id"], answer)- return entry- register_patch = patch.object(cm, "register", _register_and_answer)- else:- register_patch = patch("tools.clarify_gateway.get_clarify_timeout", return_value=1)- with register_patch:- return runner._clarify_callback_sync("Pick one", ["a", "b"]), labels+ real_register = cm.register+ seen = {"n": 0}++ def _register(**kwargs):+ entry = real_register(**kwargs)+ index = seen["n"]+ seen["n"] += 1+ target = answer if questions is None else (answers[index] if index < len(answers) else None)+ if target is not None:+ cm.resolve_gateway_clarify(kwargs["clarify_id"], target)+ return entry++ with patch.object(cm, "register", _register), \+ patch("tools.clarify_gateway.get_clarify_timeout", return_value=1):+ if questions is None:+ return runner._clarify_callback_sync("Pick one", ["a", "b"]), labels+ if via_tool:+ from tools.clarify_tool import clarify_tool+ return clarify_tool("", questions=questions,+ callback=runner._clarify_callback_sync), labels+ return runner._clarify_callback_sync("", None, questions=questions), labelsdef test_timeout_retires_the_native_card_with_the_expired_notice():@@ -89,3 +108,51 @@ def test_real_answer_starting_with_a_bracket_is_not_mistaken_for_a_sentinel():assert response == "[A] staging"assert adapter.retired == []assert labels == ["Clarify send failed to schedule"]+++# --- Batches: one card per question, stop at the first unanswered one -----+++_THREE_QUESTIONS = [{"qid": f"q{i}", "question": q, "choices": ["a", "b"]}+ for i, q in enumerate(("One?", "Two?", "Three?"))]++[email protected]("answers,asked,payload,resumed", [+ # Nobody answers question 1: the batch ends there instead of re-asking — every further+ # question used to cost another full clarify_timeout — and reports the walk-away.+ ((), ["One?"], {"answers": {}, "timed_out": True}, 0),+ # Answers already given survive; the unanswered question is not invented.+ (("use postgres",), ["One?", "Two?"],+ {"answers": {"q0": "use postgres"}, "timed_out": True}, 0),+ # A fully answered batch re-arms typing once, at the end: between two cards the re-arm+ # would only open a bubble the next question's boundary finalizes.+ (("one", "two", "three"), ["One?", "Two?", "Three?"],+ {"answers": {"q0": "one", "q1": "two", "q2": "three"}, "timed_out": False}, 1),+])+def test_batch_routing(answers, asked, payload, resumed):+ adapter = _CardAdapter()+ raw, _labels = _run_clarify(adapter, questions=_THREE_QUESTIONS, answers=answers)+ assert adapter.asked == asked+ assert json.loads(raw) == payload+ assert adapter.resumed == resumed+ if payload["timed_out"]:+ assert len(adapter.retired) == 1 # the card that expired is retired+++def test_single_question_still_rearms_after_an_answer():+ """The re-arm deferral is batch-only: one card re-arms the moment it is answered."""+ adapter = _CardAdapter()+ response, _labels = _run_clarify(adapter, answer="blue")+ assert (response, adapter.resumed) == ("blue", 1)+++def test_clarify_tool_batch_route_answers_and_stops_together():+ """End to end: the tool sees blank answers + ``timed_out``, where the legacy loop stored+ the timeout sentinel as each question's answer and never set the flag."""+ adapter = _CardAdapter()+ raw, _labels = _run_clarify(+ adapter, questions=_THREE_QUESTIONS[:2], via_tool=True)+ assert adapter.asked == ["One?"]+ result = json.loads(raw)+ assert result["timed_out"] is True+ assert [r["user_response"] for r in result["responses"]] == ["", ""]