The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: clarify cards that cannot render are re-asked as plain text, never reported as user inactivity
teknium198b4efbf482c
diff --git a/gateway/run.py b/gateway/run.pyindex 31e9fa352a2..0304da3dddc 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -756,51 +756,6 @@ def _approval_send_outcome(future, timeout: float) -> str:return "failed"-def _clarify_send_disposition(fut, *, session_key: str, clarify_mod) -> "str | None":- """Decide whether a clarify prompt send aborts the wait; returns the abort sentinel or ``None``.-- Only a DEFINITIVE failure tears down the registration; ``ambiguous`` (card may have posted) stays armed- and proceeds to the bounded wait, whose response timeout covers a lost card."""- outcome = _approval_send_outcome(fut, timeout=15)- if outcome == "declined":- # P5(b): a connector DECLINE is MORE definitive than a failure — the- # destination was authorized and refused, so the card cannot arrive and- # no late reply can resolve it. Without this branch `declined` fell- # through to the bounded wait and the agent blocked until- # clarify_timeout (indefinitely when that is configured non-positive).- logger.warning(- "Clarify prompt DECLINED by the connector's egress guard; "- "clearing registration"- )- clarify_mod.clear_session(session_key)- return "[clarify prompt could not be delivered: destination refused]"- if outcome == "failed":- # Undeliverable: clear the registration and return the sentinel so the agent falls back, not hangs.- logger.warning("Clarify send failed definitively; clearing registration")- clarify_mod.clear_session(session_key)- return "[clarify prompt could not be delivered]"- if outcome == "ambiguous":- logger.warning(- "Clarify prompt send timed out — treating as possibly-delivered "- "(no teardown; the registration stays armed for a late reply)")- return None---def _clarify_send_then_wait(fut, *, clarify_id: str, session_key: str, clarify_mod) -> tuple[str, bool]:- """Resolve a clarify prompt: send disposition, then the bounded wait.-- Returns ``(response, answered)``. ``answered`` is the only signal that a user reply arrived;- callers must not infer it from the text (a real answer may start with '[' like a sentinel)."""- abort = _clarify_send_disposition(fut, session_key=session_key, clarify_mod=clarify_mod)- if abort is not None:- return abort, False- timeout = clarify_mod.get_clarify_timeout()- response = clarify_mod.wait_for_response(clarify_id, timeout=float(timeout))- if response is None or response == "":- return f"[user did not respond within {int(timeout / 60)}m]", False- return response, True--def _resolve_progress_thread_id(platform: Any, source_thread_id: Any, event_message_id: Any, *, reply_in_thread: bool = True) -> Optional[str]:diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex dc9537b7a50..3b8a8f78961 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1334,15 +1334,27 @@ class TurnRunner:"""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 sentinelfor a single question, the batch's ``timed_out`` flag."""- from gateway.run import _clarify_send_then_wait+ from gateway.run_turn_runner_clarify_delivery import (+ UNDELIVERED_NO_SURFACE, _clarify_send_then_wait, text_fallback_coro)from tools import clarify_gateway as clarify_modimport uuidctx = self._ctxif not ctx._status_adapter:- return "", False+ # Nothing can render the question: say so, or the batch's blank answers read as+ # user inactivity (#112684).+ return UNDELIVERED_NO_SURFACE, Falsesession_key = ctx.session_key or ""clarify_id = uuid.uuid4().hex[:10]choices = list(choices) if choices else None+ send_kwargs = dict(+ chat_id=ctx._status_chat_id, question=question, choices=choices, clarify_id=clarify_id,+ session_key=session_key, metadata=ctx._status_thread_metadata,+ )++ def _text_fallback():+ """Schedule the plain-text prompt when the native card cannot render; None = no such path."""+ coro = text_fallback_coro(ctx._status_adapter, **send_kwargs)+ return None if coro is None else self._schedule(coro, "Clarify text fallback failed to schedule")clarify_mod.register(clarify_id=clarify_id, session_key=session_key, question=question, choices=choices,multi_select=bool(multi_select),@@ -1364,17 +1376,16 @@ class TurnRunner:except Exception:logger.debug("Stream-consumer flush before clarify prompt failed", exc_info=True)fut = self._schedule(- ctx._status_adapter.send_clarify(- chat_id=ctx._status_chat_id, question=question, choices=choices, clarify_id=clarify_id,- session_key=session_key, metadata=ctx._status_thread_metadata,- ),+ ctx._status_adapter.send_clarify(**send_kwargs),"Clarify send failed to schedule",)# Boundary rule (see _approval_send_outcome): a send timeout is AMBIGUOUS — the card may# have posted with a late ack. Only a definitive failure tears down the registration;- # ambiguous falls through to the bounded wait so a late reply resolves.+ # ambiguous falls through to the bounded wait so a late reply resolves. A definitive+ # failure — immediate or late — retries once as plain text before giving up.response, answered = _clarify_send_then_wait(- fut, clarify_id=clarify_id, session_key=session_key, clarify_mod=clarify_mod)+ fut, clarify_id=clarify_id, session_key=session_key, clarify_mod=clarify_mod,+ fallback=_text_fallback)# Branch on the explicit flag, never on the text: a real answer can start with '[' (a# "[A] staging" label, "[urgent] ..." free text) and must not be mistaken for a sentinel.if not answered:diff --git a/gateway/run_turn_runner_clarify_delivery.py b/gateway/run_turn_runner_clarify_delivery.pynew file mode 100644index 00000000000..399fc285b89--- /dev/null+++ b/gateway/run_turn_runner_clarify_delivery.py@@ -0,0 +1,168 @@+"""Clarify prompt delivery on messaging platforms: send disposition, plain-text fallback, bounded wait.++A native clarify card (Telegram inline keyboard, Slack blocks, …) can fail to render in three ways+the user never sees (#112684): the platform rejects it at once, the send outruns the 15 s+disposition window and only then fails (pool / connect timeouts, a stale-thread retry), or there+is no chat surface at all. Each used to end as a full ``clarify_timeout`` of silence reported as+"the user did not respond". Here every definitive failure of the native card falls back to the+adapter's plain-text ``send_clarify`` (numbered list + text capture), and a card that fails AFTER+the window releases the wait with the delivery notice instead of the inactivity one.+"""++from __future__ import annotations++import logging+from typing import Any, Callable, Optional++logger = logging.getLogger(__name__)++UNDELIVERED = "[clarify prompt could not be delivered]"+UNDELIVERED_DECLINED = "[clarify prompt could not be delivered: destination refused]"+# No status adapter (a run whose chat surface is gone): shares the ``[clarify prompt could not be+# delivered`` prefix every consumer already treats as a non-answer+# (agent/context_compressor.py::_CLARIFY_NON_RESPONSE_PREFIXES).+UNDELIVERED_NO_SURFACE = "[clarify prompt could not be delivered: no chat surface]"++# Seconds a scheduled card send may take before it is classified ``ambiguous`` (possibly posted).+SEND_ACK_WINDOW = 15+++def text_fallback_coro(adapter, **send_kwargs):+ """The base numbered-text ``send_clarify`` as a fresh coroutine, or ``None`` when the adapter has+ no native override — its ``send_clarify`` already IS the text path, so retrying it would only+ repeat the failure."""+ from gateway.platforms.base import BasePlatformAdapter++ if not isinstance(adapter, BasePlatformAdapter) \+ or type(adapter).send_clarify is BasePlatformAdapter.send_clarify:+ return None+ return BasePlatformAdapter.send_clarify(adapter, **send_kwargs)+++def _abort_for_outcome(outcome: str, *, session_key: str, clarify_mod) -> Optional[str]:+ """Map a send outcome to the abort sentinel (registration torn down) or ``None`` (proceed to wait).++ Only a DEFINITIVE failure tears down the registration; ``ambiguous`` (card may have posted) stays armed+ and proceeds to the bounded wait, whose response timeout covers a lost card."""+ if outcome == "declined":+ # P5(b): a connector DECLINE is MORE definitive than a failure — the+ # destination was authorized and refused, so the card cannot arrive and+ # no late reply can resolve it. Without this branch `declined` fell+ # through to the bounded wait and the agent blocked until+ # clarify_timeout (indefinitely when that is configured non-positive).+ logger.warning(+ "Clarify prompt DECLINED by the connector's egress guard; "+ "clearing registration"+ )+ clarify_mod.clear_session(session_key)+ return UNDELIVERED_DECLINED+ if outcome == "failed":+ # Undeliverable: clear the registration and return the sentinel so the agent falls back, not hangs.+ logger.warning("Clarify send failed definitively; clearing registration")+ clarify_mod.clear_session(session_key)+ return UNDELIVERED+ if outcome == "ambiguous":+ logger.warning(+ "Clarify prompt send timed out — treating as possibly-delivered "+ "(no teardown; the registration stays armed for a late reply)")+ return None+++def _clarify_send_disposition(fut, *, session_key: str, clarify_mod) -> Optional[str]:+ """Decide whether a clarify prompt send aborts the wait; returns the abort sentinel or ``None``."""+ from gateway.run import _approval_send_outcome++ return _abort_for_outcome(+ _approval_send_outcome(fut, timeout=SEND_ACK_WINDOW), session_key=session_key, clarify_mod=clarify_mod)+++def _clarify_send_then_wait(fut, *, clarify_id: str, session_key: str, clarify_mod,+ fallback: Optional[Callable[[], Any]] = None) -> tuple[str, bool]:+ """Resolve a clarify prompt: send disposition, plain-text fallback, then the bounded wait.++ ``fallback()`` schedules the plain-text ``send_clarify`` and returns its future (or ``None``);+ it runs when the native card failed definitively — at once, or late, after the ack window —+ and never on a connector DECLINE (re-sending refused content as text is the exfiltration the+ egress guard exists to stop). A card that fails after the window releases the wait with the+ delivery notice, not the inactivity one.++ Returns ``(response, answered)``. ``answered`` is the only signal that a user reply arrived;+ callers must not infer it from the text (a real answer may start with '[' like a sentinel)."""+ from gateway.run import _approval_send_outcome++ outcome = _approval_send_outcome(fut, timeout=SEND_ACK_WINDOW)+ if outcome == "failed" and fallback is not None:+ # The text prompt is the last resort: a late failure of ITS send has nothing to retry.+ fut, fallback = fallback(), None+ outcome = _approval_send_outcome(fut, timeout=SEND_ACK_WINDOW)+ if outcome == "sent":+ logger.info("Clarify card undeliverable; plain-text prompt sent instead (id=%s)", clarify_id)+ abort = _abort_for_outcome(outcome, session_key=session_key, clarify_mod=clarify_mod)+ if abort is not None:+ return abort, False+ late = _LateFailureWatch(fut, clarify_id=clarify_id, session_key=session_key,+ clarify_mod=clarify_mod, fallback=fallback)+ timeout = clarify_mod.get_clarify_timeout()+ response = clarify_mod.wait_for_response(clarify_id, timeout=float(timeout))+ late.disarm()+ if late.undeliverable:+ return UNDELIVERED, False+ if response is None or response == "":+ return f"[user did not respond within {int(timeout / 60)}m]", False+ return response, True+++class _LateFailureWatch:+ """Watch a possibly-delivered card send: when it resolves as a definitive failure after the+ ack window, try the text fallback once, then release the waiter with the delivery notice.++ Callbacks run on the gateway loop thread (the send future completes there); ``clear_session``+ wakes the agent thread blocked in ``wait_for_response`` and ``undeliverable`` tells it why.+ Armed only while the future is still pending: a sent card needs no watch."""++ def __init__(self, fut, *, clarify_id: str, session_key: str, clarify_mod, fallback) -> None:+ self.undeliverable = False+ self._armed = False+ self._clarify_id = clarify_id+ self._session_key = session_key+ self._clarify_mod = clarify_mod+ self._fallback = fallback+ # Test doubles hand the runner a bare ``.result()`` object; only a real pending+ # concurrent future can still resolve late.+ done = getattr(fut, "done", None)+ if callable(done) and not done():+ self._armed = True+ fut.add_done_callback(self._on_card_done)++ def disarm(self) -> None:+ self._armed = False++ @staticmethod+ def _outcome(fut) -> str:+ from gateway.run import _approval_send_outcome+ return _approval_send_outcome(fut, timeout=0)++ def _on_card_done(self, fut) -> None:+ if not self._armed:+ return+ outcome = self._outcome(fut)+ if outcome == "sent":+ return+ logger.warning("Clarify card send resolved %s after the ack window (id=%s)", outcome, self._clarify_id)+ fallback_fut = self._fallback() if outcome == "failed" and self._fallback is not None else None+ if fallback_fut is None:+ self._release()+ return+ fallback_fut.add_done_callback(self._on_fallback_done)++ def _on_fallback_done(self, fut) -> None:+ if not self._armed:+ return+ if self._outcome(fut) == "sent":+ logger.info("Clarify card undeliverable; plain-text prompt sent instead (id=%s)", self._clarify_id)+ return+ self._release()++ def _release(self) -> None:+ self.undeliverable = True+ self._clarify_mod.clear_session(self._session_key)diff --git a/tests/gateway/test_clarify_delivery_fallback.py b/tests/gateway/test_clarify_delivery_fallback.pynew file mode 100644index 00000000000..a88a55ee355--- /dev/null+++ b/tests/gateway/test_clarify_delivery_fallback.py@@ -0,0 +1,172 @@+"""A clarify card that cannot render is retried as plain text, and a card that fails late does+not pass for user inactivity (#112684).++Real ``TurnRunner._clarify_callback_sync`` + real ``tools.clarify_gateway`` + a real gateway loop+thread; the adapter is Telegram-shaped (``SendResult`` shapes from+``plugins/platforms/telegram/adapter.py::_send_prompt``) with a native ``send_clarify`` override.+"""++import asyncio+import json+import threading+import time+from types import SimpleNamespace++import pytest++from gateway.platforms.base import BasePlatformAdapter, SendResult+from tools import clarify_gateway as cm++UNDELIVERED = "[clarify prompt could not be delivered" # prefix shared by every delivery notice+++class _CardAdapter(BasePlatformAdapter):+ """Native card override; ``card`` is the coroutine function the card send runs."""++ def __init__(self, card):+ self.card = card+ self.sent_text: list[str] = []+ self.cards = 0++ def pause_typing_for_chat(self, chat_id):+ return None++ def resume_typing_for_chat(self, chat_id):+ return None++ async def send_clarify(self, **kwargs):+ self.cards += 1+ return await self.card()++ async def send(self, chat_id, content, reply_to=None, metadata=None):+ self.sent_text.append(content)+ return SendResult(success=True, message_id="t1")++ async def retire_clarify_card(self, clarify_id, notice):+ return None++ async def connect(self):+ return True++ async def disconnect(self):+ return None++ async def get_chat_info(self, chat_id):+ return {}+++def loop():+ loop = asyncio.new_event_loop()+ thread = threading.Thread(target=loop.run_forever, daemon=True)+ thread.start()+ yield loop+ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout=5)+++def _runner(adapter, loop, monkeypatch, timeout=5):+ from gateway.run_turn_runner import TurnRunner++ runner = object.__new__(TurnRunner)+ runner._ctx = SimpleNamespace(+ _status_adapter=adapter, _status_chat_id="42", _status_thread_metadata=None,+ session_key="sk-fallback", stream_consumer_holder=[None], _loop_for_step=loop)+ runner._close_native_stream_boundary = lambda *a, **k: None+ monkeypatch.setattr(cm, "get_clarify_timeout", lambda: timeout)+ return runner+++def _answer_once_text_prompt_is_seen(adapter, text):+ def _wait_then_answer():+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline and not adapter.sent_text:+ time.sleep(0.02)+ time.sleep(0.1)+ cm.resolve_text_response_for_session("sk-fallback", text)+ threading.Thread(target=_wait_then_answer, daemon=True).start()+++# --- Atom: the platform rejects the native card -> plain-text question instead of a sentinel ---+++def test_rejected_card_is_reasked_as_plain_text_and_the_typed_answer_counts(loop, monkeypatch):+ async def rejected():+ return SendResult(success=False, error="Bad Request: BUTTON_TYPE_INVALID")++ adapter = _CardAdapter(rejected)+ _answer_once_text_prompt_is_seen(adapter, "2")+ response = _runner(adapter, loop, monkeypatch)._clarify_callback_sync("Pick?", ["alpha", "beta"])+ assert response == "beta" # the numbered text prompt maps "2" back to the choice+ assert adapter.cards == 1+ assert len(adapter.sent_text) == 1 and "1. alpha" in adapter.sent_text[0]+++def test_declined_card_is_never_reasked_as_text(loop, monkeypatch):+ """A connector egress DECLINE refused the destination: re-sending the question as text into+ that chat is the exfiltration the guard exists to stop."""+ async def declined():+ return SendResult(success=False, error="egress declined: destination not allowed")++ adapter = _CardAdapter(declined)+ response = _runner(adapter, loop, monkeypatch)._clarify_callback_sync("Pick?", ["alpha", "beta"])+ assert response.startswith(UNDELIVERED)+ assert adapter.sent_text == []+++# --- Atom: the card send outruns the ack window, then fails -------------------------------+++def test_card_failing_after_the_ack_window_falls_back_to_text_instead_of_waiting(loop, monkeypatch):+ from gateway import run_turn_runner_clarify_delivery as delivery++ monkeypatch.setattr(delivery, "SEND_ACK_WINDOW", 0.2)++ async def late_failure():+ await asyncio.sleep(0.6)+ return SendResult(success=False, error="Timed out: pool timeout")++ adapter = _CardAdapter(late_failure)+ _answer_once_text_prompt_is_seen(adapter, "beta")+ started = time.monotonic()+ response = _runner(adapter, loop, monkeypatch, timeout=30)._clarify_callback_sync("Pick?", ["alpha", "beta"])+ assert response == "beta"+ assert time.monotonic() - started < 10 # never the full clarify_timeout+++def test_card_and_text_both_failing_late_release_the_wait_with_the_delivery_notice(loop, monkeypatch):+ """Before: a card whose send failed after the window left the agent blocked for the whole+ clarify_timeout and then reported ``[user did not respond within Nm]`` for a question the user+ never saw."""+ from gateway import run_turn_runner_clarify_delivery as delivery++ monkeypatch.setattr(delivery, "SEND_ACK_WINDOW", 0.2)++ async def late_failure():+ await asyncio.sleep(0.6)+ return SendResult(success=False, error="Timed out: pool timeout")++ class _NoTextEither(_CardAdapter):+ async def send(self, chat_id, content, reply_to=None, metadata=None):+ self.sent_text.append(content)+ return SendResult(success=False, error="Timed out")++ adapter = _NoTextEither(late_failure)+ started = time.monotonic()+ response, answered = _runner(adapter, loop, monkeypatch, timeout=30)._ask_clarify_question(+ "Pick?", ["alpha", "beta"], False)+ assert (response, answered) == (UNDELIVERED + "]", False)+ assert time.monotonic() - started < 10+ assert len(adapter.sent_text) == 1 # the text fallback was tried exactly once+++# --- Atom: no chat surface at all -----------------------------------------------------------+++def test_no_status_adapter_reports_the_missing_surface_not_inactivity(loop, monkeypatch):+ runner = _runner(None, loop, monkeypatch)+ payload = json.loads(runner._clarify_callback_sync(+ "", None, questions=[{"qid": "q0", "question": "One?", "choices": ["a"]}]))+ assert payload["timed_out"] is True+ assert payload["notice"].startswith(UNDELIVERED)+ assert runner._clarify_callback_sync("One?", ["a"]).startswith(UNDELIVERED)diff --git a/tests/gateway/test_clarify_send_timeout_ambiguity.py b/tests/gateway/test_clarify_send_timeout_ambiguity.pyindex e9df2f21f98..79b3139b0e3 100644--- a/tests/gateway/test_clarify_send_timeout_ambiguity.py+++ b/tests/gateway/test_clarify_send_timeout_ambiguity.py@@ -17,7 +17,7 @@ today's teardown + sentinel behavior.import concurrent.futuresfrom unittest.mock import MagicMock-from gateway.run import _clarify_send_disposition, _clarify_send_then_wait+from gateway.run_turn_runner_clarify_delivery import _clarify_send_disposition, _clarify_send_then_waitSENTINEL = "[clarify prompt could not be delivered]"diff --git a/tests/gateway/test_prompt_decline_no_fallback.py b/tests/gateway/test_prompt_decline_no_fallback.pyindex e12490d5c3d..998bd6c639d 100644--- a/tests/gateway/test_prompt_decline_no_fallback.py+++ b/tests/gateway/test_prompt_decline_no_fallback.py@@ -203,7 +203,7 @@ def test_declined_clarify_aborts_instead_of_waiting_for_a_reply():from types import SimpleNamespacefrom gateway.relay.egress import EGRESS_DECLINE_CODE- from gateway.run import _clarify_send_disposition+ from gateway.run_turn_runner_clarify_delivery import _clarify_send_dispositioncleared = []clarify_mod = SimpleNamespace(@@ -233,7 +233,7 @@ def test_ambiguous_clarify_still_waits():"""Control: a possibly-delivered card must STAY armed for a late reply."""from types import SimpleNamespace- from gateway.run import _clarify_send_disposition+ from gateway.run_turn_runner_clarify_delivery import _clarify_send_dispositioncleared = []clarify_mod = SimpleNamespace(diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.mdindex 079d51902e2..96a6cc2a439 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. 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.+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 — Hermes first retries the question as a plain numbered-list message, and only reports this when that fails too; `[clarify prompt could not be delivered: no chat surface]` when the run has no chat to prompt in), so an undelivered prompt is never reported as user inactivity.## `connections` toolsetdiff --git a/website/docs/user-guide/messaging/telegram.md b/website/docs/user-guide/messaging/telegram.mdindex ea7744e1155..f558f49e5a2 100644--- a/website/docs/user-guide/messaging/telegram.md+++ b/website/docs/user-guide/messaging/telegram.md@@ -1328,6 +1328,8 @@ Tap a button to answer, or tap **Other** to type a free-form response (the nextConfigure the response timeout via `agent.clarify_timeout` in `~/.hermes/config.yaml` (default `600` seconds). If you don't respond within the timeout, the agent unblocks with a sentinel message and adapts rather than hanging.+If Telegram cannot render the button card (the Bot API rejects it, or the send fails after its 15-second acknowledgement window), Hermes re-asks the same question as a plain numbered-list message and your typed reply (a number or the option text) is taken as the answer. When even that cannot be delivered, the agent is released at once with `[clarify prompt could not be delivered]` instead of waiting out the timeout and mistaking the silence for you not answering.+## Push notification volumeTelegram fires a push notification on every message the bot sends. For long agent turns that emit tool-progress bubbles, streaming updates, and status callbacks, this gets noisy fast. The Telegram adapter has two notification modes: