The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(clarify): batch result carries the surface's no-answer notice; trim tests
teknium1b3aef45987d9
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex d4e1de521e2..dc9537b7a50 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1315,17 +1315,20 @@ class TurnRunner:Returns the JSON shape clarify_tool's batch path reads. The stream/typing re-arm waits forthe last question — between two cards it only opens a bubble the next boundary closes."""answers: Dict[str, Any] = {}- timed_out = False+ payload: Dict[str, Any] = {"answers": answers, "timed_out": False}last = len(questions) - 1for 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+ # The surface's own no-answer text ("could not be delivered", "did not respond+ # within Nm") rides along as ``notice``: blank answers alone read as user+ # inactivity, which is the misreport #112684 describes for an undelivered card.+ payload.update(timed_out=True, notice=raw)breakanswers[entry.get("qid") or f"q{index}"] = raw- return json.dumps({"answers": answers, "timed_out": timed_out}, ensure_ascii=False)+ return json.dumps(payload, 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).diff --git a/tests/gateway/test_clarify_card_retire_on_timeout.py b/tests/gateway/test_clarify_card_retire_on_timeout.pyindex ec72648f2c7..3dbfbe66fcf 100644--- a/tests/gateway/test_clarify_card_retire_on_timeout.py+++ b/tests/gateway/test_clarify_card_retire_on_timeout.py@@ -108,6 +108,7 @@ 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"]+ assert adapter.resumed == 1 # a lone card re-arms typing the moment it is answered# --- Batches: one card per question, stop at the first unanswered one -----@@ -120,10 +121,10 @@ _THREE_QUESTIONS = [{"qid": f"q{i}", "question": q, "choices": ["a", "b"]}@pytest.mark.parametrize("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),+ ((), ["One?"], {"answers": {}, "timed_out": True, "notice": "[user did not respond within 0m]"}, 0),# Answers already given survive; the unanswered question is not invented.(("use postgres",), ["One?", "Two?"],- {"answers": {"q0": "use postgres"}, "timed_out": True}, 0),+ {"answers": {"q0": "use postgres"}, "timed_out": True, "notice": "[user did not respond within 0m]"}, 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?"],@@ -139,20 +140,28 @@ def test_batch_routing(answers, asked, payload, resumed):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)+class _UndeliverableAdapter(_CardAdapter):+ """Telegram's ``_send_prompt`` shape when the Bot API rejects the card."""++ async def send_clarify(self, **kwargs):+ self.asked.append(kwargs["question"])+ return SendResult(success=False, error="Bad Request: chat not found")-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()[email protected]("adapter_cls,notice", [+ (_CardAdapter, "[user did not respond within 0m]"),+ # #112684: an undelivered card must not read as user inactivity — the delivery+ # sentinel rides along instead of being stored as the question's "answer".+ (_UndeliverableAdapter, "[clarify prompt could not be delivered]"),+])+def test_clarify_tool_batch_route_answers_and_stops_together(adapter_cls, notice):+ """End to end: the tool sees blank answers + ``timed_out`` + the surface's notice, where the+ legacy loop stored the sentinel as each question's answer and never set the flag."""+ adapter = adapter_cls()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 result["notice"] == noticeassert [r["user_response"] for r in result["responses"]] == ["", ""]diff --git a/tools/clarify_tool.py b/tools/clarify_tool.pyindex 7cf852221f2..70d3a99df62 100644--- a/tools/clarify_tool.py+++ b/tools/clarify_tool.py@@ -136,9 +136,11 @@ def _normalize_questions(questions) -> tuple:return normalized, None-def _batch_result(normalized: List[dict], answers: dict, timed_out: bool) -> str:+def _batch_result(normalized: List[dict], answers: dict, timed_out: bool, notice: Optional[str] = None) -> str:"""Batch result JSON; unanswered -> "". The top-level ``timed_out`` flag (present only when- true) tells the agent whether blanks are deliberate skips or the user walking away."""+ true) tells the agent whether blanks are deliberate skips or the user walking away; ``notice``+ (surface-supplied, only beside ``timed_out``) says WHY the wait ended, so an undeliverable+ prompt never reads as user inactivity."""responses = []for entry in normalized:raw = answers.get(entry["qid"])@@ -149,6 +151,8 @@ def _batch_result(normalized: List[dict], answers: dict, timed_out: bool) -> strresult: Dict[str, object] = {"responses": responses}if timed_out:result["timed_out"] = True+ if notice:+ result["notice"] = str(notice)return json.dumps(result, ensure_ascii=False)@@ -161,6 +165,7 @@ def _run_batch(normalized: List[dict], callback, question: str) -> str:walked away so the loop aborts instead of pestering them; earlier answers are kept."""answers: dict = {}timed_out = False+ notice = Noneif _accepts_kwarg(callback, "questions"):raw = callback(question, None, questions=normalized)timed_out = _is_timeout(raw)@@ -169,7 +174,8 @@ def _run_batch(normalized: List[dict], callback, question: str) -> str:if isinstance(raw, dict):answers = dict(raw.get("answers") or {})timed_out = bool(raw.get("timed_out"))- return _batch_result(normalized, answers, timed_out)+ notice = raw.get("notice")+ return _batch_result(normalized, answers, timed_out, notice)for entry in normalized:raw = _invoke_callback(callback, entry["question"], entry["choices"], entry["multi_select"])if _is_timeout(raw):@@ -251,7 +257,8 @@ CLARIFY_SCHEMA = {"enumerated inside the question text (choices render as pickable ""rows; options written into the question are dead prose the user ""can't click). Result: {responses: [...]} in question order (plus "- "timed_out=true if the user stopped part-way). Prefer deciding "+ "timed_out=true, and a notice saying why, if the user stopped "+ "part-way or the prompt could not be delivered). Prefer deciding ""low-stakes questions yourself; don't use this for dangerous-command ""confirmation (the terminal tool handles that)."),diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.mdindex 2ab7502fff5..079d51902e2 100644--- a/website/docs/reference/tools-reference.md+++ b/website/docs/reference/tools-reference.md@@ -54,7 +54,7 @@ Per-surface behavior:- **TUI and CLI** show a compact status list (`✓` answered / `▸` active / `·` pending) with only the active question's choices expanded. Enter locks the active answer and jumps to the next unanswered question; Tab moves between questions to answer in any order; Esc cancels the batch.- **Messaging platforms** (Telegram, Discord, …) fall back to asking the questions one at a time through the existing single-question prompt. If the user stops responding, the remaining questions are not sent.-If the prompt times out part-way, answers the user already locked are kept: the tool result carries them plus `"timed_out": true`, with the unanswered entries left blank, so the agent can distinguish a deliberate skip from an absent user.+If the prompt times out part-way, answers the user already locked are kept: the tool result carries them plus `"timed_out": true`, with the unanswered entries left blank, so the agent can distinguish a deliberate skip from an absent user. On messaging platforms the result also carries a `"notice"` saying why the wait ended (`[user did not respond within Nm]`, or `[clarify prompt could not be delivered]` when the platform rejected the card), so an undelivered prompt is never reported as user inactivity.## `connections` toolset