From ce1f7cb5dbeaaae69fea1332d5f202527a727fe7 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 20:34:27 -0700 Subject: [PATCH] refactor(gateway/whatsapp): connect precondition table, lazy resolver import helper, merged interactive post --- gateway/platforms/whatsapp_cloud.py | 251 +++++++++++----------------- 1 file changed, 95 insertions(+), 156 deletions(-) diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.py index af6dba7b6f..c4d2b3dd56 100644 --- a/gateway/platforms/whatsapp_cloud.py +++ b/gateway/platforms/whatsapp_cloud.py @@ -1,19 +1,18 @@ -""" -WhatsApp Cloud API adapter — official Meta WhatsApp Business Platform (Graph API + +"""WhatsApp Cloud API adapter — official Meta WhatsApp Business Platform (Graph API + aiohttp webhook). Complements the Baileys bridge plugin; both share gating / mention / formatting behavior via ``WhatsAppBehaviorMixin``. Required env: WHATSAPP_CLOUD_PHONE_NUMBER_ID, WHATSAPP_CLOUD_ACCESS_TOKEN. Optional: WHATSAPP_CLOUD_APP_ID, _APP_SECRET (HMAC key for X-Hub-Signature-256), _WABA_ID, _VERIFY_TOKEN (hub.verify_token), _WEBHOOK_HOST (unset → dual-stack all interfaces), -_WEBHOOK_PORT (8090), _WEBHOOK_PATH (/whatsapp/webhook), _API_VERSION (v20.0). -""" +_WEBHOOK_PORT (8090), _WEBHOOK_PATH (/whatsapp/webhook), _API_VERSION (v20.0).""" from __future__ import annotations import asyncio import hashlib import hmac +import importlib import json import logging import mimetypes @@ -49,22 +48,19 @@ logger = logging.getLogger(__name__) DEFAULT_API_VERSION = "v20.0" -# ``None`` → aiohttp binds one socket per address family (IPv4 + IPv6). "0.0.0.0" -# bound IPv4 only and was unreachable on IPv6-only networks (e.g. Fly.io 6PN). +# ``None`` → aiohttp binds one socket per address family; "0.0.0.0" was unreachable on IPv6-only hosts. DEFAULT_WEBHOOK_HOST = None DEFAULT_WEBHOOK_PORT = 8090 DEFAULT_WEBHOOK_PATH = "/whatsapp/webhook" GRAPH_API_BASE = "https://graph.facebook.com" WEBHOOK_MAX_BODY_BYTES = 3 * 1024 * 1024 -# Meta retries failed webhooks for up to 7 days, but the practical duplicate -# risk is within minutes — 5000 FIFO entries bounds memory and covers that. +# Meta retries failed webhooks for up to 7 days, but the practical duplicate risk is +# within minutes — 5000 FIFO entries bounds memory and covers that. WAMID_DEDUP_CACHE_SIZE = 5000 -# Cap for the interactive-button state dicts and the per-chat last-wamid cache. -INTERACTIVE_STATE_CACHE_SIZE = 1000 +INTERACTIVE_STATE_CACHE_SIZE = 1000 # interactive-button state dicts + per-chat last-wamid cache -# Meta's hard per-type caps for the /media endpoint; refuse locally instead of -# round-tripping to Graph just to be rejected. -# https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media +# Meta's hard per-type caps for /media (developers.facebook.com/docs/whatsapp/cloud-api/reference/media); +# refuse locally instead of round-tripping to Graph just to be rejected. _MEDIA_SIZE_LIMITS = { "image": 5 * 1024 * 1024, "video": 16 * 1024 * 1024, "audio": 16 * 1024 * 1024, "document": 100 * 1024 * 1024, "sticker": 100 * 1024, @@ -75,13 +71,11 @@ _DEFAULT_MIME = { "document": "application/octet-stream", "sticker": "image/webp", } -# ``shutil.which`` honours PATHEXT on Windows. None → MP3 voice falls back to an -# "audio file attachment" rendering in WhatsApp. +# None → MP3 voice falls back to an "audio file attachment" rendering in WhatsApp. _FFMPEG_PATH = shutil.which("ffmpeg") -# mimetypes returns RFC-correct but uncommon extensions (audio/ogg → .oga, -# audio/mp4 → .mp4, image/jpeg → .jpe). Downstream STT/vision whitelists the -# in-the-wild forms, so pin the few Meta sends. +# mimetypes returns RFC-correct but uncommon extensions (audio/ogg → .oga, image/jpeg → .jpe); +# downstream STT/vision whitelists the in-the-wild forms, so pin the few Meta sends. _WHATSAPP_MIME_EXTENSION_OVERRIDES: Dict[str, str] = { "audio/ogg": ".ogg", "audio/x-opus+ogg": ".ogg", "audio/opus": ".ogg", "audio/mp4": ".m4a", "audio/x-m4a": ".m4a", "image/jpeg": ".jpg", @@ -129,10 +123,7 @@ def _ext_for_mime(mime: str) -> Optional[str]: """Mime → on-disk extension: WhatsApp overrides → mimetypes → None (never the shared default table).""" if not mime: return None - return ext_for_mime( - mime, overrides=_WHATSAPP_MIME_EXTENSION_OVERRIDES, - use_defaults=False, use_mimetypes=True, fallback=None, - ) + return ext_for_mime(mime, overrides=_WHATSAPP_MIME_EXTENSION_OVERRIDES, use_defaults=False, use_mimetypes=True, fallback=None) def _cloud_allow_all_opted_in() -> bool: @@ -143,6 +134,15 @@ def _reply_to_from(metadata: Optional[Dict[str, Any]]) -> Optional[str]: return (metadata or {}).get("reply_to_message_id") +def _optional_module(name: str, unavailable_log: str) -> Any: + """Lazy-import a resolver module (tools.* may be absent in slim installs); None + warning if missing.""" + try: + return importlib.import_module(name) + except ImportError: + logger.warning(unavailable_log) + return None + + # Under the hermes dir so it survives restarts/reloads — same as the Baileys bridge. _INBOUND_MEDIA_CACHE = Path(get_hermes_dir("platforms/whatsapp_cloud/media", "whatsapp_cloud/media")) @@ -161,12 +161,10 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): def __init__(self, config: PlatformConfig): super().__init__(config, Platform.WHATSAPP_CLOUD) extra = config.extra or {} - self._phone_number_id: str = str(extra.get("phone_number_id", "")).strip() - self._access_token: str = str(extra.get("access_token", "")).strip() - self._app_id: str = str(extra.get("app_id", "")).strip() - self._app_secret: str = str(extra.get("app_secret", "")).strip() - self._waba_id: str = str(extra.get("waba_id", "")).strip() - self._verify_token: str = str(extra.get("verify_token", "")).strip() + self._phone_number_id, self._access_token, self._app_id, self._app_secret, self._waba_id, self._verify_token = ( + str(extra.get(key, "")).strip() + for key in ("phone_number_id", "access_token", "app_id", "app_secret", "waba_id", "verify_token") + ) # Falsy host (None/"") collapses to the dual-stack default. raw_host = extra.get("webhook_host", DEFAULT_WEBHOOK_HOST) or DEFAULT_WEBHOOK_HOST self._webhook_host: Optional[str] = str(raw_host) if raw_host else None @@ -187,21 +185,15 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): # "allowlist" when one is configured (so it is enforced), else "open". default_dm_policy = "allowlist" if self._allow_from and not _cloud_allow_all_opted_in() else "open" self._dm_policy: str = str( - extra.get("dm_policy") - or _get_wsecret("WHATSAPP_CLOUD_DM_POLICY") - or _get_wsecret("WHATSAPP_DM_POLICY") - or default_dm_policy + extra.get("dm_policy") or _get_wsecret("WHATSAPP_CLOUD_DM_POLICY") + or _get_wsecret("WHATSAPP_DM_POLICY") or default_dm_policy ).strip().lower() self._group_policy: str = str( - extra.get("group_policy") - or _get_wsecret("WHATSAPP_CLOUD_GROUP_POLICY") - or _get_wsecret("WHATSAPP_GROUP_POLICY", default="open") - or "open" + extra.get("group_policy") or _get_wsecret("WHATSAPP_CLOUD_GROUP_POLICY") + or _get_wsecret("WHATSAPP_GROUP_POLICY", default="open") or "open" ).strip().lower() self._group_allow_from: set[str] = self._normalize_allow_ids(self._coerce_allow_list( - extra.get("group_allow_from") - or extra.get("groupAllowFrom") - or _get_wsecret("WHATSAPP_CLOUD_GROUP_ALLOW_FROM") + extra.get("group_allow_from") or extra.get("groupAllowFrom") or _get_wsecret("WHATSAPP_CLOUD_GROUP_ALLOW_FROM") )) self._mention_patterns = self._compile_mention_patterns() @@ -272,18 +264,15 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): # ------------------------------------------------------------------ lifecycle async def connect(self, *, is_reconnect: bool = False) -> bool: - if not check_whatsapp_cloud_requirements(): - self._set_fatal_error( - "whatsapp_cloud_deps_missing", - "aiohttp and httpx are required for whatsapp_cloud — reinstall hermes-agent.", retryable=False, - ) - return False - if not self._phone_number_id or not self._access_token: - self._set_fatal_error( - "whatsapp_cloud_unconfigured", - "WHATSAPP_CLOUD_PHONE_NUMBER_ID and WHATSAPP_CLOUD_ACCESS_TOKEN are required.", retryable=False, - ) - return False + for ok, code, message in ( + (check_whatsapp_cloud_requirements(), "whatsapp_cloud_deps_missing", + "aiohttp and httpx are required for whatsapp_cloud — reinstall hermes-agent."), + (self._phone_number_id and self._access_token, "whatsapp_cloud_unconfigured", + "WHATSAPP_CLOUD_PHONE_NUMBER_ID and WHATSAPP_CLOUD_ACCESS_TOKEN are required."), + ): + if not ok: + self._set_fatal_error(code, message, retryable=False) + return False # Tighter keepalive so idle CLOSE_WAIT drains promptly. from gateway.platforms._http_client_limits import platform_httpx_limits self._http_client = httpx.AsyncClient(timeout=30.0, limits=platform_httpx_limits()) @@ -301,9 +290,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): self._webhook_host, self._webhook_port, self._webhook_path, self._api_version, self._phone_number_id, ) if not self._verify_token: - logger.warning( - "[whatsapp_cloud] WHATSAPP_CLOUD_VERIFY_TOKEN is not set — the GET subscription handshake will fail until it is." - ) + logger.warning("[whatsapp_cloud] WHATSAPP_CLOUD_VERIFY_TOKEN is not set — the GET subscription handshake will fail until it is.") if not self._app_secret: logger.warning( "[whatsapp_cloud] WHATSAPP_CLOUD_APP_SECRET is not set — incoming webhook POSTs will be refused " @@ -372,13 +359,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): @staticmethod def _outbound_payload(chat_id: str, kind: str, block: Any, reply_to: Optional[str]) -> Dict[str, Any]: """Common ``/messages`` envelope; ``context`` quotes ``reply_to`` when given.""" - payload: Dict[str, Any] = { - "messaging_product": "whatsapp", - "recipient_type": "individual", - "to": chat_id, - "type": kind, - kind: block, - } + payload: Dict[str, Any] = {"messaging_product": "whatsapp", "recipient_type": "individual", "to": chat_id, "type": kind, kind: block} if reply_to: payload["context"] = {"message_id": reply_to} return payload @@ -406,8 +387,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): ) if err is not None: return SendResult(success=False, error=err) - if ids: - last_message_id = ids[0].get("id") + last_message_id = ids[0].get("id") if ids else last_message_id # Index (chat_id, wamid) → text: Meta's inbound ``context`` carries only the # quoted message's id, so this is how replies to our messages resolve text. if last_message_id: @@ -441,26 +421,19 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): logger.debug("[whatsapp_cloud] typing/read indicator returned %d (%s)", resp.status_code, code) # ------------------------------------------------------------------ interactive messages - # ``type=button``: ≤3 quick-reply buttons (id ≤256 chars, title ≤20); ``type=list``: one - # "Tap to choose" button opening ≤10 rows. Free-form (no Meta approval) but only valid - # inside the 24h window — fine, since all senders here fire in reply to a user message. - - async def _post_interactive( - self, chat_id: str, interactive_body: Dict[str, Any], reply_to: Optional[str] = None, - ) -> SendResult: - """POST an ``interactive`` message; caller supplies ``type``/``body``/``action``.""" - return await self._post_message_result( - self._outbound_payload(chat_id, "interactive", interactive_body, reply_to), - fail_log="[whatsapp_cloud] interactive send failed", - reject_log="[whatsapp_cloud] interactive rejected (status=%d): %s", - ) - + # Free-form (no Meta approval) but only valid inside the 24h window — fine, since all + # senders here fire in reply to a user message. async def _send_interactive( self, chat_id: str, interactive: Dict[str, Any], metadata: Optional[Dict[str, Any]], state: "OrderedDict[str, str]", state_id: str, session_key: str, ) -> SendResult: - """Post an interactive prompt and, on success, remember ``state_id → session_key`` for the tap.""" - result = await self._post_interactive(chat_id, interactive, reply_to=_reply_to_from(metadata)) + """POST an ``interactive`` message (caller supplies ``type``/``body``/``action``) and, on + success, remember ``state_id → session_key`` for the tap.""" + result = await self._post_message_result( + self._outbound_payload(chat_id, "interactive", interactive, _reply_to_from(metadata)), + fail_log="[whatsapp_cloud] interactive send failed", + reject_log="[whatsapp_cloud] interactive rejected (status=%d): %s", + ) if result.success: self._bounded_put(state, state_id, session_key) return result @@ -483,17 +456,16 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): @classmethod def _button_interactive(cls, body_text: str, *buttons: tuple[str, str]) -> Dict[str, Any]: + """``interactive.type=button`` body: ≤3 quick-reply buttons (id ≤256 chars, title ≤20).""" return {"type": "button", "body": {"text": body_text}, "action": {"buttons": cls._reply_buttons(*buttons)}} async def send_clarify( self, chat_id: str, question: str, choices: Optional[list], clarify_id: str, session_key: str, metadata: Optional[Dict[str, Any]] = None, ) -> SendResult: - """Clarify as native buttons: 1–3 choices → buttons, 4+ → list (+ "Other" row - that flips the entry into text-capture mode), 0 → plain text question. - - Button ``id`` carries ``cl::``; inbound dispatches on it. - """ + """Clarify as native buttons: 1–3 choices → buttons, 4+ → list (+ "Other" row that flips + the entry into text-capture mode), 0 → plain text question. Button ``id`` carries + ``cl::``; inbound dispatches on it.""" if self._http_client is None: return SendResult(success=False, error="Not connected") question = (question or "").strip() @@ -517,11 +489,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): for idx, choice_text in enumerate(choices_list) ] rows.append({"id": f"cl:{clarify_id}:other", "title": "✏️ Other", "description": "Type your own answer"}) - interactive = { - "type": "list", - "body": {"text": body_text}, - "action": {"button": "Choose", "sections": [{"title": "Options", "rows": rows}]}, - } + 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( @@ -539,12 +507,8 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): + ("\n\nSmart DENY: owner override applies to this one operation only." if smart_denied else "") ) 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(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) async def send_slash_confirm( self, chat_id: str, title: str, message: str, session_key: str, confirm_id: str, @@ -552,14 +516,10 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): ) -> SendResult: """Approve Once / Always / Cancel buttons; ``confirm_id`` is caller-supplied.""" interactive = self._button_interactive( - self._truncate_body(f"*{title}*\n\n{message}"), - (f"sc:once:{confirm_id}", "✅ Approve Once"), - (f"sc:always:{confirm_id}", "🔒 Always"), - (f"sc:cancel:{confirm_id}", "❌ Cancel"), - ) - return await self._send_interactive( - chat_id, interactive, metadata, self._slash_confirm_state, confirm_id, session_key + self._truncate_body(f"*{title}*\n\n{message}"), (f"sc:once:{confirm_id}", "✅ Approve Once"), + (f"sc:always:{confirm_id}", "🔒 Always"), (f"sc:cancel:{confirm_id}", "❌ Cancel"), ) + return await self._send_interactive(chat_id, interactive, metadata, self._slash_confirm_state, confirm_id, session_key) async def get_chat_info(self, chat_id: str) -> Dict[str, Any]: # No chat-info endpoint; profile name arrives via webhook contacts[]. @@ -574,8 +534,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): return None, "Not connected" if not os.path.exists(file_path): return None, f"File not found: {file_path}" - size = os.path.getsize(file_path) - cap = _MEDIA_SIZE_LIMITS.get(media_kind, _MEDIA_SIZE_LIMITS["document"]) + size, cap = os.path.getsize(file_path), _MEDIA_SIZE_LIMITS.get(media_kind, _MEDIA_SIZE_LIMITS["document"]) if size > cap: return None, f"File {os.path.basename(file_path)} is {size} bytes; Cloud API {media_kind} cap is {cap} bytes" mime_type = mime_type or mimetypes.guess_type(file_path)[0] or _DEFAULT_MIME.get(media_kind, "application/octet-stream") @@ -646,8 +605,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): file_name: Optional[str] = None, reply_to: Optional[str] = None, **kwargs, ) -> SendResult: return await self._send_media_from_path_or_link( - chat_id, file_path, "document", - caption=caption, filename=file_name or os.path.basename(file_path), reply_to=reply_to, + chat_id, file_path, "document", caption=caption, filename=file_name or os.path.basename(file_path), reply_to=reply_to, ) async def send_voice( @@ -662,8 +620,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): if opus_path: try: return await self._send_media_from_path_or_link( - chat_id, opus_path, "audio", caption=caption, reply_to=reply_to, - mime_type="audio/ogg; codecs=opus", + chat_id, opus_path, "audio", caption=caption, reply_to=reply_to, mime_type="audio/ogg; codecs=opus", ) finally: # The .ogg is a transient artifact next to the source MP3. @@ -673,9 +630,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): pass # No ffmpeg (warn-once logged in _convert_to_opus) → MP3 attachment. mime_type = "audio/mpeg" - return await self._send_media_from_path_or_link( - chat_id, audio_path, "audio", caption=caption, reply_to=reply_to, mime_type=mime_type, - ) + return await self._send_media_from_path_or_link(chat_id, audio_path, "audio", caption=caption, reply_to=reply_to, mime_type=mime_type) async def _convert_to_opus(self, mp3_path: str) -> Optional[str]: """MP3 → ``audio/ogg; codecs=opus``; None if ffmpeg is missing or fails. ``-application voip`` @@ -692,21 +647,20 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): out_path = mp3_path.rsplit(".", 1)[0] + ".ogg" try: proc = await asyncio.create_subprocess_exec( - _FFMPEG_PATH, "-y", "-i", mp3_path, - "-c:a", "libopus", "-b:a", "32k", "-vbr", "on", "-application", "voip", out_path, - stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE, + _FFMPEG_PATH, "-y", "-i", mp3_path, "-c:a", "libopus", "-b:a", "32k", "-vbr", "on", "-application", "voip", + out_path, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE, ) _, stderr = await proc.communicate() except Exception: logger.exception("[whatsapp_cloud] ffmpeg subprocess raised") return None - if proc.returncode != 0 or not Path(out_path).exists(): - logger.error( - "[whatsapp_cloud] ffmpeg opus conversion failed (returncode=%s): %s", - proc.returncode, (stderr or b"").decode("utf-8", errors="replace")[:500], - ) - return None - return out_path + if proc.returncode == 0 and Path(out_path).exists(): + return out_path + logger.error( + "[whatsapp_cloud] ffmpeg opus conversion failed (returncode=%s): %s", + proc.returncode, (stderr or b"").decode("utf-8", errors="replace")[:500], + ) + return None # ------------------------------------------------------------------ inbound media async def _graph_get(self, url: str, headers: Dict[str, str], what: str, media_id: str) -> Any: @@ -817,10 +771,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): def _verify_signature(self, raw_body: bytes, header: str) -> bool: """Verify ``sha256=`` HMAC of the raw body keyed by ``app_secret`` (constant-time).""" - if not self._app_secret or not header or not header.startswith("sha256="): - return False - expected_hex = header[len("sha256="):].strip() - if not expected_hex: + if not (self._app_secret and header and header.startswith("sha256=") and (expected_hex := header[7:].strip())): return False computed = hmac.new(self._app_secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest() # Compare as bytes: compare_digest raises TypeError on non-ASCII str. @@ -893,9 +844,9 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): dispatch with the button title — covers stale taps.""" inner = _interactive_inner(raw_message) button_id = str(inner.get("id") or "").strip() + sender_id = str(raw_message.get("from") or "").strip() if not button_id: return False - sender_id = str(raw_message.get("from") or "").strip() if not self._is_interactive_sender_authorized(sender_id): logger.warning("[whatsapp_cloud] Rejected unauthorized interactive tap from %s (button_id=%r)", sender_id or "", button_id) return True # claim so the tap isn't re-dispatched as plain text @@ -928,19 +879,17 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): ) if not session_key: return False - try: - from tools.clarify_gateway import resolve_gateway_clarify - except ImportError: - logger.warning("[whatsapp_cloud] clarify resolver unavailable; falling back to text dispatch") + clarify_gateway = _optional_module( + "tools.clarify_gateway", "[whatsapp_cloud] clarify resolver unavailable; falling back to text dispatch" + ) + if clarify_gateway is None: return False if choice == "other": - # Flip the entry into text-capture mode so the gateway's text intercept - # resolves the clarify with the next message; otherwise that text would - # hit the agent path while it's still blocked in clarify ("Interrupting - # current task" loop). + # Flip the entry into text-capture mode so the gateway's text intercept resolves the + # clarify with the next message; otherwise that text would hit the agent path while + # it's still blocked in clarify ("Interrupting current task" loop). try: - from tools.clarify_gateway import mark_awaiting_text - flipped = mark_awaiting_text(clarify_id) + flipped = clarify_gateway.mark_awaiting_text(clarify_id) except Exception: logger.exception("[whatsapp_cloud] mark_awaiting_text failed for %s", clarify_id) flipped = False @@ -959,7 +908,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): self._clarify_state[clarify_id] = session_key # a follow-up text can still resolve return False # Title is the numeric label; the agent has the prompt in context to interpret it. - if not resolve_gateway_clarify(clarify_id, str(inner.get("title") or str(idx + 1))): + if not clarify_gateway.resolve_gateway_clarify(clarify_id, str(inner.get("title") or str(idx + 1))): logger.info("[whatsapp_cloud] clarify resolver reported no waiter (clarify_id=%s) — falling back to text", clarify_id) return False return True @@ -975,12 +924,10 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): if choice not in ("approve", "deny"): self._exec_approval_state[approval_id] = session_key return False - try: - from tools.approval import resolve_gateway_approval - except ImportError: - logger.warning("[whatsapp_cloud] approval resolver unavailable") + approval = _optional_module("tools.approval", "[whatsapp_cloud] approval resolver unavailable") + if approval is None: return False - count = resolve_gateway_approval(session_key, choice) + count = approval.resolve_gateway_approval(session_key, choice) # A tap after the wait timed out (count == 0) must not claim approval: # the command was already denied fail-closed. if count: @@ -1002,13 +949,11 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): if choice not in ("once", "always", "cancel"): self._slash_confirm_state[confirm_id] = session_key return False - try: - from tools import slash_confirm as _slash_confirm_mod - except ImportError: - logger.warning("[whatsapp_cloud] slash_confirm resolver unavailable") + slash_confirm = _optional_module("tools.slash_confirm", "[whatsapp_cloud] slash_confirm resolver unavailable") + if slash_confirm is None: return False try: - result_text = await _slash_confirm_mod.resolve(session_key, confirm_id, choice) + result_text = await slash_confirm.resolve(session_key, confirm_id, choice) except Exception: logger.exception("[whatsapp_cloud] slash_confirm.resolve failed") return True # still claim the tap; surfacing it as text wouldn't help @@ -1016,11 +961,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): await self._reply_best_effort(to, result_text, "[whatsapp_cloud] slash_confirm reply failed") return True - _INTERACTIVE_HANDLERS = { - "cl:": _handle_clarify_tap, - "appr:": _handle_approval_tap, - "sc:": _handle_slash_confirm_tap, - } + _INTERACTIVE_HANDLERS = {"cl:": _handle_clarify_tap, "appr:": _handle_approval_tap, "sc:": _handle_slash_confirm_tap} async def _collect_inbound_media( self, msg_type_str: str, raw_message: Dict[str, Any], body: str @@ -1029,8 +970,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): media_urls: list[str] = [] media_types: list[str] = [] inner = raw_message.get(msg_type_str) or {} - media_id = str(inner.get("id") or "").strip() - inbound_mime = str(inner.get("mime_type") or "").strip() + media_id, inbound_mime = str(inner.get("id") or "").strip(), str(inner.get("mime_type") or "").strip() if not media_id: return media_urls, media_types, body local_path, dl_mime = await self._download_media_to_cache(media_id, ext_hint=_ext_for_mime(inbound_mime)) @@ -1090,8 +1030,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): chat_id = sender_id if not self._should_process_message({"chatId": chat_id, "senderId": sender_id, "isGroup": False, "body": body}): return None - media_urls: list[str] = [] - media_types: list[str] = [] + media_urls, media_types = [], [] if msg_type_str in _INBOUND_MEDIA_KINDS: media_urls, media_types, body = await self._collect_inbound_media(msg_type_str, raw_message, body) if msg_type_str == "document" and media_urls: