run_turn_runner_approval_settle.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """Tell the chat when an exec-approval prompt times out (messaging platforms).
  2. ``tools.approval_gateway_wait._await_gateway_decision`` calls ``entry.settle(reason)`` once the
  3. wait ends. Only the TUI registered such a hook, so on Telegram / Slack / WhatsApp a card whose
  4. timer ran out kept live buttons and the user never learned the command did NOT run. The turn
  5. runner registers the hook here right after the prompt was delivered.
  6. Best-effort by design: a failed notice is logged at debug — the approval already resolved as
  7. "no", and nothing here may block the agent thread.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import re
  12. from typing import Any, Callable, Optional
  13. from agent.i18n import t
  14. from gateway.platforms.base import fit_prefix
  15. from gateway.platforms.base_exec_approval import (
  16. approval_timeout_seconds, ea_default_reason_text, ea_reason_label_text, format_approval_timed_out_notice)
  17. logger = logging.getLogger(__name__)
  18. def register_timeout_notice(
  19. runner, approval_data: dict, *, command: str, card_message_id: Optional[str]) -> None:
  20. """Arm a settle hook that posts the timed-out notice for ``approval_data['request_id']``.
  21. ``runner`` is the ``TurnRunner`` (for ``_ctx`` and ``_schedule``); ``card_message_id`` is the
  22. delivered BUTTON card's id when the adapter returned one, so the card itself is edited in place
  23. (which also drops its buttons). The plain-text prompt passes ``None``: it has no buttons to
  24. drop and rewriting it would erase the record of what was asked. ``command`` is the
  25. already-redacted command shown to the user. The notice is skipped when the run is no longer
  26. current (``ctx._run_still_current``).
  27. """
  28. from tools.approval import register_gateway_settle
  29. request_id = approval_data.get("request_id")
  30. session_key = runner._ctx.session_key or ""
  31. if not request_id or not session_key:
  32. return
  33. timeout_s = approval_data.get("timeout_s")
  34. if timeout_s is None:
  35. timeout_s = approval_timeout_seconds()
  36. flagged = approval_data.get("description") or ea_default_reason_text()
  37. def settle(reason: str) -> None:
  38. if reason != "timeout":
  39. return # answered / interrupted / notify_failed already produced their own feedback
  40. # Same guard as every other late notice in TurnRunner: after /stop, /new or a restart the
  41. # turn is over and this chat belongs to a newer run — do not edit or post into it.
  42. still_current = getattr(runner._ctx, "_run_still_current", None)
  43. if callable(still_current) and not still_current():
  44. return
  45. runner._schedule(
  46. _post_timeout_notice(runner._ctx, command, card_message_id, timeout_s, flagged),
  47. "Approval timeout notice scheduling error")
  48. register_gateway_settle(session_key, request_id, settle)
  49. async def _post_timeout_notice(
  50. ctx, command: str, card_message_id: Optional[str], timeout_s: int, reason: str = "") -> None:
  51. from gateway.run import _interim_metadata
  52. from gateway.bot_peer_notices import automatic_notices_allowed
  53. adapter = ctx._status_adapter
  54. if not automatic_notices_allowed(getattr(ctx, "source", None)):
  55. return
  56. notice = format_approval_timed_out_notice(timeout_s)
  57. metadata = _interim_metadata(ctx._status_thread_metadata)
  58. try:
  59. # Plain markdown, not the card's platform markup: ``edit_message`` re-formats it itself.
  60. if card_message_id and await _edit_card(adapter, ctx._status_chat_id, card_message_id, notice, command, reason):
  61. return
  62. await adapter.send(ctx._status_chat_id, notice, metadata=metadata)
  63. except Exception:
  64. logger.debug("Approval timeout notice failed", exc_info=True)
  65. def _timed_out_card_body(adapter, chat_id: str, notice: str, command: str, reason: str = "") -> str:
  66. """The notice plus the reason and command, which are now the card's only record of the request. It must fit one
  67. message in the platform's own units (Telegram counts UTF-16), or the edit is truncated in
  68. place behind a dangling "(1/N)" and keeps streaming-preview state. A run of backticks in the
  69. command would close the card's fence and let the platform's formatter rewrite, and grow,
  70. the rest, so it is split with zero-width spaces (which also ride along in a copy)."""
  71. command, reason = (re.sub(r"`{3,}", lambda run: "\u200b".join(run.group()), s) for s in (command, reason))
  72. measure, suffix = adapter.message_len_fn_for_chat(chat_id), "..."
  73. if reason: # capped like the card's own reason, so the command keeps most of the budget
  74. notice = f"{notice}\n{ea_reason_label_text()}: {fit_prefix(reason, 500, measure, suffix)}"
  75. frame = measure(t("gateway.exec_approval.timed_out_card_body", notice=notice, command=""))
  76. budget = adapter.max_message_length_for_chat(chat_id) - frame - measure(suffix)
  77. return t("gateway.exec_approval.timed_out_card_body", notice=notice,
  78. command=fit_prefix(command, max(0, budget), measure, suffix))
  79. async def _edit_card(adapter, chat_id: str, message_id: str, notice: str, command: str, reason: str = "") -> bool:
  80. """Edit the card in place to the timed-out body; False sends the notice as a new message.
  81. Platforms whose edit replaces the markup drop the buttons here; Discord's edit keeps them,
  82. and its card's settle observer removes them."""
  83. edit: Optional[Callable[..., Any]] = getattr(adapter, "edit_message", None)
  84. if edit is None:
  85. return False
  86. try:
  87. result = await edit(chat_id, message_id, _timed_out_card_body(adapter, chat_id, notice, command, reason))
  88. except Exception:
  89. logger.debug("Approval card edit failed; sending the notice as a new message", exc_info=True)
  90. return False
  91. return bool(getattr(result, "success", False))