From ad305bead565944cea10bc07908c9dceb15440cf Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:19:43 -0700 Subject: [PATCH] refactor(gateway): send_exec_approval is a base template method; 9 adapters only render buttons MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nine surfaces (feishu, teams, slack, telegram, whatsapp_cloud, qqbot, matrix, discord, relay) each re-derived the approval choice set — [Allow Once]; session + always unless smart-denied; [Deny] — and four of them (discord, slack, teams, whatsapp_cloud) never adopted base._format_exec_approval, so header/reason/smart-deny wording and truncation budgets drifted per adapter. Three separate commits had to touch 5–9 adapters for one semantic fix. BasePlatformAdapter.send_exec_approval now builds an ExecApprovalPrompt (shared text via _format_exec_approval, shared `(label, choice, style)` rows via _exec_approval_actions) and hands it to the `_send_exec_approval_prompt` hook. Each adapter keeps only its widget mapping (~10–20 LOC); platform wording stays via the existing `_EA_*` class attrs, and a new `_exec_approval_cmd_budget` hook lets Slack/Discord budget the command against their hard message caps (3000-char section / 2000-char message) instead of computing it inline. `_EA_REASON_BUDGET` covers Slack's 500 / Discord's 300 reason caps. The runner used to detect button support by `hasattr(type(adapter), "send_exec_approval")`; that is now true for every adapter, so `_renders_exec_approval_buttons` asks `supports_exec_approval_buttons()` (hook overridden?) and keeps the duck-typed check for non-BasePlatformAdapter classes. Visible text changes (button semantics unchanged everywhere): - Discord: the smart-deny line now follows the reason (was inside the header before the fence); the truncation marker is "..." not "\n... [truncated]". - Slack: smart-deny line follows the reason instead of the header. - Teams: unchanged (same 2000-char preview, same smart-deny block). - WhatsApp Cloud: identical text; body still capped at 1024. - QQBot/relay: unchanged. --- gateway/platforms/ADDING_A_PLATFORM.md | 2 +- gateway/platforms/base.py | 76 +++++++++++++++- gateway/platforms/qqbot/adapter.py | 26 +++--- gateway/platforms/whatsapp_cloud.py | 29 +++---- gateway/relay/adapter.py | 39 +++------ gateway/run_turn_runner.py | 12 ++- plugins/platforms/discord/adapter.py | 63 +++++++------- plugins/platforms/feishu/adapter.py | 35 +++----- plugins/platforms/matrix/adapter.py | 42 ++++----- plugins/platforms/slack/adapter.py | 53 ++++++------ plugins/platforms/teams/adapter.py | 39 ++++----- plugins/platforms/telegram/adapter.py | 28 +++--- tests/gateway/test_exec_approval_template.py | 91 ++++++++++++++++++++ 13 files changed, 328 insertions(+), 207 deletions(-) create mode 100644 tests/gateway/test_exec_approval_template.py diff --git a/gateway/platforms/ADDING_A_PLATFORM.md b/gateway/platforms/ADDING_A_PLATFORM.md index c8e3f67e3c..58f95d8f60 100644 --- a/gateway/platforms/ADDING_A_PLATFORM.md +++ b/gateway/platforms/ADDING_A_PLATFORM.md @@ -117,7 +117,7 @@ If your platform supports interactive button/menu messages, implement these for | Method | Purpose | |--------|---------| | `send_clarify(chat_id, question, choices, clarify_id, session_key, ...)` | Render the `clarify` tool's multi-choice question as tappable buttons. Pair with inbound dispatch that routes button taps to `tools.clarify_gateway.resolve_gateway_clarify`. | -| `send_exec_approval(chat_id, command, session_key, description, ...)` | Render dangerous-command approval as Approve/Deny buttons. Inbound dispatch routes to `tools.approval.resolve_gateway_approval`. | +| `_send_exec_approval_prompt(prompt: ExecApprovalPrompt)` | Render a dangerous-command approval as native buttons. `send_exec_approval` is a base template method: it builds the shared text (`_format_exec_approval`, tune via the `_EA_*` class attrs) and the choice set (`prompt.actions` = `(label, choice, style)` rows, choices `once`/`session`/`always`/`deny`) — you only map those rows to widgets. Inbound dispatch routes to `tools.approval.resolve_gateway_approval`. | | `send_slash_confirm(chat_id, title, message, session_key, confirm_id, ...)` | Render slash-command confirmations (e.g. `/reload-mcp`) as Once/Always/Cancel buttons. Inbound dispatch routes to `tools.slash_confirm.resolve`. | | `send_model_picker(...)` | Interactive `/model` picker. Used by Telegram, Discord, and Slack (Socket Mode). | | `send_choice_picker(...)` | Flat single-level picker for finite-choice commands (`/reasoning`, `/fast`). Implemented by Telegram (inline keyboard), Discord (select menu), and Matrix (reactions). Platforms without it fall back to the text status card automatically. | diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index add5890e5f..4206a81cdb 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -1509,6 +1509,27 @@ def coerce_plaintext_gateway_command(event: "MessageEvent") -> None: event.text = "/restart" +@dataclass +class ExecApprovalPrompt: + """One exec-approval prompt, ready for a platform to render natively (see + ``BasePlatformAdapter.send_exec_approval``). ``actions`` rows are ``(label, choice, style)`` + with ``choice`` in ``once`` / ``session`` / ``always`` / ``deny`` — the vocabulary + ``tools.approval.resolve_gateway_approval`` accepts — and ``style`` in ``primary`` / + ``danger`` / ``""``.""" + chat_id: str + session_key: str + text: str + actions: List[Tuple[str, str, str]] + command: str + description: str + smart_denied: bool + metadata: Optional[Dict[str, Any]] = None + + @property + def choices(self) -> List[str]: + return [choice for _, choice, _ in self.actions] + + @dataclass class SendResult: """Result of sending a message.""" @@ -2482,6 +2503,7 @@ class BasePlatformAdapter(ABC): _EA_REASON_LABEL: str = "Reason: " _EA_SMART_DENY_LINE: str = "\n\nSmart DENY: owner override applies to this one operation only." _EA_CMD_BUDGET: int = 3000 + _EA_REASON_BUDGET: int = 0 # 0 = the reason is never truncated @staticmethod def _truncate_preview(text: str, budget: int, suffix: str = "...") -> str: @@ -2493,16 +2515,68 @@ class BasePlatformAdapter(ABC): """Escape hook for command preview/reason; HTML-mode platforms (Telegram) override.""" return text + def _exec_approval_cmd_budget(self, description: str, smart_denied: bool) -> int: + """Chars of command preview that fit; platforms with a hard message cap compute it.""" + return self._EA_CMD_BUDGET + def _format_exec_approval( self, command: str, description: str = "dangerous command", smart_denied: bool = False) -> str: """Shared exec-approval prompt text: header + fenced (truncated) command + reason, plus the smart-deny line. Buttons/trailing instructions stay platform-local.""" - cmd_preview = self._truncate_preview(str(command or ""), self._EA_CMD_BUDGET) + if self._EA_REASON_BUDGET: + description = self._truncate_preview(str(description or ""), self._EA_REASON_BUDGET) + cmd_preview = self._truncate_preview( + str(command or ""), self._exec_approval_cmd_budget(description, smart_denied)) text = (f"{self._EA_HEADER}" f"{self._EA_CODE_OPEN}{self._ea_escape(cmd_preview)}{self._EA_CODE_CLOSE}" f"{self._EA_REASON_LABEL}{self._ea_escape(description)}") return text + self._EA_SMART_DENY_LINE if smart_denied else text + # ── Exec-approval prompt (template method). The choice set is one rule for every button + # surface — three separate "same fix × N adapters" commits motivated lifting it here. + _EA_ACTION_LABELS: Dict[str, str] = { + "once": "Allow Once", "session": "Allow Session", "always": "Always Allow", "deny": "Deny"} + _EA_ACTION_STYLES: Dict[str, str] = {"once": "primary", "deny": "danger"} + + def _exec_approval_actions( + self, *, allow_permanent: bool, allow_session: bool, smart_denied: bool) -> List[Tuple[str, str, str]]: + """``(label, choice, style)`` rows for the approval buttons. A smart deny is an owner + override for one operation only, so it offers neither the session nor the permanent tier; + the permanent tier is never offered without the session tier.""" + choices = ["once"] + if not smart_denied and allow_session: + choices.append("session") + if allow_permanent: + choices.append("always") + choices.append("deny") + return [(self._EA_ACTION_LABELS[c], c, self._EA_ACTION_STYLES.get(c, "")) for c in choices] + + @classmethod + def supports_exec_approval_buttons(cls) -> bool: + """True when the adapter renders native approval buttons (overrides the prompt hook); + the runner otherwise sends the plain-text ``/approve`` prompt.""" + return cls._send_exec_approval_prompt is not BasePlatformAdapter._send_exec_approval_prompt + + async def send_exec_approval( + self, chat_id: str, command: str, session_key: str, description: str = "dangerous command", + metadata: Optional[Dict[str, Any]] = None, allow_permanent: bool = True, allow_session: bool = True, + smart_denied: bool = False, + ) -> SendResult: + """Interactive exec-approval prompt; a press resolves via + ``tools.approval.resolve_gateway_approval``. Text and choice set are shared; adapters + render them natively in ``_send_exec_approval_prompt``.""" + prompt = ExecApprovalPrompt( + chat_id=chat_id, session_key=session_key, metadata=metadata, command=str(command or ""), + description=description, smart_denied=smart_denied, + text=self._format_exec_approval(command, description, smart_denied), + actions=self._exec_approval_actions( + allow_permanent=allow_permanent, allow_session=allow_session, smart_denied=smart_denied)) + return await self._send_exec_approval_prompt(prompt) + + async def _send_exec_approval_prompt(self, prompt: "ExecApprovalPrompt") -> SendResult: + """Render ``prompt`` with the platform's native buttons; the default has none.""" + return SendResult(success=False, error="Not supported") + @staticmethod def _format_choice_page(options: list, page: int, per_page: int) -> "tuple[list, Dict[str, Any]]": """Shared picker pagination: clamp ``page``, slice ``options`` -> ``(page_options, meta)`` diff --git a/gateway/platforms/qqbot/adapter.py b/gateway/platforms/qqbot/adapter.py index e402373b4e..791f067a1f 100644 --- a/gateway/platforms/qqbot/adapter.py +++ b/gateway/platforms/qqbot/adapter.py @@ -39,7 +39,7 @@ except ImportError: from gateway.config import Platform, PlatformConfig from gateway.platforms.base import ( - gateway_trust_env, BasePlatformAdapter, SendResult, + gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt, SendResult, _ssrf_redirect_guard, cache_document_from_bytes_async, cache_image_from_bytes_async, ) from gateway.platforms.event import MessageEvent, MessageType @@ -1481,22 +1481,20 @@ class QQAdapter(BasePlatformAdapter): _APPROVAL_TIMEOUT_SECONDS = 300 # matches gateway's default gateway_timeout - async def send_exec_approval( - self, chat_id: str, command: str, session_key: str, description: str = "dangerous command", - metadata: Optional[Dict[str, Any]] = None, allow_permanent: bool = True, allow_session: bool = True, - smart_denied: bool = False) -> SendResult: - """Button-based exec-approval prompt (called by gateway/run.py while the - agent blocks on approval); clicks resolve via _default_interaction_dispatch.""" - del metadata # QQ has no thread_id / DM targeting overrides. - del allow_session # QQ's 3-button keyboard has no session tier. - if smart_denied: + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: + """Keyboard-card approval (called while the agent blocks on approval); clicks resolve via + _default_interaction_dispatch. QQ's 3-button keyboard has no session tier and no thread / + DM targeting, so only the ``always`` choice and the raw command/reason are used.""" + description = prompt.description + if prompt.smart_denied: description += " Owner override applies to this one operation only." req = ApprovalRequest( - session_key=session_key, title="Execute this command?", description=description, - command_preview=command, timeout_sec=self._APPROVAL_TIMEOUT_SECONDS, - allow_permanent=allow_permanent and not smart_denied) + session_key=prompt.session_key, title="Execute this command?", description=description, + command_preview=prompt.command, timeout_sec=self._APPROVAL_TIMEOUT_SECONDS, + allow_permanent="always" in prompt.choices) # QQ requires a msg_id for passive replies; the last inbound id is the natural one. - return await self.send_approval_request(chat_id, req, reply_to=self._last_msg_id.get(chat_id)) + return await self.send_approval_request( + prompt.chat_id, req, reply_to=self._last_msg_id.get(prompt.chat_id)) async def send_update_prompt( self, chat_id: str, prompt: str, default: str = "", session_key: str = "", diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.py index 84eb5378a8..f51e19ad30 100644 --- a/gateway/platforms/whatsapp_cloud.py +++ b/gateway/platforms/whatsapp_cloud.py @@ -39,7 +39,7 @@ except ImportError: httpx = None # type: ignore[assignment] from gateway.config import Platform, PlatformConfig -from gateway.platforms.base import BasePlatformAdapter, SendResult +from gateway.platforms.base import BasePlatformAdapter, ExecApprovalPrompt, SendResult from gateway.platforms.event import MessageEvent, MessageType from gateway.platforms.whatsapp_common import _OPTIN_TRUTHY, WhatsAppBehaviorMixin, _get_wsecret from gateway.platforms.media_cache import ext_for_mime @@ -468,22 +468,19 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): interactive = {"type": "list", "body": {"text": body_text}, "action": {"button": "Choose", "sections": [{"title": "Options", "rows": rows}]}} return await self._send_interactive(chat_id, interactive, metadata, self._clarify_state, clarify_id, session_key) - async def send_exec_approval( - self, chat_id: str, command: str, session_key: str, description: str = "dangerous command", - metadata: Optional[Dict[str, Any]] = None, allow_permanent: bool = True, - allow_session: bool = True, smart_denied: bool = False, - ) -> SendResult: - """Approve / Deny buttons; a tap resolves via ``tools.approval.resolve_gateway_approval``.""" - del allow_permanent, allow_session # This adapter already offers one-shot Approve / Deny only. - # Body caps at 1024; reserve room for the framing prose. - cmd_preview = (command or "")[:800] + ("..." if len(command or "") > 800 else "") - body_text = self._truncate_body( - f"⚠️ *Command Approval Required*\n\n```\n{cmd_preview}\n```\n\nReason: {description}" - + ("\n\nSmart DENY: owner override applies to this one operation only." if smart_denied else "") - ) + _EA_HEADER = "⚠️ *Command Approval Required*\n\n" + _EA_CODE_CLOSE = "\n```\n\n" + _EA_CMD_BUDGET = 800 # body caps at 1024; leave room for the framing prose + + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: + """Approve / Deny buttons only (a 3-button cap leaves no room for the session/always + tiers); a tap resolves via ``tools.approval.resolve_gateway_approval``.""" approval_id = uuid.uuid4().hex[:12] - interactive = self._button_interactive(body_text, (f"appr:{approval_id}:approve", "✅ Approve"), (f"appr:{approval_id}:deny", "❌ Deny")) - return await self._send_interactive(chat_id, interactive, metadata, self._exec_approval_state, approval_id, session_key) + interactive = self._button_interactive( + self._truncate_body(prompt.text), + (f"appr:{approval_id}:approve", "✅ Approve"), (f"appr:{approval_id}:deny", "❌ Deny")) + return await self._send_interactive( + prompt.chat_id, interactive, prompt.metadata, self._exec_approval_state, approval_id, prompt.session_key) async def send_slash_confirm( self, chat_id: str, title: str, message: str, session_key: str, confirm_id: str, metadata: Optional[Dict[str, Any]] = None, diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.py index 111959bb32..43846ee2ae 100644 --- a/gateway/relay/adapter.py +++ b/gateway/relay/adapter.py @@ -22,7 +22,7 @@ from typing import Any, Callable, Dict, Optional, Tuple, Union from gateway.config import Platform, PlatformConfig from gateway.platforms.base import ( - BasePlatformAdapter, SendResult, + BasePlatformAdapter, ExecApprovalPrompt, SendResult, ) from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome from gateway.relay.descriptor import CapabilityDescriptor @@ -1970,34 +1970,19 @@ class RelayAdapter(BasePlatformAdapter): _PROMPT_UNAVAILABLE = SendResult(success=False, error="relay prompt op unavailable") - async def send_exec_approval( - self, - chat_id: str, - command: str, - session_key: str, - description: str = "dangerous command", - metadata: Optional[Dict[str, Any]] = None, - allow_permanent: bool = True, - allow_session: bool = True, - smart_denied: bool = False, - ) -> SendResult: - """Native-button exec approval over the relay (same choice set as native; the - press resolves via tools.approval.resolve_gateway_approval). When the lane is - unavailable the send FAILS (success=False) so run.py's button→text fallback runs.""" - options: list = [{"id": "once", "label": "Allow Once", "style": "primary"}] - if not smart_denied and allow_session: - options.append({"id": "session", "label": "Allow Session"}) - if allow_permanent: - options.append({"id": "always", "label": "Always Allow"}) - options.append({"id": "deny", "label": "Deny", "style": "danger"}) + _EA_HEADER = "⚠️ **Command Approval Required**\n\n" + _EA_SMART_DENY_LINE = "\n\n**Smart DENY:** owner override applies to this one operation only." + _EA_CMD_BUDGET = 1500 - cmd_preview = command if len(command) <= 1500 else command[:1500] + "..." - text = f"⚠️ **Command Approval Required**\n\n```\n{cmd_preview}\n```\nReason: {description}" - if smart_denied: - text += "\n\n**Smart DENY:** owner override applies to this one operation only." + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: + """Native-button exec approval over the relay (the press resolves via + tools.approval.resolve_gateway_approval). When the lane is unavailable the send FAILS + (success=False) so run.py's button→text fallback runs.""" + options = [{"id": choice, "label": label, **({"style": style} if style else {})} + for label, choice, style in prompt.actions] result = await self._mint_and_send_prompt( - "exec_approval", {"session_key": session_key}, chat_id, prompt_kind="approval", - text=text, options=options, metadata=metadata, + "exec_approval", {"session_key": prompt.session_key}, prompt.chat_id, prompt_kind="approval", + text=prompt.text, options=options, metadata=prompt.metadata, ) return result if result is not None else self._PROMPT_UNAVAILABLE diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py index 295892b43a..3a147a5c1f 100644 --- a/gateway/run_turn_runner.py +++ b/gateway/run_turn_runner.py @@ -35,6 +35,16 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle) logger = logging.getLogger("gateway.run") +def _renders_exec_approval_buttons(adapter_cls: type) -> bool: + """True when the adapter class renders native approval buttons. BasePlatformAdapter subclasses + say so through ``supports_exec_approval_buttons``; anything else (test doubles, relay-style + duck types) counts when it defines ``send_exec_approval`` itself.""" + probe = getattr(adapter_cls, "supports_exec_approval_buttons", None) + if callable(probe) and issubclass(adapter_cls, BasePlatformAdapter): + return bool(probe()) + return getattr(adapter_cls, "send_exec_approval", None) is not None + + class _ExecApprovalDeclined(RuntimeError): """The connector refused the approval card's destination. @@ -1309,7 +1319,7 @@ class TurnRunner: desc = approval_data.get("description", "dangerous command") flags = {k: approval_data.get(k, d) for k, d in (("allow_permanent", True), ("allow_session", True), ("smart_denied", False))} # Check the *class*, not the instance — MagicMock auto-creates attributes in tests. - if getattr(type(adapter), "send_exec_approval", None) is not None: + if _renders_exec_approval_buttons(type(adapter)): try: fut = self._schedule( adapter.send_exec_approval( diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py index 15279c467b..e465d93b04 100644 --- a/plugins/platforms/discord/adapter.py +++ b/plugins/platforms/discord/adapter.py @@ -261,7 +261,7 @@ from gateway.platforms.helpers import ( ) from utils import atomic_json_write, env_float from gateway.platforms.base import ( - BasePlatformAdapter, SendResult, + BasePlatformAdapter, ExecApprovalPrompt, SendResult, cache_image_from_url, cache_image_from_bytes_async, cache_audio_from_url, cache_audio_from_bytes_async, cache_document_from_bytes_async, SUPPORTED_DOCUMENT_TYPES, _TEXT_INJECT_EXTENSIONS, _prefix_within_utf16_limit, utf16_len, validate_inbound_media_size, @@ -5236,47 +5236,44 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter): """Trim to Discord's 4096-char embed description limit (conservatively).""" return text if len(text) <= limit else text[: limit - 3] + "..." - async def send_exec_approval( - self, chat_id: str, command: str, session_key: str, description: str = "dangerous command", - metadata: Optional[dict] = None, allow_permanent: bool = True, allow_session: bool = True, - smart_denied: bool = False, - ) -> SendResult: - """Button-based exec approval prompt; buttons call ``resolve_gateway_approval()`` (not /approve).""" + # Payload lives in plain content: embeds can be invisible/detached on web/mobile. + _EA_HEADER = ("⚠️ **Command Approval Required**\n\n" + "Do you want Hermes to run this command?\n\n" + "**Requested command:**\n") + _EA_CODE_OPEN = "```bash\n" + _EA_CODE_CLOSE = "\n```\n" + _EA_REASON_LABEL = "**Reason:** " + _EA_SMART_DENY_LINE = "\n\n**Smart DENY:** owner override applies to this one operation only." + _EA_REASON_BUDGET = 300 + + def _exec_approval_cmd_budget(self, description: str, smart_denied: bool) -> int: + # Mentions ride in front of the content and count against the 2000-char message cap too. + fixed = (len(self._EA_HEADER) + len(self._EA_CODE_OPEN) + len(self._EA_CODE_CLOSE) + + len(self._EA_REASON_LABEL) + len(description) + len("...") + + (len(self._EA_SMART_DENY_LINE) if smart_denied else 0) + + len(self._approval_mention_content() or "") + 1) + return max(0, self.MAX_MESSAGE_LENGTH - fixed) + + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: + """Button view + embed mirror; buttons call ``resolve_gateway_approval()`` (not /approve).""" def _build(_channel): - # Payload in plain content: embeds can be invisible/detached on web/mobile. - reason_budget = 300 - reason_display = str(description or "dangerous command") - if len(reason_display) > reason_budget: - reason_display = reason_display[: reason_budget - 15] + "... [truncated]" - prompt_prefix = ( - "⚠️ **Command Approval Required**\n\n" - "Do you want Hermes to run this command?\n\n" - "**Requested command:**\n```bash\n" - ) - if smart_denied: - prompt_prefix += "**Smart DENY:** owner override applies to this one operation only.\n\n" + content = prompt.text mention_content = self._approval_mention_content() if mention_content: - prompt_prefix = f"{mention_content}\n{prompt_prefix}" - prompt_tail = f"\n```\n**Reason:** {reason_display}" - truncated_suffix = "\n... [truncated]" - command_budget = max(0, self.MAX_MESSAGE_LENGTH - len(prompt_prefix) - len(prompt_tail)) - content_cmd_display = str(command or "") - if len(content_cmd_display) > command_budget: - content_cmd_display = content_cmd_display[: max(0, command_budget - len(truncated_suffix))] + truncated_suffix - content = f"{prompt_prefix}{content_cmd_display}{prompt_tail}" + content = f"{mention_content}\n{content}" embed = discord.Embed( title="⚠️ Command Approval Required", - description=f"```\n{self._embed_body(str(command or ''))}\n```", + description=f"```\n{self._embed_body(prompt.command)}\n```", color=discord.Color.orange(), ) - embed.add_field(name="Reason", value=reason_display, inline=False) + embed.add_field(name="Reason", value=self._truncate_preview(prompt.description, self._EA_REASON_BUDGET), inline=False) require_admin, admin_user_ids = _resolve_exec_approval_admin_gate(getattr(self.config, "extra", None)) + choices = set(prompt.choices) view = ExecApprovalView( - session_key=session_key, allowed_user_ids=self._allowed_user_ids, + session_key=prompt.session_key, allowed_user_ids=self._allowed_user_ids, allowed_role_ids=self._allowed_role_ids, require_admin=require_admin, - admin_user_ids=admin_user_ids, allow_permanent=allow_permanent, - allow_session=allow_session, smart_denied=smart_denied, + admin_user_ids=admin_user_ids, allow_permanent="always" in choices, + allow_session="session" in choices, smart_denied=prompt.smart_denied, ) send_kwargs: Dict[str, Any] = {"content": content, "embed": embed, "view": view} if mention_content: @@ -5286,7 +5283,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter): users=True, roles=False, everyone=False, replied_user=False, ) return send_kwargs, view - return await self._send_prompt(chat_id, metadata, _build) + return await self._send_prompt(prompt.chat_id, prompt.metadata, _build) async def send_slash_confirm( self, chat_id: str, title: str, message: str, session_key: str, diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.py index f6381ae94e..191184f778 100644 --- a/plugins/platforms/feishu/adapter.py +++ b/plugins/platforms/feishu/adapter.py @@ -83,7 +83,7 @@ FEISHU_WEBHOOK_AVAILABLE = aiohttp is not None from gateway.config import Platform, PlatformConfig from gateway.platforms.base import ( - BasePlatformAdapter, SendResult, + BasePlatformAdapter, ExecApprovalPrompt, SendResult, SUPPORTED_DOCUMENT_TYPES, cache_document_from_bytes_async, cache_image_from_url, cache_audio_from_bytes_async, cache_image_from_bytes_async, ) @@ -1646,35 +1646,24 @@ class FeishuAdapter(BasePlatformAdapter): _EA_SMART_DENY_LINE = "\n\n**Smart DENY:** owner override applies to this one operation only." _EA_CMD_BUDGET = 3000 - async def send_exec_approval( - self, chat_id: str, command: str, session_key: str, description: str = "dangerous command", - metadata: Optional[Dict[str, Any]] = None, allow_permanent: bool = True, allow_session: bool = True, - smart_denied: bool = False, - ) -> SendResult: + _EA_ACTION_LABELS = {"once": "✅ Allow Once", "session": "✅ Session", "always": "✅ Always", "deny": "❌ Deny"} + _EA_CARD_ACTIONS = {"once": "approve_once", "session": "approve_session", "always": "approve_always", "deny": "deny"} + + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: """Approval-button card; ``hermes_action`` in each button value lets the click callback route to ``resolve_gateway_approval()`` and unblock the waiting agent thread.""" if not self._client: return SendResult(success=False, error="Not connected") - try: approval_id = next(self._approval_counter) - - def _btn(label: str, action_name: str, btn_type: str = "default") -> dict: - return _card_button(label, btn_type, {"hermes_action": action_name, "approval_id": approval_id}) - - actions = [_btn("✅ Allow Once", "approve_once", "primary")] - if not smart_denied and allow_session: - actions.append(_btn("✅ Session", "approve_session")) - if allow_permanent: - actions.append(_btn("✅ Always", "approve_always")) - actions.append(_btn("❌ Deny", "deny", "danger")) - card = _card( - "⚠️ Command Approval Required", "orange", - self._format_exec_approval(command, description, smart_denied), actions=actions, - ) + actions = [ + _card_button(label, style or "default", + {"hermes_action": self._EA_CARD_ACTIONS[choice], "approval_id": approval_id}) + for label, choice, style in prompt.actions] + card = _card("⚠️ Command Approval Required", "orange", prompt.text, actions=actions) return await self._send_interactive_card( - chat_id, card, metadata, "send_exec_approval failed", - state_map=self._approval_state, state_id=approval_id, session_key=session_key, + prompt.chat_id, card, prompt.metadata, "send_exec_approval failed", + state_map=self._approval_state, state_id=approval_id, session_key=prompt.session_key, ) except Exception as exc: logger.warning("[Feishu] send_exec_approval failed: %s", exc) diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py index 7cb681ac62..0bde795135 100644 --- a/plugins/platforms/matrix/adapter.py +++ b/plugins/platforms/matrix/adapter.py @@ -59,7 +59,7 @@ except ImportError: from gateway.config import Platform, PlatformConfig from gateway.platforms.base import ( - gateway_trust_env, BasePlatformAdapter, + gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt, SendResult, resolve_proxy_url, proxy_kwargs_for_aiohttp, _ssrf_redirect_guard, ) from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome @@ -1621,32 +1621,24 @@ class MatrixAdapter(BasePlatformAdapter): logger.debug("Matrix: failed to add %s reaction %s: %s", label, emoji, exc) return result - async def send_exec_approval( - self, chat_id: str, command: str, session_key: str, description: str = "dangerous command", - metadata: Optional[dict] = None, allow_permanent: bool = True, allow_session: bool = True, - smart_denied: bool = False) -> SendResult: + _EA_REACTIONS = {"once": "✅", "session": "🌀", "always": "♾️", "deny": "❌"} + _EA_LEGEND = {"once": "✅ = approve once", "session": "🌀 = approve for this session", + "always": "♾️ = approve always", "deny": "❎ = deny"} + _EA_TYPED_HINT = {"session": "Reply `!approve session` to approve this pattern for the session, ", + "always": "`!approve always` to approve permanently, "} + + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: + """Reaction-driven approval: the bot seeds one reaction per offered choice.""" if not self._client: return SendResult(success=False, error="Not connected") - if smart_denied: - scope_choices = "Smart DENY: owner override applies to this one operation only.\n" - else: - scope_choices = ( - ("Reply `!approve session` to approve this pattern for the session, " if allow_session else "") - + ("`!approve always` to approve permanently, " if allow_permanent else "")) - legend = ["✅ = approve once"] - reactions = ["✅"] - if allow_session: - legend.append("🌀 = approve for this session") - reactions.append("🌀") - if allow_permanent: - legend.append("♾️ = approve always") - reactions.append("♾️") - legend.append("❎ = deny") - reactions.append("❌") + choices = prompt.choices + typed_hints = "" if prompt.smart_denied else "".join(self._EA_TYPED_HINT[c] for c in choices if c in self._EA_TYPED_HINT) text = ( - f"{self._format_exec_approval(command, description)}\n\n" - f"{scope_choices}Reply `!approve` to execute once, or `!deny` to cancel.\n\n" - "You can also click the reaction to approve:\n" + "\n".join(legend)) + f"{prompt.text}\n\n" + f"{typed_hints}Reply `!approve` to execute once, or `!deny` to cancel.\n\n" + "You can also click the reaction to approve:\n" + "\n".join(self._EA_LEGEND[c] for c in choices)) + reactions = tuple(self._EA_REACTIONS[c] for c in choices) + session_key, chat_id = prompt.session_key, prompt.chat_id def _make(message_id, requester, expires_at): old_event = self._approval_prompt_by_session.get(session_key) @@ -1657,7 +1649,7 @@ class MatrixAdapter(BasePlatformAdapter): session_key=session_key, chat_id=chat_id, message_id=message_id, requester_user_id=requester, expires_at=expires_at) return await self._send_reaction_prompt( - chat_id, text, metadata, _make, self._approval_prompts_by_event, tuple(reactions), "approval") + chat_id, text, prompt.metadata, _make, self._approval_prompts_by_event, reactions, "approval") async def send_model_picker( self, chat_id: str, providers: list, current_model: str, current_provider: str, session_key: str, diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.py index 275e841879..fc54e654ad 100644 --- a/plugins/platforms/slack/adapter.py +++ b/plugins/platforms/slack/adapter.py @@ -37,7 +37,7 @@ from gateway.config import Platform, PlatformConfig from gateway.platforms.helpers import MessageDeduplicator from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, yaml_env_setter as _yaml_env_setter from gateway.platforms.base import ( - gateway_trust_env, BasePlatformAdapter, + gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt, SendResult, SUPPORTED_DOCUMENT_TYPES, SUPPORTED_VIDEO_TYPES, _TEXT_INJECT_EXTENSIONS, is_host_excluded_by_no_proxy, resolve_proxy_url, safe_url_for_log, _ssrf_redirect_guard, cache_document_from_bytes_async, cache_video_from_bytes_async, @@ -4630,40 +4630,37 @@ class SlackAdapter(BasePlatformAdapter): logger.error("[Slack] %s failed: %s", label, e, exc_info=True) return SendResult(success=False, error=str(e)) - async def send_exec_approval( - self, chat_id: str, command: str, session_key: str, description: str = "dangerous command", - metadata: Optional[Dict[str, Any]] = None, allow_permanent: bool = True, - allow_session: bool = True, smart_denied: bool = False) -> SendResult: - """Send a Block Kit approval prompt with interactive buttons. - The buttons call ``resolve_gateway_approval()`` to unblock the waiting agent thread — same - mechanism as the text ``/approve`` flow.""" + _EA_HEADER = ":warning: *Command Approval Required*\n" + _EA_CODE_OPEN = "```" + _EA_CODE_CLOSE = "```\n" + _EA_SMART_DENY_LINE = "\n*Smart DENY:* owner override applies to this one operation only." + _EA_REASON_BUDGET = 500 + _EA_SECTION_CAP = 3000 # a longer section text → invalid_blocks → no buttons at all + _EA_ACTION_IDS = {"once": "hermes_approve_once", "session": "hermes_approve_session", + "always": "hermes_approve_always", "deny": "hermes_deny"} + + def _exec_approval_cmd_budget(self, description: str, smart_denied: bool) -> int: + # execute_code approvals embed the whole script, so budget the preview against the cap. + fixed = (len(self._EA_HEADER) + len(self._EA_CODE_OPEN) + len(self._EA_CODE_CLOSE) + + len(self._EA_REASON_LABEL) + len(description) + len("...") + + (len(self._EA_SMART_DENY_LINE) if smart_denied else 0)) + return max(0, self._EA_SECTION_CAP - fixed) + + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: + """Block Kit approval prompt; the buttons call ``resolve_gateway_approval()`` to unblock the + waiting agent thread — same mechanism as the text ``/approve`` flow.""" def _build() -> Tuple[str, list]: - # Slack caps a section's text at 3000 chars (overflow → invalid_blocks → no buttons); - # execute_code approvals embed the whole script, so budget the preview. - header = ":warning: *Command Approval Required*\n" - if smart_denied: - header += "*Smart DENY:* owner override applies to this one operation only.\n" - reason = f"Reason: {description[:500]}" - budget = 3000 - len(header) - len(reason) - len("``````\n") - len("...") - cmd_preview = command[:budget] + "..." if len(command) > budget else command actions = [ - self._button("Allow Once", "hermes_approve_once", session_key, style="primary")] - if not smart_denied and allow_session: - actions.append(self._button("Allow Session", "hermes_approve_session", session_key)) - if allow_permanent: - actions.append( - self._button("Always Allow", "hermes_approve_always", session_key)) - actions.append(self._button("Deny", "hermes_deny", session_key, style="danger")) + self._button(label, self._EA_ACTION_IDS[choice], prompt.session_key, style=style) + for label, choice, style in prompt.actions] blocks = [ - { - "type": "section", - "text": {"type": "mrkdwn", "text": f"{header}```{cmd_preview}```\n{reason}"}}, + {"type": "section", "text": {"type": "mrkdwn", "text": prompt.text}}, {"type": "actions", "elements": actions}] - return f"⚠️ Command approval required: {cmd_preview[:100]}", blocks + return f"⚠️ Command approval required: {prompt.command[:100]}", blocks return await self._send_interactive_prompt( - chat_id, metadata, _build, "send_exec_approval", + prompt.chat_id, prompt.metadata, _build, "send_exec_approval", resolved=self._approval_resolved, resolved_max=self._APPROVAL_RESOLVED_MAX) async def send_slash_confirm( diff --git a/plugins/platforms/teams/adapter.py b/plugins/platforms/teams/adapter.py index 649d843010..1cc29509c8 100644 --- a/plugins/platforms/teams/adapter.py +++ b/plugins/platforms/teams/adapter.py @@ -55,7 +55,7 @@ HttpMethod = str # type: ignore[assignment,misc] from gateway.config import Platform, PlatformConfig from gateway.platforms.helpers import MessageDeduplicator from gateway.platforms.base import ( - gateway_trust_env, BasePlatformAdapter, SendResult, cache_image_from_url, cache_media_bytes_async, + gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt, SendResult, cache_image_from_url, cache_media_bytes_async, ) from gateway.platforms.event import MessageEvent, MessageType from gateway.platforms._shared import coerce_port, get_scoped_secret as _get_scoped_secret @@ -624,31 +624,28 @@ class TeamsAdapter(BasePlatformAdapter): return "⛔ Not authorized." return None - async def send_exec_approval( - self, chat_id: str, command: str, session_key: str, description: str = "dangerous command", - metadata: Optional[Dict[str, Any]] = None, allow_permanent: bool = True, allow_session: bool = True, - smart_denied: bool = False) -> SendResult: + _EA_CMD_BUDGET = 2000 + _EA_CARD_ACTIONS = {"once": "approve_once", "session": "approve_session", "always": "approve_always", "deny": "deny"} + _EA_CARD_STYLES = {"primary": "positive", "danger": "destructive"} + + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: + """Adaptive Card: the shared text is split into its header / fenced command / reason blocks.""" if not self._app: return SendResult(success=False, error="Teams app not initialized") # Button data carries a truncated cmd — just enough to reconstruct the card body. - btn_data_base = {"session_key": session_key, "cmd": _truncate(command, 200), "desc": description} - - def _action(title: str, hermes_action: str, **kw) -> "ExecuteAction": - return ExecuteAction( - title=title, verb="hermes_approve", data={**btn_data_base, "hermes_action": hermes_action}, **kw) - - actions = [_action("Allow Once", "approve_once", style="positive")] - if not smart_denied and allow_session: - actions.append(_action("Allow Session", "approve_session")) - if allow_permanent: - actions.append(_action("Always Allow", "approve_always")) - actions.append(_action("Deny", "deny", style="destructive")) - body = _approval_body(_truncate(command, 2000), description, always=True) - if smart_denied: - body.append(TextBlock(text="Smart DENY: owner override applies to this one operation only.", wrap=True)) + btn_data_base = {"session_key": prompt.session_key, "cmd": _truncate(prompt.command, 200), "desc": prompt.description} + actions = [] + for label, choice, style in prompt.actions: + kw = {"style": self._EA_CARD_STYLES[style]} if style else {} + actions.append(ExecuteAction( + title=label, verb="hermes_approve", + data={**btn_data_base, "hermes_action": self._EA_CARD_ACTIONS[choice]}, **kw)) + body = _approval_body(self._truncate_preview(prompt.command, self._EA_CMD_BUDGET), prompt.description, always=True) + if prompt.smart_denied: + body.append(TextBlock(text=self._EA_SMART_DENY_LINE.strip(), wrap=True)) card = AdaptiveCard().with_version("1.4").with_body(body).with_actions(actions) try: - result = await self._send_card(chat_id, card) + result = await self._send_card(prompt.chat_id, card) return SendResult(success=True, message_id=getattr(result, "id", None) if result else None) except Exception as e: logger.error("[teams] send_exec_approval failed: %s", e, exc_info=True) diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py index 03edcbdd55..376b2d3c5f 100644 --- a/plugins/platforms/telegram/adapter.py +++ b/plugins/platforms/telegram/adapter.py @@ -142,7 +142,7 @@ sys.path.insert(0, str(_Path(__file__).resolve().parents[3])) from gateway.authz_mixin import _coerce_allow_set from gateway.config import Platform, PlatformConfig from gateway.platforms.base import ( - BasePlatformAdapter, SendResult, classify_send_error, + BasePlatformAdapter, ExecApprovalPrompt, SendResult, classify_send_error, cache_image_from_bytes_async, cache_audio_from_bytes_async, cache_video_from_bytes_async, resolve_proxy_url, SUPPORTED_VIDEO_TYPES, SUPPORTED_DOCUMENT_TYPES, SUPPORTED_IMAGE_DOCUMENT_TYPES, _TEXT_INJECT_EXTENSIONS, utf16_len, ) @@ -3797,30 +3797,24 @@ class TelegramAdapter(BasePlatformAdapter): def _ea_escape(self, text: str) -> str: return _html.escape(text) - async def send_exec_approval( - self, chat_id: str, command: str, session_key: str, description: str = "dangerous command", - metadata: Optional[Dict[str, Any]] = None, allow_permanent: bool = True, allow_session: bool = True, - smart_denied: bool = False) -> SendResult: - """Send an inline-keyboard approval prompt; buttons call ``resolve_gateway_approval()`` like the + _EA_ACTION_LABELS = {"once": "✅ Allow Once", "session": "✅ Session", "always": "✅ Always", "deny": "❌ Deny"} + + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: + """Inline-keyboard approval prompt; buttons call ``resolve_gateway_approval()`` like the text ``/approve`` flow.""" def build(): - text = self._format_exec_approval(command, description, smart_denied) # Short monotonic ids in callback_data map back to session_key. import itertools if not hasattr(self, "_approval_counter"): self._approval_counter = itertools.count(1) approval_id = next(self._approval_counter) - buttons = [InlineKeyboardButton("✅ Allow Once", callback_data=f"ea:once:{approval_id}")] - if not smart_denied and allow_session: - buttons.append(InlineKeyboardButton("✅ Session", callback_data=f"ea:session:{approval_id}")) - if allow_permanent: - buttons.append(InlineKeyboardButton("✅ Always", callback_data=f"ea:always:{approval_id}")) - buttons.append(InlineKeyboardButton("❌ Deny", callback_data=f"ea:deny:{approval_id}")) - return text, InlineKeyboardMarkup( - self._rows_of_two(buttons)), lambda msg: self._approval_state.__setitem__(approval_id, session_key) + buttons = [InlineKeyboardButton(label, callback_data=f"ea:{choice}:{approval_id}") + for label, choice, _ in prompt.actions] + return prompt.text, InlineKeyboardMarkup(self._rows_of_two(buttons)), ( + lambda msg: self._approval_state.__setitem__(approval_id, prompt.session_key)) return await self._send_prompt( - "send_exec_approval", chat_id, metadata, build, parse_mode=ParseMode.HTML, - thread_id=self._metadata_thread_id(metadata), reply_to_mode=self._reply_to_mode) + "send_exec_approval", prompt.chat_id, prompt.metadata, build, parse_mode=ParseMode.HTML, + thread_id=self._metadata_thread_id(prompt.metadata), reply_to_mode=self._reply_to_mode) async def send_slash_confirm( self, chat_id: str, title: str, message: str, session_key: str, confirm_id: str, diff --git a/tests/gateway/test_exec_approval_template.py b/tests/gateway/test_exec_approval_template.py new file mode 100644 index 0000000000..0ea8960b39 --- /dev/null +++ b/tests/gateway/test_exec_approval_template.py @@ -0,0 +1,91 @@ +"""Invariants for the exec-approval template method on BasePlatformAdapter. + +The choice set (once / session / always / deny, minus the persistent tiers under a smart deny) +used to be re-derived in every button adapter and needed three separate "same fix × N adapters" +sweeps. It now comes from one place; adapters only render it. +""" + +from typing import Any, Dict + +import pytest + +from gateway.config import Platform, PlatformConfig +from gateway.platforms.base import BasePlatformAdapter, ExecApprovalPrompt, SendResult +from gateway.run_turn_runner import _renders_exec_approval_buttons + + +class _Plain(BasePlatformAdapter): + def __init__(self): + super().__init__(PlatformConfig(enabled=True), Platform.TELEGRAM) + + async def connect(self, *, is_reconnect: bool = False) -> bool: + return True + + async def disconnect(self) -> None: + pass + + async def send(self, *a: Any, **k: Any) -> SendResult: + return SendResult(success=True) + + async def get_chat_info(self, chat_id: str) -> Dict[str, Any]: + return {} + + +class _Buttons(_Plain): + def __init__(self): + super().__init__() + self.prompts: list = [] + + async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: + self.prompts.append(prompt) + return SendResult(success=True, message_id="m1") + + +@pytest.mark.parametrize( + "allow_permanent, allow_session, smart_denied, expected", + [ + (True, True, False, ["once", "session", "always", "deny"]), + (False, True, False, ["once", "session", "deny"]), + (True, False, False, ["once", "deny"]), # no session tier → no permanent tier either + (True, True, True, ["once", "deny"]), # smart deny: owner override is one-shot + (False, False, True, ["once", "deny"]), + ], +) +@pytest.mark.asyncio +async def test_choice_set_follows_the_shared_rule(allow_permanent, allow_session, smart_denied, expected): + adapter = _Buttons() + result = await adapter.send_exec_approval( + "chat", "rm -rf /tmp/x", "sess", description="cleanup", + allow_permanent=allow_permanent, allow_session=allow_session, smart_denied=smart_denied) + assert result.success + (prompt,) = adapter.prompts + assert prompt.choices == expected + assert "rm -rf /tmp/x" in prompt.text and "cleanup" in prompt.text + assert ("one operation only" in prompt.text) is smart_denied + + +@pytest.mark.asyncio +async def test_command_is_truncated_to_the_platform_budget(): + class _Small(_Buttons): + _EA_CMD_BUDGET = 20 + + adapter = _Small() + await adapter.send_exec_approval("chat", "x" * 100, "sess") + (prompt,) = adapter.prompts + assert "x" * 20 + "..." in prompt.text and "x" * 21 not in prompt.text + assert prompt.command == "x" * 100 # the raw command stays available for embeds/cards + + +def test_runner_only_offers_buttons_to_adapters_that_render_them(): + """Plain adapters get the text ``/approve`` prompt; the base send_exec_approval must not make + the runner believe every adapter has buttons (its default reports failure and the runner would + log a spurious fallback on every approval).""" + assert _renders_exec_approval_buttons(_Buttons) is True + assert _renders_exec_approval_buttons(_Plain) is False + + class _DuckTyped: + async def send_exec_approval(self, *a, **k): + return SendResult(success=True) + + assert _renders_exec_approval_buttons(_DuckTyped) is True + assert _renders_exec_approval_buttons(object) is False